diff --git a/go.mod b/go.mod index 23358d21b1..c42cb2ae80 100644 --- a/go.mod +++ b/go.mod @@ -28,76 +28,77 @@ require ( github.com/google/go-containerregistry v0.21.7 github.com/google/nftables v0.3.0 github.com/google/uuid v1.6.0 - github.com/googleapis/gax-go/v2 v2.21.0 + github.com/googleapis/gax-go/v2 v2.22.0 github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 - github.com/jackc/pgx/v5 v5.10.0 - github.com/klauspost/compress v1.19.1 + github.com/jackc/pgx/v5 v5.11.0 + github.com/klauspost/compress v1.20.1 github.com/myzhan/boomer v1.6.1-0.20250711115830-8a2c7ce4c7b1 github.com/opencontainers/runtime-spec v1.3.0 github.com/openfga/api/proto v0.0.0-20260319214821-f153694bfc20 - github.com/openfga/language/pkg/go v0.3.2-0.20260730144454-83fedf8a4e70 - github.com/openfga/openfga v1.20.0 - github.com/pressly/goose/v3 v3.27.3 - github.com/prometheus/client_golang v1.24.1 + github.com/openfga/language/pkg/go v0.3.2 + github.com/openfga/openfga v1.23.0 + github.com/pressly/goose/v3 v3.29.0 + github.com/prometheus/client_golang v1.25.0 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 - github.com/spiffe/go-spiffe/v2 v2.7.0 + github.com/spiffe/go-spiffe/v2 v2.8.1 github.com/stretchr/testify v1.12.1 github.com/testcontainers/testcontainers-go v0.44.0 github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 github.com/vishvananda/netlink v1.3.1 github.com/vishvananda/netns v0.0.5 go.opentelemetry.io/contrib/bridges/prometheus v0.68.0 - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0 - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 - go.opentelemetry.io/otel v1.45.0 + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 + go.opentelemetry.io/otel v1.47.0 go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0 go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0 - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 go.opentelemetry.io/otel/exporters/prometheus v0.65.0 - go.opentelemetry.io/otel/log v0.21.0 - go.opentelemetry.io/otel/metric v1.45.0 - go.opentelemetry.io/otel/sdk v1.45.0 + go.opentelemetry.io/otel/log v1.47.0 + go.opentelemetry.io/otel/metric v1.47.0 + go.opentelemetry.io/otel/sdk v1.47.0 go.opentelemetry.io/otel/sdk/log v0.21.0 - go.opentelemetry.io/otel/sdk/metric v1.45.0 - go.opentelemetry.io/otel/trace v1.45.0 - go.opentelemetry.io/proto/otlp v1.11.0 - golang.org/x/net v0.60.0 - golang.org/x/oauth2 v0.36.0 - golang.org/x/sync v0.23.0 - golang.org/x/sys v0.48.0 + go.opentelemetry.io/otel/sdk/metric v1.47.0 + go.opentelemetry.io/otel/trace v1.47.0 + go.opentelemetry.io/proto/otlp v1.11.1 + golang.org/x/net v0.62.0 + golang.org/x/oauth2 v0.37.0 + golang.org/x/sync v0.24.0 + golang.org/x/sys v0.49.0 golang.org/x/time v0.15.0 - google.golang.org/api v0.274.0 - google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d - google.golang.org/grpc v1.83.2 + google.golang.org/api v0.278.0 + google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b + google.golang.org/grpc v1.84.0 google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 k8s.io/api v0.37.0 - k8s.io/apiextensions-apiserver v0.36.1 + k8s.io/apiextensions-apiserver v0.37.0 k8s.io/apimachinery v0.37.0 k8s.io/client-go v0.37.0 k8s.io/kubelet v0.37.0 k8s.io/metrics v0.36.1 k8s.io/utils v0.0.0-20260626114624-be93311217bd - sigs.k8s.io/controller-runtime v0.24.1 + sigs.k8s.io/controller-runtime v0.25.2 sigs.k8s.io/kustomize/api v0.21.1 sigs.k8s.io/kustomize/kyaml v0.21.1 sigs.k8s.io/yaml v1.6.0 ) require ( + cel.dev/cel-go v0.33.2 // indirect cel.dev/expr v0.25.2 // indirect cloud.google.com/go v0.123.0 // indirect - cloud.google.com/go/auth v0.19.0 // indirect + cloud.google.com/go/auth v0.20.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect cloud.google.com/go/longrunning v0.9.0 // indirect dario.cat/mergo v1.0.2 // indirect - github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 // indirect + github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0 // indirect github.com/IBM/pgxpoolprometheus v1.1.3 // indirect - github.com/Microsoft/go-winio v0.6.2 // indirect + github.com/Microsoft/go-winio v0.6.3 // indirect github.com/Yiling-J/theine-go v0.6.2 // indirect github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef // indirect @@ -129,7 +130,7 @@ require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/docker/cli v29.5.3+incompatible // indirect github.com/docker/docker-credential-helpers v0.9.3 // indirect - github.com/docker/go-connections v0.7.0 // indirect + github.com/docker/go-connections v0.8.2 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/ebitengine/purego v0.10.1 // indirect github.com/emicklei/go-restful/v3 v3.13.0 // indirect @@ -144,33 +145,32 @@ require ( github.com/go-jose/go-jose/v4 v4.1.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.3.0 // indirect - github.com/go-openapi/jsonpointer v1.0.0 // indirect - github.com/go-openapi/jsonreference v1.0.0 // indirect - github.com/go-openapi/swag v0.28.0 // indirect - github.com/go-openapi/swag/cmdutils v0.28.0 // indirect - github.com/go-openapi/swag/conv v0.28.0 // indirect - github.com/go-openapi/swag/fileutils v0.28.0 // indirect - github.com/go-openapi/swag/jsonutils v0.28.0 // indirect - github.com/go-openapi/swag/loading v0.28.0 // indirect - github.com/go-openapi/swag/mangling v0.28.0 // indirect - github.com/go-openapi/swag/netutils v0.28.0 // indirect - github.com/go-openapi/swag/pools v0.28.0 // indirect - github.com/go-openapi/swag/stringutils v0.28.0 // indirect - github.com/go-openapi/swag/typeutils v0.28.0 // indirect - github.com/go-openapi/swag/yamlutils v0.28.0 // indirect + github.com/go-openapi/jsonpointer v1.0.2 // indirect + github.com/go-openapi/jsonreference v1.0.3 // indirect + github.com/go-openapi/swag v0.29.2 // indirect + github.com/go-openapi/swag/cmdutils v0.29.2 // indirect + github.com/go-openapi/swag/conv v0.29.2 // indirect + github.com/go-openapi/swag/fileutils v0.29.2 // indirect + github.com/go-openapi/swag/jsonutils v0.29.2 // indirect + github.com/go-openapi/swag/loading v0.29.2 // indirect + github.com/go-openapi/swag/mangling v0.29.2 // indirect + github.com/go-openapi/swag/netutils v0.29.2 // indirect + github.com/go-openapi/swag/pools v0.29.2 // indirect + github.com/go-openapi/swag/stringutils v0.29.2 // indirect + github.com/go-openapi/swag/typeutils v0.29.2 // indirect + github.com/go-openapi/swag/yamlutils v0.29.2 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect - github.com/google/cel-go v0.31.0 // indirect github.com/google/gnostic-models v0.7.0 // indirect github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 // indirect github.com/google/s2a-go v0.1.9 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.14 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.15 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect - github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect + github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.4 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/jackc/puddle/v2 v2.2.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.0.9 // indirect github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect @@ -185,8 +185,8 @@ require ( github.com/mfridman/interpolate v0.0.2 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/go-archive v0.3.0 // indirect - github.com/moby/moby/api v1.55.0 // indirect - github.com/moby/moby/client v0.5.1 // indirect + github.com/moby/moby/api v1.56.1 // indirect + github.com/moby/moby/client v0.6.2 // indirect github.com/moby/patternmatcher v0.6.1 // indirect github.com/moby/spdystream v0.5.1 // indirect github.com/moby/sys/sequential v0.7.0 // indirect @@ -211,16 +211,16 @@ require ( github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.70.1 // indirect + github.com/prometheus/client_model v0.6.3 // indirect + github.com/prometheus/common v0.72.0 // indirect github.com/prometheus/otlptranslator v1.0.0 // indirect - github.com/prometheus/procfs v0.21.1 // indirect + github.com/prometheus/procfs v0.22.0 // indirect github.com/rivo/uniseg v0.2.0 // indirect github.com/sagikazarmark/locafero v0.9.0 // indirect - github.com/sethvargo/go-retry v0.4.0 // indirect + github.com/sethvargo/go-retry v0.5.0 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect github.com/shirou/gopsutil/v4 v4.26.6 // indirect - github.com/sirupsen/logrus v1.9.4 // indirect + github.com/sirupsen/logrus v1.10.2 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect @@ -236,20 +236,20 @@ require ( github.com/zeromq/goczmq v4.1.0+incompatible // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect go.uber.org/mock v0.6.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.28.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/crypto v0.57.0 // indirect - golang.org/x/exp v0.0.0-20260718201538-764159d718ef // indirect - golang.org/x/term v0.46.0 // indirect - golang.org/x/text v0.42.0 // indirect + golang.org/x/crypto v0.58.0 // indirect + golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e // indirect + golang.org/x/term v0.47.0 // indirect + golang.org/x/text v0.43.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect gonum.org/v1/gonum v0.17.0 // indirect google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect k8s.io/klog/v2 v2.140.0 // indirect diff --git a/go.sum b/go.sum index 64c57966a0..f8445e7fa2 100644 --- a/go.sum +++ b/go.sum @@ -1,10 +1,12 @@ +cel.dev/cel-go v0.33.2 h1:eAcEdBguc6AFrGbPOyE0g168Uey4kKFW9J6qsBLSeMU= +cel.dev/cel-go v0.33.2/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU= cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -cloud.google.com/go/auth v0.19.0 h1:DGYwtbcsGsT1ywuxsIoWi1u/vlks0moIblQHgSDgQkQ= -cloud.google.com/go/auth v0.19.0/go.mod h1:2Aph7BT2KnaSFOM0JDPyiYgNh6PL9vGMiP8CUIXZ+IY= +cloud.google.com/go/auth v0.20.0 h1:kXTssoVb4azsVDoUiF8KvxAqrsQcQtB53DcSgta74CA= +cloud.google.com/go/auth v0.20.0/go.mod h1:942/yi/itH1SsmpyrbnTMDgGfdy2BUqIKyd0cyYLc5Q= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= @@ -33,11 +35,11 @@ filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk= github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 h1:m2xcjRABtG288vnlV3U/PKh/HnPURxZp50RKNUwBxM8= +github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4/go.mod h1:MTUE7ZuZO89FAtAwozGg6AWD83pcdefnEq5gF82MB8s= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 h1:l7+6kwRMJNwdCvYdDl7Eax+wzEYHSnNY7zrrfbhDdTA= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0 h1:yzIYdwuro811Z27D3T80Wkd3rqZzb0K43nner7Eh1yE= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 h1:UnDZ/zFfG1JhH/DqxIZYU/1CUAlTUScoXD/LcM2Ykk8= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0/go.mod h1:IA1C1U7jO/ENqm/vhi7V9YYpBsp+IMyqNrEN94N7tVc= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.55.0 h1:7t/qx5Ost0s0wbA/VDrByOooURhp+ikYwv20i9Y07TQ= @@ -50,8 +52,8 @@ github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1 github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM= github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= -github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= -github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/Microsoft/go-winio v0.6.3 h1:M/52tsoyTfwaxajLnXZm7PqkbMGRH8iSWP+8fcg9MQ4= +github.com/Microsoft/go-winio v0.6.3/go.mod h1:ma0QpxizD4fyyzJ1C7MIblymTD2Nxz5Mho/3CepwIZg= github.com/Yiling-J/theine-go v0.6.2 h1:1GeoXeQ0O0AUkiwj2S9Jc0Mzx+hpqzmqsJ4kIC4M9AY= github.com/Yiling-J/theine-go v0.6.2/go.mod h1:08QpMa5JZ2pKN+UJCRrCasWYO1IKCdl54Xa836rpmDU= github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= @@ -143,12 +145,12 @@ github.com/docker/cli v29.5.3+incompatible h1:nbEFfz774vBwQ5KRYv7c/AghjReqnGISvr github.com/docker/cli v29.5.3+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8= github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo= -github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= -github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= +github.com/docker/go-connections v0.8.2 h1:9d9DEokx5W7qlr0shkFXIxEA7+TTD+llwzcykSlxMNc= +github.com/docker/go-connections v0.8.2/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= @@ -197,42 +199,42 @@ github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= -github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= -github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= -github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= -github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0= -github.com/go-openapi/swag v0.28.0 h1:xkgbOSKj6DZziNpyqRRAOt3GJGtgjgsd2RoyT30VWuw= -github.com/go-openapi/swag v0.28.0/go.mod h1:4qYnT3Cqr1p1VknOdPo70evN4rgQnAg6jwApHyxSGIg= -github.com/go-openapi/swag/cmdutils v0.28.0 h1:7TOeNtkYru1SG8Y34tDh9WBbLsMqGnptuxWiHREPZ4Q= -github.com/go-openapi/swag/cmdutils v0.28.0/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= -github.com/go-openapi/swag/conv v0.28.0 h1:GtqqbyFe7vR5Y7ehxG9W6/OvrSFdf1OLeTGp40TqxH8= -github.com/go-openapi/swag/conv v0.28.0/go.mod h1:mbUE+mzctnhxi864m0Q07SpN8OowD9JhxmxuYvZZD/k= -github.com/go-openapi/swag/fileutils v0.28.0 h1:Z04XWQD7R8Eq+7GnOrjovBxPPmZzsS4gt2H2GPGIViU= -github.com/go-openapi/swag/fileutils v0.28.0/go.mod h1:VvJFZLTZS0AI854gEQz5tk7dBESdLjiNUMSZ/th2ry8= -github.com/go-openapi/swag/jsonutils v0.28.0 h1:YIch6FwO7RXzeAnbO8Tu7dWBZeUEH+4nA0HXltVTnv4= -github.com/go-openapi/swag/jsonutils v0.28.0/go.mod h1:CYM3WlTUcagR2ZoHdz54di/cbBqt82tuxuXgAjxw+mg= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0 h1:qV+VVUAx5Oro8WjVWpZeql7YReTKhT4smR4zhcOQZr0= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY= -github.com/go-openapi/swag/loading v0.28.0 h1:td8QZdZC9MIYGGSnSPKShKiK22I2tU5UQvuUhIBPRLU= -github.com/go-openapi/swag/loading v0.28.0/go.mod h1:rXB0QiQX5mMveXEA7ouM4KiiM9jVJe4K6BVbwhD1M4k= -github.com/go-openapi/swag/mangling v0.28.0 h1:pH8eyeNO9SLYsTMWJrurnNfKmDa28XrlA+HePVD53VM= -github.com/go-openapi/swag/mangling v0.28.0/go.mod h1:jtBE2+V+3pILxOR7Vgce+Cwp6A2PgZbvVqfNntbVs0w= -github.com/go-openapi/swag/netutils v0.28.0 h1:YXN6TALEi2pzts8/8GNm6T61HTAZsieukGZidap989k= -github.com/go-openapi/swag/netutils v0.28.0/go.mod h1:J+WYyFMLtvtCGqa6jLv+YNUmIKI3ZRQRrvfNDMoQoEQ= -github.com/go-openapi/swag/pools v0.28.0 h1:HPMZWSAfce3rdVTFcjFiCIBtDg9h4x2QlRrHipwhxeU= -github.com/go-openapi/swag/pools v0.28.0/go.mod h1:kVQefhSK5RWuRe7BXsL8htgBPAMpN7HDGpGEknqugeE= -github.com/go-openapi/swag/stringutils v0.28.0 h1:ixsc9iYgDPubHL/8nSkbnryEHpD2VRlBMLKpQyPXcDU= -github.com/go-openapi/swag/stringutils v0.28.0/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM= -github.com/go-openapi/swag/typeutils v0.28.0 h1:nRBKSBXjDgf01VDPB3fWeD9nQuhCOVeIYAkUx2tbkyY= -github.com/go-openapi/swag/typeutils v0.28.0/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ= -github.com/go-openapi/swag/yamlutils v0.28.0 h1:TV3JXH6DS46KUroDtMLAYHGkdWf5VDq3wVWFirmzROY= -github.com/go-openapi/swag/yamlutils v0.28.0/go.mod h1:x0q/yndZHEgk9Rx3DyDqzFUmHy55KTvIZldvF2dTJXs= -github.com/go-openapi/testify/enable/yaml/v2 v2.6.0 h1:gGHwAJ0R/5jU8BEGDbfRNR3hL68dAVi84WuOApp29B0= -github.com/go-openapi/testify/enable/yaml/v2 v2.6.0/go.mod h1:tY+St1SGq4NFl0QIqdTY4aEdbChAHxhyB77XQi9iJCo= -github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug= -github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= -github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw= -github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= +github.com/go-openapi/jsonpointer v1.0.2 h1:NbW7xT2b+l7x+JefiPGDsZWsrLk1ogrz4AHK1TTzMt8= +github.com/go-openapi/jsonpointer v1.0.2/go.mod h1:N0rI4MbNKD7xAFTiHtB+5Nhrg2j/wwYg7m7Fmb4/jk8= +github.com/go-openapi/jsonreference v1.0.3 h1:5rDbq+JsjCv6/nUDDJt83nLZoADI4w03uvHXer+4aYQ= +github.com/go-openapi/jsonreference v1.0.3/go.mod h1:OJSlMXHysgH272D9z2tiy2MGe5A9vQLHaCPb6KbYdE4= +github.com/go-openapi/swag v0.29.2 h1:9n8frkcsuQRA0INU31VbxNxt1zBaHxrHYGEf5BUjFi4= +github.com/go-openapi/swag v0.29.2/go.mod h1:RkCiX1gCVXWgLOavDXE3ALJrQ/VO2ziiIzOUs3z10xo= +github.com/go-openapi/swag/cmdutils v0.29.2 h1:cXEzX/nWCODon251f+1HgL75/R4XXML5IZxgLCWMoro= +github.com/go-openapi/swag/cmdutils v0.29.2/go.mod h1:XziaSVzYqkDvpWXzASfWajw2YvJrLscq610O2XiyqJw= +github.com/go-openapi/swag/conv v0.29.2 h1:8c9shoB8l0QRSR6ymq1llHdBWDqpIgJfjTGHx3Vuhm0= +github.com/go-openapi/swag/conv v0.29.2/go.mod h1:AZS0YigTNf8qNtD6WqJz/N4RUNmpr76SyjFGkq4+p6Q= +github.com/go-openapi/swag/fileutils v0.29.2 h1:mdUL+Vw5ah1fO1AvFCoHeIyv7YZsCz2MN3KNqd/lLVI= +github.com/go-openapi/swag/fileutils v0.29.2/go.mod h1:7QKmmodjAebaq61lGVJa8ldLdGeMF4DSgYv8tXOGGo0= +github.com/go-openapi/swag/jsonutils v0.29.2 h1:uZNSD2/rJDYAfvsLYkykTzXuyxM3QpDKV9jhRHrMu6k= +github.com/go-openapi/swag/jsonutils v0.29.2/go.mod h1:ONTdNvj3Y+IXRzfa17E+Rgt2ns/qiSOYjIo2K7v2yDs= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2 h1:w+Fd6EBOMGlC74GYGHqCLGyb3Bpams8TtNrgM/SG4jo= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2/go.mod h1:HC2egPORFzbj/gf05Zrfgz8Mgplx3oW7hgGi7pjZVhM= +github.com/go-openapi/swag/loading v0.29.2 h1:QU1ry24e6r6Shoxe380Nx0X5iKkpRO+hJffsyJ2dVlY= +github.com/go-openapi/swag/loading v0.29.2/go.mod h1:DqilDjuiJKETecsS4TRopWG1acUDsfqN39ZmQhPu6uI= +github.com/go-openapi/swag/mangling v0.29.2 h1:ltdo3K0tTP4P6zWhVVWDU9D37/YYBuMJRdZxiS2Dtog= +github.com/go-openapi/swag/mangling v0.29.2/go.mod h1:RjDi4TnItAenS3cgCXSpIl1kKbjG7il6pnmQVl/8bp8= +github.com/go-openapi/swag/netutils v0.29.2 h1:dBli6jyUa93sDS/XYWShJzf4+nnVfFKfvY9SLUaUzB8= +github.com/go-openapi/swag/netutils v0.29.2/go.mod h1:1pM6Xg/Um8E1eps3umWl8Hme3ByWXOtHsvFC0CULHUE= +github.com/go-openapi/swag/pools v0.29.2 h1:PlGoDRF8WtSyXkedZZkpW3f9wDhFf3u8KtaBcmgmh8c= +github.com/go-openapi/swag/pools v0.29.2/go.mod h1:V3lhxVT4qDYRqc2MRSSbLsTYIYV/2HlHafhyEkmzLIc= +github.com/go-openapi/swag/stringutils v0.29.2 h1:lcnBxwAaysT3bMUVBfn9V/PkfVqkurpqufKU6rTUMGk= +github.com/go-openapi/swag/stringutils v0.29.2/go.mod h1:i9cdh7sGaa0nm3CqIvH5IM5h2QClk1wns2ktKeILvRI= +github.com/go-openapi/swag/typeutils v0.29.2 h1:O7aVvkTs3pXwikgtrPLenigEMdQFgONKRooQA9pgf2I= +github.com/go-openapi/swag/typeutils v0.29.2/go.mod h1:7+GDG+uz9Ke+eVt4rClZg7wklSDp8hT/mKNh/pC26TE= +github.com/go-openapi/swag/yamlutils v0.29.2 h1:IFKFFeDnuIwzfsuWRQU+rI8iL3g4XyAYjV/RlnlxPLM= +github.com/go-openapi/swag/yamlutils v0.29.2/go.mod h1:7MGqtcrK73sxQ4ceiyIf8qiXS/s09JLMdR5esK5euYQ= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0 h1:wPW6YRgx3+SID1yUy/Xwa17L8kFEaEKod2VRbJDZNUs= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0/go.mod h1:mI1M88etYbc3PhgHsWQK2kwvNwW5aGFqMPbmib+SGIs= +github.com/go-openapi/testify/v2 v2.8.0 h1:19QDx5b57p8KjO2E4sgs/woL4Akp+FGLRlVm2xn0Rho= +github.com/go-openapi/testify/v2 v2.8.0/go.mod h1:4gUN8jC+RqOE2qjW/vDmfyTvl5BCht4qL7oca0odrak= +github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= +github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= @@ -250,8 +252,6 @@ github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/cel-go v0.31.0 h1:H0bhpFTqOvmHrBGrWKp7ZlhBm5Hh8PYUEXnwxT1LL7A= -github.com/google/cel-go v0.31.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8= github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -272,18 +272,18 @@ github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8= -github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= -github.com/googleapis/gax-go/v2 v2.21.0 h1:h45NjjzEO3faG9Lg/cFrBh2PgegVVgzqKzuZl/wMbiI= -github.com/googleapis/gax-go/v2 v2.21.0/go.mod h1:But/NJU6TnZsrLai/xBAQLLz+Hc7fHZJt/hsCz3Fih4= +github.com/googleapis/enterprise-certificate-proxy v0.3.15 h1:xolVQTEXusUcAA5UgtyRLjelpFFHWlPQ4XfWGc7MBas= +github.com/googleapis/enterprise-certificate-proxy v0.3.15/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= +github.com/googleapis/gax-go/v2 v2.22.0 h1:PjIWBpgGIVKGoCXuiCoP64altEJCj3/Ei+kSU5vlZD4= +github.com/googleapis/gax-go/v2 v2.22.0/go.mod h1:irWBbALSr0Sk3qlqb9SyJ1h68WjgeFuiOzI4Rqw5+aY= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI= github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8= -github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 h1:B+8ClL/kCQkRiU82d9xajRPKYMrB7E0MbtzWVi1K4ns= -github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3/go.mod h1:NbCUVmiS4foBGBHOYlCT25+YmGpJ32dZPi75pGEUpj4= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY= +github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.4 h1:9ZJYjPEJpcleIKcqysXOo14NLQYwu23fzmKRFpIjPjc= +github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.4/go.mod h1:0xydIeg2omQ9DH6zYMP24Kk57793rnLUvP8fwdbFvz8= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 h1:5T5Ns3kMpWr+z3s5ZA0e7ljVyWNVNxK76sHPAxi5D1k= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0/go.mod h1:oWNYw09cH8wl8fFgC5hKlBLxR4XfKy2KQpP8MJjeCcc= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48= @@ -294,16 +294,16 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= -github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= -github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= -github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -344,10 +344,10 @@ github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3N github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/go-archive v0.3.0 h1:nos4BtzzUIqB406BgQnWGMI4qib9BZ8XUHU+ucv/n1c= github.com/moby/go-archive v0.3.0/go.mod h1:Npdv43fFqlhZW7Xo8fbm3ZMYFvAGNviUPqX21VERbcE= -github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= -github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= -github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw= -github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM= +github.com/moby/moby/api v1.56.1 h1:PpWkvVPB7Fr/No8w+TfyJ/I6rWZ2YPZhT3JorIg+06c= +github.com/moby/moby/api v1.56.1/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk= +github.com/moby/moby/client v0.6.2 h1:ekSPlMccrZGcw6Scb8T9D39qE0mB+XupU/yS0zNw9N4= +github.com/moby/moby/client v0.6.2/go.mod h1:DGcnO7qmPJrqobx/ggQgQ/AUk+2wgVdQv7uxB0/mEsc= github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= github.com/moby/spdystream v0.5.1 h1:9sNYeYZUcci9R6/w7KDaFWEWeV4LStVG78Mpyq/Zm/Y= @@ -378,8 +378,8 @@ github.com/myzhan/gomq/zmtp v0.0.0-20220926014711-4eea0d4a1e75 h1:yVyx8Vc/WCldQj github.com/myzhan/gomq/zmtp v0.0.0-20220926014711-4eea0d4a1e75/go.mod h1:+nAGtxfeMKPOBqMEAAozdV5x38YsnxJr5WDerNKtznQ= github.com/natefinch/wrap v0.2.0 h1:IXzc/pw5KqxJv55gV0lSOcKHYuEZPGbQrOOXr/bamRk= github.com/natefinch/wrap v0.2.0/go.mod h1:6gMHlAl12DwYEfKP3TkuykYUfLSEAvHw67itm4/KAS8= -github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= -github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/oklog/ulid/v2 v2.1.2 h1:IEclFb9JNvzYA6MW2SCxbLzcHTVsfqm3PrqGQJH5zec= github.com/oklog/ulid/v2 v2.1.2/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 h1:zrbMGy9YXpIeTnGj4EljqMiZsIcE09mmF8XsD5AYOJc= @@ -402,10 +402,10 @@ github.com/opencontainers/runtime-spec v1.3.0 h1:YZupQUdctfhpZy3TM39nN9Ika5CBWT5 github.com/opencontainers/runtime-spec v1.3.0/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/openfga/api/proto v0.0.0-20260319214821-f153694bfc20 h1:xdVG0EDz9Z9Uhd7YZ5OMN1F8tkAz/Dpgdjxd0cuTBJo= github.com/openfga/api/proto v0.0.0-20260319214821-f153694bfc20/go.mod h1:XDX4qYNBUM2Rsa2AbKPh+oocZc2zgme+EF2fFC6amVU= -github.com/openfga/language/pkg/go v0.3.2-0.20260730144454-83fedf8a4e70 h1:9RtXJ5iSKUnIFB+OduCFEY+TEDqpOKOJRZcD8LZB7Ng= -github.com/openfga/language/pkg/go v0.3.2-0.20260730144454-83fedf8a4e70/go.mod h1:HJr87kSwUb6NLfspULfl8IoQk6BcXjR+EvzyTnyp7II= -github.com/openfga/openfga v1.20.0 h1:5dly6ON46VgH8xA1/tn2lNuJzxol0f7TGAwiDzIS6YA= -github.com/openfga/openfga v1.20.0/go.mod h1:Rq7ij090J1lZRn322Ttc/b11ZaN/0ogph+rPAP0SNAE= +github.com/openfga/language/pkg/go v0.3.2 h1:QN/cBYzL50RzEh46e+7ILvFeBs0exge7Sia0B6uXjms= +github.com/openfga/language/pkg/go v0.3.2/go.mod h1:Ia3Luc0WcZdLogjjnFFKbce8+427wwlDaUG3dREZVCY= +github.com/openfga/openfga v1.23.0 h1:qYx1FfQ6ZZZzYX89HLW73G+jgcCf5jXgYdM4OTIW/+Y= +github.com/openfga/openfga v1.23.0/go.mod h1:0a7wx2Zy4ZQ/bH4oTKrEogGrtxTleGhKj5La0NIwI4M= github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= github.com/pelletier/go-toml/v2 v2.4.0 h1:Mwu0mAkUKbittDs3/ADDWXqMmq3EOK2VHiuCkV00Row= @@ -420,19 +420,19 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= -github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA= -github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY= -github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= -github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= +github.com/pressly/goose/v3 v3.29.0 h1:dtEnBCT7CqkHIUCdgrXsrmeisaN8gFkRU4Y5OEwif4o= +github.com/pressly/goose/v3 v3.29.0/go.mod h1:plA4aP4+u+Q3FMTgbFbhF8TuAWpAdfWpoFGkJsIFWh0= +github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= +github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= -github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= -github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= +github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= +github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= +github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4= +github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk= github.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos= github.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM= -github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= -github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= +github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics= +github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= @@ -444,15 +444,15 @@ github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFT github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk= github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= -github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw= -github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= +github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= +github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs= github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= -github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo= +github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= @@ -466,8 +466,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= -github.com/spiffe/go-spiffe/v2 v2.7.0 h1:uXe1MflJoHw58wAUvxVlcM7WpKtijWG7I1UidcGh6g4= -github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= +github.com/spiffe/go-spiffe/v2 v2.8.1 h1:eXZMLsu+3MLEPJyGJkolqtVrteZfQdUpOWj6LTiDl/E= +github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= @@ -514,42 +514,42 @@ go.opentelemetry.io/contrib/bridges/prometheus v0.68.0 h1:w3zlHYETbDwXyWHZlyyR58 go.opentelemetry.io/contrib/bridges/prometheus v0.68.0/go.mod h1:GR/mClR2nn7vE8RLwxKjoBNg+QtgdDhRzxVa93koy5o= go.opentelemetry.io/contrib/detectors/gcp v1.44.0 h1:NmLfL734pJhM0JKaYd2Y28+nY9dPRWYAAbxhRCrKXPw= go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0 h1:oECp5f+hN7nkwjU/8BxQ/q23bGPb8FIrD839owX222E= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0/go.mod h1:DqEFwLumhzMBDQv9PcWbyoDxHI/4lAk6CM4nJBH39sc= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 h1:Tq+E65HaNbZTeqcLw6QUhsV+/EIWdkfUH2CQzcrlE5M= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0/go.mod h1:A+EVhDakAj1waJBPhmTszZaSr08ww8MRRKy1nB1rqck= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0 h1:WseeVYf5dJZTsyPiyW5L14k5qsSibqXAMTSiFEDiWr0= go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0/go.mod h1:SiLZnQS6Qk2eCpvr2CH/XMAOa64TWGXxEZJZCpD2Lmc= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0 h1:8UQVDcZxOJLtX6gxtDt3vY2WTgvZqMQRzjsqiIHQdkc= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0/go.mod h1:2lmweYCiHYpEjQ/lSJBYhj9jP1zvCvQW4BqL9dnT7FQ= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 h1:UFpxOpYPmMNUtOWhdb+nC1WELIgVf8z9higURrbzYU4= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0/go.mod h1:YBGjxe3lt0jtXoEXxGrGhv/jM7oUBUDVK7zhAvNyEjc= go.opentelemetry.io/otel/exporters/prometheus v0.65.0 h1:jOveH/b4lU9HT7y+Gfamf18BqlOuz2PWEvs8yM7Q6XE= go.opentelemetry.io/otel/exporters/prometheus v0.65.0/go.mod h1:i1P8pcumauPtUI4YNopea1dhzEMuEqWP1xoUZDylLHo= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.43.0 h1:TC+BewnDpeiAmcscXbGMfxkO+mwYUwE/VySwvw88PfA= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.43.0/go.mod h1:J/ZyF4vfPwsSr9xJSPyQ4LqtcTPULFR64KwTikGLe+A= -go.opentelemetry.io/otel/log v0.21.0 h1:SLsVDGmtyBrdw8/a2Z0bOIxou/+bN4z56GebH7T0LvA= -go.opentelemetry.io/otel/log v0.21.0/go.mod h1:iReetQrZL9Wyg84cCkOoCmqDHS5RCFfyxC7J+r8fn8g= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/metric/x v0.67.0 h1:PcicCNZFkZ4bXfSooXdo3WN7RBOVOtjVdo1wD358Uns= -go.opentelemetry.io/otel/metric/x v0.67.0/go.mod h1:FBjCWZe6wgcqxcMtjdGiClDKXb2YxxXii0CXftE4QtI= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM= +go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= go.opentelemetry.io/otel/sdk/log v0.21.0 h1:QsE7XSR0ktQdKmRKGnR+f1ObGF32WG+7MER/P9KgmYc= go.opentelemetry.io/otel/sdk/log v0.21.0/go.mod h1:m9mApjCoD2/1QuKCAptjv+BrG9WKOvQLVdNx+iBldTo= go.opentelemetry.io/otel/sdk/log/logtest v0.21.0 h1:X+JBBgKlswCGYsmgL0CnoUUtlE//VB345c84jYAYkdQ= go.opentelemetry.io/otel/sdk/log/logtest v0.21.0/go.mod h1:HD1575K8e6sIFBBDd5tZB3t9DlMytWXq9FuR+Y4rfjE= -go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= -go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= -go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= -go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= +go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= +go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= +go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw= +go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -570,19 +570,19 @@ go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20260718201538-764159d718ef h1:LkZ48HFgy/TvhTI0bcWkjgFkgLyKUwcTbDjS0DUjw+A= -golang.org/x/exp v0.0.0-20260718201538-764159d718ef/go.mod h1:EdfpwwqSu+0Li0mzskwHU6FWDV3t9Q+RZDo3QMUtL3Q= +golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A= +golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e/go.mod h1:DBoxwWhjaW8DJJw/YeM4zpeOKMC1FMXSblsYy+1mFSw= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -591,18 +591,18 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= -golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= +golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -610,19 +610,18 @@ golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -634,8 +633,8 @@ golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -644,8 +643,8 @@ gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/api v0.274.0 h1:aYhycS5QQCwxHLwfEHRRLf9yNsfvp1JadKKWBE54RFA= -google.golang.org/api v0.274.0/go.mod h1:JbAt7mF+XVmWu6xNP8/+CTiGH30ofmCmk9nM8d8fHew= +google.golang.org/api v0.278.0 h1:W7jiRvRi53VYFfZ/HoZjQBtJk7gOFbHD8ot1RzVZU6E= +google.golang.org/api v0.278.0/go.mod h1:B9TqLBwJqVjp1mtt7WeoQwWRwvu/400y5lETOql+giQ= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= @@ -653,17 +652,17 @@ google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0= google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e h1:e789sLZjeTdc02ZCQGTSzHOu0fR73+dwPQVKUp67Z88= +google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e/go.mod h1:vHV3wJM9WZyfV7GyB+OQGq5dWVrFwCDxapPK4WlRD88= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b h1:6WNWHZk91dp4gZ25642OALkuG1UVNZbwENJD19DnB8k= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= -google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= +google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0= +google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -686,8 +685,8 @@ honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= k8s.io/api v0.37.0 h1:Z//Vj9N7RA/yS2sDmxyeo7h+RR4zbUrd2vrd3Z0TbB4= k8s.io/api v0.37.0/go.mod h1:LKXgcJWMc+f4OLbP5SFR8rulEg07zZhpi/zMULiBImk= -k8s.io/apiextensions-apiserver v0.36.1 h1:6JfYmPUsuUIHuN+3QxutXYWj492RqF5fBSx67GYK5Ks= -k8s.io/apiextensions-apiserver v0.36.1/go.mod h1:pLzZin90riwisdzKwv/GoTwENooytoIx5zWJb4Hkby8= +k8s.io/apiextensions-apiserver v0.37.0 h1:zRMQ3+/LIE5oZ0tVvXwYHC+dIkSP5cjNWju7AZU1LOI= +k8s.io/apiextensions-apiserver v0.37.0/go.mod h1:HU0PfSBwchHL5iDau6jjt9zU6ryWkDDlaVUiq91NK80= k8s.io/apimachinery v0.36.0-alpha.2.0.20260904094813-f8600edbddc8 h1:DM+nt+gJGNT2flQOkxKzrPCNuwOqwxcfSCHBUnvmweY= k8s.io/apimachinery v0.36.0-alpha.2.0.20260904094813-f8600edbddc8/go.mod h1:1Um7tr4O65Pd822NFLn+MI08uCzUIPahh2lCPsWzNgk= k8s.io/client-go v0.37.0 h1:nsN31fy8wBySuZ+QRnKmrjRSQLOG2rvoGN0tKd12zhQ= @@ -706,18 +705,18 @@ k8s.io/streaming v0.37.0 h1:iPBUZLZiKt5bV+lxJurASMOV07VuBhNpiwJt2//AWrM= k8s.io/streaming v0.37.0/go.mod h1:APlJR26ZWRcVy5bIEj0QRrKUXROtBHPcxl2NT7EAzPU= k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= -modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k= -modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co= +modernc.org/libc v1.79.0 h1:9Dvvv++bAMSkSuBzuOFAatbTV5OIoq6Y6FohmD3e7q8= +modernc.org/libc v1.79.0/go.mod h1:uT3kR61NsbeKJSLqq83GJwSnZMVLlSjyAz4DfTaBy1M= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= -modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= -modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= -modernc.org/sqlite v1.57.0 h1:qNQP6xnx5M0ISNtlnxoOX0+cD5bJ0/gr9aMmndFczzg= -modernc.org/sqlite v1.57.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/sqlite v1.61.0 h1:sQi63oLQ9uquAUA4CzOisH35Q3pEszkPBuHM0tFL8CY= +modernc.org/sqlite v1.61.0/go.mod h1:f4gr5tbpx2umklaT/QVtbi/50hNdM+4ng+2zMo8KXJ0= pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk= pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= -sigs.k8s.io/controller-runtime v0.24.1 h1:miPEwrmirImAvgME1L9qebGHrOnGJoVmVdtOU9fRfo4= -sigs.k8s.io/controller-runtime v0.24.1/go.mod h1:vFkfY5fGt5xAC/sKb8IBFKgWPNKG9OUG29dR8Y2wImw= +sigs.k8s.io/controller-runtime v0.25.2 h1:bEkK3PVOIVK9X8QWLGVhJgmFc++47vfT6wakSzAOLsQ= +sigs.k8s.io/controller-runtime v0.25.2/go.mod h1:4QqLdT6z/L6Olj8JJCtvztid4/fnIiYsfaTFScegctc= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= sigs.k8s.io/kustomize/api v0.21.1 h1:lzqbzvz2CSvsjIUZUBNFKtIMsEw7hVLJp0JeSIVmuJs= diff --git a/vendor/github.com/google/cel-go/LICENSE b/vendor/cel.dev/cel-go/LICENSE similarity index 100% rename from vendor/github.com/google/cel-go/LICENSE rename to vendor/cel.dev/cel-go/LICENSE diff --git a/vendor/github.com/google/cel-go/cel/BUILD.bazel b/vendor/cel.dev/cel-go/cel/BUILD.bazel similarity index 92% rename from vendor/github.com/google/cel-go/cel/BUILD.bazel rename to vendor/cel.dev/cel-go/cel/BUILD.bazel index 62a56036a0..b8eae36c3b 100644 --- a/vendor/github.com/google/cel-go/cel/BUILD.bazel +++ b/vendor/cel.dev/cel-go/cel/BUILD.bazel @@ -15,6 +15,7 @@ go_library( "inlining.go", "io.go", "library.go", + "timestamp_legacy.go", "macro.go", "optimizer.go", "options.go", @@ -23,7 +24,7 @@ go_library( "validator.go", ], embedsrcs = ["templates/authoring.tmpl"], - importpath = "github.com/google/cel-go/cel", + importpath = "cel.dev/cel-go/cel", visibility = ["//visibility:public"], deps = [ "//cel/async:go_default_library", @@ -32,6 +33,7 @@ go_library( "//common:go_default_library", "//common/ast:go_default_library", "//common/containers:go_default_library", + "//common/cost:go_default_library", "//common/decls:go_default_library", "//common/env:go_default_library", "//common/functions:go_default_library", @@ -62,14 +64,20 @@ go_library( go_test( name = "go_default_test", srcs = [ + "cel_adapter_test.go", "cel_example_test.go", "cel_test.go", + "timestamp_legacy_test.go", + "cost_test.go", + "cost_k8s_test.go", "decls_test.go", + "env_ext_test.go", "env_test.go", "fieldpaths_test.go", "folding_test.go", "inlining_test.go", "io_test.go", + "memory_test.go", "optimizer_test.go", "program_async_test.go", "prompt_test.go", @@ -87,6 +95,7 @@ go_test( ], deps = [ "//cel/async:go_default_library", + "//common/cost:go_default_library", "//common/operators:go_default_library", "//common/overloads:go_default_library", "//common/types:go_default_library", diff --git a/vendor/github.com/google/cel-go/cel/async/BUILD.bazel b/vendor/cel.dev/cel-go/cel/async/BUILD.bazel similarity index 93% rename from vendor/github.com/google/cel-go/cel/async/BUILD.bazel rename to vendor/cel.dev/cel-go/cel/async/BUILD.bazel index 85b28bcdb5..e77dfaec50 100644 --- a/vendor/github.com/google/cel-go/cel/async/BUILD.bazel +++ b/vendor/cel.dev/cel-go/cel/async/BUILD.bazel @@ -9,7 +9,7 @@ go_library( srcs = [ "async.go", ], - importpath = "github.com/google/cel-go/cel/async", + importpath = "cel.dev/cel-go/cel/async", visibility = ["//visibility:public"], deps = [ "//common/decls:go_default_library", diff --git a/vendor/github.com/google/cel-go/cel/async/async.go b/vendor/cel.dev/cel-go/cel/async/async.go similarity index 97% rename from vendor/github.com/google/cel-go/cel/async/async.go rename to vendor/cel.dev/cel-go/cel/async/async.go index a011114bdc..b8621a784d 100644 --- a/vendor/github.com/google/cel-go/cel/async/async.go +++ b/vendor/cel.dev/cel-go/cel/async/async.go @@ -21,11 +21,11 @@ import ( "errors" "time" - "github.com/google/cel-go/common/decls" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/interpreter" + "cel.dev/cel-go/common/decls" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/interpreter" ) // Call describes a pending or completed asynchronous function call. diff --git a/vendor/github.com/google/cel-go/cel/cel.go b/vendor/cel.dev/cel-go/cel/cel.go similarity index 100% rename from vendor/github.com/google/cel-go/cel/cel.go rename to vendor/cel.dev/cel-go/cel/cel.go diff --git a/vendor/github.com/google/cel-go/cel/decls.go b/vendor/cel.dev/cel-go/cel/decls.go similarity index 98% rename from vendor/github.com/google/cel-go/cel/decls.go rename to vendor/cel.dev/cel-go/cel/decls.go index 53941146dc..8a01116c7b 100644 --- a/vendor/github.com/google/cel-go/cel/decls.go +++ b/vendor/cel.dev/cel-go/cel/decls.go @@ -17,11 +17,11 @@ package cel import ( "fmt" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/decls" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/decls" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" celpb "cel.dev/expr" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" @@ -346,6 +346,9 @@ func FunctionBinding(binding functions.FunctionOp) OverloadOpt { // LateFunctionBinding indicates that the function has a binding which is not known at compile time. // This is useful for functions which have side-effects or are not deterministically computable. +// +// The implementation is supplied at evaluation time as a LateBoundFunction within an activation +// created by FunctionVars, and is subject to the same runtime type-guard as an eager binding. func LateFunctionBinding() OverloadOpt { return decls.LateFunctionBinding() } diff --git a/vendor/github.com/google/cel-go/cel/env.go b/vendor/cel.dev/cel-go/cel/env.go similarity index 89% rename from vendor/github.com/google/cel-go/cel/env.go rename to vendor/cel.dev/cel-go/cel/env.go index 794c62f781..9853a9a925 100644 --- a/vendor/github.com/google/cel-go/cel/env.go +++ b/vendor/cel.dev/cel-go/cel/env.go @@ -23,19 +23,20 @@ import ( "strings" "sync" - "github.com/google/cel-go/checker" - chkdecls "github.com/google/cel-go/checker/decls" - "github.com/google/cel-go/common" - celast "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/containers" - "github.com/google/cel-go/common/decls" - "github.com/google/cel-go/common/env" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/stdlib" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/interpreter" - "github.com/google/cel-go/parser" + "cel.dev/cel-go/checker" + chkdecls "cel.dev/cel-go/checker/decls" + "cel.dev/cel-go/common" + celast "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/containers" + "cel.dev/cel-go/common/cost" + "cel.dev/cel-go/common/decls" + "cel.dev/cel-go/common/env" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/stdlib" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/interpreter" + "cel.dev/cel-go/parser" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" "google.golang.org/protobuf/reflect/protoreflect" @@ -149,7 +150,9 @@ type Env struct { limits map[limitID]int libraries map[string]SingletonLibrary validators []ASTValidator - costOptions []checker.CostOption + costOptions []cost.Option + costConfig *costConfig + costModel costModelOptions // Flags for copy-on-write behavior with env.Extend. funcsShared bool @@ -185,6 +188,60 @@ type Env struct { progOpts []ProgramOption } +// costConfig accumulates the cost options while the environment is configured. Env.configure +// builds the environment's costModelOptions from it once the options have run; it is kept only so +// that Env.Extend can configure a copy. +type costConfig struct { + strategy cost.SizingStrategy + models []cost.OverloadModel + + // version pins the cost model revision used for estimation and tracking. + // + // A pointer rather than a value because version 0 is a meaningful pin, so the + // nil case is the only way to express "caller did not ask for a revision". + version *uint32 +} + +func (c *costConfig) copy() *costConfig { + return &costConfig{ + strategy: c.strategy, + models: slices.Clone(c.models), + version: c.version, + } +} + +// build derives the estimation and tracking options. A cost.ModelOption serves both, so the two +// lists hold the same options. +func (c *costConfig) build() costModelOptions { + var opts []cost.ModelOption + if len(c.models) > 0 { + opts = append(opts, cost.Model(c.models...)) + } + if c.strategy != nil { + opts = append(opts, cost.WithSizingStrategy(c.strategy)) + } + if c.version != nil { + opts = append(opts, cost.ModelVersion(*c.version)) + } + built := costModelOptions{ + estimate: make([]cost.Option, len(opts)), + tracker: make([]cost.TrackerOption, len(opts)), + } + for i, opt := range opts { + built.estimate[i] = opt + built.tracker[i] = opt + } + return built +} + +// costModelOptions are the options which apply the environment's cost models, sizing strategy, and +// revision to estimation and tracking. They precede the caller's options so the caller may +// override them. +type costModelOptions struct { + estimate []cost.Option + tracker []cost.TrackerOption +} + // ToConfig produces a YAML-serializable env.Config object from the given environment. // // The serialized configuration value is intended to represent a baseline set of config @@ -220,8 +277,14 @@ func (e *Env) ToConfig(name string) (*env.Config, error) { // Track the options which have been configured by a library and // then diff the library version against the configured function // to detect incremental overloads or rewrites. - libEnv, _ := NewCustomEnv() - libEnv, _ = Lib(lib)(libEnv) + libEnv, err := NewCustomEnv() + if err != nil { + return nil, err + } + libEnv, err = Lib(lib)(libEnv) + if err != nil { + return nil, err + } for fnName, fnDecl := range libEnv.Functions() { if len(fnDecl.OverloadDecls()) == 0 { continue @@ -399,7 +462,8 @@ func NewCustomEnv(opts ...EnvOption) (*Env, error) { libraries: map[string]SingletonLibrary{}, validators: []ASTValidator{}, progOpts: []ProgramOption{}, - costOptions: []checker.CostOption{}, + costOptions: []cost.Option{}, + costConfig: &costConfig{}, }).configure(opts) } @@ -589,6 +653,7 @@ func (e *Env) Extend(opts ...EnvOption) (*Env, error) { chkOpts: chkOptsCopy, prsrOpts: prsrOptsCopy, costOptions: costOptsCopy, + costConfig: e.costConfig.copy(), // Copy-on-write flags. funcsShared: true, featuresShared: true, @@ -855,6 +920,12 @@ func (e *Env) PartialVars(vars any) (PartialActivation, error) { // // See the PartialVars helper for how to construct a PartialActivation. // +// Note: if the original Ast contains a comprehension macro (e.g. all, exists, exists_one, +// filter, map) whose range or predicate cannot be fully resolved by partial evaluation, the +// Env must have been created with the EnableMacroCallTracking() option. Without it, this method +// returns an error when it cannot re-serialize the unresolved comprehension's expanded internal +// representation back into CEL source syntax. +// // TODO: Consider adding an option to generate a Program.Residual to avoid round-tripping to an // Ast format and then Program again. func (e *Env) ResidualAst(a *Ast, details *EvalDetails) (*Ast, error) { @@ -881,11 +952,13 @@ func (e *Env) ResidualAst(a *Ast, details *EvalDetails) (*Ast, error) { // EstimateCost estimates the cost of a type checked CEL expression using the length estimates of input data and // extension functions provided by estimator. -func (e *Env) EstimateCost(ast *Ast, estimator checker.CostEstimator, opts ...checker.CostOption) (checker.CostEstimate, error) { - extendedOpts := make([]checker.CostOption, 0, len(e.costOptions)) - extendedOpts = append(extendedOpts, opts...) +func (e *Env) EstimateCost(ast *Ast, estimator cost.Estimator, opts ...cost.CostOption) (cost.CostEstimate, error) { + modelOpts := e.costModel.estimate + extendedOpts := make([]cost.Option, 0, len(modelOpts)+len(e.costOptions)+len(opts)) + extendedOpts = append(extendedOpts, modelOpts...) extendedOpts = append(extendedOpts, e.costOptions...) - return checker.Cost(ast.NativeRep(), estimator, extendedOpts...) + extendedOpts = append(extendedOpts, opts...) + return cost.Cost(ast.NativeRep(), estimator, extendedOpts...) } // configure applies a series of EnvOptions to the current environment. @@ -912,6 +985,22 @@ func (e *Env) configure(opts []EnvOption) (*Env, error) { } } + // If strict timestamp parsing has been disabled, configure the legacy parsing overloads. This + // is applied after the legacy timezone overloads so that the relaxed offset parsing takes + // precedence when both features are disabled. + if strict, isSet := e.features[featureStrictTimestampParsing]; isSet && !strict { + if !e.appliedFeatures[featureStrictTimestampParsing] { + e.ensureMutableAppliedFeatures() + e.appliedFeatures[featureStrictTimestampParsing] = true + e, err = Lib(timestampLegacyParsingLibrary{})(e) + if err != nil { + return nil, err + } + } + } + + e.costModel = e.costConfig.build() + // Configure the parser. prsrOpts := []parser.Option{} prsrOpts = append(prsrOpts, e.prsrOpts...) @@ -976,6 +1065,39 @@ func (e *Env) initChecker() (*checker.Env, error) { chkOpts = append(chkOpts, checker.JSONFieldNames(e.HasFeature(featureJSONFieldNames))) + chkOpts = append(chkOpts, checker.Catalog(func() *env.Catalog { + conf, err := e.ToConfig("") + if err != nil { + return env.NewCatalog() + } + cat := conf.ToCatalog() + for _, f := range e.functions { + cat.Add(&env.CatalogSymbol{ + Name: f.Name(), + Kind: env.FunctionKind, + }) + } + for _, t := range stdlib.Types() { + cat.Add(&env.CatalogSymbol{ + Name: t.Name(), + Kind: env.TypeKind, + }) + } + for _, m := range e.macros { + cat.Add(&env.CatalogSymbol{ + Name: m.Function(), + Kind: env.MacroKind, + }) + } + // TODO: Come up with a better mechanism to dynamically populate catalog symbols + // for un-enabled libraries (e.g. leaning on the introspection and serialization + // properties used by ToConfig). + if !e.HasLibrary("cel.lib.optional") { + cat.Add((&optionalLib{}).CatalogSymbols()...) + } + return cat + })) + if e.parent != nil && e.funcsShared { parentChk, err := e.parent.initChecker() if err != nil { diff --git a/vendor/github.com/google/cel-go/cel/fieldpaths.go b/vendor/cel.dev/cel-go/cel/fieldpaths.go similarity index 98% rename from vendor/github.com/google/cel-go/cel/fieldpaths.go rename to vendor/cel.dev/cel-go/cel/fieldpaths.go index 570fce3a46..b63c2ba2ac 100644 --- a/vendor/github.com/google/cel-go/cel/fieldpaths.go +++ b/vendor/cel.dev/cel-go/cel/fieldpaths.go @@ -4,8 +4,8 @@ import ( "slices" "strings" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/types" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/types" ) // fieldPath represents a selection path to a field from a variable in a CEL environment. diff --git a/vendor/github.com/google/cel-go/cel/folding.go b/vendor/cel.dev/cel-go/cel/folding.go similarity index 87% rename from vendor/github.com/google/cel-go/cel/folding.go rename to vendor/cel.dev/cel-go/cel/folding.go index e3459034cc..494f38dac1 100644 --- a/vendor/github.com/google/cel-go/cel/folding.go +++ b/vendor/cel.dev/cel-go/cel/folding.go @@ -19,12 +19,12 @@ import ( "errors" "fmt" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" ) // ConstantFoldingOption defines a functional option for configuring constant folding. @@ -98,8 +98,8 @@ func (opt *constantFoldingOptimizer) Optimize(ctx *OptimizerContext, a *ast.AST) if fold.Kind() == ast.CallKind && maybePruneBranches(ctx, a, fold) { continue } - // Late-bound function calls cannot be folded. - if fold.Kind() == ast.CallKind && isLateBoundFunctionCall(ctx, fold) { + // Async and late-bound function calls cannot be folded. + if fold.Kind() == ast.CallKind && (isLateBoundFunctionCall(ctx, fold) || isAsyncFunctionCall(ctx, fold)) { continue } // Otherwise, assume all context is needed to evaluate the expression. @@ -162,6 +162,7 @@ func (opt *constantFoldingOptimizer) tryFold(ctx *OptimizerContext, a *ast.AST, } // Update the fold expression to be a literal. ctx.UpdateExpr(expr, ctx.NewLiteral(out)) + delete(a.ReferenceMap(), expr.ID()) return nil } @@ -177,7 +178,7 @@ func evaluateExpr(ctx *OptimizerContext, a *ast.AST, navigableExpr ast.Navigable if err != nil { return nil, errCannotFold } - // Folding will not attempt to call async functions which are all marked as late-bound, + // Folding will not attempt to call async functions, // but the presence of such functions requires the use of `ConcurrentEval` in order to // avoid an early return error which blocks async functions from running in `Eval` and // `ContextEval` call paths. @@ -198,6 +199,15 @@ func isLateBoundFunctionCall(ctx *OptimizerContext, expr ast.Expr) bool { return function.HasLateBinding() } +func isAsyncFunctionCall(ctx *OptimizerContext, expr ast.Expr) bool { + call := expr.AsCall() + function := ctx.Functions()[call.FunctionName()] + if function == nil { + return false + } + return function.IsAsync() +} + // maybePruneBranches inspects the non-strict call expression to determine whether // a branch can be removed. Evaluation will naturally prune logical and / or calls, // but conditional will not be pruned cleanly, so this is one small area where the @@ -217,32 +227,23 @@ func maybePruneBranches(ctx *OptimizerContext, a *ast.AST, expr ast.NavigableExp } if cond.AsLiteral() == types.True { ctx.UpdateExpr(expr, truthy) + updateMetadata(a, expr.ID(), truthy.ID()) } else { ctx.UpdateExpr(expr, falsy) + updateMetadata(a, expr.ID(), falsy.ID()) } return true case operators.In: haystack := args[1] - if haystack.Kind() == ast.ListKind && haystack.AsList().Size() == 0 { + if isCollectionEmpty(haystack) { ctx.UpdateExpr(expr, ctx.NewLiteral(types.False)) + delete(a.ReferenceMap(), expr.ID()) return true } - needle := args[0] - if (needle.Kind() == ast.LiteralKind || isSelfEqualIdent(needle)) && haystack.Kind() == ast.ListKind { - needleIsLit := needle.Kind() == ast.LiteralKind - needleLitVal := needle.AsLiteral() - needleIdentVal := needle.AsIdent() - list := haystack.AsList() - for _, elem := range list.Elements() { - if needleIsLit && elem.Kind() == ast.LiteralKind && elem.AsLiteral().Equal(needleLitVal) == types.True { - ctx.UpdateExpr(expr, ctx.NewLiteral(types.True)) - return true - } - if !needleIsLit && elem.Kind() == ast.IdentKind && elem.AsIdent() == needleIdentVal { - ctx.UpdateExpr(expr, ctx.NewLiteral(types.True)) - return true - } - } + if collectionContainsNeedle(args[0], haystack) { + ctx.UpdateExpr(expr, ctx.NewLiteral(types.True)) + delete(a.ReferenceMap(), expr.ID()) + return true } case operators.Add: if len(args) == 2 && args[0].Kind() == ast.ListKind && args[1].Kind() == ast.ListKind { @@ -262,6 +263,7 @@ func maybePruneBranches(ctx *OptimizerContext, a *ast.AST, expr ast.NavigableExp combinedList := ctx.NewList(elems, optIndices) ctx.UpdateExpr(expr, combinedList) + delete(a.ReferenceMap(), expr.ID()) return true } } @@ -286,6 +288,7 @@ func maybeShortcircuitLogic(ctx *OptimizerContext, a *ast.AST, function string, } if arg.AsLiteral() == shortcircuit { ctx.UpdateExpr(expr, arg) + updateMetadata(a, expr.ID(), arg.ID()) return true } } @@ -300,12 +303,27 @@ func maybeShortcircuitLogic(ctx *OptimizerContext, a *ast.AST, function string, return false } ctx.UpdateExpr(expr, newArgs[0]) + updateMetadata(a, expr.ID(), newArgs[0].ID()) return true } ctx.UpdateExpr(expr, ctx.NewCall(function, newArgs...)) return true } +func updateMetadata(a *ast.AST, targetID, updatedID int64) { + if a == nil { + return + } + if ref, found := a.ReferenceMap()[updatedID]; found { + a.ReferenceMap()[targetID] = ref + } else { + delete(a.ReferenceMap(), targetID) + } + if t, found := a.TypeMap()[updatedID]; found { + a.TypeMap()[targetID] = t + } +} + func isBoolType(a *ast.AST, e ast.Expr) bool { if a != nil && a.GetType(e.ID()) == types.BoolType { return true @@ -581,8 +599,8 @@ func (opt *constantFoldingOptimizer) constantExprMatcher(ctx *OptimizerContext, if e.Kind() == ast.IdentKind && !vars[e.AsIdent()] { constantExprs = false } - // Late-bound function calls cannot be folded. - if e.Kind() == ast.CallKind && isLateBoundFunctionCall(ctx, e) { + // Async and late-bound function calls cannot be folded. + if e.Kind() == ast.CallKind && (isLateBoundFunctionCall(ctx, e) || isAsyncFunctionCall(ctx, e)) { constantExprs = false } }) @@ -631,24 +649,9 @@ func constantCallMatcher(e ast.NavigableExpr) bool { return false } haystack := children[1] - if haystack.Kind() == ast.ListKind && haystack.AsList().Size() == 0 { + if isCollectionEmpty(haystack) || collectionContainsNeedle(children[0], haystack) { return true } - needle := children[0] - if (needle.Kind() == ast.LiteralKind || isSelfEqualIdent(needle)) && haystack.Kind() == ast.ListKind { - needleIsLit := needle.Kind() == ast.LiteralKind - needleLitVal := needle.AsLiteral() - needleIdentVal := needle.AsIdent() - list := haystack.AsList() - for _, elem := range list.Elements() { - if needleIsLit && elem.Kind() == ast.LiteralKind && elem.AsLiteral().Equal(needleLitVal) == types.True { - return true - } - if !needleIsLit && elem.Kind() == ast.IdentKind && elem.AsIdent() == needleIdentVal { - return true - } - } - } } if fnName == operators.Add { if len(children) == 2 && children[0].Kind() == ast.ListKind && children[1].Kind() == ast.ListKind { @@ -664,6 +667,70 @@ func constantCallMatcher(e ast.NavigableExpr) bool { return true } +func isCollectionEmpty(e ast.Expr) bool { + switch e.Kind() { + case ast.ListKind: + return e.AsList().Size() == 0 + case ast.MapKind: + return e.AsMap().Size() == 0 + default: + return false + } +} + +func exprEqualsNeedle(needle, target ast.Expr) bool { + if needle.Kind() == ast.LiteralKind && target.Kind() == ast.LiteralKind { + return target.AsLiteral().Equal(needle.AsLiteral()) == types.True + } + if needle.Kind() == ast.IdentKind && target.Kind() == ast.IdentKind { + return target.AsIdent() == needle.AsIdent() + } + return false +} + +func collectionContainsNeedle(needle, haystack ast.Expr) bool { + if needle.Kind() != ast.LiteralKind && !isSelfEqualIdent(needle) { + return false + } + switch haystack.Kind() { + case ast.ListKind: + list := haystack.AsList() + for i, elem := range list.Elements() { + if list.IsOptional(int32(i)) { + if needle.Kind() == ast.LiteralKind && elem.Kind() == ast.LiteralKind { + if opt, ok := elem.AsLiteral().(*types.Optional); ok && opt.HasValue() { + if opt.GetValue().Equal(needle.AsLiteral()) == types.True { + return true + } + } + } + continue + } + if exprEqualsNeedle(needle, elem) { + return true + } + } + case ast.MapKind: + for _, entryExpr := range haystack.AsMap().Entries() { + entry := entryExpr.AsMapEntry() + if entry.IsOptional() { + if val := entry.Value(); val.Kind() == ast.LiteralKind { + if opt, ok := val.AsLiteral().(*types.Optional); ok && opt.HasValue() { + if exprEqualsNeedle(needle, entry.Key()) { + return true + } + } + } + continue + } + if exprEqualsNeedle(needle, entry.Key()) { + return true + } + } + } + return false +} + // isSelfEqualIdent indicates whether the expression is an identifier whose static type // guarantees that its runtime value is equal to itself. // diff --git a/vendor/github.com/google/cel-go/cel/inlining.go b/vendor/cel.dev/cel-go/cel/inlining.go similarity index 97% rename from vendor/github.com/google/cel-go/cel/inlining.go rename to vendor/cel.dev/cel-go/cel/inlining.go index d9a5e89a5f..3ade2204d0 100644 --- a/vendor/github.com/google/cel-go/cel/inlining.go +++ b/vendor/cel.dev/cel-go/cel/inlining.go @@ -15,12 +15,12 @@ package cel import ( - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/containers" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/containers" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/traits" ) // InlineVariable holds a variable name to be matched and an AST representing diff --git a/vendor/github.com/google/cel-go/cel/io.go b/vendor/cel.dev/cel-go/cel/io.go similarity index 90% rename from vendor/github.com/google/cel-go/cel/io.go rename to vendor/cel.dev/cel-go/cel/io.go index c991c95c3f..3af85c59a6 100644 --- a/vendor/github.com/google/cel-go/cel/io.go +++ b/vendor/cel.dev/cel-go/cel/io.go @@ -21,12 +21,12 @@ import ( "google.golang.org/protobuf/proto" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" - "github.com/google/cel-go/parser" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" + "cel.dev/cel-go/parser" celpb "cel.dev/expr" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" @@ -118,18 +118,42 @@ func AstToParsedExpr(a *Ast) (*exprpb.ParsedExpr, error) { }, nil } +// ASTFormatOption is a functional option for configuring the output formatting of AstToString and ExprToString. +type ASTFormatOption func() parser.UnparserOption + +// FormatEscapeIdentifiers configures whether non-standard or reserved identifiers are quoted with backticks. +func FormatEscapeIdentifiers(escape bool) ASTFormatOption { + return func() parser.UnparserOption { + return parser.EscapeIdentifiers(escape) + } +} + +// FormatWrapOnColumn configures expression word-wrapping when the string length exceeds the specified column limit. +func FormatWrapOnColumn(col int) ASTFormatOption { + return func() parser.UnparserOption { + return parser.WrapOnColumn(col) + } +} + // AstToString converts an Ast back to a string if possible. // // Note, the conversion may not be an exact replica of the original expression, but will produce // a string that is semantically equivalent and whose textual representation is stable. -func AstToString(a *Ast) (string, error) { - return ExprToString(a.NativeRep().Expr(), a.NativeRep().SourceInfo()) +func AstToString(a *Ast, opts ...ASTFormatOption) (string, error) { + if a == nil { + return "", errors.New("unsupported expr") + } + return ExprToString(a.NativeRep().Expr(), a.NativeRep().SourceInfo(), opts...) } // ExprToString converts an AST Expr node back to a string using macro call tracking metadata from // source info if any macros are encountered within the expression. -func ExprToString(e ast.Expr, info *ast.SourceInfo) (string, error) { - return parser.Unparse(e, info) +func ExprToString(e ast.Expr, info *ast.SourceInfo, opts ...ASTFormatOption) (string, error) { + unparserOpts := make([]parser.UnparserOption, len(opts)) + for i, opt := range opts { + unparserOpts[i] = opt() + } + return parser.Unparse(e, info, unparserOpts...) } // RefValueToValue converts between ref.Val and google.api.expr.v1alpha1.Value. diff --git a/vendor/github.com/google/cel-go/cel/library.go b/vendor/cel.dev/cel-go/cel/library.go similarity index 75% rename from vendor/github.com/google/cel-go/cel/library.go rename to vendor/cel.dev/cel-go/cel/library.go index 43912eaae2..933551228a 100644 --- a/vendor/github.com/google/cel-go/cel/library.go +++ b/vendor/cel.dev/cel-go/cel/library.go @@ -18,18 +18,19 @@ import ( "fmt" "math" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/decls" - "github.com/google/cel-go/common/env" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/stdlib" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" - "github.com/google/cel-go/interpreter" - "github.com/google/cel-go/parser" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/cost" + "cel.dev/cel-go/common/decls" + "cel.dev/cel-go/common/env" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/stdlib" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" + "cel.dev/cel-go/interpreter" + "cel.dev/cel-go/parser" ) const ( @@ -42,8 +43,11 @@ const ( optionalOfNonZeroValueFunc = "optional.ofNonZeroValue" optionalUnwrapFunc = "optional.unwrap" valueFunc = "value" - unusedIterVar = "#unused" - targetVar = "@target" + + optionalHasValueValueOverload = "optional_hasValue_value" + + unusedIterVar = "#unused" + targetVar = "@target" ) // Library provides a collection of EnvOption and ProgramOption values used to configure a CEL @@ -89,6 +93,11 @@ type LibraryVersioner interface { LibraryVersion() uint32 } +// LibraryCataloguer provides catalog symbols exported by the library when it is not enabled. +type LibraryCataloguer interface { + CatalogSymbols() []*env.CatalogSymbol +} + // Lib creates an EnvOption out of a Library, allowing libraries to be provided as functional args, // and to be linked to each other. func Lib(l Library) EnvOption { @@ -315,24 +324,38 @@ func (*stdLibrary) ProgramOptions() []ProgramOption { // // # OptMap // -// Apply a transformation to the optional's underlying value if it is not empty -// and return an optional typed result based on the transformation. The -// transformation expression type must return a type T which is wrapped into -// an optional. +// Applies a transformation to the optional's value if it holds one, and wraps the +// result in an optional. An optional which holds no value is returned unchanged. +// Starting in **OptionalTypes library version 4**, `optMap` avoids evaluating +// complex target expressions more than once. The change for more efficient +// evaluation alters the cost model in a backward incompatible manner, hence +// the versioned rollout. // -// msg.?elements.optMap(e, e.size()).orValue(0) +// .optMap(, ) -> +// +// Examples: +// +// optional.of(2).optMap(i, i * 2).value() == 4 +// optional.none().optMap(i, i * 2) == optional.none() // // # OptFlatMap // // Introduced in version: 1 // -// Apply a transformation to the optional's underlying value if it is not empty -// and return the result. The transform expression must return an optional(T) -// rather than type T. This can be useful when dealing with zero values and -// conditionally generating an empty or non-empty result in ways which cannot -// be expressed with `optMap`. +// Applies a transformation to the optional's value if it holds one, and returns +// the result. Unlike `optMap`, the transformation must itself produce an +// optional, which makes it possible to express results that may be empty in ways +// `optMap` cannot. Starting in **OptionalTypes library version 4**, `optFlatMap` +// avoids evaluating complex target expressions more than once. The change for more +// efficient evaluation alters the cost model in a backward incompatible manner, +// hence the versioned rollout. +// +// .optFlatMap(, ) -> // -// msg.?elements.optFlatMap(e, e[?0]) // return the first element if present. +// Examples: +// +// {'key': {'sub': 'value'}}.?key.optFlatMap(k, k.?sub).value() == 'value' +// {'key': {}}.?key.optFlatMap(k, k.?sub) == optional.none() // // # First // @@ -341,7 +364,7 @@ func (*stdLibrary) ProgramOptions() []ProgramOption { // Returns an optional with the first value from the right hand list, or // optional.None. // -// [1, 2, 3].first().value() == 1 +// [1, 2, 3].first().value() == 1 // // # Last // @@ -350,7 +373,7 @@ func (*stdLibrary) ProgramOptions() []ProgramOption { // Returns an optional with the last value from the right hand list, or // optional.None. // -// [1, 2, 3].last().value() == 3 +// [1, 2, 3].last().value() == 3 // // This is syntactic sugar for msg.elements[msg.elements.size()-1]. // @@ -363,6 +386,27 @@ func (*stdLibrary) ProgramOptions() []ProgramOption { // // optional.unwrap([optional.of(42), optional.none()]) == [42] // [optional.of(42), optional.none()].unwrapOpt() == [42] +// +// # HasValue with a value argument +// +// Introduced in version: 3 +// +// Determine whether the optional contains a value equal to the argument, which +// is equivalent to the expression `opt.hasValue() ? opt.value() == v : false`. +// +// optional.of(42).hasValue(42) // true +// optional.of(42).hasValue(21) // false +// optional.none().hasValue(42) // false +// +// The argument is compared against the value held by the optional and is never +// unwrapped, so an optional_type(T) argument is only equal to the value of an +// optional_type(optional_type(T)). The type-checker enforces this agreement, +// but when the argument is dyn-typed the comparison is deferred to runtime +// where a type mismatch evaluates to false, just as it would for `==`. +// +// optional.of(optional.of(42)).hasValue(optional.of(42)) // true +// optional.of(42).hasValue(dyn(optional.of(42))) // false +// optional.of(42).hasValue(dyn(42)) // true func OptionalTypes(opts ...OptionalTypesOption) EnvOption { lib := &optionalLib{version: math.MaxUint32} for _, opt := range opts { @@ -409,6 +453,60 @@ func (lib *optionalLib) LibraryVersion() uint32 { return lib.version } +// CatalogSymbols implements the LibraryCataloguer interface method. +func (*optionalLib) CatalogSymbols() []*env.CatalogSymbol { + return []*env.CatalogSymbol{ + { + Name: "optional", + Kind: env.NamespaceKind, + Library: "cel.lib.optional", + Option: "cel.OptionalTypes()", + }, + { + Name: "optional_type", + Kind: env.TypeKind, + Library: "cel.lib.optional", + Option: "cel.OptionalTypes()", + }, + { + Name: optionalNoneFunc, + Kind: env.FunctionKind, + Library: "cel.lib.optional", + Option: "cel.OptionalTypes()", + }, + { + Name: optionalOfFunc, + Kind: env.FunctionKind, + Library: "cel.lib.optional", + Option: "cel.OptionalTypes()", + }, + { + Name: optionalOfNonZeroValueFunc, + Kind: env.FunctionKind, + Library: "cel.lib.optional", + Option: "cel.OptionalTypes()", + }, + { + Name: optMapMacro, + Kind: env.MacroKind, + Library: "cel.lib.optional", + Option: "cel.OptionalTypes()", + }, + { + Name: optFlatMapMacro, + Kind: env.MacroKind, + Library: "cel.lib.optional", + Option: "cel.OptionalTypes()", + }, + { + Name: "optSelect", + Kind: env.MacroKind, + Library: "cel.lib.optional", + Option: "cel.OptionalTypes()", + }, + } +} + // CompileOptions implements the Library interface method. func (lib *optionalLib) CompileOptions() []EnvOption { paramTypeK := TypeParamType("K") @@ -418,6 +516,11 @@ func (lib *optionalLib) CompileOptions() []EnvOption { mapTypeKV := MapType(paramTypeK, paramTypeV) listOptionalTypeV := ListType(optionalTypeV) + optMapMacroExpander := optMap + if lib.version >= 4 { + optMapMacroExpander = optMapV2 + } + opts := []EnvOption{ // Enable the optional syntax in the parser. enableOptionalSyntax(), @@ -426,7 +529,7 @@ func (lib *optionalLib) CompileOptions() []EnvOption { Types(types.OptionalType), // Configure the optMap and optFlatMap macros. - Macros(ReceiverMacro(optMapMacro, 2, optMap, + Macros(ReceiverMacro(optMapMacro, 2, optMapMacroExpander, MacroDocs(`perform computation on the value if present and return the result as an optional`), MacroExamples( common.MultilineDescription( @@ -458,7 +561,7 @@ func (lib *optionalLib) CompileOptions() []EnvOption { }))), Function(optionalNoneFunc, FunctionDocs(`singleton value representing an optional without a value`), - Overload("optional_none", []*Type{}, optionalTypeV, + Overload(overloads.OptionalNone, []*Type{}, optionalTypeV, OverloadExamples(`optional.none()`), FunctionBinding(func(values ...ref.Val) ref.Val { return types.OptionalNone @@ -530,7 +633,11 @@ func (lib *optionalLib) CompileOptions() []EnvOption { Overload("optional_map_index_value", []*Type{OptionalType(mapTypeKV), paramTypeK}, optionalTypeV)), } if lib.version >= 1 { - opts = append(opts, Macros(ReceiverMacro(optFlatMapMacro, 2, optFlatMap, + optFlatMapMacroExpander := optFlatMap + if lib.version >= 4 { + optFlatMapMacroExpander = optFlatMapV2 + } + opts = append(opts, Macros(ReceiverMacro(optFlatMapMacro, 2, optFlatMapMacroExpander, MacroDocs(`perform computation on the value if present and produce an optional value within the computation`), MacroExamples( common.MultilineDescription( @@ -589,14 +696,108 @@ func (lib *optionalLib) CompileOptions() []EnvOption { UnaryBinding(optUnwrap)))) } + if lib.version >= 3 { + opts = append(opts, Function(hasValueFunc, + MemberOverload(optionalHasValueValueOverload, []*Type{optionalTypeV, paramTypeV}, BoolType, + OverloadExamples( + `optional.of(1).hasValue(1) // true`, + `optional.of(1).hasValue(2) // false`, + `optional.none().hasValue(1) // false`, + common.MultilineDescription( + `// the argument is compared against the optional's value, and is not unwrapped`, + `optional.of(1).hasValue(dyn(optional.of(1))) // false`, + `optional.of(optional.of(1)).hasValue(optional.of(1)) // true`)), + BinaryBinding(func(value, other ref.Val) ref.Val { + opt := value.(*types.Optional) + if !opt.HasValue() { + return types.False + } + return types.Equal(opt.GetValue(), other) + })))) + opts = append(opts, CostEstimatorOptions( + cost.OverloadCostEstimate(optionalHasValueValueOverload, estimateOptionalHasValue))) + } + return opts } // ProgramOptions implements the Library interface method. func (lib *optionalLib) ProgramOptions() []ProgramOption { - return []ProgramOption{ + opts := []ProgramOption{ CustomDecoratorV2(decorateOptionalOr), } + if lib.version >= 3 { + opts = append(opts, CostTrackerOptions( + cost.OverloadTracker(optionalHasValueValueOverload, trackOptionalHasValue))) + } + return opts +} + +// estimateOptionalHasValue estimates the cost of comparing an optional's value against the input +// argument. +// +// The overload is sugar for 'opt.hasValue() ? opt.value() == v : false' where the equality check +// dominates the cost, so the estimate mirrors the O(min(m, n)) cost of an equality comparison. +func estimateOptionalHasValue(estimator cost.Estimator, target *cost.AstNode, args []cost.AstNode) *cost.CallEstimate { + if target == nil || len(args) != 1 { + return nil + } + optSize := sizeOrUnknown(*target) + argSize := sizeOrUnknown(args[0]) + smallestMax := optSize.Max + if argSize.Max < smallestMax { + smallestMax = argSize.Max + } + minCost := uint64(0) + if smallestMax > 0 { + // equality of 2 scalar values results in a cost of 1 + minCost = 1 + } + return &cost.CallEstimate{ + CostEstimate: cost.CostEstimate{Min: minCost, Max: smallestMax}. + MultiplyByCostFactor(cost.StringTraversalCostFactor), + } +} + +// sizeOrUnknown returns the size estimate computed for the node, or an unknown size if the node +// size could not be determined at check time. +func sizeOrUnknown(node cost.AstNode) cost.SizeEstimate { + if sz := node.ComputedSize(); sz != nil { + return *sz + } + return cost.UnknownSizeEstimate() +} + +// trackOptionalHasValue computes the runtime cost of comparing an optional's value against the +// input argument, which is bounded by the size of the smaller of the two values. +func trackOptionalHasValue(args []ref.Val, result ref.Val) *uint64 { + if len(args) != 2 { + return nil + } + callCost := cost.SafeMultiplyByFactor( + min(optionalValueSize(args[0]), optionalValueSize(args[1])), cost.StringTraversalCostFactor) + return &callCost +} + +// optionalValueSize returns the size of the value being compared, unwrapping nested optional +// values to the value they contain, and reporting a size of 1 for values which are not sizable. +func optionalValueSize(value ref.Val) uint64 { + for { + opt, isOpt := value.(*types.Optional) + if !isOpt { + break + } + if !opt.HasValue() { + return 1 + } + value = opt.GetValue() + } + if sizer, isSizer := value.(traits.Sizer); isSizer { + if sz, isInt := sizer.Size().(types.Int); isInt { + return uint64(sz) + } + } + return 1 } // Version returns the current version of the library. @@ -605,6 +806,34 @@ func (lib *optionalLib) Version() uint32 { } func optMap(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *Error) { + varIdent := args[0] + varName := "" + switch varIdent.Kind() { + case ast.IdentKind: + varName = varIdent.AsIdent() + default: + return nil, meh.NewError(varIdent.ID(), "optMap() variable name must be a simple identifier") + } + mapExpr := args[1] + return meh.NewCall( + operators.Conditional, + meh.NewMemberCall(hasValueFunc, target), + meh.NewCall(optionalOfFunc, + meh.NewComprehension( + meh.NewList(), + unusedIterVar, + varName, + meh.NewMemberCall(valueFunc, meh.Copy(target)), + meh.NewLiteral(types.False), + meh.NewIdent(varName), + mapExpr, + ), + ), + meh.NewCall(optionalNoneFunc), + ), nil +} + +func optMapV2(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *Error) { varIdent := args[0] varName := "" switch varIdent.Kind() { @@ -649,6 +878,32 @@ func optMap(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, * } func optFlatMap(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *Error) { + varIdent := args[0] + varName := "" + switch varIdent.Kind() { + case ast.IdentKind: + varName = varIdent.AsIdent() + default: + return nil, meh.NewError(varIdent.ID(), "optFlatMap() variable name must be a simple identifier") + } + mapExpr := args[1] + return meh.NewCall( + operators.Conditional, + meh.NewMemberCall(hasValueFunc, target), + meh.NewComprehension( + meh.NewList(), + unusedIterVar, + varName, + meh.NewMemberCall(valueFunc, meh.Copy(target)), + meh.NewLiteral(types.False), + meh.NewIdent(varName), + mapExpr, + ), + meh.NewCall(optionalNoneFunc), + ), nil +} + +func optFlatMapV2(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *Error) { varIdent := args[0] varName := "" switch varIdent.Kind() { @@ -785,7 +1040,7 @@ func (opt *evalOptionalOr) Exec(frame *interpreter.ExecutionFrame) ref.Val { // Eval evaluates the left-hand side optional to determine whether it contains a value, else // proceeds with the right-hand side evaluation. func (opt *evalOptionalOr) Eval(ctx interpreter.Activation) ref.Val { - return opt.Exec(interpreter.AsFrame(ctx)) + return interpreter.EvalActivation(ctx, opt.Exec) } // evalOptionalOrValue selects between an optional or a concrete value. If the optional has a value, @@ -821,7 +1076,7 @@ func (opt *evalOptionalOrValue) Exec(frame *interpreter.ExecutionFrame) ref.Val // Eval evaluates the left-hand side optional to determine whether it contains a value, else // proceeds with the right-hand side evaluation. func (opt *evalOptionalOrValue) Eval(ctx interpreter.Activation) ref.Val { - return opt.Exec(interpreter.AsFrame(ctx)) + return interpreter.EvalActivation(ctx, opt.Exec) } type timeLegacyLibrary struct{} diff --git a/vendor/github.com/google/cel-go/cel/macro.go b/vendor/cel.dev/cel-go/cel/macro.go similarity index 99% rename from vendor/github.com/google/cel-go/cel/macro.go rename to vendor/cel.dev/cel-go/cel/macro.go index 3d3c5be1b7..aed4a8da1f 100644 --- a/vendor/github.com/google/cel-go/cel/macro.go +++ b/vendor/cel.dev/cel-go/cel/macro.go @@ -17,10 +17,10 @@ package cel import ( "fmt" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/parser" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/parser" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" ) diff --git a/vendor/github.com/google/cel-go/cel/optimizer.go b/vendor/cel.dev/cel-go/cel/optimizer.go similarity index 98% rename from vendor/github.com/google/cel-go/cel/optimizer.go rename to vendor/cel.dev/cel-go/cel/optimizer.go index 6e260a93cf..97dba5f44a 100644 --- a/vendor/github.com/google/cel-go/cel/optimizer.go +++ b/vendor/cel.dev/cel-go/cel/optimizer.go @@ -18,10 +18,10 @@ import ( "fmt" "sort" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // StaticOptimizer contains a sequence of ASTOptimizer instances which will be applied in order. @@ -38,6 +38,7 @@ type StaticOptimizer struct { sourceOverride *Source } +// OptimizerOption configures a StaticOptimizer instance. type OptimizerOption func(*StaticOptimizer) (*StaticOptimizer, error) // NewStaticOptimizer creates a StaticOptimizer with a sequence of ASTOptimizer's to be applied @@ -317,6 +318,11 @@ func (opt *optimizerExprFactory) MacroCalls() map[int64]ast.Expr { return opt.sourceInfo.MacroCalls() } +// AddExtension adds an extension record into the tracked source info metadata. +func (opt *optimizerExprFactory) AddExtension(ext ast.Extension) { + opt.sourceInfo.AddExtension(ext) +} + // NewBindMacro creates an AST expression representing the expanded bind() macro, and a macro expression // representing the unexpanded call signature to be inserted into the source info macro call metadata. func (opt *optimizerExprFactory) NewBindMacro(macroID int64, varName string, varInit, remaining ast.Expr) (astExpr, macroExpr ast.Expr) { diff --git a/vendor/github.com/google/cel-go/cel/options.go b/vendor/cel.dev/cel-go/cel/options.go similarity index 80% rename from vendor/github.com/google/cel-go/cel/options.go rename to vendor/cel.dev/cel-go/cel/options.go index 709ce007a2..9df7f26daa 100644 --- a/vendor/github.com/google/cel-go/cel/options.go +++ b/vendor/cel.dev/cel-go/cel/options.go @@ -17,6 +17,7 @@ package cel import ( "errors" "fmt" + "reflect" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protodesc" @@ -24,17 +25,17 @@ import ( "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/dynamicpb" - "github.com/google/cel-go/cel/async" - "github.com/google/cel-go/checker" - "github.com/google/cel-go/common/containers" - "github.com/google/cel-go/common/decls" - "github.com/google/cel-go/common/env" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/pb" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/interpreter" - "github.com/google/cel-go/parser" + "cel.dev/cel-go/cel/async" + "cel.dev/cel-go/common/containers" + "cel.dev/cel-go/common/cost" + "cel.dev/cel-go/common/decls" + "cel.dev/cel-go/common/env" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/pb" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/interpreter" + "cel.dev/cel-go/parser" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" descpb "google.golang.org/protobuf/types/descriptorpb" @@ -75,6 +76,11 @@ const ( // Enable accessing fields by JSON names within protobuf messages featureJSONFieldNames + + // Enable strict RFC 3339 validation of timestamp strings and strict range validation of + // numeric timezone offsets. Strict validation is the default; the feature only has an effect + // when it is explicitly disabled, see StrictTimestampParsing. + featureStrictTimestampParsing ) var featureIDsToNames = map[int]string{ @@ -165,6 +171,9 @@ func ClearMacros() EnvOption { // Note: This option must be specified before the Types and TypeDescs options when used together. func CustomTypeAdapter(adapter types.Adapter) EnvOption { return func(e *Env) (*Env, error) { + if adapter == nil { + return nil, errors.New("custom type adapter must not be nil") + } e.adapter = adapter return e, nil } @@ -177,6 +186,9 @@ func CustomTypeAdapter(adapter types.Adapter) EnvOption { // Note: This option must be specified before the Types and TypeDescs options when used together. func CustomTypeProvider(provider any) EnvOption { return func(e *Env) (*Env, error) { + if provider == nil { + return nil, errors.New("custom type provider must not be nil") + } var err error e.provider, err = maybeInteropProvider(provider) return e, err @@ -328,6 +340,22 @@ func Abbrevs(qualifiedNames ...string) EnvOption { } } +// NativeTypeDesc describes a native Go struct type for registration with CEL. +type NativeTypeDesc = types.NativeTypeDesc + +// NativeTypeOption is a functional option for configuring handling of native types. +type NativeTypeOption = types.NativeTypeOption + +var ( + // NativeTypeAlias configures a custom CEL type name (alias) for a native type descriptor. + NativeTypeAlias = types.NativeTypeAlias +) + +// NativeTypeFor constructs a NativeTypeDesc for a Go struct type T with the given options. +func NativeTypeFor[T any](opts ...NativeTypeOption) *NativeTypeDesc { + return types.NativeTypeFor[T](opts...) +} + // protoTypeRegistry is an internal-only interface containing the minimum methods required to support // custom types. It is a subset of methods from ref.TypeRegistry. type protoTypeRegistry interface { @@ -335,11 +363,16 @@ type protoTypeRegistry interface { RegisterType(...ref.Type) error } +type nativeTypeRegistry interface { + RegisterNativeType(reflect.Type, ...types.NativeTypeOption) error + RegisterNativeTypeDesc(*types.NativeTypeDesc) error +} + // Types adds one or more type declarations to the environment, allowing for construction of // type-literals whose definitions are included in the common expression built-in set. // -// The input types may either be instances of `proto.Message` or `ref.Type`. Any other type -// provided to this option will result in an error. +// The input types may either be instances of `proto.Message`, `ref.Type`, `reflect.Type`, or `*NativeTypeDesc`. +// Any other type provided to this option will result in an error. // // Well-known protobuf types within the `google.protobuf.*` package are included in the standard // environment by default. @@ -366,6 +399,24 @@ func Types(addTypes ...any) EnvOption { if err != nil { return nil, err } + case reflect.Type: + nreg, isNReg := e.provider.(nativeTypeRegistry) + if !isNReg { + return nil, fmt.Errorf("native types not supported by provider: %T", e.provider) + } + err := nreg.RegisterNativeType(v) + if err != nil { + return nil, err + } + case *types.NativeTypeDesc: + nreg, isNReg := e.provider.(nativeTypeRegistry) + if !isNReg { + return nil, fmt.Errorf("native types not supported by provider: %T", e.provider) + } + err := nreg.RegisterNativeTypeDesc(v) + if err != nil { + return nil, err + } default: return nil, fmt.Errorf("unsupported type: %T", t) } @@ -497,6 +548,11 @@ func Functions(funcs ...*functions.Overload) ProgramOption { // a Lib EnvOption, vars may shadow variables provided by previously added libraries. // // The vars value may either be an `cel.Activation` instance or a `map[string]any`. +// +// The vars value may supply late-bound function implementations, e.g. via FunctionVars, in which +// case they apply to every evaluation of the program. Only one source of function bindings is +// permitted, so an error is returned when Globals is applied more than once and more than one of +// the activations supplies them. func Globals(vars any) ProgramOption { return func(p *prog) (*prog, error) { defaultVars, err := NewActivation(vars) @@ -506,6 +562,9 @@ func Globals(vars any) ProgramOption { if p.defaultVars != nil { defaultVars = interpreter.NewHierarchicalActivation(p.defaultVars, defaultVars) } + if _, err := interpreter.FindFunctionActivation(defaultVars); err != nil { + return nil, err + } p.defaultVars = defaultVars return p, nil } @@ -653,7 +712,7 @@ func configToEnvOptions(config *env.Config, provider types.Provider, optFactorie // Configure validators for _, val := range config.Validators { - if fac, found := astValidatorFactories[val.Name]; found { + if fac, found := astValidatorFactories()[val.Name]; found { envOpts = append(envOpts, func(e *Env) (*Env, error) { validator, err := fac(val) if err != nil { @@ -729,6 +788,10 @@ const ( // // Deprecated: use ext.StringsValidateFormatCalls() as this option is now a no-op. OptCheckStringFormat EvalOption = 1 << iota + + // OptTrackMemory enables the runtime peak memory tracking and returns the peak watermark within + // evalDetails via func PeakMemory() + OptTrackMemory EvalOption = 1 << iota ) // EvalOptions sets one or more evaluation options which may affect the evaluation or Result. @@ -791,18 +854,73 @@ func ConcurrentDrainStrategy(strategy async.DrainStrategy) ProgramOption { } } +// BypassAsyncProtection allows for the bypass of hasAsync protection in Eval and ContextEval if present. +// +// By default, expressions in an environment with asynchronous functions will reject calls to +// Eval and ContextEval, requiring ConcurrentEval instead. This option bypasses that check, allowing +// synchronous evaluation of expressions that do not actually call asynchronous functions (such as +// constant validations). +func BypassAsyncProtection() ProgramOption { + return func(p *prog) (*prog, error) { + p.hasAsync = false + return p, nil + } +} + // CostEstimatorOptions configure type-check time options for estimating expression cost. -func CostEstimatorOptions(costOpts ...checker.CostOption) EnvOption { +func CostEstimatorOptions(costOpts ...cost.CostOption) EnvOption { return func(e *Env) (*Env, error) { e.costOptions = append(e.costOptions, costOpts...) return e, nil } } +// CostModel configures overload cost estimators and cost trackers from a set of cost.OverloadModel definitions. +// +// Models are validated here because neither the estimator nor the tracker compiled from a model +// can report a problem once evaluation has begun. See cost.OverloadModel.Validate. +func CostModel(models ...cost.OverloadModel) EnvOption { + return func(e *Env) (*Env, error) { + if err := cost.ValidateOverloadModels(models...); err != nil { + return nil, err + } + e.costConfig.models = append(e.costConfig.models, models...) + return e, nil + } +} + +// CostSizingStrategy configures a SizingStrategy for both cost estimation and runtime cost tracking. +func CostSizingStrategy(strategy cost.SizingStrategy) EnvOption { + return func(e *Env) (*Env, error) { + e.costConfig.strategy = strategy + return e, nil + } +} + +// CostModelVersion pins cost estimation and runtime cost tracking to a revision of the cost +// model's rules. +// +// The pin applies to the standard models and to any model supplied via CostModel, for both +// estimation and tracking, so an environment's estimates and charges come from one consistent set +// of rules. +// +// If this option is not set, the latest cost model version is used. Use this only as a temporary +// migration aid to hold estimates stable against a baseline recorded under an earlier release. +// Because version 0 preserves legacy behaviors with known soundness gaps where static estimates can +// underestimate runtime cost, callers are strongly encouraged to switch to CostModelVersion(1) or +// higher (or omit this option to use the latest revision) for improved soundness; see +// cost.ModelVersion for the per-revision details. +func CostModelVersion(version uint32) EnvOption { + return func(e *Env) (*Env, error) { + e.costConfig.version = &version + return e, nil + } +} + // CostTrackerOptions configures a set of options for cost-tracking. // // Note, CostTrackerOptions is a no-op unless CostTracking is also enabled. -func CostTrackerOptions(costOpts ...interpreter.CostTrackerOption) ProgramOption { +func CostTrackerOptions(costOpts ...cost.TrackerOption) ProgramOption { return func(p *prog) (*prog, error) { p.costOptions = append(p.costOptions, costOpts...) return p, nil @@ -810,7 +928,7 @@ func CostTrackerOptions(costOpts ...interpreter.CostTrackerOption) ProgramOption } // CostTracking enables cost tracking and registers a ActualCostEstimator that can optionally provide a runtime cost estimate for any function calls. -func CostTracking(costEstimator interpreter.ActualCostEstimator) ProgramOption { +func CostTracking(costEstimator cost.ActualCostEstimator) ProgramOption { return func(p *prog) (*prog, error) { p.callCostEstimator = costEstimator p.evalOpts |= OptTrackCost @@ -818,6 +936,36 @@ func CostTracking(costEstimator interpreter.ActualCostEstimator) ProgramOption { } } +// MemoryTracking enables peak memory tracking during evaluation with an optional set of +// types.MemoryTrackerOption values to configure the tracker's size calculator, sample +// interval, and limit behaviors. +// +// Peak memory is measured in aggregate element counts as computed by a types.SizeCalculator +// and is observed at the points where values materialize during evaluation: resolved +// attributes, call results, constructed aggregates, and comprehension results. The peak +// watermark is available via the EvalDetails.PeakMemory() method. +func MemoryTracking(memOpts ...types.MemoryTrackerOption) ProgramOption { + return func(p *prog) (*prog, error) { + p.memoryOptions = append(p.memoryOptions, memOpts...) + p.evalOpts |= OptTrackMemory + return p, nil + } +} + +// MemoryLimit enables memory tracking and configures program evaluation to exit early with a +// "memory limit exceeded" error if the peak tracked memory exceeds the limit. +// +// The MemoryLimit is a metric that corresponds to the aggregate element counts of the values +// observed during evaluation. It is indicative of memory usage, not CPU usage; see CostLimit +// for bounding compute. +func MemoryLimit(memLimit uint32) ProgramOption { + return func(p *prog) (*prog, error) { + p.memoryLimit = &memLimit + p.evalOpts |= OptTrackMemory + return p, nil + } +} + // CostLimit enables cost tracking and sets configures program evaluation to exit early with a // "runtime cost limit exceeded" error if the runtime cost exceeds the costLimit. // The CostLimit is a metric that corresponds to the number and estimated expense of operations @@ -953,6 +1101,11 @@ func ContextProtoVars(ctx proto.Message, opts ...types.RegistryOption) (Activati // EnableMacroCallTracking ensures that call expressions which are replaced by macros // are tracked in the `SourceInfo` of parsed and checked expressions. +// +// This is required for Env.ResidualAst to succeed when the residual Ast contains an +// unresolved comprehension macro (all, exists, exists_one, filter, map): without it, +// ResidualAst cannot re-serialize the macro's expanded internal representation back +// into CEL source syntax and returns an error instead of the residual expression. func EnableMacroCallTracking() EnvOption { return features(featureEnableMacroCallTracking, true) } @@ -974,6 +1127,30 @@ func DefaultUTCTimeZone(enabled bool) EnvOption { return features(featureDefaultUTCTimeZone, enabled) } +// StrictTimestampParsing controls how strictly timestamp strings and numeric timezone offsets are +// validated. +// +// Strict parsing is the default and is equivalent to StrictTimestampParsing(true): +// +// - timestamp(string) accepts only RFC 3339 date-time strings. Inputs which time.Parse accepts +// but RFC 3339 forbids are rejected: a ',' fractional second separator, single-digit time +// fields, and numeric offsets whose hours exceed 23 or whose minutes exceed 59. +// - Numeric timezone offsets passed to the timestamp accessors, e.g. getHours('+05:30'), must +// have hours in [-23, 23] and minutes in [0, 59]. +// +// StrictTimestampParsing(false) restores the parsing behavior of cel-go releases prior to v0.30.0 +// for the timestamp(string) conversion and prior to v0.31.0 for timezone offsets: timestamp +// strings are accepted whenever time.Parse(time.RFC3339, ...) accepts them, and numeric offsets +// are not range checked. Note that some of these inputs resolve to an instant other than the one +// the string appears to describe; for example an offset of '+05:60' is treated as '+06:00'. +// +// Disabling strict parsing is intended as a compatibility aid for embedders which must keep +// evaluating expressions, or data, that were accepted by earlier releases. The relaxed rules also +// apply to timestamp literal validation (see ValidateTimestampLiterals). +func StrictTimestampParsing(enabled bool) EnvOption { + return features(featureStrictTimestampParsing, enabled) +} + // features sets the given feature flags. See list of Feature constants above. func features(flag int, enabled bool) EnvOption { return func(e *Env) (*Env, error) { @@ -1059,11 +1236,19 @@ func EnableHiddenAccumulatorName(enabled bool) EnvOption { } } +type legacyTypeProvider interface { + EnumValue(enumName string) ref.Val + FindIdent(identName string) (ref.Val, bool) + FindType(typeName string) (*exprpb.Type, bool) + FindFieldType(messageType, fieldName string) (*ref.FieldType, bool) + NewValue(typeName string, fields map[string]ref.Val) ref.Val +} + func maybeInteropProvider(provider any) (types.Provider, error) { switch p := provider.(type) { case types.Provider: return p, nil - case ref.TypeProvider: + case legacyTypeProvider: return &interopCELTypeProvider{TypeProvider: p}, nil default: return nil, fmt.Errorf("unsupported type provider: %T", provider) diff --git a/vendor/github.com/google/cel-go/cel/program.go b/vendor/cel.dev/cel-go/cel/program.go similarity index 73% rename from vendor/github.com/google/cel-go/cel/program.go rename to vendor/cel.dev/cel-go/cel/program.go index 07849974a1..60c13b0c31 100644 --- a/vendor/github.com/google/cel-go/cel/program.go +++ b/vendor/cel.dev/cel-go/cel/program.go @@ -20,13 +20,15 @@ import ( "fmt" "time" - "github.com/google/cel-go/cel/async" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/interpreter" + "cel.dev/cel-go/cel/async" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/cost" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/interpreter" ) // Program is an evaluable view of an Ast. @@ -114,6 +116,52 @@ func PartialVars(vars any, return interpreter.NewPartialActivation(vars, unknowns...) } +// FunctionActivation extends the Activation interface with implementations for the functions +// declared with a late binding. +type FunctionActivation = interpreter.FunctionActivation + +// LateBoundFunction is the signature required of all late-bound function implementations. +// +// The overload id indicates which of the declared overloads matched the call arguments, which +// permits a single implementation to serve all overloads of the function. +// +// An implementation which depends on the state of the evaluation should capture that state in a +// closure, as the activation is not an input to the call. +type LateBoundFunction = functions.LateBoundOp + +// FunctionVars returns a FunctionActivation combining the variable bindings from `vars` with +// the late-bound function implementations from `funcs`. FunctionVars support late-bound function +// definitions where the function behavior depends on the context of the evaluation. This can only +// be accomplished by closing over state that is not otherwise exposed to the CEL author or CEL +// runtime. +// +// - Function bindings occupy a namespace separate from variables, allowing a function and a +// variable to share the same qualified name. +// - The `vars` argument may be an Activation or any valid input to NewActivation (e.g. map[string]any). +// - FunctionVars may not be nested, and only one instance of FunctionVars may be supplied to an +// evaluation. FunctionVars returns an error if `vars` already contains function bindings. +// +// Function implementations can capture evaluation-scoped state via closures without exposing that +// state directly as expression variables: +// +// roles := map[string]string{"tristan": "admin"} +// act, err := cel.FunctionVars(map[string]any{"user": "tristan"}, map[string]cel.LateBoundFunction{ +// "role": func(overloadID string, args ...ref.Val) ref.Val { +// role, found := roles[string(args[0].(types.String))] +// if !found { +// return types.NewErr("no role for user: %s", args[0]) +// } +// return types.String(role) +// }, +// }) +// +// CEL expects that late-bound functions, like regular functions, yield the same output given the same +// input. For example, a function comparing a validity window `valid_until(t)` could be implemented as +// a late-bound function closed over a fixed timestamp value. +func FunctionVars(vars any, funcs map[string]LateBoundFunction) (FunctionActivation, error) { + return interpreter.NewFunctionActivation(vars, funcs) +} + // AttributePattern returns an AttributePattern that matches a top-level variable. The pattern is // mutable, and its methods support the specification of one or more qualifier patterns. // @@ -140,7 +188,8 @@ type AttributePatternType = interpreter.AttributePattern // EvalDetails holds additional information observed during the Eval() call. type EvalDetails struct { state interpreter.EvalState - costTracker *interpreter.CostTracker + costTracker *cost.Tracker + memTracker *types.MemoryTracker } // State of the evaluation, non-nil if the OptTrackState or OptExhaustiveEval is specified @@ -162,6 +211,16 @@ func (ed *EvalDetails) ActualCost() *uint64 { return &cost } +// PeakMemory returns the peak memory watermark observed through the course of execution when +// `MemoryTracking` is enabled. Otherwise, returns nil if memory tracking was not enabled. +func (ed *EvalDetails) PeakMemory() *uint32 { + if ed == nil || ed.memTracker == nil { + return nil + } + peak := ed.memTracker.Peak() + return &peak +} + // EvalResult encapsulates the response from a ConcurrentEval call. type EvalResult struct { Val ref.Val @@ -169,6 +228,23 @@ type EvalResult struct { Err error } +// captureCostTracker records the frame's cost tracker within the evaluation details, allocating +// the details when cost tracking is enabled and no details have been created yet. +// +// The details must be fully populated before they are handed off to the caller, as any mutation +// after the hand-off would race with the caller's reads. +func captureCostTracker(det *EvalDetails, frame *interpreter.ExecutionFrame) *EvalDetails { + tracker := frame.CostTracker() + if tracker == nil { + return det + } + if det == nil { + det = &EvalDetails{} + } + det.costTracker = tracker + return det +} + // prog is the internal implementation of the Program interface. type prog struct { *Env @@ -186,9 +262,11 @@ type prog struct { // Interpretable configured from an Ast and aggregate decorator set based on program options. interpretable interpreter.InterpretableV2 observable *interpreter.ObservableInterpretable - callCostEstimator interpreter.ActualCostEstimator - costOptions []interpreter.CostTrackerOption + callCostEstimator cost.ActualCostEstimator + costOptions []cost.TrackerOption costLimit *uint64 + memoryOptions []types.MemoryTrackerOption + memoryLimit *uint32 // hasAsync indicates the planned expression contains an asynchronous function call, which can // only be resolved by ConcurrentEval. @@ -247,7 +325,7 @@ func newProgram(e *Env, a *ast.AST, opts []ProgramOption) (Program, error) { Env: e, plannerOptions: []interpreter.PlannerOption{}, dispatcher: disp, - costOptions: []interpreter.CostTrackerOption{}, + costOptions: []cost.TrackerOption{}, drainStrategy: async.DrainReady(100 * time.Microsecond), hasAsync: hasAsync, } @@ -313,35 +391,59 @@ func newProgram(e *Env, a *ast.AST, opts []ProgramOption) (Program, error) { plannerOptions = append(plannerOptions, interpreter.RegexProgramSizeLimit(limit)) } - // Enable exhaustive eval, state tracking and cost tracking last since they require a factory. - if p.evalOpts&(OptExhaustiveEval|OptTrackState|OptTrackCost) != 0 { - costOptCount := len(p.costOptions) - if p.costLimit != nil { - costOptCount++ - } - costOpts := make([]interpreter.CostTrackerOption, 0, costOptCount) - costOpts = append(costOpts, p.costOptions...) - if p.costLimit != nil { - costOpts = append(costOpts, interpreter.CostTrackerLimit(*p.costLimit)) - } - // Creating a new cost tracker for each evaluation causes significant work that - // needs to be repeated for each evaluation even though the cost tracker is - // mostly read-only once constructed. Therefore it gets constructed - // once now and later a cheap clone is used for each evaluation. - tracker, err := interpreter.NewCostTracker(p.callCostEstimator, costOpts...) - if err != nil { - return nil, fmt.Errorf("construct cost tracker: %w", err) - } - trackerFactory := func() (*interpreter.CostTracker, error) { - return tracker.Clone() - } + // Enable exhaustive eval, state tracking, cost tracking, and memory tracking last since they + // require a factory. + if p.evalOpts&(OptExhaustiveEval|OptTrackState|OptTrackCost|OptTrackMemory) != 0 { var observers []interpreter.PlannerOption if p.evalOpts&(OptExhaustiveEval|OptTrackState) != 0 { // EvalStateObserver is required for OptExhaustiveEval. observers = append(observers, interpreter.EvalStateObserver()) } if p.evalOpts&OptTrackCost == OptTrackCost { - observers = append(observers, interpreter.CostObserver(interpreter.CostTrackerFactory(trackerFactory))) + trackerOpts := p.costModel.tracker + costOptCount := len(trackerOpts) + len(p.costOptions) + 1 + if p.costLimit != nil { + costOptCount++ + } + costOpts := make([]cost.TrackerOption, 0, costOptCount) + costOpts = append(costOpts, cost.TrackerLimitExceededHandler(func() { + panic(interpreter.EvalCancelledError{ + Cause: interpreter.CostLimitExceeded, + Message: "operation cancelled: actual cost limit exceeded", + }) + })) + costOpts = append(costOpts, trackerOpts...) + costOpts = append(costOpts, p.costOptions...) + if p.costLimit != nil { + costOpts = append(costOpts, cost.TrackerLimit(*p.costLimit)) + } + // Creating a new cost tracker for each evaluation causes significant work that + // needs to be repeated for each evaluation even though the cost tracker is + // mostly read-only once constructed. Therefore it gets constructed + // once now and later a cheap clone is used for each evaluation. + tracker, err := cost.NewTracker(p.callCostEstimator, costOpts...) + if err != nil { + return nil, fmt.Errorf("construct cost tracker: %w", err) + } + trackerFactory := func() (*cost.Tracker, error) { + return tracker.Clone() + } + plannerOptions = append(plannerOptions, interpreter.CostObserver(interpreter.CostTrackerFactory(trackerFactory))) + } + if p.evalOpts&OptTrackMemory == OptTrackMemory { + memOptCount := len(p.memoryOptions) + if p.memoryLimit != nil { + memOptCount++ + } + memOpts := make([]types.MemoryTrackerOption, 0, memOptCount) + memOpts = append(memOpts, p.memoryOptions...) + if p.memoryLimit != nil { + memOpts = append(memOpts, types.MemoryTrackerLimit(*p.memoryLimit)) + } + memTrackerFactory := func() (*types.MemoryTracker, error) { + return types.NewMemoryTracker(memOpts...), nil + } + observers = append(observers, interpreter.MemoryObserver(interpreter.MemoryTrackerFactory(memTrackerFactory))) } // Enable exhaustive eval over a basic observer since it offers a superset of features. if p.evalOpts&OptExhaustiveEval == OptExhaustiveEval { @@ -369,19 +471,9 @@ func (p *prog) initInterpretable(a *ast.AST, plannerOptions []interpreter.Planne // Eval implements the Program interface method. func (p *prog) Eval(input any) (out ref.Val, det *EvalDetails, err error) { - // Configure error recovery for unexpected panics during evaluation. Note, the use of named - // return values makes it possible to modify the error response during the recovery - // function. - defer func() { - if r := recover(); r != nil { - switch t := r.(type) { - case interpreter.EvalCancelledError: - err = t - default: - err = fmt.Errorf("internal error: %v", r) - } - } - }() + if p == nil { + return nil, nil, errors.New("program is nil") + } // Asynchronous calls cannot be resolved by a single-pass evaluation. Reject before doing any // work (this also covers ContextEval, which delegates here); ConcurrentEval does not call Eval. if p.hasAsync { @@ -389,6 +481,7 @@ func (p *prog) Eval(input any) (out ref.Val, det *EvalDetails, err error) { } // Build a hierarchical activation if there are default vars set. var frame *interpreter.ExecutionFrame + var mustClose bool if f, ok := input.(*interpreter.ExecutionFrame); ok { frame = f } else { @@ -396,21 +489,43 @@ func (p *prog) Eval(input any) (out ref.Val, det *EvalDetails, err error) { if err != nil { return nil, nil, err } - defer frame.Close() + mustClose = true } + // Configure error recovery and details capture for evaluation. + defer func() { + det = captureCostTracker(det, frame) + if r := recover(); r != nil { + switch t := r.(type) { + case interpreter.EvalCancelledError: + err = t + case cost.LimitExceededError: + err = interpreter.EvalCancelledError{ + Cause: interpreter.CostLimitExceeded, + Message: t.Message, + } + default: + err = fmt.Errorf("internal error: %v", r) + } + } + if mustClose { + frame.Close() + } + }() + if p.observable != nil { det = &EvalDetails{} out = p.observable.ObserveExec(frame, func(observed any) { switch o := observed.(type) { case interpreter.EvalState: det.state = o - case *interpreter.CostTracker: - det.costTracker = o + case *types.MemoryTracker: + det.memTracker = o } }) } else { out = p.interpretable.Exec(frame) } + // The output of an internal Eval may have a value (`v`) that is a types.Err. This step // translates the CEL value to a Go error response. This interface does not quite match the // RPC signature which allows for multiple errors to be returned, but should be sufficient. @@ -422,8 +537,11 @@ func (p *prog) Eval(input any) (out ref.Val, det *EvalDetails, err error) { // ContextEval implements the Program interface. func (p *prog) ContextEval(ctx context.Context, input any) (ref.Val, *EvalDetails, error) { + if p == nil { + return nil, nil, errors.New("program is nil") + } if ctx == nil { - return nil, nil, fmt.Errorf("context can not be nil") + return nil, nil, errors.New("context can not be nil") } frame, err := p.newExecutionFrame(input) if err != nil { @@ -445,10 +563,11 @@ func (p *prog) newExecutionFrame(input any) (*interpreter.ExecutionFrame, error) return nil, err } if p.defaultVars != nil { - // Update the frame's activation in place. - frame.Activation = interpreter.NewHierarchicalActivation(p.defaultVars, frame.Activation) + if err := frame.SetDefaultVars(p.defaultVars); err != nil { + frame.Close() + return nil, err + } } - return frame, nil } @@ -503,6 +622,11 @@ func (p *prog) resolveCompletionBufferSize() int { // ConcurrentEval implements the Program interface. func (p *prog) ConcurrentEval(ctx context.Context, input any) <-chan EvalResult { resCh := make(chan EvalResult, 1) + if p == nil { + resCh <- EvalResult{Err: errors.New("program is nil")} + close(resCh) + return resCh + } if ctx == nil { resCh <- EvalResult{Err: errors.New("context can not be nil")} close(resCh) @@ -511,18 +635,6 @@ func (p *prog) ConcurrentEval(ctx context.Context, input any) <-chan EvalResult go func() { defer close(resCh) - // Ensure concurrent eval handles panic / recovery properly - defer func() { - if r := recover(); r != nil { - switch t := r.(type) { - case interpreter.EvalCancelledError: - resCh <- EvalResult{Err: t} - default: - resCh <- EvalResult{Err: fmt.Errorf("internal error: %v", r)} - } - } - }() - frame, err := p.newAsyncFrame(ctx, input) if err != nil { resCh <- EvalResult{Err: err} @@ -530,6 +642,35 @@ func (p *prog) ConcurrentEval(ctx context.Context, input any) <-chan EvalResult } defer frame.Close() + var det *EvalDetails + // Ensure concurrent eval handles panic / recovery properly. + // + // The details are only captured and published here for the panic case. Every normal + // return path populates the details and sends them on the result channel itself, and + // the receiver may read them as soon as the send completes. Mutating det from this + // defer, which runs after the send, would race with those reads. + defer func() { + r := recover() + if r == nil { + return + } + det = captureCostTracker(det, frame) + switch t := r.(type) { + case interpreter.EvalCancelledError: + resCh <- EvalResult{EvalDetails: det, Err: t} + case cost.LimitExceededError: + resCh <- EvalResult{ + EvalDetails: det, + Err: interpreter.EvalCancelledError{ + Cause: interpreter.CostLimitExceeded, + Message: t.Message, + }, + } + default: + resCh <- EvalResult{EvalDetails: det, Err: fmt.Errorf("internal error: %v", r)} + } + }() + // Completions are signaled to this channel as async calls finish. The asyncCallState // fan-in also selects on ctx.Done(), so the sender will not leak if this loop returns early. completions := make(chan int64, p.resolveCompletionBufferSize()) @@ -537,7 +678,6 @@ func (p *prog) ConcurrentEval(ctx context.Context, input any) <-chan EvalResult for { var out ref.Val - var det *EvalDetails if p.observable != nil { det = &EvalDetails{} @@ -545,13 +685,16 @@ func (p *prog) ConcurrentEval(ctx context.Context, input any) <-chan EvalResult switch o := observed.(type) { case interpreter.EvalState: det.state = o - case *interpreter.CostTracker: - det.costTracker = o + case *types.MemoryTracker: + det.memTracker = o } }) } else { out = p.interpretable.Exec(frame) } + // Capture the cost tracker before the result is published on the channel: once the + // send completes the receiver owns the details and they must not be mutated. + det = captureCostTracker(det, frame) // Communicate errors quickly. if types.IsError(out) { diff --git a/vendor/github.com/google/cel-go/cel/prompt.go b/vendor/cel.dev/cel-go/cel/prompt.go similarity index 97% rename from vendor/github.com/google/cel-go/cel/prompt.go rename to vendor/cel.dev/cel-go/cel/prompt.go index f599348271..e5e2acde7a 100644 --- a/vendor/github.com/google/cel-go/cel/prompt.go +++ b/vendor/cel.dev/cel-go/cel/prompt.go @@ -20,10 +20,10 @@ import ( "strings" "text/template" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" ) //go:embed templates/authoring.tmpl diff --git a/vendor/github.com/google/cel-go/cel/templates/authoring.tmpl b/vendor/cel.dev/cel-go/cel/templates/authoring.tmpl similarity index 100% rename from vendor/github.com/google/cel-go/cel/templates/authoring.tmpl rename to vendor/cel.dev/cel-go/cel/templates/authoring.tmpl diff --git a/vendor/cel.dev/cel-go/cel/timestamp_legacy.go b/vendor/cel.dev/cel-go/cel/timestamp_legacy.go new file mode 100644 index 0000000000..a9cea365a9 --- /dev/null +++ b/vendor/cel.dev/cel-go/cel/timestamp_legacy.go @@ -0,0 +1,135 @@ +// Copyright 2026 Google LLC +// +// 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 cel + +import ( + "strconv" + "strings" + "time" + + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" +) + +// timestampLegacyParsingLibrary re-declares the standard overloads affected by strict timestamp +// parsing with the bindings used before strict parsing was introduced. It is configured when +// StrictTimestampParsing(false) is set. +type timestampLegacyParsingLibrary struct{} + +func (timestampLegacyParsingLibrary) CompileOptions() []EnvOption { + return timestampLegacyParsingDeclarations +} + +func (timestampLegacyParsingLibrary) ProgramOptions() []ProgramOption { + return []ProgramOption{} +} + +const ( + // Bounds of the CEL timestamp range: 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + legacyMinUnixTime int64 = -62135596800 + legacyMaxUnixTime int64 = 253402300799 +) + +// legacyStringToTimestamp converts a string to a timestamp the way cel-go did before v0.30.0: +// any string accepted by time.Parse(time.RFC3339, ...) is accepted. +func legacyStringToTimestamp(val ref.Val) ref.Val { + s, ok := val.(types.String) + if !ok { + return types.MaybeNoSuchOverloadErr(val) + } + t, err := time.Parse(time.RFC3339, string(s)) + if err != nil { + return types.NewErr("type conversion error from '%s' to '%s'", types.StringType, types.TimestampType) + } + if t.Unix() < legacyMinUnixTime || t.Unix() > legacyMaxUnixTime { + return types.NewErr("timestamp overflow") + } + return types.Timestamp{Time: t} +} + +// legacyInTimeZone resolves a timezone argument the way cel-go did before v0.31.0: numeric +// offsets of the form [+-]HH:MM are not range checked. +func legacyInTimeZone(ts, tz ref.Val) (time.Time, error) { + t := ts.(types.Timestamp) + val := string(tz.(types.String)) + ind := strings.Index(val, ":") + if ind == -1 { + loc, err := time.LoadLocation(val) + if err != nil { + return time.Time{}, err + } + return t.In(loc), nil + } + hr, err := strconv.Atoi(val[0:ind]) + if err != nil { + return time.Time{}, err + } + min, err := strconv.Atoi(val[ind+1:]) + if err != nil { + return time.Time{}, err + } + var offset int + if val[0] == '-' { + offset = hr*60 - min + } else { + offset = hr*60 + min + } + secondsEastOfUTC := int((time.Duration(offset) * time.Minute).Seconds()) + return t.In(time.FixedZone("", secondsEastOfUTC)), nil +} + +// legacyTimestampAccessor builds a binding for a timestamp accessor with a timezone argument. +func legacyTimestampAccessor(get func(time.Time) int) func(ref.Val, ref.Val) ref.Val { + return func(ts, tz ref.Val) ref.Val { + t, err := legacyInTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(get(t)) + } +} + +func legacyTimezoneOverload(function, overloadID string, get func(time.Time) int) EnvOption { + return Function(function, + MemberOverload(overloadID, []*Type{TimestampType, StringType}, IntType, + BinaryBinding(legacyTimestampAccessor(get)))) +} + +var timestampLegacyParsingDeclarations = []EnvOption{ + Function(overloads.TypeConvertTimestamp, + Overload(overloads.StringToTimestamp, []*Type{StringType}, TimestampType, + UnaryBinding(legacyStringToTimestamp))), + legacyTimezoneOverload(overloads.TimeGetFullYear, overloads.TimestampToYearWithTz, + func(t time.Time) int { return t.Year() }), + legacyTimezoneOverload(overloads.TimeGetMonth, overloads.TimestampToMonthWithTz, + func(t time.Time) int { return int(t.Month()) - 1 }), + legacyTimezoneOverload(overloads.TimeGetDayOfYear, overloads.TimestampToDayOfYearWithTz, + func(t time.Time) int { return t.YearDay() - 1 }), + legacyTimezoneOverload(overloads.TimeGetDayOfMonth, overloads.TimestampToDayOfMonthZeroBasedWithTz, + func(t time.Time) int { return t.Day() - 1 }), + legacyTimezoneOverload(overloads.TimeGetDate, overloads.TimestampToDayOfMonthOneBasedWithTz, + func(t time.Time) int { return t.Day() }), + legacyTimezoneOverload(overloads.TimeGetDayOfWeek, overloads.TimestampToDayOfWeekWithTz, + func(t time.Time) int { return int(t.Weekday()) }), + legacyTimezoneOverload(overloads.TimeGetHours, overloads.TimestampToHoursWithTz, + func(t time.Time) int { return t.Hour() }), + legacyTimezoneOverload(overloads.TimeGetMinutes, overloads.TimestampToMinutesWithTz, + func(t time.Time) int { return t.Minute() }), + legacyTimezoneOverload(overloads.TimeGetSeconds, overloads.TimestampToSecondsWithTz, + func(t time.Time) int { return t.Second() }), + legacyTimezoneOverload(overloads.TimeGetMilliseconds, overloads.TimestampToMillisecondsWithTz, + func(t time.Time) int { return t.Nanosecond() / 1000000 }), +} diff --git a/vendor/github.com/google/cel-go/cel/validator.go b/vendor/cel.dev/cel-go/cel/validator.go similarity index 97% rename from vendor/github.com/google/cel-go/cel/validator.go rename to vendor/cel.dev/cel-go/cel/validator.go index 229defe79e..a6835be0f0 100644 --- a/vendor/github.com/google/cel-go/cel/validator.go +++ b/vendor/cel.dev/cel-go/cel/validator.go @@ -15,15 +15,15 @@ package cel import ( - "context" "fmt" "reflect" "regexp" + "sync" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/env" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/env" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" ) const ( @@ -46,7 +46,17 @@ const ( ) var ( - astValidatorFactories = map[string]ASTValidatorFactory{ + astValidatorFactoriesOnce sync.Once + astValidatorFactoriesMap map[string]ASTValidatorFactory +) + +func astValidatorFactories() map[string]ASTValidatorFactory { + astValidatorFactoriesOnce.Do(initASTValidatorFactories) + return astValidatorFactoriesMap +} + +func initASTValidatorFactories() { + astValidatorFactoriesMap = map[string]ASTValidatorFactory{ nestingLimitValidatorName: func(val *env.Validator) (ASTValidator, error) { limit, err := validatorIntConfig(val, "limit") if err != nil { @@ -81,7 +91,7 @@ var ( return ValidateHomogeneousAggregateLiterals(), nil }, } -) +} // ASTValidatorFactory creates an ASTValidator as configured by the input map type ASTValidatorFactory func(*env.Validator) (ASTValidator, error) @@ -308,13 +318,12 @@ func (v formatValidator) Validate(e *Env, _ ValidatorConfig, a *ast.AST, iss *Is func evalCall(env *Env, call, arg ast.Expr) error { ast := &Ast{impl: ast.NewAST(call, ast.NewSourceInfo(nil))} - prg, err := env.Program(ast) + prg, err := env.Program(ast, BypassAsyncProtection()) if err != nil { return err } - resCh := prg.ConcurrentEval(context.Background(), NoVars()) - res := <-resCh - return res.Err + _, _, err = prg.Eval(NoVars()) + return err } func compileRegex(_ *Env, _, arg ast.Expr) error { diff --git a/vendor/github.com/google/cel-go/checker/BUILD.bazel b/vendor/cel.dev/cel-go/checker/BUILD.bazel similarity index 92% rename from vendor/github.com/google/cel-go/checker/BUILD.bazel rename to vendor/cel.dev/cel-go/checker/BUILD.bazel index 678b412a95..73fc9a57a0 100644 --- a/vendor/github.com/google/cel-go/checker/BUILD.bazel +++ b/vendor/cel.dev/cel-go/checker/BUILD.bazel @@ -18,15 +18,17 @@ go_library( "scopes.go", "types.go", ], - importpath = "github.com/google/cel-go/checker", + importpath = "cel.dev/cel-go/checker", visibility = ["//visibility:public"], deps = [ "//checker/decls:go_default_library", "//common:go_default_library", "//common/ast:go_default_library", "//common/containers:go_default_library", + "//common/cost:go_default_library", "//common/debug:go_default_library", "//common/decls:go_default_library", + "//common/env:go_default_library", "//common/operators:go_default_library", "//common/overloads:go_default_library", "//common/stdlib:go_default_library", @@ -49,6 +51,7 @@ go_test( "cost_test.go", "env_test.go", "format_test.go", + "types_test.go", ], embed = [ ":go_default_library", diff --git a/vendor/github.com/google/cel-go/checker/checker.go b/vendor/cel.dev/cel-go/checker/checker.go similarity index 97% rename from vendor/github.com/google/cel-go/checker/checker.go rename to vendor/cel.dev/cel-go/checker/checker.go index 42d27a4283..bc4e62d128 100644 --- a/vendor/github.com/google/cel-go/checker/checker.go +++ b/vendor/cel.dev/cel-go/checker/checker.go @@ -22,13 +22,13 @@ import ( "slices" "strings" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/containers" - "github.com/google/cel-go/common/decls" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/containers" + "cel.dev/cel-go/common/decls" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) type checker struct { @@ -56,7 +56,7 @@ func Check(parsed *ast.AST, source common.Source, env *Env) (*ast.AST, *common.E AST: ast.NewCheckedAST(parsed, typeMap, refMap), ExprFactory: ast.NewExprFactory(), env: env, - errors: &typeErrors{errs: errs}, + errors: &typeErrors{errs: errs, env: env}, mappings: newMapping(), freeTypeVarCounter: 0, } @@ -152,6 +152,10 @@ func (c *checker) checkSelect(e ast.Expr) { e.SetKindCase(c.NewIdent(e.ID(), name)) return } + if c.errors.checkUndeclaredIdent(c.env, e.ID(), c.location(e), qualifiers...) { + c.setType(e, types.ErrorType) + return + } } resultType := c.checkSelectField(e, sel.Operand(), sel.FieldName(), false) @@ -307,6 +311,10 @@ func (c *checker) checkCall(e ast.Expr) { c.resolveOverloadOrError(e, fn, nil, args) return } + if c.errors.checkUndeclaredFunction(c.env, e.ID(), c.location(e), qualifiedPrefix, fnName) { + c.setType(e, types.ErrorType) + return + } } // Regular instance call. @@ -638,23 +646,11 @@ func (c *checker) newTypeVar() *types.Type { } func (c *checker) isAssignable(t1, t2 *types.Type) bool { - subs := isAssignable(c.mappings, t1, t2) - if subs != nil { - c.mappings = subs - return true - } - - return false + return isAssignable(c.mappings, t1, t2) } func (c *checker) isAssignableList(l1, l2 []*types.Type) bool { - subs := isAssignableList(c.mappings, l1, l2) - if subs != nil { - c.mappings = subs - return true - } - - return false + return isAssignableList(c.mappings, l1, l2) } func maybeUnwrapString(e ast.Expr) (string, bool) { diff --git a/vendor/cel.dev/cel-go/checker/cost.go b/vendor/cel.dev/cel-go/checker/cost.go new file mode 100644 index 0000000000..00a1151137 --- /dev/null +++ b/vendor/cel.dev/cel-go/checker/cost.go @@ -0,0 +1,115 @@ +// Copyright 2022 Google LLC +// +// 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 checker + +import ( + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/cost" + "cel.dev/cel-go/common/types" +) + +type ( + // CostEstimator estimates the sizes of variable length input data and the costs of functions. + // + // Deprecated: use cost.CostEstimator + CostEstimator = cost.Estimator + + // CallEstimate includes a CostEstimate for the call, and an optional estimate of the result object size. + // + // Deprecated: use cost.CallEstimate + CallEstimate = cost.CallEstimate + + // AstNode represents an AST node for the purpose of cost estimations. + // + // Deprecated: use cost.AstNode + AstNode = cost.AstNode + + // SizeEstimate represents an estimated size of a variable length string, bytes, map or list. + // + // Deprecated: use cost.SizeEstimate + SizeEstimate = cost.SizeEstimate + + // CostEstimate represents an estimated cost range and provides add and multiply operations + // that do not overflow. + // + // Deprecated: use cost.CostEstimate + CostEstimate = cost.CostEstimate + + // CostOption configures flags which affect cost computations. + // + // Deprecated: use cost.CostOption + CostOption = cost.CostOption + + // FunctionEstimator provides a CallEstimate given the target and arguments for a specific function, overload pair. + // + // Deprecated: use cost.FunctionEstimator + FunctionEstimator = cost.FunctionEstimator +) + +// UnknownSizeEstimate returns a size between 0 and max uint. +// +// Deprecated: use cost.UnknownSizeEstimate +func UnknownSizeEstimate() SizeEstimate { + return cost.UnknownSizeEstimate() +} + +// FixedSizeEstimate returns a size estimate with a fixed min and max range. +// +// Deprecated: use cost.FixedSizeEstimate +func FixedSizeEstimate(size uint64) SizeEstimate { + return cost.FixedSizeEstimate(size) +} + +// UnknownCostEstimate returns a cost with an unknown impact. +// +// Deprecated: use cost.UnknownCostEstimate +func UnknownCostEstimate() CostEstimate { + return cost.UnknownCostEstimate() +} + +// FixedCostEstimate returns a cost with a fixed min and max range. +// +// Deprecated: use cost.FixedCostEstimate +func FixedCostEstimate(fixedCost uint64) CostEstimate { + return cost.FixedCostEstimate(fixedCost) +} + +// PresenceTestHasCost determines whether presence testing has a cost of one or zero. +// +// Deprecated: use cost.PresenceTestHasCost +func PresenceTestHasCost(hasCost bool) CostOption { + return cost.PresenceTestHasCost(hasCost) +} + +// OverloadCostEstimate binds a FunctionEstimator to a specific function overload ID. +// +// Deprecated: use cost.OverloadCostEstimate +func OverloadCostEstimate(overloadID string, functionCoster FunctionEstimator) CostOption { + return cost.OverloadCostEstimate(overloadID, functionCoster) +} + +// NewAstNode creates a new AstNode for cost estimation. +// +// Deprecated: use cost.NewAstNode +func NewAstNode(expr ast.Expr, path []string, t *types.Type, derivedSize *SizeEstimate) AstNode { + return cost.NewAstNode(expr, path, t, derivedSize) +} + +// Cost estimates the cost of the parsed and type checked CEL expression. +// +// Deprecated: use cost.Cost +func Cost(checked *ast.AST, estimator CostEstimator, opts ...CostOption) (CostEstimate, error) { + return cost.Cost(checked, estimator, opts...) +} diff --git a/vendor/github.com/google/cel-go/checker/decls/BUILD.bazel b/vendor/cel.dev/cel-go/checker/decls/BUILD.bazel similarity index 89% rename from vendor/github.com/google/cel-go/checker/decls/BUILD.bazel rename to vendor/cel.dev/cel-go/checker/decls/BUILD.bazel index a6b0be292c..fe53801662 100644 --- a/vendor/github.com/google/cel-go/checker/decls/BUILD.bazel +++ b/vendor/cel.dev/cel-go/checker/decls/BUILD.bazel @@ -10,7 +10,7 @@ go_library( srcs = [ "decls.go", ], - importpath = "github.com/google/cel-go/checker/decls", + importpath = "cel.dev/cel-go/checker/decls", deps = [ "@org_golang_google_genproto_googleapis_api//expr/v1alpha1:go_default_library", "@org_golang_google_protobuf//types/known/emptypb:go_default_library", diff --git a/vendor/github.com/google/cel-go/checker/decls/decls.go b/vendor/cel.dev/cel-go/checker/decls/decls.go similarity index 100% rename from vendor/github.com/google/cel-go/checker/decls/decls.go rename to vendor/cel.dev/cel-go/checker/decls/decls.go diff --git a/vendor/github.com/google/cel-go/checker/env.go b/vendor/cel.dev/cel-go/checker/env.go similarity index 90% rename from vendor/github.com/google/cel-go/checker/env.go rename to vendor/cel.dev/cel-go/checker/env.go index 9c3de9517b..8acf806f0b 100644 --- a/vendor/github.com/google/cel-go/checker/env.go +++ b/vendor/cel.dev/cel-go/checker/env.go @@ -17,12 +17,14 @@ package checker import ( "fmt" "strings" - - "github.com/google/cel-go/common/containers" - "github.com/google/cel-go/common/decls" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/parser" + "sync" + + "cel.dev/cel-go/common/containers" + "cel.dev/cel-go/common/decls" + "cel.dev/cel-go/common/env" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/parser" ) type aggregateLiteralElementType int @@ -75,6 +77,9 @@ type Env struct { aggLitElemType aggregateLiteralElementType filteredOverloadIDs map[string]struct{} jsonFieldNames bool + catalogSupplier CatalogSupplier + catalogOnce sync.Once + catalog *env.Catalog } // NewEnv returns a new *Env with the given parameters. @@ -106,9 +111,23 @@ func NewEnv(container *containers.Container, provider types.Provider, opts ...Op aggLitElemType: aggLitElemType, filteredOverloadIDs: filteredOverloadIDs, jsonFieldNames: envOptions.jsonFieldNames, + catalogSupplier: envOptions.catalogSupplier, }, nil } +// Catalog returns the symbol catalog configured on the environment, or nil if none is configured. +func (e *Env) Catalog() *env.Catalog { + if e == nil { + return nil + } + e.catalogOnce.Do(func() { + if e.catalog == nil && e.catalogSupplier != nil { + e.catalog = e.catalogSupplier() + } + }) + return e.catalog +} + // AddIdents configures the checker with a list of variable declarations. // // If there are overlapping declarations, the method will error. @@ -320,26 +339,28 @@ func (e *Env) validatedDeclarations() *Scopes { return e.declarations } -// enterScope creates a new Env instance with a new innermost declaration scope. -func (e *Env) enterScope() *Env { - childDecls := e.declarations.Push() +// cloneWithDecls creates a copy of the Env with a new declaration scope stack. +func (e *Env) cloneWithDecls(decls *Scopes) *Env { return &Env{ - declarations: childDecls, - container: e.container, - provider: e.provider, - aggLitElemType: e.aggLitElemType, + container: e.container, + provider: e.provider, + declarations: decls, + aggLitElemType: e.aggLitElemType, + filteredOverloadIDs: e.filteredOverloadIDs, + jsonFieldNames: e.jsonFieldNames, + catalogSupplier: e.catalogSupplier, + catalog: e.catalog, } } +// enterScope creates a new Env instance with a new innermost declaration scope. +func (e *Env) enterScope() *Env { + return e.cloneWithDecls(e.declarations.Push()) +} + // exitScope creates a new Env instance with the nearest outer declaration scope. func (e *Env) exitScope() *Env { - parentDecls := e.declarations.Pop() - return &Env{ - declarations: parentDecls, - container: e.container, - provider: e.provider, - aggLitElemType: e.aggLitElemType, - } + return e.cloneWithDecls(e.declarations.Pop()) } // errorMsg is a type alias meant to represent error-based return values which diff --git a/vendor/github.com/google/cel-go/checker/errors.go b/vendor/cel.dev/cel-go/checker/errors.go similarity index 54% rename from vendor/github.com/google/cel-go/checker/errors.go rename to vendor/cel.dev/cel-go/checker/errors.go index 3535440baa..970e7f420c 100644 --- a/vendor/github.com/google/cel-go/checker/errors.go +++ b/vendor/cel.dev/cel-go/checker/errors.go @@ -15,14 +15,26 @@ package checker import ( - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/types" + "fmt" + "strings" + + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/env" + "cel.dev/cel-go/common/types" ) // typeErrors is a specialization of Errors. type typeErrors struct { errs *common.Errors + env *Env +} + +func (e *typeErrors) getCatalog() *env.Catalog { + if e == nil || e.env == nil { + return nil + } + return e.env.Catalog() } func (e *typeErrors) fieldTypeMismatch(id int64, l common.Location, name string, field, value *types.Type) { @@ -54,7 +66,11 @@ func (e *typeErrors) notAnOptionalFieldSelection(id int64, l common.Location, fi } func (e *typeErrors) notAType(id int64, l common.Location, typeName string) { - e.errs.ReportErrorAtID(id, l, "'%s' is not a type", typeName) + suggestion := "" + if cat := e.getCatalog(); cat != nil { + suggestion = formatSuggestionSuffix(typeName, cat.Find(typeName)) + } + e.errs.ReportErrorAtID(id, l, "'%s' is not a type%s", typeName, suggestion) } func (e *typeErrors) notAMessageType(id int64, l common.Location, typeName string) { @@ -80,7 +96,86 @@ func (e *typeErrors) undefinedField(id int64, l common.Location, field string) { } func (e *typeErrors) undeclaredReference(id int64, l common.Location, container string, name string) { - e.errs.ReportErrorAtID(id, l, "undeclared reference to '%s' (in container '%s')", name, container) + var syms []*env.CatalogSymbol + if cat := e.getCatalog(); cat != nil { + syms = cat.Find(name) + } + e.undeclaredReferenceWithSymbols(id, l, container, name, syms) +} + +func (e *typeErrors) undeclaredReferenceWithSymbols(id int64, l common.Location, container string, name string, syms []*env.CatalogSymbol) { + containerSuffix := "" + if container != "" { + containerSuffix = fmt.Sprintf(" (in container '%s')", container) + } + suggestion := formatSuggestionSuffix(name, syms) + e.errs.ReportErrorAtID(id, l, "undeclared reference to '%s'%s%s", name, containerSuffix, suggestion) +} + +func (e *typeErrors) checkUndeclaredIdent(env *Env, id int64, l common.Location, qualifiers ...string) bool { + if len(qualifiers) <= 1 || e.hasDeclaredPrefix(env, qualifiers[:len(qualifiers)-1]...) { + return false + } + return e.checkUndeclaredReference(env, id, l, strings.Join(qualifiers, ".")) +} + +func (e *typeErrors) checkUndeclaredFunction(env *Env, id int64, l common.Location, qualifiedPrefix, fnName string) bool { + prefixParts := strings.Split(qualifiedPrefix, ".") + if e.hasDeclaredPrefix(env, prefixParts...) { + return false + } + return e.checkUndeclaredReference(env, id, l, qualifiedPrefix+"."+fnName) +} + +func (e *typeErrors) checkUndeclaredReference(env *Env, id int64, l common.Location, qualifiedName string) bool { + if env == nil { + return false + } + cat := env.Catalog() + if cat == nil { + return false + } + syms := cat.Find(qualifiedName) + if len(syms) == 0 { + return false + } + container := "" + if env.container != nil { + container = env.container.Name() + } + e.undeclaredReferenceWithSymbols(id, l, container, qualifiedName, syms) + return true +} + +func (e *typeErrors) hasDeclaredPrefix(env *Env, qualifierPrefixes ...string) bool { + if env == nil { + return false + } + for i := 1; i <= len(qualifierPrefixes); i++ { + if env.resolveQualifiedIdent(qualifierPrefixes[:i]...) != nil { + return true + } + } + return false +} + +func formatSuggestionSuffix(name string, syms []*env.CatalogSymbol) string { + if len(syms) == 0 { + return "" + } + if len(syms) == 1 && syms[0].Name == name { + if syms[0].Option != "" { + return fmt.Sprintf(" (enable with `%s`)", syms[0].Option) + } + return "" + } + if len(syms) == 1 { + if syms[0].Option != "" { + return fmt.Sprintf(" (did you mean '%s'?, enable with `%s`)", syms[0].Name, syms[0].Option) + } + return fmt.Sprintf(" (did you mean '%s'?)", syms[0].Name) + } + return fmt.Sprintf(" (did you mean '%s' or '%s'?)", syms[0].Name, syms[1].Name) } func (e *typeErrors) unexpectedFailedResolution(id int64, l common.Location, typeName string) { diff --git a/vendor/github.com/google/cel-go/checker/format.go b/vendor/cel.dev/cel-go/checker/format.go similarity index 98% rename from vendor/github.com/google/cel-go/checker/format.go rename to vendor/cel.dev/cel-go/checker/format.go index 95842905e6..17b1a4d24d 100644 --- a/vendor/github.com/google/cel-go/checker/format.go +++ b/vendor/cel.dev/cel-go/checker/format.go @@ -18,8 +18,8 @@ import ( "fmt" "strings" - chkdecls "github.com/google/cel-go/checker/decls" - "github.com/google/cel-go/common/types" + chkdecls "cel.dev/cel-go/checker/decls" + "cel.dev/cel-go/common/types" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" ) diff --git a/vendor/github.com/google/cel-go/checker/mapping.go b/vendor/cel.dev/cel-go/checker/mapping.go similarity index 54% rename from vendor/github.com/google/cel-go/checker/mapping.go rename to vendor/cel.dev/cel-go/checker/mapping.go index 8163a908a5..2fd506ea5d 100644 --- a/vendor/github.com/google/cel-go/checker/mapping.go +++ b/vendor/cel.dev/cel-go/checker/mapping.go @@ -15,11 +15,21 @@ package checker import ( - "github.com/google/cel-go/common/types" + "cel.dev/cel-go/common/types" ) type mapping struct { mapping map[string]*types.Type + // undo records what each add replaced while an attempt is in progress, + // so that a failed attempt can be rolled back. + undo []undoEntry + recording bool +} + +type undoEntry struct { + key string + prev *types.Type + had bool } func newMapping() *mapping { @@ -29,7 +39,32 @@ func newMapping() *mapping { } func (m *mapping) add(from, to *types.Type) { - m.mapping[FormatCELType(from)] = to + key := FormatCELType(from) + if m.recording { + prev, had := m.mapping[key] + m.undo = append(m.undo, undoEntry{key, prev, had}) + } + m.mapping[key] = to +} + +// attempt runs f against m in place, rolling back what f added if it reports +// false. Attempts do not nest. +func (m *mapping) attempt(f func() bool) bool { + m.recording = true + ok := f() + m.recording = false + if !ok { + for i := len(m.undo) - 1; i >= 0; i-- { + e := m.undo[i] + if e.had { + m.mapping[e.key] = e.prev + } else { + delete(m.mapping, e.key) + } + } + } + m.undo = m.undo[:0] + return ok } func (m *mapping) find(from *types.Type) (*types.Type, bool) { @@ -38,12 +73,3 @@ func (m *mapping) find(from *types.Type) (*types.Type, bool) { } return nil, false } - -func (m *mapping) copy() *mapping { - c := newMapping() - - for k, v := range m.mapping { - c.mapping[k] = v - } - return c -} diff --git a/vendor/github.com/google/cel-go/checker/options.go b/vendor/cel.dev/cel-go/checker/options.go similarity index 80% rename from vendor/github.com/google/cel-go/checker/options.go rename to vendor/cel.dev/cel-go/checker/options.go index 10d3bcbc0a..2fae7acd5d 100644 --- a/vendor/github.com/google/cel-go/checker/options.go +++ b/vendor/cel.dev/cel-go/checker/options.go @@ -14,16 +14,32 @@ package checker +import ( + "cel.dev/cel-go/common/env" +) + +// CatalogSupplier returns a Catalog of symbols. +type CatalogSupplier func() *env.Catalog + type options struct { crossTypeNumericComparisons bool homogeneousAggregateLiterals bool validatedDeclarations *Scopes jsonFieldNames bool + catalogSupplier CatalogSupplier } // Option is a functional option for configuring the type-checker type Option func(*options) error +// Catalog configures the checker with a symbol catalog supplier used for error suggestions and refinement. +func Catalog(cat CatalogSupplier) Option { + return func(opts *options) error { + opts.catalogSupplier = cat + return nil + } +} + // CrossTypeNumericComparisons toggles type-checker support for numeric comparisons across type // See https://github.com/google/cel-spec/wiki/proposal-210 for more details. func CrossTypeNumericComparisons(enabled bool) Option { @@ -49,4 +65,3 @@ func JSONFieldNames(enabled bool) Option { return nil } } - diff --git a/vendor/github.com/google/cel-go/checker/printer.go b/vendor/cel.dev/cel-go/checker/printer.go similarity index 95% rename from vendor/github.com/google/cel-go/checker/printer.go rename to vendor/cel.dev/cel-go/checker/printer.go index 7a3984f02c..c90711e4ca 100644 --- a/vendor/github.com/google/cel-go/checker/printer.go +++ b/vendor/cel.dev/cel-go/checker/printer.go @@ -17,8 +17,8 @@ package checker import ( "sort" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/debug" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/debug" ) type semanticAdorner struct { diff --git a/vendor/github.com/google/cel-go/checker/scopes.go b/vendor/cel.dev/cel-go/checker/scopes.go similarity index 99% rename from vendor/github.com/google/cel-go/checker/scopes.go rename to vendor/cel.dev/cel-go/checker/scopes.go index 2fcfdf29e2..88b664af6b 100644 --- a/vendor/github.com/google/cel-go/checker/scopes.go +++ b/vendor/cel.dev/cel-go/checker/scopes.go @@ -17,7 +17,7 @@ package checker import ( "strings" - "github.com/google/cel-go/common/decls" + "cel.dev/cel-go/common/decls" ) // Scopes represents nested Decl sets where the Scopes value contains a Groups containing all diff --git a/vendor/github.com/google/cel-go/checker/types.go b/vendor/cel.dev/cel-go/checker/types.go similarity index 81% rename from vendor/github.com/google/cel-go/checker/types.go rename to vendor/cel.dev/cel-go/checker/types.go index 4c65b2737c..01d858d81b 100644 --- a/vendor/github.com/google/cel-go/checker/types.go +++ b/vendor/cel.dev/cel-go/checker/types.go @@ -15,7 +15,7 @@ package checker import ( - "github.com/google/cel-go/common/types" + "cel.dev/cel-go/common/types" ) // isDyn returns true if the input t is either type DYN or a well-known ANY message. @@ -90,12 +90,35 @@ func isEqualOrLessSpecific(t1, t2 *types.Type) bool { return isEqualOrLessSpecific(t1.Parameters()[0], t2.Parameters()[0]) && isEqualOrLessSpecific(t1.Parameters()[1], t2.Parameters()[1]) case types.TypeKind: - return true + p1Len, p2Len := len(t1.Parameters()), len(t2.Parameters()) + if p1Len > 0 && p2Len > 0 { + if p1Len != p2Len { + return false + } + return isEqualOrLessSpecific(t1.Parameters()[0], t2.Parameters()[0]) + } + return p1Len == 0 default: return t1.IsExactType(t2) } } +// hasTypeParam returns true if the type is a type parameter or contains any type parameters directly or transitively. +func hasTypeParam(t *types.Type) bool { + if t == nil { + return false + } + if t.Kind() == types.TypeParamKind { + return true + } + for _, param := range t.Parameters() { + if hasTypeParam(param) { + return true + } + } + return false +} + // / internalIsAssignable returns true if t1 is assignable to t2. func internalIsAssignable(m *mapping, t1, t2 *types.Type) bool { // Process type parameters. @@ -143,7 +166,28 @@ func internalIsAssignable(m *mapping, t1, t2 *types.Type) bool { // Struct types. return t2.IsAssignableType(t1) case types.TypeKind: - return kind2 == types.TypeKind + if kind2 != types.TypeKind { + return false + } + p1Len, p2Len := len(t1.Parameters()), len(t2.Parameters()) + if p1Len == 0 || p2Len == 0 { + return p2Len == 0 + } + if p1Len != p2Len { + return false + } + fromType := t1.Parameters()[0] + toType := t2.Parameters()[0] + // If either type contains a type parameter (e.g., type(T) in foo(data, type(T)) -> T), + // delegate to inner type unification to bind or validate type parameter substitutions. + // Returns true if the inner types structurally match, unify with an unbound type param, + // or conform to an existing binding in 'm'. Returns false on structural/kind mismatches + // (e.g., int vs list(T)), occurs-check cycles, or conflicting type param bindings. + if hasTypeParam(fromType) || hasTypeParam(toType) { + return internalIsAssignable(m, fromType, toType) + } + // Concrete types are coassignable in CEL (e.g., type(1) == type("a"), type([1]) == list). + return true case types.OpaqueKind, types.ListKind, types.MapKind: return t1.Kind() == t2.Kind() && t1.TypeName() == t2.TypeName() && internalIsAssignableList(m, t1.Parameters(), t2.Parameters()) @@ -219,22 +263,16 @@ func isLegacyNullable(t *types.Type) bool { return false } -// isAssignable returns an updated type substitution mapping if t1 is assignable to t2. -func isAssignable(m *mapping, t1, t2 *types.Type) *mapping { - mCopy := m.copy() - if internalIsAssignable(mCopy, t1, t2) { - return mCopy - } - return nil +// isAssignable reports whether t1 is assignable to t2, adding the substitutions that make it so +// to m. If t1 is not assignable to t2, m is left as it was. +func isAssignable(m *mapping, t1, t2 *types.Type) bool { + return m.attempt(func() bool { return internalIsAssignable(m, t1, t2) }) } -// isAssignableList returns an updated type substitution mapping if l1 is assignable to l2. -func isAssignableList(m *mapping, l1, l2 []*types.Type) *mapping { - mCopy := m.copy() - if internalIsAssignableList(mCopy, l1, l2) { - return mCopy - } - return nil +// isAssignableList reports whether l1 is assignable to l2, adding the substitutions that make it +// so to m. If l1 is not assignable to l2, m is left as it was. +func isAssignableList(m *mapping, l1, l2 []*types.Type) bool { + return m.attempt(func() bool { return internalIsAssignableList(m, l1, l2) }) } // mostGeneral returns the more general of two types which are known to unify. diff --git a/vendor/github.com/google/cel-go/common/BUILD.bazel b/vendor/cel.dev/cel-go/common/BUILD.bazel similarity index 93% rename from vendor/github.com/google/cel-go/common/BUILD.bazel rename to vendor/cel.dev/cel-go/common/BUILD.bazel index 1b1b7914d6..4088884722 100644 --- a/vendor/github.com/google/cel-go/common/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/BUILD.bazel @@ -15,7 +15,7 @@ go_library( "location.go", "source.go", ], - importpath = "github.com/google/cel-go/common", + importpath = "cel.dev/cel-go/common", deps = [ "//common/runes:go_default_library", "@org_golang_google_genproto_googleapis_api//expr/v1alpha1:go_default_library", diff --git a/vendor/github.com/google/cel-go/common/ast/BUILD.bazel b/vendor/cel.dev/cel-go/common/ast/BUILD.bazel similarity index 95% rename from vendor/github.com/google/cel-go/common/ast/BUILD.bazel rename to vendor/cel.dev/cel-go/common/ast/BUILD.bazel index 9824f57a9f..036d7eb8e9 100644 --- a/vendor/github.com/google/cel-go/common/ast/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/ast/BUILD.bazel @@ -10,11 +10,12 @@ go_library( srcs = [ "ast.go", "conversion.go", + "equiv.go", "expr.go", "factory.go", "navigable.go", ], - importpath = "github.com/google/cel-go/common/ast", + importpath = "cel.dev/cel-go/common/ast", deps = [ "//common:go_default_library", "//common/types:go_default_library", @@ -31,6 +32,7 @@ go_test( srcs = [ "ast_test.go", "conversion_test.go", + "equiv_test.go", "expr_test.go", "navigable_test.go", ], diff --git a/vendor/github.com/google/cel-go/common/ast/ast.go b/vendor/cel.dev/cel-go/common/ast/ast.go similarity index 98% rename from vendor/github.com/google/cel-go/common/ast/ast.go rename to vendor/cel.dev/cel-go/common/ast/ast.go index c8f8f8a022..d8e84713a4 100644 --- a/vendor/github.com/google/cel-go/common/ast/ast.go +++ b/vendor/cel.dev/cel-go/common/ast/ast.go @@ -18,9 +18,9 @@ package ast import ( "slices" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // AST contains a protobuf expression and source info along with CEL-native type and reference information. @@ -452,7 +452,9 @@ func (s *SourceInfo) Extensions() []Extension { // at least as great as the lowest minor version specified. func (s *SourceInfo) HasExtension(id string, minVersion ExtensionVersion) bool { for _, ext := range s.Extensions() { - return ext.ID == id && ext.Version.Major == minVersion.Major && ext.Version.Minor >= minVersion.Minor + if ext.ID == id && ext.Version.Major == minVersion.Major && ext.Version.Minor >= minVersion.Minor { + return true + } } return false } @@ -462,6 +464,11 @@ func (s *SourceInfo) AddExtension(ext Extension) { if s == nil { return } + for _, e := range s.extensions { + if e.ID == ext.ID && e.Version == ext.Version && slices.Equal(e.Components, ext.Components) { + return + } + } s.extensions = append(s.extensions, ext) } diff --git a/vendor/github.com/google/cel-go/common/ast/conversion.go b/vendor/cel.dev/cel-go/common/ast/conversion.go similarity index 99% rename from vendor/github.com/google/cel-go/common/ast/conversion.go rename to vendor/cel.dev/cel-go/common/ast/conversion.go index 380f8c1181..5d032cc1df 100644 --- a/vendor/github.com/google/cel-go/common/ast/conversion.go +++ b/vendor/cel.dev/cel-go/common/ast/conversion.go @@ -19,8 +19,8 @@ import ( "google.golang.org/protobuf/proto" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" celpb "cel.dev/expr" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" diff --git a/vendor/cel.dev/cel-go/common/ast/equiv.go b/vendor/cel.dev/cel-go/common/ast/equiv.go new file mode 100644 index 0000000000..3f5b9edce2 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/ast/equiv.go @@ -0,0 +1,459 @@ +// Copyright 2024 Google LLC +// +// 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 ast + +import ( + "math" + "slices" + + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" +) + +// EquivOption configures the structural equivalence comparison between ASTs or expressions. +type EquivOption func(*equivOptions) + +// EquivTypes configures the type maps to use for validating type equivalence between two expressions or ASTs. +func EquivTypes(aTypes, bTypes map[int64]*types.Type) EquivOption { + return func(opts *equivOptions) { + opts.aTypes = aTypes + opts.bTypes = bTypes + opts.checkTypes = aTypes != nil || bTypes != nil + } +} + +// EquivReferences configures the reference maps to use for validating reference equivalence between two expressions or ASTs. +func EquivReferences(aRefs, bRefs map[int64]*ReferenceInfo) EquivOption { + return func(opts *equivOptions) { + opts.aRefs = aRefs + opts.bRefs = bRefs + opts.checkRefs = aRefs != nil || bRefs != nil + } +} + +// EquivIgnoreIdentifiers configures whether comprehension variable names (accuVar, iterVar, iterVar2) +// should be ignored during equivalence comparison. +func EquivIgnoreIdentifiers(enabled ...bool) EquivOption { + return func(opts *equivOptions) { + if len(enabled) == 0 { + opts.ignoreIdentifiers = true + return + } + opts.ignoreIdentifiers = enabled[0] + } +} + +// EquivMacroCalls configures whether to compare expressions by their macro call metadata +// if present, rather than their expanded AST representation. +func EquivMacroCalls(enabled ...bool) EquivOption { + return func(opts *equivOptions) { + if len(enabled) == 0 { + opts.checkMacros = true + return + } + opts.checkMacros = enabled[0] + } +} + +// EquivMacros configures the macro call maps to use for validating macro call equivalence between two expressions or ASTs. +func EquivMacros(aMacros, bMacros map[int64]Expr) EquivOption { + return func(opts *equivOptions) { + opts.aMacros = aMacros + opts.bMacros = bMacros + opts.checkMacros = aMacros != nil || bMacros != nil + } +} + +type equivOptions struct { + aTypes map[int64]*types.Type + bTypes map[int64]*types.Type + aRefs map[int64]*ReferenceInfo + bRefs map[int64]*ReferenceInfo + aMacros map[int64]Expr + bMacros map[int64]Expr + checkTypes bool + checkRefs bool + checkMacros bool + ignoreIdentifiers bool +} + +// EquivAST determines whether two ASTs are structurally equivalent. +// +// The comparison ignores numeric IDs except for resolving references and types. +// If both inputs are *AST instances, type and reference metadata are automatically +// compared if present. +// +// Note: expressions may be functionally equivalent, but not structurally equivalent. +// Proof of functional equivalence may be checked using the cel-java formal verification +// package (https://github.com/google/cel-java/blob/develop/optimizer/src/main/java/dev/cel/optimizer/verifier/README.md). +func EquivAST(a, b *AST, opts ...EquivOption) bool { + if a == nil || b == nil { + return a == b + } + optState := &equivOptions{ + aTypes: a.TypeMap(), + bTypes: b.TypeMap(), + aRefs: a.ReferenceMap(), + bRefs: b.ReferenceMap(), + aMacros: a.SourceInfo().MacroCalls(), + bMacros: b.SourceInfo().MacroCalls(), + checkTypes: a.IsChecked() || b.IsChecked(), + checkRefs: len(a.ReferenceMap()) > 0 || len(b.ReferenceMap()) > 0, + } + + for _, opt := range opts { + opt(optState) + } + + state := &equivState{equivOptions: optState} + return state.exprEquiv(a.Expr(), b.Expr()) +} + +// EquivExpr determines whether two expressions are structurally equivalent. +// +// The comparison ignores numeric IDs except for resolving references and types +// if options are provided. +func EquivExpr(a, b Expr, opts ...EquivOption) bool { + optState := &equivOptions{} + for _, opt := range opts { + opt(optState) + } + state := &equivState{equivOptions: optState} + return state.exprEquiv(a, b) +} + +// Equiv returns true if two ASTs are structurally equivalent. +// +// If the ASTs are type-checked, type and reference information will be compared by default. +// Options can be supplied to customize type or reference comparison. +func (a *AST) Equiv(other *AST, opts ...EquivOption) bool { + return EquivAST(a, other, opts...) +} + +type equivState struct { + *equivOptions + ignored1 []string + ignored2 []string +} + +func (s *equivState) pushIgnored(comp1, comp2 ComprehensionExpr) int { + prev := len(s.ignored1) + if comp1.IterVar() != "" { + s.ignored1 = append(s.ignored1, comp1.IterVar()) + } + if comp1.HasIterVar2() { + s.ignored1 = append(s.ignored1, comp1.IterVar2()) + } + if comp1.AccuVar() != "" { + s.ignored1 = append(s.ignored1, comp1.AccuVar()) + } + + if comp2.IterVar() != "" { + s.ignored2 = append(s.ignored2, comp2.IterVar()) + } + if comp2.HasIterVar2() { + s.ignored2 = append(s.ignored2, comp2.IterVar2()) + } + if comp2.AccuVar() != "" { + s.ignored2 = append(s.ignored2, comp2.AccuVar()) + } + return prev +} + +func (s *equivState) popIgnored(prev int) { + s.ignored1 = s.ignored1[:prev] + s.ignored2 = s.ignored2[:prev] +} + +func (s *equivState) isIgnored(name1, name2 string) bool { + idx1 := lastIgnored(s.ignored1, name1) + idx2 := lastIgnored(s.ignored2, name2) + if idx1 >= 0 || idx2 >= 0 { + return idx1 == idx2 + } + return name1 == name2 +} + +func lastIgnored(stack []string, name string) int { + for i, s := range slices.Backward(stack) { + if s == name { + return i + } + } + return -1 +} + +func (s *equivState) exprEquiv(e1, e2 Expr) bool { + if e1 == nil || e2 == nil { + return e1 == e2 + } + if !s.typeAndRefEquiv(e1.ID(), e2.ID()) { + return false + } + if s.checkMacros { + m1, found1 := s.aMacros[e1.ID()] + m2, found2 := s.bMacros[e2.ID()] + if found1 != found2 { + return false + } + if found1 { + return s.exprEquiv(m1, m2) + } + } + if e1.Kind() != e2.Kind() { + return false + } + switch e1.Kind() { + case UnspecifiedExprKind: + return true + case IdentKind: + name1 := e1.AsIdent() + name2 := e2.AsIdent() + if s.ignoreIdentifiers { + return s.isIgnored(name1, name2) + } + return name1 == name2 + case LiteralKind: + return equivLiteral(e1.AsLiteral(), e2.AsLiteral()) + case SelectKind: + s1 := e1.AsSelect() + s2 := e2.AsSelect() + if s1.IsTestOnly() != s2.IsTestOnly() { + return false + } + if s1.FieldName() != s2.FieldName() { + return false + } + return s.exprEquiv(s1.Operand(), s2.Operand()) + case CallKind: + c1 := e1.AsCall() + c2 := e2.AsCall() + if c1.FunctionName() != c2.FunctionName() || c1.IsMemberFunction() != c2.IsMemberFunction() { + return false + } + args1 := c1.Args() + args2 := c2.Args() + if len(args1) != len(args2) { + return false + } + if c1.IsMemberFunction() { + if !s.exprEquiv(c1.Target(), c2.Target()) { + return false + } + } + + for i := range args1 { + if !s.exprEquiv(args1[i], args2[i]) { + return false + } + } + return true + case ListKind: + l1 := e1.AsList() + l2 := e2.AsList() + if l1.Size() != l2.Size() { + return false + } + if len(l1.OptionalIndices()) != len(l2.OptionalIndices()) { + return false + } + elems1 := l1.Elements() + elems2 := l2.Elements() + for i := range elems1 { + if l1.IsOptional(int32(i)) != l2.IsOptional(int32(i)) { + return false + } + if !s.exprEquiv(elems1[i], elems2[i]) { + return false + } + } + return true + case MapKind: + m1 := e1.AsMap() + m2 := e2.AsMap() + if m1.Size() != m2.Size() { + return false + } + entries1 := m1.Entries() + entries2 := m2.Entries() + for i := range entries1 { + if !s.entryExprEquiv(entries1[i], entries2[i]) { + return false + } + } + return true + case StructKind: + st1 := e1.AsStruct() + st2 := e2.AsStruct() + if st1.TypeName() != st2.TypeName() { + return false + } + fields1 := st1.Fields() + fields2 := st2.Fields() + if len(fields1) != len(fields2) { + return false + } + for i := range fields1 { + if !s.entryExprEquiv(fields1[i], fields2[i]) { + return false + } + } + return true + case ComprehensionKind: + comp1 := e1.AsComprehension() + comp2 := e2.AsComprehension() + if comp1.HasIterVar2() != comp2.HasIterVar2() { + return false + } + if (comp1.IterVar() == "") != (comp2.IterVar() == "") || + (comp1.AccuVar() == "") != (comp2.AccuVar() == "") { + return false + } + if !s.ignoreIdentifiers { + if comp1.IterVar() != comp2.IterVar() || + comp1.IterVar2() != comp2.IterVar2() || + comp1.AccuVar() != comp2.AccuVar() { + return false + } + } + if !s.exprEquiv(comp1.IterRange(), comp2.IterRange()) || + !s.exprEquiv(comp1.AccuInit(), comp2.AccuInit()) { + return false + } + var prev int + if s.ignoreIdentifiers { + prev = s.pushIgnored(comp1, comp2) + } + equiv := s.exprEquiv(comp1.LoopCondition(), comp2.LoopCondition()) && + s.exprEquiv(comp1.LoopStep(), comp2.LoopStep()) && + s.exprEquiv(comp1.Result(), comp2.Result()) + if s.ignoreIdentifiers { + s.popIgnored(prev) + } + return equiv + default: + return false + } +} + +func (s *equivState) entryExprEquiv(e1, e2 EntryExpr) bool { + if e1 == nil || e2 == nil { + return e1 == e2 + } + if e1.Kind() != e2.Kind() { + return false + } + if !s.typeAndRefEquiv(e1.ID(), e2.ID()) { + return false + } + switch e1.Kind() { + case MapEntryKind: + me1 := e1.AsMapEntry() + me2 := e2.AsMapEntry() + if me1.IsOptional() != me2.IsOptional() { + return false + } + return s.exprEquiv(me1.Key(), me2.Key()) && s.exprEquiv(me1.Value(), me2.Value()) + case StructFieldKind: + sf1 := e1.AsStructField() + sf2 := e2.AsStructField() + if sf1.IsOptional() != sf2.IsOptional() { + return false + } + if sf1.Name() != sf2.Name() { + return false + } + return s.exprEquiv(sf1.Value(), sf2.Value()) + default: + return true + } +} + +func (s *equivState) typeAndRefEquiv(id1, id2 int64) bool { + if s.checkTypes { + t1, found1 := s.aTypes[id1] + t2, found2 := s.bTypes[id2] + if found1 != found2 { + return false + } + if found1 { + if t1 == nil || t2 == nil { + return t1 == t2 + } + if !t1.IsEquivalentType(t2) { + return false + } + } + } + if s.checkRefs { + r1, found1 := s.aRefs[id1] + r2, found2 := s.bRefs[id2] + if found1 != found2 { + return false + } + if found1 && !s.refEquiv(r1, r2) { + return false + } + } + return true +} + +func (s *equivState) refEquiv(r1, r2 *ReferenceInfo) bool { + if r1 == nil || r2 == nil { + return r1 == r2 + } + if s.ignoreIdentifiers { + if !s.isIgnored(r1.Name, r2.Name) { + return false + } + } else if r1.Name != r2.Name { + return false + } + if len(r1.OverloadIDs) != len(r2.OverloadIDs) { + return false + } + if len(r1.OverloadIDs) != 0 { + overloadMap := make(map[string]struct{}, len(r1.OverloadIDs)) + for _, id := range r1.OverloadIDs { + overloadMap[id] = struct{}{} + } + for _, id := range r2.OverloadIDs { + if _, found := overloadMap[id]; !found { + return false + } + } + } + if r1.Value == nil || r2.Value == nil { + return r1.Value == r2.Value + } + return r1.Value.Equal(r2.Value) == types.True +} + +func equivLiteral(l1, l2 ref.Val) bool { + if l1 == nil || l2 == nil { + return l1 == l2 + } + if l1.Type().TypeName() != l2.Type().TypeName() { + return false + } + if d1, ok := l1.(types.Double); ok { + if d2, ok := l2.(types.Double); ok { + if math.IsNaN(float64(d1)) && math.IsNaN(float64(d2)) { + return true + } + } + } + return l1.Equal(l2) == types.True +} diff --git a/vendor/github.com/google/cel-go/common/ast/expr.go b/vendor/cel.dev/cel-go/common/ast/expr.go similarity index 99% rename from vendor/github.com/google/cel-go/common/ast/expr.go rename to vendor/cel.dev/cel-go/common/ast/expr.go index 9f55cb3b9f..459311f0d9 100644 --- a/vendor/github.com/google/cel-go/common/ast/expr.go +++ b/vendor/cel.dev/cel-go/common/ast/expr.go @@ -15,7 +15,7 @@ package ast import ( - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // ExprKind represents the expression node kind. diff --git a/vendor/github.com/google/cel-go/common/ast/factory.go b/vendor/cel.dev/cel-go/common/ast/factory.go similarity index 99% rename from vendor/github.com/google/cel-go/common/ast/factory.go rename to vendor/cel.dev/cel-go/common/ast/factory.go index d4dcde4d94..b83e5555a8 100644 --- a/vendor/github.com/google/cel-go/common/ast/factory.go +++ b/vendor/cel.dev/cel-go/common/ast/factory.go @@ -14,7 +14,7 @@ package ast -import "github.com/google/cel-go/common/types/ref" +import "cel.dev/cel-go/common/types/ref" // ExprFactory interfaces defines a set of methods necessary for building native expression values. type ExprFactory interface { diff --git a/vendor/github.com/google/cel-go/common/ast/navigable.go b/vendor/cel.dev/cel-go/common/ast/navigable.go similarity index 99% rename from vendor/github.com/google/cel-go/common/ast/navigable.go rename to vendor/cel.dev/cel-go/common/ast/navigable.go index 364edfa3af..3a71f865f4 100644 --- a/vendor/github.com/google/cel-go/common/ast/navigable.go +++ b/vendor/cel.dev/cel-go/common/ast/navigable.go @@ -15,8 +15,8 @@ package ast import ( - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // NavigableExpr represents the base navigable expression value with methods to inspect the diff --git a/vendor/github.com/google/cel-go/common/containers/BUILD.bazel b/vendor/cel.dev/cel-go/common/containers/BUILD.bazel similarity index 89% rename from vendor/github.com/google/cel-go/common/containers/BUILD.bazel rename to vendor/cel.dev/cel-go/common/containers/BUILD.bazel index 81197f0641..7def2f256b 100644 --- a/vendor/github.com/google/cel-go/common/containers/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/containers/BUILD.bazel @@ -10,7 +10,7 @@ go_library( srcs = [ "container.go", ], - importpath = "github.com/google/cel-go/common/containers", + importpath = "cel.dev/cel-go/common/containers", deps = [ "//common/ast:go_default_library", ], diff --git a/vendor/github.com/google/cel-go/common/containers/container.go b/vendor/cel.dev/cel-go/common/containers/container.go similarity index 99% rename from vendor/github.com/google/cel-go/common/containers/container.go rename to vendor/cel.dev/cel-go/common/containers/container.go index fcfcdfc3f4..2330e0764f 100644 --- a/vendor/github.com/google/cel-go/common/containers/container.go +++ b/vendor/cel.dev/cel-go/common/containers/container.go @@ -21,7 +21,7 @@ import ( "strings" "unicode" - "github.com/google/cel-go/common/ast" + "cel.dev/cel-go/common/ast" ) var ( diff --git a/vendor/github.com/google/cel-go/common/cost.go b/vendor/cel.dev/cel-go/common/cost.go similarity index 78% rename from vendor/github.com/google/cel-go/common/cost.go rename to vendor/cel.dev/cel-go/common/cost.go index 5e24bd0f47..125b60e06b 100644 --- a/vendor/github.com/google/cel-go/common/cost.go +++ b/vendor/cel.dev/cel-go/common/cost.go @@ -16,25 +16,39 @@ package common const ( // SelectAndIdentCost is the cost of an operation that accesses an identifier or performs a select. + // + // Deprecated: use cost.SelectAndIdentCost SelectAndIdentCost = 1 // ConstCost is the cost of an operation that accesses a constant. + // + // Deprecated: use cost.ConstCost ConstCost = 0 // ListCreateBaseCost is the base cost of any operation that creates a new list. + // + // Deprecated: use cost.ListCreateBaseCost ListCreateBaseCost = 10 // MapCreateBaseCost is the base cost of any operation that creates a new map. + // + // Deprecated: use cost.MapCreateBaseCost MapCreateBaseCost = 30 // StructCreateBaseCost is the base cost of any operation that creates a new struct. + // + // Deprecated: use cost.StructCreateBaseCost StructCreateBaseCost = 40 // StringTraversalCostFactor is multiplied to a length of a string when computing the cost of traversing the entire // string once. + // + // Deprecated: use cost.StringTraversalCostFactor StringTraversalCostFactor = 0.1 - // RegexStringLengthCostFactor is multiplied ot the length of a regex string pattern when computing the cost of + // RegexStringLengthCostFactor is multiplied to the length of a regex string pattern when computing the cost of // applying the regex to a string of unit cost. + // + // Deprecated: use cost.RegexStringLengthCostFactor RegexStringLengthCostFactor = 0.25 ) diff --git a/vendor/cel.dev/cel-go/common/cost/BUILD.bazel b/vendor/cel.dev/cel-go/common/cost/BUILD.bazel new file mode 100644 index 0000000000..5c38b80dcf --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/BUILD.bazel @@ -0,0 +1,67 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +package( + default_visibility = ["//visibility:public"], + licenses = ["notice"], # Apache 2.0 +) + +go_library( + name = "go_default_library", + srcs = [ + "aggregate_strategy.go", + "cost.go", + "default_strategy.go", + "estimator.go", + "helper.go", + "model.go", + "standard.go", + "strategy.go", + "tracker.go", + "validate.go", + "version.go", + ], + importpath = "cel.dev/cel-go/common/cost", + deps = [ + "//common/ast:go_default_library", + "//common/operators:go_default_library", + "//common/overloads:go_default_library", + "//common/types:go_default_library", + "//common/types/ref:go_default_library", + "//common/types/traits:go_default_library", + ], +) + +go_test( + name = "go_default_test", + size = "small", + srcs = [ + "aggregate_strategy_test.go", + "algebra_test.go", + "cost_bounds_test.go", + "cost_test.go", + "default_strategy_test.go", + "length_test.go", + "model_test.go", + "optional_cost_test.go", + "optional_test.go", + "standard_test.go", + "totals_test.go", + "tracker_test.go", + "validate_test.go", + "version_test.go", + ], + embed = [ + ":go_default_library", + ], + deps = [ + "//cel:go_default_library", + "//common/ast:go_default_library", + "//common/decls:go_default_library", + "//common/operators:go_default_library", + "//common/overloads:go_default_library", + "//common/types:go_default_library", + "//common/types/ref:go_default_library", + "//ext:go_default_library", + "//test/proto3pb:go_default_library", + ], +) diff --git a/vendor/cel.dev/cel-go/common/cost/aggregate_strategy.go b/vendor/cel.dev/cel-go/common/cost/aggregate_strategy.go new file mode 100644 index 0000000000..a8e7726182 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/aggregate_strategy.go @@ -0,0 +1,244 @@ +// Copyright 2026 Google LLC +// +// 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 cost + +import ( + "math" + + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" +) + +// AggregateSizingStrategy returns a SizingStrategy that computes recursive size estimates +// by following paths during cost estimation, and calculates actual runtime size using +// AggregateSize during cost tracking. +// +// The strategy pins stringUnitLength to 1, overriding the types package default, so that +// raw character and byte lengths reach the cost model unscaled. This is deliberate: sizing +// strategies report raw dimensions, and cost expressions own the conversion to cost units +// by applying factors such as StringTraversalCostFactor. +// +// Callers may supply additional SizeCalculatorOption values, which are applied after the +// pinned default. +// +// Warning: passing types.SizeCalculatorStringUnitLength with a value other than 1 overrides +// the pinned default and causes string costs to be discounted twice, once by the calculator +// and again by the cost factor in the cost expression. A unit length of 10 combined with +// StringTraversalCostFactor yields an effective 100x discount rather than 10x. +func AggregateSizingStrategy(opts ...types.SizeCalculatorOption) SizingStrategy { + if len(opts) == 0 { + return defaultAggregateSizing + } + defaultOpts := []types.SizeCalculatorOption{types.SizeCalculatorStringUnitLength(1)} + return &aggregateSizingStrategy{calc: types.NewSizeCalculator(append(defaultOpts, opts...)...)} +} + +type aggregateSizingStrategy struct { + calc *types.SizeCalculator +} + +// TrackSize calculates the actual runtime aggregate size of a value during cost tracking. +// +// An optional is 1 plus the aggregate size of the value it holds, and an empty optional is 1, as +// types.Optional reports it; see Optional. +func (a *aggregateSizingStrategy) TrackSize(ctx TrackContext, value ref.Val) (uint64, bool) { + if value == nil { + return 0, false + } + return uint64(a.calc.AggregateSize(value)), true +} + +// EstimateSize computes recursive aggregate size estimates for an AST node during cost estimation. +func (a *aggregateSizingStrategy) EstimateSize(ctx EstimateContext, node AstNode) (SizeEstimate, bool) { + if node == nil { + return SizeEstimate{}, false + } + if sz := node.ComputedSize(); sz != nil { + return *sz, true + } + if node.Expr() != nil && node.Expr().Kind() == ast.LiteralKind { + return FixedSizeEstimate(uint64(a.calc.AggregateSize(node.Expr().AsLiteral()))), true + } + if node.Type() == nil { + return estimateScalarOrFallback(ctx, node) + } + switch node.Type().Kind() { + case types.ListKind: + return estimateAggregateListSize(ctx, node) + case types.MapKind: + return estimateAggregateMapSize(ctx, node) + case types.DynKind, types.AnyKind, types.TypeParamKind: + return estimateAggregateDynSize(ctx, node) + default: + return estimateScalarOrFallback(ctx, node) + } +} + +// estimateAggregateDynSize calculates the aggregate size estimate for a dynamically typed AST node, +// folding nested container hints ("@items", "@keys", "@values") into the aggregate size up to the +// hinted depth. +func estimateAggregateDynSize(ctx EstimateContext, node AstNode) (SizeEstimate, bool) { + if node.Expr() != nil { + switch node.Expr().Kind() { + case ast.ListKind: + return estimateAggregateListSize(ctx, node) + case ast.MapKind: + return estimateAggregateMapSize(ctx, node) + case ast.CallKind: + if call := node.Expr().AsCall(); call.FunctionName() == operators.Conditional { + if u, ok := estimateConditionalSize(ctx, node.Type(), call.Args()); ok { + return u, true + } + } + } + } + var baseSz *SizeEstimate + if sz, ok := estimateScalarOrFallback(ctx, node); ok { + if sz.Elem != nil || sz.Key != nil { + return sz, true + } + baseSz = &sz + } + if len(node.Path()) > 0 { + if elemSz := resolveDynamicChild(ctx, node.Path(), "@items"); elemSz != nil { + if baseSz == nil { + return combineListSize(nil, elemSz) + } + return SizeEstimate{ + Min: min(baseSz.Min, SafeAdd(1, SafeMultiply(baseSz.Min, max(elemSz.Min, 1)))), + Max: max(baseSz.Max, SafeAdd(1, SafeMultiply(baseSz.Max, max(elemSz.Max, 1)))), + Elem: elemSz, + }, true + } + keySz := resolveDynamicChild(ctx, node.Path(), "@keys") + valSz := resolveDynamicChild(ctx, node.Path(), "@values") + if keySz != nil || valSz != nil { + if baseSz == nil { + return combineMapSize(nil, keySz, valSz) + } + minKey, maxKey, keySz := resolveElemBounds(keySz, baseSz.Max > 0) + minVal, maxVal, valSz := resolveElemBounds(valSz, baseSz.Max > 0) + return SizeEstimate{ + Min: min(baseSz.Min, SafeAdd(1, SafeMultiply(baseSz.Min, SafeAdd(minKey, minVal)))), + Max: max(baseSz.Max, SafeAdd(1, SafeMultiply(baseSz.Max, SafeAdd(max(maxKey, 1), max(maxVal, 1))))), + Key: keySz, + Elem: valSz, + }, true + } + } + if baseSz != nil { + return *baseSz, true + } + return SizeEstimate{}, false +} + +// estimateAggregateListSize computes list aggregate size: 1 (header) + listSize * elemSize. +// +// Calls (e.g. `+` or `? :`) already hold aggregate sub-expression sizes. For `+`, 1 is +// deducted to deduplicate headers: (1+L) + (1+R) - 1 = 1+L+R. +// Unhinted variable-width elements default to [1, math.MaxUint64]. +func estimateAggregateListSize(ctx EstimateContext, node AstNode) (SizeEstimate, bool) { + elemType := listElemType(node.Type()) + listSize, elemSize := estimateListExpr(ctx, node, elemType) + + // When node is a call expression, estimateListExpr already evaluated aggregate sizes of sub-expressions. + if node.Expr() != nil && node.Expr().Kind() == ast.CallKind && listSize != nil { + call := node.Expr().AsCall() + if call.FunctionName() == operators.Add && len(call.Args()) == 2 { + // Concatenation of two lists: (1 + left) + (1 + right) = 2 + left + right. + // Subtract 1 to correct for the single resulting list container header. + minVal := max(SafeSubtract(listSize.Min, 1), 1) + maxVal := max(SafeSubtract(listSize.Max, 1), 1) + res := RangedSizeEstimate(minVal, maxVal) + res.Elem = elemSize + return res, true + } + // For other calls (e.g. conditional branches), listSize is already the branch aggregate size. + listSize.Key = nil + return *listSize, true + } + + listSize, elemSize = resolveListSizes(ctx, node, elemType, listSize, elemSize) + // The list length may be unknown (listSize == nil) while elemSize is known—for example, + // when the list has fixed-width primitive elements (e.g. list where elemSize is [1, 1]) + // or when a size hint was provided on the "@items" subpath without a hint on the list itself. + // combineListSize returns an unknown container size [0, MaxUint64] while preserving Elem so + // downstream operations (such as indexing or comprehensions) can still use the known element size. + if listSize == nil { + return combineListSize(nil, elemSize) + } + minElem, maxElem, elemSize := resolveElemBounds(elemSize, listSize.Max > 0) + aggMin := SafeAdd(1, SafeMultiply(listSize.Min, minElem)) + aggMax := SafeAdd(1, SafeMultiply(listSize.Max, maxElem)) + return SizeEstimate{ + Min: aggMin, + Max: aggMax, + Elem: elemSize, + }, true +} + +// estimateAggregateMapSize computes map aggregate size: 1 (header) + mapSize * (keySize + valSize). +// +// Calls (e.g. `? :`) already hold aggregate sub-expression sizes. +// Unhinted variable-width keys/values default to [1, math.MaxUint64]. +func estimateAggregateMapSize(ctx EstimateContext, node AstNode) (SizeEstimate, bool) { + keyType, valType := mapKeyValueTypes(node.Type()) + mapSize, keySize, valSize := estimateMapExpr(ctx, node, keyType, valType) + + // For call expressions (e.g. conditional branches), mapSize is already the branch aggregate size. + if node.Expr() != nil && node.Expr().Kind() == ast.CallKind && mapSize != nil { + return *mapSize, true + } + + mapSize, keySize, valSize = resolveMapSizes(ctx, node, keyType, valType, mapSize, keySize, valSize) + // The map entry count may be unknown (mapSize == nil) while keySize or valSize is known + // (e.g. fixed-width key/value types like int, or hints provided only on "@keys"/"@values"). + // combineMapSize returns an unknown container size while preserving Key and Elem estimates. + if mapSize == nil { + return combineMapSize(nil, keySize, valSize) + } + minKey, maxKey, keySize := resolveElemBounds(keySize, mapSize.Max > 0) + minVal, maxVal, valSize := resolveElemBounds(valSize, mapSize.Max > 0) + entryMin := SafeAdd(minKey, minVal) + entryMax := SafeAdd(maxKey, maxVal) + aggMin := SafeAdd(1, SafeMultiply(mapSize.Min, entryMin)) + aggMax := SafeAdd(1, SafeMultiply(mapSize.Max, entryMax)) + return SizeEstimate{ + Min: aggMin, + Max: aggMax, + Key: keySize, + Elem: valSize, + }, true +} + +// resolveElemBounds returns the [min, max] bounds for a child element/key/value in aggregate size +// calculation. Every value has aggregate size at least 1, so each bound is at least 1 and a +// container's size is at least 1 plus its length. For variable-width elements with no hint +// (sz == nil), the upper bound is math.MaxUint64; if the parent container can be non-empty, sz is +// populated with UnknownSizeEstimate(). +func resolveElemBounds(sz *SizeEstimate, nonEmptyContainer bool) (uint64, uint64, *SizeEstimate) { + if sz != nil { + return max(sz.Min, 1), max(sz.Max, 1), sz + } + if nonEmptyContainer { + u := UnknownSizeEstimate() + sz = &u + } + return 1, math.MaxUint64, sz +} + +var defaultAggregateSizing SizingStrategy = &aggregateSizingStrategy{calc: types.NewSizeCalculator(types.SizeCalculatorStringUnitLength(1))} diff --git a/vendor/cel.dev/cel-go/common/cost/cost.go b/vendor/cel.dev/cel-go/common/cost/cost.go new file mode 100644 index 0000000000..c73fc38bcf --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/cost.go @@ -0,0 +1,483 @@ +// Copyright 2026 Google LLC +// +// 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 cost provides cost estimation, cost tracking, and saturating arithmetic. +// +// Costs and sizes are unsigned 64-bit values where math.MaxUint64 doubles as the representation +// of an unbounded, or unknown, quantity. Every operation in this package saturates at +// math.MaxUint64 rather than wrapping so that an unbounded input remains unbounded through any +// sequence of operations. +package cost + +import ( + "math" + + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" +) + +const ( + // SelectAndIdentCost is the cost of an operation that accesses an identifier or performs a select. + SelectAndIdentCost = 1 + + // ConstCost is the cost of an operation that accesses a constant. + ConstCost = 0 + + // ListCreateBaseCost is the base cost of any operation that creates a new list. + ListCreateBaseCost = 10 + + // MapCreateBaseCost is the base cost of any operation that creates a new map. + MapCreateBaseCost = 30 + + // StructCreateBaseCost is the base cost of any operation that creates a new struct. + StructCreateBaseCost = 40 + + // StringTraversalCostFactor is multiplied to a length of a string when computing the cost of traversing the entire + // string once. + StringTraversalCostFactor = 0.1 + + // RegexStringLengthCostFactor is multiplied to the length of a regex string pattern when computing the cost of + // applying the regex to a string of unit cost. + RegexStringLengthCostFactor = 0.25 +) + +var ( + // CallCostEstimate is the base cost estimate for an O(1) function call. + CallCostEstimate = FixedCostEstimate(1) + + // CallCost is the base cost for an O(1) function call. + CallCost = uint64(1) + + // ListAllocCost is the base cost estimate for allocating a list. + ListAllocCost = FixedCostEstimate(ListCreateBaseCost) + + // StringCostFactor is the cost factor for traversing a string once. + StringCostFactor = StringTraversalCostFactor +) + +// maxUint64AsFloat is the smallest float64 value greater than math.MaxUint64. +// +// Conversion of a float64 to a uint64 is undefined when the value is out of range, so float +// results are compared against this bound before conversion. +var maxUint64AsFloat = math.Ldexp(1.0, 64) + +// SafeAdd returns the sum of the input values, saturating at math.MaxUint64. +func SafeAdd(x, y uint64, rest ...uint64) uint64 { + sum := x + if y > 0 && sum > math.MaxUint64-y { + return math.MaxUint64 + } + sum += y + for _, r := range rest { + if r > 0 && sum > math.MaxUint64-r { + return math.MaxUint64 + } + sum += r + } + return sum +} + +// SafeSubtract returns the difference of x - y, saturating at zero. +// If x is saturated (math.MaxUint64), it remains saturated. +func SafeSubtract(x, y uint64) uint64 { + if x == math.MaxUint64 { + return math.MaxUint64 + } + if x > y { + return x - y + } + return 0 +} + +// SafeMultiply returns the product of the input values, saturating at math.MaxUint64. +func SafeMultiply(x, y uint64) uint64 { + if y != 0 && x > math.MaxUint64/y { + return math.MaxUint64 + } + return x * y +} + +// SafeMultiplyByFactor multiplies a value by a cost factor and returns the nearest integer +// value, rounded up, saturating at math.MaxUint64. +func SafeMultiplyByFactor(x uint64, factor float64) uint64 { + xFloat := float64(x) + if xFloat > 0 && factor > 0 && xFloat > math.MaxUint64/factor { + return math.MaxUint64 + } + return SafeCeil(xFloat * factor) +} + +// SafeCeil returns the smallest integer value greater than or equal to the input, saturating at +// math.MaxUint64 and flooring at zero. +// +// Negative and NaN inputs return zero. +func SafeCeil(x float64) uint64 { + if math.IsNaN(x) || x <= 0 { + return 0 + } + ceil := math.Ceil(x) + if ceil >= maxUint64AsFloat { + return math.MaxUint64 + } + return uint64(ceil) +} + +// SafeTrunc returns the integer part of the input, saturating at math.MaxUint64 and flooring at +// zero. +// +// # Negative inputs return zero, and NaN saturates to max uint64 +// +// Cost trackers which report a truncated cost should prefer this helper over a direct conversion, +// as conversion of an out-of-range float64 to a uint64 is platform-defined. +func SafeTrunc(x float64) uint64 { + if x <= 0 { + return 0 + } + if math.IsNaN(x) || x >= maxUint64AsFloat { + return math.MaxUint64 + } + return uint64(x) +} + +// SafeMultiplyByFactorTrunc multiplies a value by a cost factor and returns the integer part of +// the result, truncated, saturating at math.MaxUint64. +// +// This is the truncating counterpart to SafeMultiplyByFactor, which rounds up. +func SafeMultiplyByFactorTrunc(x uint64, factor float64) uint64 { + xFloat := float64(x) + if xFloat > 0 && factor > 0 && xFloat > math.MaxUint64/factor { + return math.MaxUint64 + } + return SafeTrunc(xFloat * factor) +} + +// SizeEstimate represents an estimated size of a variable length string, bytes, map or list. +type SizeEstimate struct { + // Min is the minimum estimated size (inclusive). + Min uint64 + + // Max is the maximum estimated size (inclusive). + Max uint64 + + // Key indicates the estimated size of a key, set if the size estimate is for a map. + Key *SizeEstimate + + // Elem indicates the estimated size of a value, set if size estimate is for a map or list. + Elem *SizeEstimate +} + +// UnknownSizeEstimate returns a size between 0 and max uint. +func UnknownSizeEstimate() SizeEstimate { + return unknownSizeEstimate +} + +// FixedSizeEstimate returns a size estimate with a fixed min and max range. +func FixedSizeEstimate(size uint64) SizeEstimate { + return SizeEstimate{Min: size, Max: size} +} + +// RangedSizeEstimate returns a size estimate bounded by min and max. +func RangedSizeEstimate(min, max uint64) SizeEstimate { + return SizeEstimate{Min: min, Max: max} +} + +// AtLeastOneSize returns a size estimate with min and max guaranteed to be at least 1. +func AtLeastOneSize(size SizeEstimate) SizeEstimate { + if size.Min == 0 { + size.Min = 1 + } + if size.Max == 0 { + size.Max = 1 + } + return size +} + +// ListSizeEstimate returns a SizeEstimate for a list with the given list length and element size. +func ListSizeEstimate(listSize SizeEstimate, elemSize SizeEstimate) SizeEstimate { + listSize.Key = nil + listSize.Elem = &elemSize + return listSize +} + +// MapSizeEstimate returns a SizeEstimate for a map with the given map size, key size, and value size. +func MapSizeEstimate(mapSize SizeEstimate, keySize SizeEstimate, valSize SizeEstimate) SizeEstimate { + mapSize.Key = &keySize + mapSize.Elem = &valSize + return mapSize +} + +// Add adds to another SizeEstimate and returns the sum. +// If add would result in an uint64 overflow, the result is math.MaxUint64. +func (se SizeEstimate) Add(sizeEstimate SizeEstimate) SizeEstimate { + res := SizeEstimate{ + Min: SafeAdd(se.Min, sizeEstimate.Min), + Max: SafeAdd(se.Max, sizeEstimate.Max), + } + res.Key = mergeSizeEstimatePtr(se.Key, sizeEstimate.Key) + res.Elem = mergeSizeEstimatePtr(se.Elem, sizeEstimate.Elem) + return res +} + +// Subtract subtracts another SizeEstimate and returns the difference, saturating at zero. +func (se SizeEstimate) Subtract(sizeEstimate SizeEstimate) SizeEstimate { + res := SizeEstimate{ + Min: SafeSubtract(se.Min, sizeEstimate.Max), + Max: SafeSubtract(se.Max, sizeEstimate.Min), + } + res.Key = mergeSizeEstimatePtr(se.Key, sizeEstimate.Key) + res.Elem = mergeSizeEstimatePtr(se.Elem, sizeEstimate.Elem) + return res +} + +// Multiply multiplies by another SizeEstimate and returns the product. +// If multiply would result in an uint64 overflow, the result is math.MaxUint64. +// +// The product carries the union of the operands' key and element sizes, as Add, Subtract and +// Union do: a length scaled by a factor describes the same kind of element it started with. An +// estimator whose result holds something other than its operands' elements — expanded strings, for +// instance — must state that with List or Map rather than let the operands' sizes be inherited. +func (se SizeEstimate) Multiply(sizeEstimate SizeEstimate) SizeEstimate { + res := SizeEstimate{ + Min: SafeMultiply(se.Min, sizeEstimate.Min), + Max: SafeMultiply(se.Max, sizeEstimate.Max), + } + res.Key = mergeSizeEstimatePtr(se.Key, sizeEstimate.Key) + res.Elem = mergeSizeEstimatePtr(se.Elem, sizeEstimate.Elem) + return res +} + +// MultiplyByCostFactor multiplies a SizeEstimate by a cost factor and returns the CostEstimate with the +// nearest integer of the result, rounded up. +func (se SizeEstimate) MultiplyByCostFactor(costPerUnit float64) CostEstimate { + return CostEstimate{ + Min: SafeMultiplyByFactor(se.Min, costPerUnit), + Max: SafeMultiplyByFactor(se.Max, costPerUnit), + } +} + +// MultiplyByCost multiplies by the cost and returns the product. +// If multiply would result in an uint64 overflow, the result is math.MaxUint64. +func (se SizeEstimate) MultiplyByCost(estimate CostEstimate) CostEstimate { + return CostEstimate{ + SafeMultiply(se.Min, estimate.Min), + SafeMultiply(se.Max, estimate.Max), + } +} + +// Union returns a SizeEstimate that encompasses both input SizeEstimate values. +func (se SizeEstimate) Union(size SizeEstimate) SizeEstimate { + result := se + if size.Min < result.Min { + result.Min = size.Min + } + if size.Max > result.Max { + result.Max = size.Max + } + result.Key = mergeSizeEstimatePtr(se.Key, size.Key) + result.Elem = mergeSizeEstimatePtr(se.Elem, size.Elem) + return result +} + +// mergeSizeEstimatePtr merges two optional SizeEstimate pointers using union. +func mergeSizeEstimatePtr(a, b *SizeEstimate) *SizeEstimate { + if a == nil { + return b + } + if b == nil { + return a + } + u := a.Union(*b) + return &u +} + +// AsCost converts a size estimate to an equivalent cost estimate. +func (se SizeEstimate) AsCost() CostEstimate { + return se.MultiplyByCostFactor(1) +} + +// IsUnknown returns true if the size estimate represents an unknown size (0 to math.MaxUint64 with no key or element sizes). +func (se SizeEstimate) IsUnknown() bool { + return se == unknownSizeEstimate +} + +// Estimate represents an estimated cost range and provides add and multiply operations +// that do not overflow. +type Estimate struct { + Min, Max uint64 +} + +// CostEstimate is an alias for Estimate. +// +// Deprecated: use Estimate. +type CostEstimate = Estimate + +// UnknownCostEstimate returns a cost with an unknown impact. +func UnknownCostEstimate() CostEstimate { + return unknownCostEstimate +} + +// IsUnknown returns true if the cost estimate represents an unknown cost (0 to math.MaxUint64). +func (ce CostEstimate) IsUnknown() bool { + return ce == unknownCostEstimate +} + +// FixedCostEstimate returns a cost with a fixed min and max range. +func FixedCostEstimate(fixedCost uint64) CostEstimate { + return CostEstimate{Min: fixedCost, Max: fixedCost} +} + +// RangedCostEstimate returns a cost estimate bounded by min and max. +func RangedCostEstimate(min, max uint64) CostEstimate { + return CostEstimate{Min: min, Max: max} +} + +// Add adds the costs and returns the sum. +// If add would result in an uint64 overflow for the min or max, the value is set to math.MaxUint64. +func (ce CostEstimate) Add(estimate CostEstimate) CostEstimate { + return CostEstimate{ + Min: SafeAdd(ce.Min, estimate.Min), + Max: SafeAdd(ce.Max, estimate.Max), + } +} + +// Multiply multiplies by the cost and returns the product. +// If multiply would result in an uint64 overflow, the result is math.MaxUint64. +func (ce CostEstimate) Multiply(estimate CostEstimate) CostEstimate { + return CostEstimate{ + Min: SafeMultiply(ce.Min, estimate.Min), + Max: SafeMultiply(ce.Max, estimate.Max), + } +} + +// MultiplyByCostFactor multiplies a CostEstimate by a cost factor and returns the CostEstimate with the +// nearest integer of the result, rounded up. +func (ce CostEstimate) MultiplyByCostFactor(costPerUnit float64) CostEstimate { + return CostEstimate{ + Min: SafeMultiplyByFactor(ce.Min, costPerUnit), + Max: SafeMultiplyByFactor(ce.Max, costPerUnit), + } +} + +// Union returns a CostEstimate that encompasses both input CostEstimates. +func (ce CostEstimate) Union(size CostEstimate) CostEstimate { + result := ce + if size.Min < result.Min { + result.Min = size.Min + } + if size.Max > result.Max { + result.Max = size.Max + } + return result +} + +// CallEstimate includes a CostEstimate for the call, and an optional estimate of the result object size. +// The ResultSize should only be provided if the call results in a map, list, string or bytes. +type CallEstimate struct { + CostEstimate + + ResultSize *SizeEstimate +} + +// NewCallEstimate creates a new CallEstimate with the given cost and optional result size. +func NewCallEstimate(cost CostEstimate, sz *SizeEstimate) *CallEstimate { + return &CallEstimate{CostEstimate: cost, ResultSize: sz} +} + +// NewListCallEstimate creates a CallEstimate for a call that allocates a list, adding CallCost and +// ListCreateBaseCost to work and setting ResultSize to resultSize. +func NewListCallEstimate(work CostEstimate, resultSize SizeEstimate) *CallEstimate { + return NewCallEstimate( + work.Add(FixedCostEstimate(CallCost+ListCreateBaseCost)), + &resultSize, + ) +} + +// ActualSize returns the size of the value for all traits.Sizer values, +// and returns a size of 1 for all other value types. +func ActualSize(value ref.Val) uint64 { + if sz, ok := value.(traits.Sizer); ok { + return uint64(sz.Size().(types.Int)) + } + return 1 +} + +// EstimateSize returns a SizeEstimate for the given node from its computed size, estimator, or unknown. +func EstimateSize(estimator Estimator, node AstNode) SizeEstimate { + if node == nil { + return UnknownSizeEstimate() + } + if l := node.ComputedSize(); l != nil { + return *l + } + if estimator != nil { + if l := estimator.EstimateSize(node); l != nil { + return *l + } + } + return UnknownSizeEstimate() +} + +// EstimateTraversal computes cost as a function of the size of the target object and whether the call allocates memory. +func EstimateTraversal(nodeSize SizeEstimate, costFactor float64, allocationCost *CostEstimate) (CostEstimate, *SizeEstimate) { + cost := nodeSize.MultiplyByCostFactor(costFactor) + if allocationCost != nil { + cost = cost.Add(*allocationCost) + } + return cost, &nodeSize +} + +// EstimateStringScan estimates cost for scanning a string. +func EstimateStringScan(sz SizeEstimate) (CostEstimate, *SizeEstimate) { + return EstimateTraversal(sz, StringCostFactor, nil) +} + +// EstimateListAlloc estimates cost for allocating a list. +func EstimateListAlloc(sz SizeEstimate, costFactor float64) (CostEstimate, *SizeEstimate) { + return EstimateTraversal(sz, costFactor, &ListAllocCost) +} + +// UintValue returns the value of a non-negative literal int or uint node as a uint64, or false if +// the node is not a non-negative integer literal. +func UintValue(node AstNode) (uint64, bool) { + if node == nil || node.Expr() == nil || node.Expr().Kind() != ast.LiteralKind { + return 0, false + } + switch v := node.Expr().AsLiteral().(type) { + case types.Int: + if v < types.IntZero { + return 0, false + } + return uint64(v), true + case types.Uint: + return uint64(v), true + default: + return 0, false + } +} + +// NodeAsUintValue returns the value of a literal int node as a uint64, or the default value if the +// node is not a non-negative int literal. +func NodeAsUintValue(node AstNode, defaultVal uint64) uint64 { + if val, ok := UintValue(node); ok { + return val + } + if node != nil && node.Expr() != nil && node.Expr().Kind() == ast.LiteralKind { + if v, ok := node.Expr().AsLiteral().(types.Int); ok && v < types.IntZero { + return 0 + } + } + return defaultVal +} diff --git a/vendor/cel.dev/cel-go/common/cost/default_strategy.go b/vendor/cel.dev/cel-go/common/cost/default_strategy.go new file mode 100644 index 0000000000..1e5394aa36 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/default_strategy.go @@ -0,0 +1,554 @@ +// Copyright 2026 Google LLC +// +// 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 cost + +import ( + "slices" + + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" +) + +// DefaultSizingStrategy returns the default SizingStrategy implementation. +func DefaultSizingStrategy() SizingStrategy { + return defaultSizing +} + +// defaultSizingStrategy is the default implementation of SizingStrategy. +type defaultSizingStrategy struct{} + +// EstimateSize computes the size estimate for an AST node during cost estimation. +func (defaultSizingStrategy) EstimateSize(ctx EstimateContext, node AstNode) (SizeEstimate, bool) { + if node == nil { + return SizeEstimate{}, false + } + if sz := node.ComputedSize(); sz != nil { + return *sz, true + } + if node.Expr() != nil { + if sz := computeExprSize(node.Expr()); sz != nil { + return *sz, true + } + } + if node.Type() == nil { + return estimateScalarOrFallback(ctx, node) + } + switch node.Type().Kind() { + case types.ListKind: + return estimateDefaultListSize(ctx, node) + case types.MapKind: + return estimateDefaultMapSize(ctx, node) + case types.DynKind, types.AnyKind, types.TypeParamKind: + return estimateDefaultDynSize(ctx, node) + default: + return estimateScalarOrFallback(ctx, node) + } +} + +// maxHintDepth bounds how many nested container hint levels ("@items", "@keys", "@values") +// dynamic type size estimation inspects. +const maxHintDepth = 32 + +// estimateDefaultListSize calculates the size and element size of a list AST node. +func estimateDefaultListSize(ctx EstimateContext, node AstNode) (SizeEstimate, bool) { + elemType := listElemType(node.Type()) + listSize, elemSize := estimateListExpr(ctx, node, elemType) + listSize, elemSize = resolveListSizes(ctx, node, elemType, listSize, elemSize) + return combineListSize(listSize, elemSize) +} + +// estimateDefaultMapSize calculates the size, key size, and value size of a map AST node. +func estimateDefaultMapSize(ctx EstimateContext, node AstNode) (SizeEstimate, bool) { + keyType, valType := mapKeyValueTypes(node.Type()) + mapSize, keySize, valSize := estimateMapExpr(ctx, node, keyType, valType) + mapSize, keySize, valSize = resolveMapSizes(ctx, node, keyType, valType, mapSize, keySize, valSize) + return combineMapSize(mapSize, keySize, valSize) +} + +// estimateDefaultDynSize calculates the size estimate for a dynamically typed AST node. +// For variable/path nodes, the nesting of hints ("@items", "@keys", "@values") determines +// the possible container depth; any level beyond the hinted depth remains nil (unknown). +func estimateDefaultDynSize(ctx EstimateContext, node AstNode) (SizeEstimate, bool) { + if node.Expr() != nil { + switch node.Expr().Kind() { + case ast.ListKind: + return estimateDefaultListSize(ctx, node) + case ast.MapKind: + return estimateDefaultMapSize(ctx, node) + case ast.CallKind: + if call := node.Expr().AsCall(); call.FunctionName() == operators.Conditional { + if u, ok := estimateConditionalSize(ctx, node.Type(), call.Args()); ok { + return u, true + } + } + } + } + var baseSz *SizeEstimate + if sz, ok := estimateScalarOrFallback(ctx, node); ok { + if sz.Elem != nil || sz.Key != nil { + return sz, true + } + baseSz = &sz + } + if len(node.Path()) > 0 { + if elemSz := resolveDynamicChild(ctx, node.Path(), "@items"); elemSz != nil { + return combineListSize(baseSz, elemSz) + } + keySz := resolveDynamicChild(ctx, node.Path(), "@keys") + valSz := resolveDynamicChild(ctx, node.Path(), "@values") + if keySz != nil || valSz != nil { + return combineMapSize(baseSz, keySz, valSz) + } + } + if baseSz != nil { + return *baseSz, true + } + return SizeEstimate{}, false +} + +// resolveDynamicChild probes a child hint subpath ("@items", "@keys", "@values") under a +// dynamic node, recursing only when the estimator provides an explicit hint at that subpath. +func resolveDynamicChild(ctx EstimateContext, parentPath []string, subPath string) *SizeEstimate { + if len(parentPath) == 0 || len(parentPath) >= maxHintDepth || ctx == nil || ctx.Estimator() == nil { + return nil + } + childPath := append(slices.Clone(parentPath), subPath) + childNode := NewAstNode(nil, childPath, types.DynType, nil) + if ctx.Estimator().EstimateSize(childNode) == nil { + return nil + } + sz := ctx.Size(childNode) + if sz.IsUnknown() { + return nil + } + return &sz +} + +// resolveListSizes resolves a list node's container size and element size using the estimator, +// subpath hints ("@items"), and type fallbacks when not already determined from the expression. +func resolveListSizes(ctx EstimateContext, node AstNode, elemType *types.Type, listSize, elemSize *SizeEstimate) (*SizeEstimate, *SizeEstimate) { + if listSize == nil && ctx != nil && ctx.Estimator() != nil { + listSize = ctx.Estimator().EstimateSize(node) + } + if elemSize == nil && listSize != nil { + elemSize = cloneSizeEstimate(listSize.Elem) + } + if listSize == nil || listSize.Max > 0 || (ctx != nil && versionOf(ctx) < 1) { + elemSize = resolveChildSize(ctx, node.Path(), "@items", elemType, elemSize) + } + // If neither the list length nor element size is known for an AST expression node + // (e.g. an unhinted list variable), default listSize to unknown so the + // strategy computes the worst-case bound. + if listSize == nil && elemSize == nil && node.Expr() != nil { + u := UnknownSizeEstimate() + listSize = &u + } + return listSize, elemSize +} + +// resolveMapSizes resolves a map node's container size, key size, and value size using the +// estimator, subpath hints ("@keys", "@values"), and type fallbacks. +func resolveMapSizes(ctx EstimateContext, node AstNode, keyType, valType *types.Type, mapSize, keySize, valSize *SizeEstimate) (*SizeEstimate, *SizeEstimate, *SizeEstimate) { + if mapSize == nil && ctx != nil && ctx.Estimator() != nil { + mapSize = ctx.Estimator().EstimateSize(node) + } + if mapSize != nil { + if keySize == nil { + keySize = cloneSizeEstimate(mapSize.Key) + } + if valSize == nil { + valSize = cloneSizeEstimate(mapSize.Elem) + } + } + // Query subpaths @keys and @values if hints were not provided on the parent map node. + if mapSize == nil || mapSize.Max > 0 || (ctx != nil && versionOf(ctx) < 1) { + keySize = resolveChildSize(ctx, node.Path(), "@keys", keyType, keySize) + valSize = resolveChildSize(ctx, node.Path(), "@values", valType, valSize) + } + // If no map, key, or value sizes are known for an AST expression node (e.g. an unhinted + // map), default mapSize to unknown to compute the worst-case bound. + if mapSize == nil && keySize == nil && valSize == nil && node.Expr() != nil { + u := UnknownSizeEstimate() + mapSize = &u + } + return mapSize, keySize, valSize +} + +// resolveChildSize looks up child size estimates on the given subPath (e.g. "@items", "@keys", "@values") +// when the current estimate is missing or lacks nested container details, falling back to primitive/type hints. +func resolveChildSize(ctx EstimateContext, parentPath []string, subPath string, childType *types.Type, current *SizeEstimate) *SizeEstimate { + if current == nil || (current.Elem == nil && (isContainerKind(childType.Kind()) || isDynamicKind(childType.Kind()))) { + if len(parentPath) > 0 && ctx != nil { + childPath := append(slices.Clone(parentPath), subPath) + sz := ctx.Size(NewAstNode(nil, childPath, childType, nil)) + if !sz.IsUnknown() { + if current == nil { + current = &sz + } else { + current.Elem = sz.Elem + current.Key = sz.Key + } + } + } + } + if current == nil { + current = fallbackElemSize(ctx, childType) + } + return current +} + +// isContainerKind reports whether kind is a list or map container type. +func isContainerKind(kind types.Kind) bool { + return kind == types.ListKind || kind == types.MapKind +} + +// isDynamicKind reports whether kind represents a dynamically typed value. +func isDynamicKind(kind types.Kind) bool { + return kind == types.DynKind || kind == types.AnyKind || kind == types.TypeParamKind +} + +// fallbackElemSize resolves fixed-width primitive type sizes via computeTypeSize, +// or queries the estimator with an untyped/pathless node for type-level hints. +func fallbackElemSize(ctx EstimateContext, elemType *types.Type) *SizeEstimate { + if sz := computeTypeSize(elemType, versionOf(ctx)); sz != nil { + return ownedSize(sz) + } + if ctx != nil && ctx.Estimator() != nil { + elemNode := NewAstNode(nil, nil, elemType, nil) + return ctx.Estimator().EstimateSize(elemNode) + } + return nil +} + +// cloneSizeEstimate makes a copy of a SizeEstimate to prevent in-place mutation of cached/shared estimates. +func cloneSizeEstimate(se *SizeEstimate) *SizeEstimate { + if se == nil { + return nil + } + clone := *se + return &clone +} + +// TrackSize computes the actual runtime size of a value. +func (defaultSizingStrategy) TrackSize(ctx TrackContext, value ref.Val) (uint64, bool) { + if value == nil { + return 0, false + } + if opt, isOpt := value.(*types.Optional); isOpt { + return optionalLength(trackVersionOf(ctx), opt), true + } + return ActualSize(value), true +} + +// optionalLength reports the size of an optional under the default sizing strategy, at the given +// cost model version. +// +// From version 1 an optional is 1 plus the length of the value it holds, so an empty optional is 1, +// and the optional's element is that value; see Optional. Version 0 sizes every optional as 1, as +// cel-go v0.32.0 charged it through ActualSize, for which an optional is not a traits.Sizer. +func optionalLength(version uint32, opt *types.Optional) uint64 { + if version < 1 || !opt.HasValue() { + return 1 + } + if inner, isOpt := opt.GetValue().(*types.Optional); isOpt { + return SafeAdd(1, optionalLength(version, inner)) + } + return SafeAdd(1, ActualSize(opt.GetValue())) +} + +// trackVersionContext is implemented by TrackContext values which know the cost model version they +// track under. It is unexported because TrackContext is an interface third parties may implement. +type trackVersionContext interface { + modelVersion() uint32 +} + +// trackVersionOf reports the cost model version of a TrackContext: the latest version for a context +// which does not report one. +func trackVersionOf(ctx TrackContext) uint32 { + if v, ok := ctx.(trackVersionContext); ok { + return v.modelVersion() + } + return defaultModelVersion +} + +// optionalValueOf reports whether value is an optional, and if so returns the value it holds, or +// nil when the optional is empty. +func optionalValueOf(value ref.Val) (ref.Val, bool) { + opt, isOpt := value.(*types.Optional) + if !isOpt { + return nil, false + } + if !opt.HasValue() { + return nil, true + } + return opt.GetValue(), true +} + +// listElemType extracts the element type of a list, defaulting to DynType if not parameterized. +func listElemType(t *types.Type) *types.Type { + if len(t.Parameters()) > 0 && t.Parameters()[0] != nil { + return t.Parameters()[0] + } + return types.DynType +} + +// mapKeyValueTypes extracts key and value types of a map, defaulting to DynType if not parameterized. +func mapKeyValueTypes(t *types.Type) (keyType, valType *types.Type) { + keyType = types.DynType + valType = types.DynType + if len(t.Parameters()) >= 2 { + keyType = t.Parameters()[0] + valType = t.Parameters()[1] + } + return keyType, valType +} + +// unionAccumulator merges a new size estimate into an existing accumulator pointer. +func unionAccumulator(acc *SizeEstimate, next SizeEstimate) *SizeEstimate { + if acc == nil { + return &next + } + u := acc.Union(next) + return &u +} + +// estimateConditionalSize computes the union SizeEstimate of the branches in a conditional call. +func estimateConditionalSize(ctx EstimateContext, nodeType *types.Type, args []ast.Expr) (SizeEstimate, bool) { + if len(args) == 3 { + tVal := ctx.Size(NewAstNode(args[1], nil, nodeType, nil)) + fVal := ctx.Size(NewAstNode(args[2], nil, nodeType, nil)) + return tVal.Union(fVal), true + } + return SizeEstimate{}, false +} + +// estimateListExpr computes the list and element size estimates for literal list expressions +// or container call operations (e.g. Add, Conditional). +func estimateListExpr(ctx EstimateContext, node AstNode, elemType *types.Type) (listSize *SizeEstimate, elemSize *SizeEstimate) { + if node.Expr() == nil { + return nil, nil + } + switch node.Expr().Kind() { + case ast.ListKind: + list := node.Expr().AsList() + elements := list.Elements() + l := FixedSizeEstimate(uint64(len(elements))) + // An optional element is omitted when it has no value, so only the required + // elements count toward the minimum length. + l.Min = uint64(len(elements) - len(list.OptionalIndices())) + optional := make(map[int32]bool, len(list.OptionalIndices())) + for _, i := range list.OptionalIndices() { + optional[i] = true + } + for i, elem := range elements { + if optional[int32(i)] { + // The list holds the optional's value, if any, rather than the optional. + var present bool + if elem, present = optionalLiteralValue(elem); !present { + l.Max = SafeSubtract(l.Max, 1) + continue + } + } + elemNode := NewAstNode(elem, nil, elemType, nil) + elemSize = unionAccumulator(elemSize, ctx.Size(elemNode)) + } + listSize = &l + case ast.CallKind: + call := node.Expr().AsCall() + args := call.Args() + switch call.FunctionName() { + case operators.Add: + if len(args) == 2 { + lhs := ctx.Size(NewAstNode(args[0], nil, node.Type(), nil)) + rhs := ctx.Size(NewAstNode(args[1], nil, node.Type(), nil)) + added := lhs.Add(rhs) + listSize = &added + elemSize = added.Elem + } + case operators.Conditional: + if u, ok := estimateConditionalSize(ctx, node.Type(), args); ok { + listSize = &u + elemSize = u.Elem + } + } + } + return listSize, elemSize +} + +// estimateMapExpr computes map, key, and value size estimates for literal map expressions +// or container call operations (e.g. Conditional). +func estimateMapExpr(ctx EstimateContext, node AstNode, keyType, valType *types.Type) (mapSize *SizeEstimate, keySize *SizeEstimate, valSize *SizeEstimate) { + if node.Expr() == nil { + return nil, nil, nil + } + switch node.Expr().Kind() { + case ast.MapKind: + entries := node.Expr().AsMap().Entries() + m := FixedSizeEstimate(uint64(len(entries))) + mapSize = &m + for _, entry := range entries { + mapEntry := entry.AsMapEntry() + if mapEntry.IsOptional() { + // An optional entry is omitted when its value is absent. + m.Min = SafeSubtract(m.Min, 1) + } + kNode := NewAstNode(mapEntry.Key(), nil, keyType, nil) + vNode := NewAstNode(mapEntry.Value(), nil, valType, nil) + keySize = unionAccumulator(keySize, ctx.Size(kNode)) + valSize = unionAccumulator(valSize, ctx.Size(vNode)) + } + case ast.CallKind: + call := node.Expr().AsCall() + switch call.FunctionName() { + case "cel.@mapInsert": + args := call.Args() + if len(args) == 3 { + lhs := ctx.Size(NewAstNode(args[0], nil, node.Type(), nil)) + kSz := ctx.Size(NewAstNode(args[1], nil, keyType, nil)) + vSz := ctx.Size(NewAstNode(args[2], nil, valType, nil)) + keySize = mergeSizeEstimatePtr(lhs.Key, &kSz) + valSize = mergeSizeEstimatePtr(lhs.Elem, &vSz) + added := lhs.Add(FixedSizeEstimate(1)) + added.Key = keySize + added.Elem = valSize + mapSize = &added + } else if len(args) == 2 { + lhs := ctx.Size(NewAstNode(args[0], nil, node.Type(), nil)) + rhs := ctx.Size(NewAstNode(args[1], nil, node.Type(), nil)) + added := lhs.Add(rhs) + mapSize = &added + keySize = added.Key + valSize = added.Elem + } + case operators.Conditional: + if u, ok := estimateConditionalSize(ctx, node.Type(), call.Args()); ok { + mapSize = &u + keySize = u.Key + valSize = u.Elem + } + } + } + return mapSize, keySize, valSize +} + +// estimateScalarOrFallback returns size estimates using custom estimator hints or primitive type sizes. +func estimateScalarOrFallback(ctx EstimateContext, node AstNode) (SizeEstimate, bool) { + if node != nil && node.Expr() != nil { + if sz := computeExprSize(node.Expr()); sz != nil { + return *sz, true + } + } + if ctx != nil && ctx.Estimator() != nil { + if sz := ctx.Estimator().EstimateSize(node); sz != nil { + return *sz, true + } + } + if node.Type() != nil { + if sz := computeTypeSize(node.Type(), versionOf(ctx)); sz != nil { + return *sz, true + } + } + return SizeEstimate{}, false +} + +// combineListSize constructs a list SizeEstimate combining container length and element size. +// +// A list that can be non-empty (Max > 0) whose element size is unknown carries an explicit +// UnknownSizeEstimate in Elem rather than nil, so combining it with a literal list (e.g. +// ['a'] + unhinted) widens the element size to unknown instead of dropping it to the literal's. +// Empty list literals (Max == 0) leave Elem nil so they contribute no element bound when joined. +func combineListSize(listSize, elemSize *SizeEstimate) (SizeEstimate, bool) { + if listSize != nil { + if elemSize == nil && listSize.Max > 0 { + u := UnknownSizeEstimate() + elemSize = &u + } + listSize.Key = nil + listSize.Elem = elemSize + return *listSize, true + } + if elemSize != nil { + res := UnknownSizeEstimate() + res.Elem = elemSize + return res, true + } + return SizeEstimate{}, false +} + +// combineMapSize constructs a map SizeEstimate combining map size, key size, and value size. +// +// As with combineListSize, a map that can be non-empty (Max > 0) records an explicit +// UnknownSizeEstimate for an unhinted Key or Elem so merging with a literal map widens the bound +// rather than dropping the unknown side. +func combineMapSize(mapSize, keySize, valSize *SizeEstimate) (SizeEstimate, bool) { + if mapSize != nil { + if mapSize.Max > 0 { + if keySize == nil { + u := UnknownSizeEstimate() + keySize = &u + } + if valSize == nil { + u := UnknownSizeEstimate() + valSize = &u + } + } + mapSize.Key = keySize + mapSize.Elem = valSize + return *mapSize, true + } + if keySize != nil || valSize != nil { + if keySize == nil { + u := UnknownSizeEstimate() + keySize = &u + } + if valSize == nil { + u := UnknownSizeEstimate() + valSize = &u + } + res := UnknownSizeEstimate() + res.Key = keySize + res.Elem = valSize + return res, true + } + return SizeEstimate{}, false +} + +var defaultSizing SizingStrategy = defaultSizingStrategy{} + +// optionalLiteralValue returns the value an optional list element contributes: nothing for +// optional.none(), the argument of optional.of(x) or optional.ofNonZeroValue(x), and otherwise +// the element itself, whose value is not known statically. +func optionalLiteralValue(e ast.Expr) (ast.Expr, bool) { + if e.Kind() != ast.CallKind { + return e, true + } + call := e.AsCall() + if call.IsMemberFunction() { + return e, true + } + switch call.FunctionName() { + case "optional.none": + if len(call.Args()) == 0 { + return nil, false + } + case "optional.of", "optional.ofNonZeroValue": + if len(call.Args()) == 1 { + return call.Args()[0], true + } + } + return e, true +} diff --git a/vendor/cel.dev/cel-go/common/cost/estimator.go b/vendor/cel.dev/cel-go/common/cost/estimator.go new file mode 100644 index 0000000000..69e25f12d0 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/estimator.go @@ -0,0 +1,1260 @@ +// Copyright 2022 Google LLC +// +// 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 cost + +import ( + "fmt" + "math" + "strconv" + + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" +) + +// Estimator provides CallCost and Size estimates for cost calculation. +type Estimator interface { + + // EstimateCallCost returns the CallEstimate for a function, overload and target and arguments. + // + // If nil is returned, the cost of the function is calculated by the OverloadCostEstimate if + // provided, or standard CEL function cost estimation. + EstimateCallCost(function, overloadID string, target *AstNode, args []AstNode) *CallEstimate + + // EstimateSize returns the SizeEstimate of an AstNode. + // + // If nil is returned, the size of the node is calculated by the SizingStrategy. + EstimateSize(element AstNode) *SizeEstimate +} + +// AstNode represents an AST node for estimating cost. +type AstNode interface { + // Path returns a field path through the provided type declarations to the type of the AstNode, or nil if the AstNode does not + // represent type directly reachable from the provided type declarations. + // The first path element is a variable. All subsequent path elements are one of: field name, '@items', '@keys', '@values'. + Path() []string + + // Type returns the deduced type of the AstNode. + Type() *types.Type + + // Expr returns the expression of the AstNode. + Expr() ast.Expr + + // ComputedSize returns a size estimate of the AstNode derived from information available in the CEL expression. + // For constants and inline list and map declarations, the exact size is returned. For concatenated list, strings + // and bytes, the size is derived from the size estimates of the operands. nil is returned if there is no + // computed size available. + ComputedSize() *SizeEstimate +} + +// astNode implements the AstNode interface. +type astNode struct { + path []string + t *types.Type + expr ast.Expr + derivedSize *SizeEstimate +} + +// Path returns the field path to the node, if known. +func (e astNode) Path() []string { + return e.path +} + +// Type returns the type of the node. +func (e astNode) Type() *types.Type { + return e.t +} + +// Expr returns the underlying CEL expression. +func (e astNode) Expr() ast.Expr { + return e.expr +} + +// ComputedSize returns the precomputed or derived size estimate of the node. +func (e astNode) ComputedSize() *SizeEstimate { + return e.derivedSize +} + +// NewAstNode returns an AstNode with the given expression, path, type, and derived size. +func NewAstNode(expr ast.Expr, path []string, t *types.Type, derivedSize *SizeEstimate) AstNode { + return astNode{ + path: path, + t: t, + expr: expr, + derivedSize: derivedSize, + } +} + +// Option configures flags which affect cost computations. +type Option interface { + applyCoster(*coster) error +} + +type costerOption func(*coster) error + +func (opt costerOption) applyCoster(c *coster) error { + return opt(c) +} + +// CostOption is an alias for Option. +// +// Deprecated: use Option. +type CostOption = Option + +// PresenceTestHasCost determines whether presence testing has a cost of one or zero. +// +// Defaults to presence test has a cost of one. +func PresenceTestHasCost(hasCost bool) Option { + return costerOption(func(c *coster) error { + if hasCost { + c.presenceTestCost = selectAndIdentCost + return nil + } + c.presenceTestCost = FixedCostEstimate(0) + return nil + }) +} + +// FunctionEstimator provides a CallEstimate given the target and arguments for a specific function, overload pair. +type FunctionEstimator func(estimator Estimator, target *AstNode, args []AstNode) *CallEstimate + +// OverloadCostEstimate binds a FunctionEstimator to a specific function overload ID. +// +// When an OverloadCostEstimate is provided, it overrides the cost calculation of the Estimator +// provided to the Cost() call. +func OverloadCostEstimate(overloadID string, functionCoster FunctionEstimator) Option { + return costerOption(func(c *coster) error { + if functionCoster == nil { + return fmt.Errorf("OverloadCostEstimate(%q) requires a FunctionEstimator", overloadID) + } + c.overloadEstimators.mutable()[overloadID] = functionCoster + return nil + }) +} + +// Cost estimates the cost of the parsed and type checked CEL expression. +func Cost(checked *ast.AST, estimator Estimator, opts ...Option) (CostEstimate, error) { + c, err := newCoster(checked, estimator, opts...) + if err != nil { + return CostEstimate{}, err + } + return c.cost(checked.Expr()), nil +} + +// newCoster returns a coster configured by the options. Its configuration is fixed once it is +// returned; only the per-expression state gathered while costing changes. +func newCoster(checked *ast.AST, estimator Estimator, opts ...Option) (*coster, error) { + c := &coster{ + checkedAST: checked, + estimator: estimator, + modelRules: defaultModelRules(), + exprPaths: map[int64][]string{}, + localVars: make(scopes), + computedSizes: map[int64]SizeEstimate{}, + presenceTestCost: FixedCostEstimate(1), + } + for _, opt := range opts { + if mo, ok := opt.(ModelOption); ok { + c.modelRules.override(mo) + } + } + for _, opt := range opts { + if err := opt.applyCoster(c); err != nil { + return nil, err + } + } + // The package-level estimators are compiled under the default rules. + c.standardOverloadEstimators = stdOverloadEstimators + if !c.modelRules.isDefault() { + c.standardOverloadEstimators = StandardOverloadEstimatorsWithOptions(c.modelRules.modelOptions()...) + } + c.est = versionedEstimator{ + coster: c, + delegate: estimator, + version: c.modelVersion, + strategy: c.sizingStrategy, + } + c.evalCtx = estimatorEvalContext{ + coster: c, + estimator: estimator, + strategy: c.sizingStrategy, + version: c.modelVersion, + } + return c, nil +} + +// coster performs recursive cost and size calculation on checked AST expressions. +type coster struct { + // exprPaths maps from Expr Id to field path. + exprPaths map[int64][]string + // localVars tracks the local and iteration variables assigned during evaluation. + localVars scopes + // computedSizes tracks the computed sizes of call results. + computedSizes map[int64]SizeEstimate + + checkedAST *ast.AST + estimator Estimator + modelRules + overloadEstimators overloadTable[FunctionEstimator] + standardOverloadEstimators map[string]FunctionEstimator + // presenceTestCost will either be a zero or one based on whether has() macros count against cost computations. + presenceTestCost CostEstimate + // est and evalCtx are owned by the coster and handed out by pointer, so that passing them to + // estimators and sizing strategies does not allocate. + est versionedEstimator + evalCtx estimatorEvalContext +} + +// localVar captures the local variable size estimates if they exist for variables +type localVar struct { + exprID int64 + path []string + size *SizeEstimate +} + +// scopes is a stack of variable name to integer id stack to handle scopes created by cel.bind() like macros +type scopes map[string][]*localVar + +// push adds a variable name to the scope stack with its path and size estimates. +func (s scopes) push(varName string, expr ast.Expr, path []string, size *SizeEstimate) { + s[varName] = append(s[varName], &localVar{ + exprID: expr.ID(), + path: path, + size: size, + }) +} + +// pop removes the most recent variable from the scope stack for the given name. +func (s scopes) pop(varName string) { + varStack := s[varName] + s[varName] = varStack[:len(varStack)-1] +} + +// peek returns the top of the stack for the given variable name. +func (s scopes) peek(varName string) (*localVar, bool) { + varStack := s[varName] + if len(varStack) > 0 { + return varStack[len(varStack)-1], true + } + return nil, false +} + +// pushIterKey pushes the iteration key or index variable for a comprehension onto the scope stack. +func (c *coster) pushIterKey(varName string, rangeExpr ast.Expr) { + rangeSize := c.sizeOrUnknown(rangeExpr) + container := c.getType(rangeExpr).Kind() + var size *SizeEstimate + subpath := "@keys" + if container == types.ListKind { + s := FixedSizeEstimate(1) + size = &s + subpath = "@indices" + } else if rangeSize.Key != nil { + size = rangeSize.Key + } + var varPath []string + if path := c.getPath(rangeExpr); len(path) > 0 || c.modelVersion < 1 { + varPath = append(path, subpath) + } + c.localVars.push(varName, rangeExpr, varPath, size) +} + +// pushIterValue pushes the iteration value variable for a comprehension onto the scope stack. +func (c *coster) pushIterValue(varName string, rangeExpr ast.Expr) { + rangeSize := c.sizeOrUnknown(rangeExpr) + var size *SizeEstimate + if rangeSize.Elem != nil { + size = rangeSize.Elem + } + container := c.getType(rangeExpr).Kind() + subpath := "@values" + if container == types.ListKind { + subpath = "@items" + } + var varPath []string + if path := c.getPath(rangeExpr); len(path) > 0 || c.modelVersion < 1 { + varPath = append(path, subpath) + } + c.localVars.push(varName, rangeExpr, varPath, size) +} + +// pushIterSingle pushes a single iteration variable (items for list, keys for map) onto the scope stack. +func (c *coster) pushIterSingle(varName string, rangeExpr ast.Expr) { + rangeSize := c.sizeOrUnknown(rangeExpr) + var size *SizeEstimate + subpath := "@keys" + container := c.getType(rangeExpr).Kind() + if container == types.ListKind || (container == types.DynKind && rangeSize.Key == nil && rangeSize.Elem != nil) { + size = rangeSize.Elem + subpath = "@items" + } else { + size = rangeSize.Key + } + var varPath []string + if path := c.getPath(rangeExpr); len(path) > 0 || c.modelVersion < 1 { + varPath = append(path, subpath) + } + c.localVars.push(varName, rangeExpr, varPath, size) +} + +// pushLocalVar records a local variable binding with its path and size estimates. +func (c *coster) pushLocalVar(varName string, e ast.Expr) { + path := c.getPath(e) + c.localVars.push(varName, e, path, ownedSize(c.computeSize(e))) +} + +// peekLocalVar looks up the top of the scope stack for a local variable name. +func (c *coster) peekLocalVar(varName string) (*localVar, bool) { + return c.localVars.peek(varName) +} + +// popLocalVar pops the scope stack for a local variable name. +func (c *coster) popLocalVar(varName string) { + c.localVars.pop(varName) +} + +// cost recursively calculates the cost estimate for an expression node. +func (c *coster) cost(e ast.Expr) CostEstimate { + if e == nil { + return CostEstimate{} + } + switch e.Kind() { + case ast.LiteralKind: + return constCost + case ast.IdentKind: + return c.costIdent(e) + case ast.SelectKind: + return c.costSelect(e) + case ast.CallKind: + return c.costCall(e) + case ast.ListKind: + return c.costCreateList(e) + case ast.MapKind: + return c.costCreateMap(e) + case ast.StructKind: + return c.costCreateStruct(e) + case ast.ComprehensionKind: + if c.isBind(e) { + return c.costBind(e) + } + return c.costComprehension(e) + default: + return CostEstimate{} + } +} + +// costIdent estimates the cost of evaluating an identifier and tracks its path. +func (c *coster) costIdent(e ast.Expr) CostEstimate { + ident := e.AsIdent() + if v, ok := c.peekLocalVar(ident); ok { + c.addPath(e, v.path) + } else { + c.addPath(e, []string{ident}) + } + return selectAndIdentCost +} + +// costSelect estimates the cost of a field selection or map key access. +func (c *coster) costSelect(e ast.Expr) CostEstimate { + sel := e.AsSelect() + var sum CostEstimate + if sel.IsTestOnly() { + sum = sum.Add(c.presenceTestCost) + sum = sum.Add(branchQualifierCost(sel.Operand())) + } else { + sum = sum.Add(selectAndIdentCost) + } + sum = sum.Add(c.cost(sel.Operand())) + sum = sum.Add(c.relativeAttributeCost(sel.Operand())) + targetPath := c.getPath(sel.Operand()) + if len(targetPath) > 0 { + c.addPath(e, append(targetPath, sel.FieldName())) + } + return sum +} + +// branchQualifierCost is the cost of the qualification a presence test applies to the branch of a +// conditional at the root of its operand's attribute chain. The interpreter charges it when the +// selected branch is computed. When the branch is an attribute, the estimate already accounts for +// it with the cost of the branch's root, which the interpreter resolves without charging. +func branchQualifierCost(operand ast.Expr) CostEstimate { + root := attributeChainRoot(operand) + if !isConditionalCall(root) { + return CostEstimate{} + } + args := root.AsCall().Args() + if len(args) != 3 { + return CostEstimate{} + } + branch := func(e ast.Expr) CostEstimate { + if !isAttributeChain(e) || (e.Kind() == ast.SelectKind && e.AsSelect().IsTestOnly()) { + return FixedCostEstimate(SelectAndIdentCost) + } + return branchQualifierCost(e) + } + return branch(args[1]).Union(branch(args[2])) +} + +// attributeChainRoot returns the expression an attribute chain starts from, past the selections +// and index operations which extend it. +func attributeChainRoot(e ast.Expr) ast.Expr { + for { + switch e.Kind() { + case ast.SelectKind: + if e.AsSelect().IsTestOnly() { + return e + } + e = e.AsSelect().Operand() + case ast.CallKind: + call := e.AsCall() + switch call.FunctionName() { + case operators.Index, operators.OptIndex, operators.OptSelect: + if len(call.Args()) > 0 { + e = call.Args()[0] + continue + } + } + return e + default: + return e + } + } +} + +// relativeAttributeCost is the cost of qualifying a value which was computed rather than named. +func (c *coster) relativeAttributeCost(operand ast.Expr) CostEstimate { + if c.modelVersion < 1 || isAttributeChain(operand) { + return CostEstimate{} + } + return FixedCostEstimate(SelectAndIdentCost) +} + +// isAttributeChain reports whether an expression is resolved as part of a single attribute +// during evaluation. A chain begins at an identifier, or at a ternary which selects between +// attributes, and is extended by field selections and index operations, including their +// optional variants. +// +// This predicate must mirror the planner's decision to wrap an operand in a relative +// attribute: any expression which plans to an interpretable attribute extends the chain and +// does not incur an additional attribute resolution cost. +func isAttributeChain(e ast.Expr) bool { + switch e.Kind() { + case ast.IdentKind, ast.SelectKind: + return true + case ast.CallKind: + switch e.AsCall().FunctionName() { + case operators.Index, operators.OptIndex, operators.OptSelect, operators.Conditional: + return true + } + } + return false +} + +// costCall estimates the cost of evaluating a function call expression. +func (c *coster) costCall(e ast.Expr) CostEstimate { + if e.AsCall().FunctionName() == "cel.@block" { + return c.costBlock(e) + } + // Dyn is just a way to disable type-checking, so return the cost of 1 with the cost of the argument + if dynEstimate := c.maybeUnwrapDynCall(e); dynEstimate != nil { + return *dynEstimate + } + + // Continue estimating the cost of all other calls. + call := e.AsCall() + args := call.Args() + var sum CostEstimate + + // Index-like operators qualify their first argument, which requires a relative attribute + // when the operand is a computed value rather than a named one. + switch call.FunctionName() { + case operators.Index, operators.OptIndex, operators.OptSelect: + if len(args) > 0 { + sum = sum.Add(c.relativeAttributeCost(args[0])) + } + } + + var argCostBuf [4]CostEstimate + var argCosts []CostEstimate + if len(args) <= len(argCostBuf) { + argCosts = argCostBuf[:len(args)] + } else { + argCosts = make([]CostEstimate, len(args)) + } + for i, arg := range args { + argCosts[i] = c.cost(arg) + } + if call.FunctionName() == operators.Conditional && len(args) == 3 && c.modelVersion >= 1 { + argCosts[1] = conditionalBranchCost(args[1], argCosts[1]) + argCosts[2] = conditionalBranchCost(args[2], argCosts[2]) + } + + overloadIDs := c.checkedAST.GetOverloadIDs(e.ID()) + if len(overloadIDs) == 0 { + var argCostSum CostEstimate + for _, a := range argCosts { + argCostSum = argCostSum.Add(a) + } + return FixedCostEstimate(1).Add(sum).Add(argCostSum) + } + if call.IsMemberFunction() { + sum = sum.Add(c.cost(call.Target())) + } + var argTypeBuf [4]AstNode + var argTypes []AstNode + var targetNode AstNode + var targetType *AstNode + if c.needsCallNodes(overloadIDs) { + if len(args) <= len(argTypeBuf) { + argTypes = argTypeBuf[:len(args)] + } else { + argTypes = make([]AstNode, len(args)) + } + for i, arg := range args { + argTypes[i] = c.newAstNode(arg) + } + if call.IsMemberFunction() { + targetNode = c.newAstNode(call.Target()) + targetType = &targetNode + } + } + // Pick a cost estimate range that covers all the overload cost estimation ranges + fnCost := CostEstimate{Min: uint64(math.MaxUint64), Max: 0} + var resultSize *SizeEstimate + for _, overload := range overloadIDs { + overloadCost := c.functionCost(e, call.FunctionName(), overload, targetType, argTypes, argCosts) + fnCost = fnCost.Union(overloadCost.CostEstimate) + overloadSize := overloadCost.ResultSize + optIndex := c.modelVersion >= 1 && isOptionalIndex(overload) + // build and track the field path for index operations + if field, ok := c.indexFieldPath(overload); ok && len(args) > 0 { + if targetPath := c.getPath(args[0]); len(targetPath) > 0 { + c.addPath(e, append(targetPath, field)) + } else if containerSize := c.indexedContainerSize(overload, args[0]); containerSize != nil && containerSize.Elem != nil { + elemSize := *containerSize.Elem + overloadSize = &elemSize + } + } + if overloadSize == nil { + if optIndex { + overloadSize = c.optionalValueSize(e) + } else { + overloadSize = c.computeSize(e) + } + } + if optIndex && overloadSize != nil { + wrapped := optionalSizeOf(*overloadSize) + overloadSize = &wrapped + } + resultSize = mergeSizeEstimatePtr(resultSize, overloadSize) + } + c.setSize(e, resultSize) + return sum.Add(fnCost) +} + +// isOptionalIndex reports whether an overload is an optional index operation, l[?i] or m[?k], which +// returns an optional holding the element it selects. +func isOptionalIndex(overloadID string) bool { + switch overloadID { + case overloads.OptIndexList, overloads.OptIndexMap, overloads.OptIndexOptionalList, overloads.OptIndexOptionalMap: + return true + } + return false +} + +// indexedContainerSize returns the size of the container an index operation selects from. From +// version 1 the operand of an optional index on an optional receiver is the optional, whose element +// is the container. +func (c *coster) indexedContainerSize(overloadID string, operand ast.Expr) *SizeEstimate { + size := c.computeSize(operand) + if size == nil || c.modelVersion < 1 { + return size + } + switch overloadID { + case overloads.OptIndexOptionalList, overloads.OptIndexOptionalMap: + return size.Elem + } + return size +} + +// optionalValueSize estimates the value an optional-typed expression holds from the size hints for +// its path and the value's type. +func (c *coster) optionalValueSize(e ast.Expr) *SizeEstimate { + t := c.getType(e) + if t.Kind() != types.OpaqueKind || len(t.Parameters()) != 1 { + return nil + } + node := astNode{path: c.getPath(e), t: t.Parameters()[0]} + if size, ok := c.sizingStrategy.EstimateSize(c.newEstimateContext(), node); ok { + return &size + } + return nil +} + +func (c *coster) needsCallNodes(overloadIDs []string) bool { + if c.estimator != nil { + return true + } + std := c.standardOverloadEstimators + for _, id := range overloadIDs { + if _, ok := c.overloadEstimators.fns[id]; ok { + return true + } + if _, ok := std[id]; ok { + return true + } + } + return false +} + +// indexFieldPath reports the field path segment an index overload qualifies its operand with, so +// that the size hint recorded for a container's elements is found when one of them is read. +// +// The optional forms count only from version 1. Before the revision `l[?0]` recorded no path, +// so the `@items` hint that `l[0]` finds was never consulted and every estimate below an optional +// index was unbounded. A pinned caller keeps that. +func (c *coster) indexFieldPath(overloadID string) (string, bool) { + switch overloadID { + case overloads.IndexList: + return "@items", true + case overloads.IndexMap: + return "@values", true + case overloads.OptIndexList, overloads.OptIndexOptionalList: + return "@items", c.modelVersion >= 1 + case overloads.OptIndexMap, overloads.OptIndexOptionalMap: + return "@values", c.modelVersion >= 1 + } + return "", false +} + +// maybeUnwrapDynCall handles the 'dyn' call wrapper, returning an estimate if matched. +func (c *coster) maybeUnwrapDynCall(e ast.Expr) *CostEstimate { + call := e.AsCall() + if call.FunctionName() != "dyn" { + return nil + } + arg := call.Args()[0] + argCost := c.cost(arg) + c.copySizeEstimates(e, arg) + callCost := FixedCostEstimate(1).Add(argCost) + return &callCost +} + +// costBlock estimates the cost of a cel.@block([slot0, slot1, ...], resultExpr) call, +// binding each slot expression to @index0, @index1, ... while evaluating the block result. +func (c *coster) costBlock(e ast.Expr) CostEstimate { + call := e.AsCall() + args := call.Args() + if len(args) != 2 || args[0].Kind() != ast.ListKind { + return FixedCostEstimate(1) + } + slots := args[0].AsList().Elements() + var sum CostEstimate + for i, slot := range slots { + sum = sum.Add(c.cost(slot)) + c.pushLocalVar("@index"+strconv.Itoa(i), slot) + } + sum = sum.Add(c.cost(args[1])) + if p := c.getPath(args[1]); len(p) > 0 { + c.addPath(e, p) + } + c.copySizeEstimates(e, args[1]) + for i := len(slots) - 1; i >= 0; i-- { + c.popLocalVar("@index" + strconv.Itoa(i)) + } + return sum +} + +// costCreateList estimates the cost of constructing a list literal. +func (c *coster) costCreateList(e ast.Expr) CostEstimate { + create := e.AsList() + var sum CostEstimate + for _, elem := range create.Elements() { + sum = sum.Add(c.cost(elem)) + } + return sum.Add(createListBaseCost) +} + +// costCreateMap estimates the cost of constructing a map literal. +func (c *coster) costCreateMap(e ast.Expr) CostEstimate { + mapVal := e.AsMap() + var sum CostEstimate + for _, ent := range mapVal.Entries() { + entry := ent.AsMapEntry() + sum = sum.Add(c.cost(entry.Key())) + sum = sum.Add(c.cost(entry.Value())) + } + return sum.Add(createMapBaseCost) +} + +// costCreateStruct estimates the cost of constructing a struct or message literal. +func (c *coster) costCreateStruct(e ast.Expr) CostEstimate { + msgVal := e.AsStruct() + var sum CostEstimate + for _, ent := range msgVal.Fields() { + field := ent.AsStructField() + sum = sum.Add(c.cost(field.Value())) + } + return sum.Add(createMessageBaseCost) +} + +// costComprehension estimates the cost of evaluating a comprehension loop. +func (c *coster) costComprehension(e ast.Expr) CostEstimate { + comp := e.AsComprehension() + var sum CostEstimate + sum = sum.Add(c.cost(comp.IterRange())) + sum = sum.Add(c.cost(comp.AccuInit())) + c.pushLocalVar(comp.AccuVar(), comp.AccuInit()) + + // Track the iterRange of each IterVar and AccuVar for field path construction + if comp.HasIterVar2() { + c.pushIterKey(comp.IterVar(), comp.IterRange()) + c.pushIterValue(comp.IterVar2(), comp.IterRange()) + } else { + c.pushIterSingle(comp.IterVar(), comp.IterRange()) + } + + // Determine the cost for each element in the loop + loopCost := c.cost(comp.LoopCondition()) + stepCost := c.cost(comp.LoopStep()) + stepSize := c.computeSize(comp.LoopStep()) + + // Clear the intermediate variable tracking. + c.popLocalVar(comp.IterVar()) + if comp.HasIterVar2() { + c.popLocalVar(comp.IterVar2()) + } + + // Determine the result cost. + sum = sum.Add(c.cost(comp.Result())) + c.localVars.pop(comp.AccuVar()) + + // Estimate the cost of the loop. + rangeSize := c.sizeOrUnknown(comp.IterRange()) + // The loop runs once per element or entry of the range, which the sizing strategy may + // size by content rather than by length. + rangeCnt := countBounds(c.sizingStrategy, rangeSize) + rangeCnt.Key, rangeCnt.Elem = rangeSize.Key, rangeSize.Elem + rangeCost := rangeCnt.MultiplyByCost(stepCost.Add(loopCost)) + sum = sum.Add(rangeCost) + + switch k := comp.AccuInit().Kind(); k { + case ast.LiteralKind: + c.setSize(e, c.computeSize(comp.AccuInit())) + case ast.ListKind, ast.MapKind: + accuSize := rangeCnt + if k == ast.ListKind { + accuSize.Key = nil + } + if stepSize != nil { + if stepSize.Elem != nil { + accuSize.Elem = stepSize.Elem + } + if k == ast.MapKind && stepSize.Key != nil { + accuSize.Key = stepSize.Key + } + } + // A conditional step, as in filter, may skip an iteration, so the container may hold + // no entries at all. + if isConditionalCall(comp.LoopStep()) { + accuSize.Min = 0 + } + // The accumulated container holds at most one entry per iteration; report the size the + // sizing strategy assigns to it. + sized := containerSizeFor(c.sizingStrategy, accuSize, accumulatedEntrySize(accuSize)) + sized.Key, sized.Elem = accuSize.Key, accuSize.Elem + accuSize = sized + c.setSize(e, &accuSize) + } + return sum +} + +// accumulatedEntrySize returns the size of one entry of an accumulated container: its element, or +// its key and value. An unknown part is unbounded. +func accumulatedEntrySize(sz SizeEstimate) SizeEstimate { + entry := UnknownSizeEstimate() + if sz.Elem != nil { + entry = RangedSizeEstimate(sz.Elem.Min, sz.Elem.Max) + } + if sz.Key != nil { + withKey := entry.Add(RangedSizeEstimate(sz.Key.Min, sz.Key.Max)) + entry = RangedSizeEstimate(withKey.Min, withKey.Max) + } + return entry +} + +// conditionalBranchCost is the cost of a conditional's branch from cost model version 1. +// +// A branch which is an attribute chain rooted at an identifier, such as x, m.a or x[0], is resolved +// as part of the conditional's attribute: the interpreter charges the condition and the branch's +// qualifiers, but not the resolution of the branch's root identifier, which the estimate of the +// branch includes. A branch rooted at a nested conditional is priced by that conditional, and a +// computed branch is charged in full. +func conditionalBranchCost(branch ast.Expr, cost CostEstimate) CostEstimate { + if !isAttributeChain(branch) || attributeChainRoot(branch).Kind() != ast.IdentKind { + return cost + } + if branch.Kind() == ast.SelectKind && branch.AsSelect().IsTestOnly() { + return cost + } + return CostEstimate{ + Min: SafeSubtract(cost.Min, SelectAndIdentCost), + Max: SafeSubtract(cost.Max, SelectAndIdentCost), + } +} + +// isConditionalCall reports whether e is a call to the conditional operator. +func isConditionalCall(e ast.Expr) bool { + return e.Kind() == ast.CallKind && e.AsCall().FunctionName() == operators.Conditional +} + +// isBind returns true if the given expression represents a cel.bind() macro structure. +func (c *coster) isBind(e ast.Expr) bool { + comp := e.AsComprehension() + iterRange := comp.IterRange() + loopCond := comp.LoopCondition() + return iterRange.Kind() == ast.ListKind && iterRange.AsList().Size() == 0 && + loopCond.Kind() == ast.LiteralKind && loopCond.AsLiteral() == types.False && + !isAccumulatorVar(comp.AccuVar()) +} + +// costBind estimates the cost of a cel.bind() variable declaration macro. +func (c *coster) costBind(e ast.Expr) CostEstimate { + comp := e.AsComprehension() + var sum CostEstimate + // Binds are lazily initialized, so we retain the cost of an empty iteration range. + sum = sum.Add(c.cost(comp.IterRange())) + initCost := c.cost(comp.AccuInit()) + if c.modelVersion >= 1 && !mustReadVar(comp.Result(), comp.AccuVar()) { + // The bound value is computed only if the result reads it, so unless every evaluation of + // the result reads it, its cost contributes to the upper bound alone. + initCost = CostEstimate{Min: 0, Max: initCost.Max} + } + sum = sum.Add(initCost) + + c.pushLocalVar(comp.AccuVar(), comp.AccuInit()) + sum = sum.Add(c.cost(comp.Result())) + if p := c.getPath(comp.Result()); len(p) > 0 { + c.addPath(e, p) + } + // Associate the bind output size with the result size before popping the bound variable. + c.copySizeEstimates(e, comp.Result()) + c.popLocalVar(comp.AccuVar()) + + return sum +} + +// mustReadVar reports whether every evaluation of e reads the variable name. It is conservative: +// operands which may be skipped, such as the right side of a logical operator, the branches of a +// conditional, the alternative of an optional, and the body of a comprehension, do not count, +// and neither does the bound value of a nested bind, which is itself lazy. +func mustReadVar(e ast.Expr, name string) bool { + switch e.Kind() { + case ast.IdentKind: + return e.AsIdent() == name + case ast.SelectKind: + return mustReadVar(e.AsSelect().Operand(), name) + case ast.CallKind: + call := e.AsCall() + args := call.Args() + switch call.FunctionName() { + case operators.LogicalAnd, operators.LogicalOr, operators.Conditional: + return len(args) > 0 && mustReadVar(args[0], name) + case "or", "orValue": + if call.IsMemberFunction() { + return mustReadVar(call.Target(), name) + } + } + if call.IsMemberFunction() && mustReadVar(call.Target(), name) { + return true + } + for _, arg := range args { + if mustReadVar(arg, name) { + return true + } + } + return false + case ast.ListKind: + for _, elem := range e.AsList().Elements() { + if mustReadVar(elem, name) { + return true + } + } + return false + case ast.MapKind: + for _, entry := range e.AsMap().Entries() { + me := entry.AsMapEntry() + if mustReadVar(me.Key(), name) || mustReadVar(me.Value(), name) { + return true + } + } + return false + case ast.StructKind: + for _, field := range e.AsStruct().Fields() { + if mustReadVar(field.AsStructField().Value(), name) { + return true + } + } + return false + case ast.ComprehensionKind: + comp := e.AsComprehension() + if mustReadVar(comp.IterRange(), name) { + return true + } + // A bind's value is lazy: it is computed only when its result reads it, and its result, + // unless the bind shadows name, may read name directly. A loop's initial accumulator is + // always computed. + isBind := comp.IterRange().Kind() == ast.ListKind && comp.IterRange().AsList().Size() == 0 && + !isAccumulatorVar(comp.AccuVar()) + if isBind { + if comp.AccuVar() != name && mustReadVar(comp.Result(), name) { + return true + } + return mustReadVar(comp.Result(), comp.AccuVar()) && mustReadVar(comp.AccuInit(), name) + } + return mustReadVar(comp.AccuInit(), name) + default: + return false + } +} + +// calculateArgCost combines the costs of a call's arguments at the given cost model version. +func calculateArgCost(overloadID string, argCosts []CostEstimate, version uint32) CostEstimate { + switch overloadID { + case overloads.LogicalOr, overloads.LogicalAnd: + if len(argCosts) == 2 { + return CostEstimate{Min: argCosts[0].Min, Max: argCosts[0].Add(argCosts[1]).Max} + } + case overloads.Conditional: + if len(argCosts) == 3 { + return argCosts[0].Add(argCosts[1].Union(argCosts[2])) + } + case overloads.OptionalOrOptional, overloads.OptionalOrValueValue: + // The alternative is evaluated only when the receiver is empty, so it contributes to the + // upper bound alone. These are member overloads, which means the receiver is costed by + // the caller and argCosts holds only the alternative. Before version 1 the alternative + // was summed like any other argument. + if len(argCosts) == 1 && version >= 1 { + return CostEstimate{Min: 0, Max: argCosts[0].Max} + } + } + var sum CostEstimate + for _, a := range argCosts { + sum = sum.Add(a) + } + return sum +} + +func (c *coster) functionCost(e ast.Expr, function, overloadID string, target *AstNode, args []AstNode, argCosts []CostEstimate) CallEstimate { + argCost := calculateArgCost(overloadID, argCosts, c.modelVersion) + c.est.callID = e.ID() + estCtx := c.getEstimator() + if estimator, found := c.overloadEstimators.fns[overloadID]; found { + if est := estimator(estCtx, target, args); est != nil { + return CallEstimate{CostEstimate: est.Add(argCost), ResultSize: est.ResultSize} + } + } + if c.estimator != nil { + if est := c.estimator.EstimateCallCost(function, overloadID, target, args); est != nil { + return CallEstimate{CostEstimate: est.Add(argCost), ResultSize: est.ResultSize} + } + } + if estimator, found := c.standardOverloadEstimators[overloadID]; found { + if est := estimator(estCtx, target, args); est != nil { + return CallEstimate{CostEstimate: est.Add(argCost), ResultSize: est.ResultSize} + } + } + // O(1) functions + // See CostTracker.costCall for more details about O(1) cost calculations + + // Benchmarks suggest that most of the other operations take +/- 50% of a base cost unit + // which on an Intel xeon 2.20GHz CPU is 50ns. + return CallEstimate{CostEstimate: FixedCostEstimate(1).Add(argCost)} +} + +// getType returns the deduced type of an expression ID from the checked AST. +func (c *coster) getType(e ast.Expr) *types.Type { + return c.checkedAST.GetType(e.ID()) +} + +// getPath returns the tracked field path for an expression node, resolving through local variables if needed. +func (c *coster) getPath(e ast.Expr) []string { + if e == nil { + return nil + } + if e.Kind() == ast.IdentKind { + if v, found := c.peekLocalVar(e.AsIdent()); found { + return v.path[:] + } + } + if path, ok := c.exprPaths[e.ID()]; ok { + return path + } + return nil +} + +// addPath associates an expression ID with its path. +func (c *coster) addPath(e ast.Expr, path []string) { + c.exprPaths[e.ID()] = path +} + +var ( + stdOverloadEstimators = StandardOverloadEstimators() +) + +func isAccumulatorVar(name string) bool { + return name == accumulatorName || name == hiddenAccumulatorName +} + +func (c *coster) newAstNode(e ast.Expr) AstNode { + return astNode{ + path: c.getPath(e), + t: c.getType(e), + expr: e, + derivedSize: ownedSize(c.computeSize(e))} +} + +// ownedSize returns a size estimate pointer which the caller may retain or modify. +// +// computeSize returns the shared unitSizeEstimate and zeroSizeEstimate for scalars and empty or +// single-unit literals so that the common case does not allocate. Those values back every such +// estimate, so a pointer which escapes into a retained structure, or to a FunctionEstimator through +// AstNode.ComputedSize, is copied first; a write through it must never reach the shared values. +func ownedSize(sz *SizeEstimate) *SizeEstimate { + if sz == &unitSizeEstimate || sz == &zeroSizeEstimate { + owned := *sz + return &owned + } + return sz +} + +// setSize stores a computed size estimate for an expression ID. +func (c *coster) setSize(e ast.Expr, size *SizeEstimate) { + if size == nil { + return + } + // Store the computed size with the expression + c.computedSizes[e.ID()] = *size +} + +func (c *coster) sizeOrUnknown(node ast.Expr) SizeEstimate { + if sz := c.computeSize(node); sz != nil { + return *sz + } + return UnknownSizeEstimate() +} + +// copySizeEstimates copies computed sizes and entry sizes from a source expression to a destination expression. +func (c *coster) copySizeEstimates(dst, src ast.Expr) { + c.setSize(dst, c.computeSize(src)) +} + +type versionedEstimator struct { + coster *coster + delegate Estimator + version uint32 + strategy SizingStrategy + // callID is the expression ID of the call being estimated, if any. + callID int64 +} + +func (v *versionedEstimator) EstimateSize(element AstNode) *SizeEstimate { + if v.delegate == nil { + return nil + } + return v.delegate.EstimateSize(element) +} + +func (v *versionedEstimator) EstimateCallCost(function, overloadID string, target *AstNode, args []AstNode) *CallEstimate { + if v.delegate == nil { + return nil + } + return v.delegate.EstimateCallCost(function, overloadID, target, args) +} + +func (v *versionedEstimator) modelVersion() uint32 { + return v.version +} + +func (v *versionedEstimator) sizingStrategy() SizingStrategy { + return v.strategy +} + +func (v *versionedEstimator) resultType() (*types.Type, bool) { + return v.coster.checkedAST.GetType(v.callID), true +} + +func (c *coster) getEstimator() Estimator { + return &c.est +} + +func (c *coster) newEstimateContext() *estimatorEvalContext { + return &c.evalCtx +} + +// computeSize resolves the size estimate for an expression, caching the result when found. +func (c *coster) computeSize(e ast.Expr) *SizeEstimate { + if size, ok := c.computedSizes[e.ID()]; ok { + if size == unitSizeEstimate { + return &unitSizeEstimate + } + if size == zeroSizeEstimate { + return &zeroSizeEstimate + } + return &size + } + if e.Kind() == ast.IdentKind { + varName := e.AsIdent() + if v, ok := c.peekLocalVar(varName); ok && v.size != nil { + if c.modelVersion < 1 && c.estimator != nil { + node := astNode{expr: e, path: c.getPath(e), t: c.getType(e)} + if size := c.estimator.EstimateSize(node); size != nil { + c.computedSizes[e.ID()] = *size + return size + } + } + return v.size + } + } + strategy := c.sizingStrategy + if strategy == defaultSizing { + if size := computeExprSize(e); size != nil { + c.computedSizes[e.ID()] = *size + return size + } + // Without an Estimator to supply hints, only a container's size needs the strategy. + if t := c.getType(e); c.estimator == nil && !isContainerKind(t.Kind()) { + if size := computeTypeSize(t, c.modelVersion); size != nil { + c.computedSizes[e.ID()] = *size + return size + } + return nil + } + } + node := astNode{expr: e, path: c.getPath(e), t: c.getType(e)} + ctx := c.newEstimateContext() + if size, ok := strategy.EstimateSize(ctx, node); ok { + c.computedSizes[e.ID()] = size + if size == unitSizeEstimate { + return &unitSizeEstimate + } + if size == zeroSizeEstimate { + return &zeroSizeEstimate + } + return &size + } + if size := computeExprSize(e); size != nil { + return size + } + if size := computeTypeSize(c.getType(e), c.modelVersion); size != nil { + return size + } + return nil +} + +// computeExprSize computes the size estimate from literal and declared container expressions. +func computeExprSize(expr ast.Expr) *SizeEstimate { + var v uint64 + switch expr.Kind() { + case ast.LiteralKind: + switch ck := expr.AsLiteral().(type) { + case types.String: + // converting to runes here is an O(n) operation, but + // this is consistent with how size is computed at runtime, + // and how the language definition defines string size + v = uint64(len([]rune(ck))) + case types.Bytes: + v = uint64(len(ck)) + case types.Bool, types.Double, types.Duration, + types.Int, types.Timestamp, types.Uint, + types.Null: + return &unitSizeEstimate + default: + return nil + } + default: + return nil + } + if v == 1 { + return &unitSizeEstimate + } + if v == 0 { + return &zeroSizeEstimate + } + size := FixedSizeEstimate(v) + return &size +} + +// computeTypeSize returns a fixed unit size estimate if the type is a constant-size scalar. +// computeTypeSize returns the size every value of a type has at the given cost model version, or nil +// if values of the type vary in size. +// +// A scalar has size 1. An optional of a scalar has size 1 before version 1, and from version 1 is 1 +// plus the scalar, which is its element; see Optional. +func computeTypeSize(t *types.Type, version uint32) *SizeEstimate { + if isScalar(t) { + return &unitSizeEstimate + } + if isOptionalType(t) && isScalar(t.Parameters()[0]) { + if version < 1 { + return &unitSizeEstimate + } + size := optionalSizeOf(unitSizeEstimate) + return &size + } + return nil +} + +// isOptionalType reports whether t is an optional type with a value type. +func isOptionalType(t *types.Type) bool { + return t.Kind() == types.OpaqueKind && t.TypeName() == "optional_type" && len(t.Parameters()) == 1 +} + +// optionalSizeOf returns the size of an optional which holds a value of size v, from cost model +// version 1: 1 plus the value, whose size is the optional's element. See Optional. +func optionalSizeOf(v SizeEstimate) SizeEstimate { + size := RangedSizeEstimate(SafeAdd(1, v.Min), SafeAdd(1, v.Max)) + size.Elem = &v + return size +} + +// isScalar returns true if the given type is known to be of a constant size at +// compile time. isScalar will return false for strings (they are variable-width) +// in addition to protobuf.Any and protobuf.Value (their size is not knowable at compile time). +func isScalar(t *types.Type) bool { + switch t.Kind() { + case types.BoolKind, types.DoubleKind, types.DurationKind, types.IntKind, types.TimestampKind, types.UintKind, types.TypeKind: + return true + } + return false +} + +var ( + unknownSizeEstimate = SizeEstimate{Min: 0, Max: math.MaxUint64} + unknownCostEstimate = unknownSizeEstimate.MultiplyByCostFactor(1) + unitSizeEstimate = FixedSizeEstimate(1) + zeroSizeEstimate = FixedSizeEstimate(0) + + selectAndIdentCost = FixedCostEstimate(SelectAndIdentCost) + constCost = FixedCostEstimate(ConstCost) + + createListBaseCost = FixedCostEstimate(ListCreateBaseCost) + createMapBaseCost = FixedCostEstimate(MapCreateBaseCost) + createMessageBaseCost = FixedCostEstimate(StructCreateBaseCost) + + accumulatorName = "__result__" + hiddenAccumulatorName = "@result" +) diff --git a/vendor/cel.dev/cel-go/common/cost/helper.go b/vendor/cel.dev/cel-go/common/cost/helper.go new file mode 100644 index 0000000000..ba5d956459 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/helper.go @@ -0,0 +1,599 @@ +// Copyright 2026 Google LLC +// +// 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 cost + +import ( + "math" + "math/bits" + + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" +) + +// ContainerSizing describes what the size of a container measures under a sizing strategy. +type ContainerSizing int + +const ( + // SizedByLength means a container's size is its length, as under the default sizing strategy. + SizedByLength ContainerSizing = iota + // SizedByContent means a container's size is 1 plus the sizes of its entries, as under the + // aggregate sizing strategy. + SizedByContent + // SizedOpaque means the relationship between a container's size and its contents is not known, + // as under a custom sizing strategy. + SizedOpaque +) + +// ContainerSizingOf reports what a container's size measures for the given Estimator. +// +// A hand-written FunctionEstimator which builds a result's size from lengths, rather than from +// the sizes of its operands, uses it to report the size in the units of the sizing strategy. For +// an Estimator which carries no strategy, sizes are lengths. Prefer describing an overload by an +// OverloadModel, whose List and Map follow the strategy themselves. +func ContainerSizingOf(estimator Estimator) ContainerSizing { + s, ok := estimator.(sizingStrategyContext) + if !ok { + return SizedByLength + } + switch s.sizingStrategy().(type) { + case defaultSizingStrategy: + return SizedByLength + case *aggregateSizingStrategy: + return SizedByContent + default: + return SizedOpaque + } +} + +// sizingStrategyContext is implemented by EstimateContext values which expose their sizing +// strategy. It is unexported because EstimateContext is an interface third parties may implement. +type sizingStrategyContext interface { + sizingStrategy() SizingStrategy +} + +// strategyOf returns the sizing strategy of a context. A context which does not report one, such +// as a third-party EstimateContext, is sized by the default strategy, whose sizes are lengths. +func strategyOf(ctx EstimateContext) SizingStrategy { + if s, ok := ctx.(sizingStrategyContext); ok { + return s.sizingStrategy() + } + return defaultSizing +} + +// resultTypeContext is implemented by EstimateContext values which know the checked type of the +// call's result. It is unexported because EstimateContext is an interface third parties may +// implement. +type resultTypeContext interface { + resultType() (*types.Type, bool) +} + +// operandKind returns the kind of the checked type of an Arg, Target or Result operand. +func operandKind(ctx EstimateContext, e QuantityExpr) (types.Kind, bool) { + var t *types.Type + var ok bool + switch x := e.(type) { + case argExpr: + t, ok = ctx.ArgType(x.index) + case targetExpr: + t, ok = ctx.TargetType() + case resultExpr: + if rc, isRC := ctx.(resultTypeContext); isRC { + t, ok = rc.resultType() + } + } + if !ok || t == nil { + return types.UnspecifiedKind, false + } + switch t.Kind() { + case types.DynKind, types.AnyKind, types.TypeParamKind, types.UnspecifiedKind, types.ErrorKind: + return types.UnspecifiedKind, false + } + return t.Kind(), true +} + +// operandNodeContext is implemented by EstimateContext values which know the AST nodes of the +// call being estimated. It is unexported because EstimateContext is an interface third parties may +// implement. +type operandNodeContext interface { + operandNode(e QuantityExpr) (AstNode, bool) +} + +// operandLiteral returns the value of an Arg or Target operand which is a literal. +func operandLiteral(ctx EstimateContext, e QuantityExpr) (ref.Val, bool) { + oc, ok := ctx.(operandNodeContext) + if !ok { + return nil, false + } + node, ok := oc.operandNode(e) + if !ok || node == nil || node.Expr() == nil || node.Expr().Kind() != ast.LiteralKind { + return nil, false + } + return node.Expr().AsLiteral(), true +} + +// hasUnitLength reports whether every value of a kind has length 1: those which are neither +// strings, bytes nor containers. +func hasUnitLength(k types.Kind) bool { + switch k { + case types.BoolKind, types.DoubleKind, types.DurationKind, types.IntKind, types.NullTypeKind, + types.TimestampKind, types.UintKind: + return true + default: + return false + } +} + +// totalEstimate bounds the summed size of one part of a container, its elements or its keys, from +// the container's size estimate sz and the estimated size of one part. whole reports whether the +// part is the container's entire content, as the elements of a list are, rather than a share of +// it, as the keys or values of a map are. +// +// - Default strategy: a container's size is its length, so the total is the length multiplied +// by the part size. +// - Aggregate strategy: a container's size is 1 plus the sizes of its entries, so every part +// totals at most the content size, sz-1. The content size is also the lower bound when the +// part is the whole content; otherwise the lower bound is 0. +// - Other strategies define no relationship between a container's size and its contents, so the +// total is unknown. +// +// A value which the checker typed as having no elements, such as a string, and a container which +// may not hold anything, total 0. A container which may hold something, but whose part size is not +// stated, has an unknown total under the default strategy. +func totalEstimate(ctx EstimateContext, operand QuantityExpr, sz SizeEstimate, part *SizeEstimate, whole bool) SizeEstimate { + if !carriesElements(ctx, operand) || !mayHoldElements(ctx, sz) { + return FixedSizeEstimate(0) + } + switch strategyOf(ctx).(type) { + case defaultSizingStrategy: + if part == nil { + return UnknownSizeEstimate() + } + total := RangedSizeEstimate(sz.Min, sz.Max).Multiply(*part) + return RangedSizeEstimate(total.Min, total.Max) + case *aggregateSizingStrategy: + hi := SafeSubtract(sz.Max, 1) + if sz.Max == math.MaxUint64 { + hi = math.MaxUint64 + } + lo := uint64(0) + if whole { + lo = SafeSubtract(sz.Min, 1) + } + return RangedSizeEstimate(min(lo, hi), hi) + default: + return UnknownSizeEstimate() + } +} + +// isListOperand reports whether the operand of a total is a list, whose elements are its entire +// content, rather than a map, whose values are only part of it. The checked type decides when it is +// known; otherwise the metadata does, since a list states an element size but no key size. +func isListOperand(ctx EstimateContext, operand QuantityExpr, sz SizeEstimate) bool { + if kind, known := operandKind(ctx, operand); known { + return kind == types.ListKind + } + return sz.Elem != nil && sz.Key == nil +} + +// countBounds bounds the element count of a container from its size estimate under a strategy. +// It bounds comprehension iteration counts; see costComprehension. +// +// The default strategy sizes a container by its length, so the count is the size itself. The +// aggregate strategy sizes a container as 1 plus the sizes of its entries, each of which is at +// least 1, so the count is at least the content size divided by the largest entry. Its upper bound +// is the size itself rather than the content size divided by the smallest entry, so the bound +// remains sound for a size which a custom estimator reports as a length. Other strategies make no +// guarantee, so the count is unknown. +func countBounds(strategy SizingStrategy, sz SizeEstimate) SizeEstimate { + switch strategy.(type) { + case defaultSizingStrategy: + return RangedSizeEstimate(sz.Min, sz.Max) + case *aggregateSizingStrategy: + entry := aggregateEntrySize(sz) + lo := uint64(0) + if sz.Min > 1 && entry.Max != math.MaxUint64 { + content := sz.Min - 1 + lo = content / entry.Max + if content%entry.Max != 0 { + lo++ + } + } + return RangedSizeEstimate(min(lo, sz.Max), sz.Max) + default: + return UnknownSizeEstimate() + } +} + +// aggregateEntrySize bounds the aggregate size of one entry of a container: an element of a list, +// or a key and value of a map. Every value has aggregate size at least 1. +func aggregateEntrySize(sz SizeEstimate) SizeEstimate { + elem := RangedSizeEstimate(1, math.MaxUint64) + if sz.Elem != nil { + elem = AtLeastOneSize(RangedSizeEstimate(sz.Elem.Min, sz.Elem.Max)) + } + if sz.Key == nil { + return elem + } + key := AtLeastOneSize(RangedSizeEstimate(sz.Key.Min, sz.Key.Max)) + sum := key.Add(elem) + return RangedSizeEstimate(sum.Min, sum.Max) +} + +// rational is a non-negative scale factor p/q. A zero q marks a factor with no exact rational form +// within the supported range, which is applied in floating point. +type rational struct { + p, q uint64 +} + +// maxRationalDenominator bounds the denominator of an exact scale factor so that products of +// factors, and of a factor with a quantity, can be computed in 128-bit arithmetic. +const maxRationalDenominator = uint64(1) << 32 + +// rationalOf returns the simplest rational p/q whose float64 value is f, found from the continued +// fraction expansion of f. A decimal factor such as 0.1 is therefore applied as exactly 1/10, which +// is what the author wrote, rather than as the binary value nearest to it. +// +// Factors which are not finite and positive, or whose simplest form needs a denominator above +// maxRationalDenominator, report q == 0. +func rationalOf(f float64) rational { + if math.IsNaN(f) || math.IsInf(f, 0) || f <= 0 || f >= math.MaxUint64 { + return rational{} + } + // Convergents h/k of the continued fraction of f. + hPrev, h := uint64(0), uint64(1) + kPrev, k := uint64(1), uint64(0) + x := f + for i := 0; i < 64; i++ { + a := math.Floor(x) + if a >= math.MaxUint64 { + return rational{} + } + ai := uint64(a) + hiH, loH := bits.Mul64(ai, h) + hiK, loK := bits.Mul64(ai, k) + if hiH != 0 || hiK != 0 { + return rational{} + } + hNext, carryH := bits.Add64(loH, hPrev, 0) + kNext, carryK := bits.Add64(loK, kPrev, 0) + if carryH != 0 || carryK != 0 || kNext > maxRationalDenominator { + return rational{} + } + hPrev, h = h, hNext + kPrev, k = k, kNext + if float64(h)/float64(k) == f { + return rational{p: h, q: k} + } + frac := x - a + if frac == 0 { + return rational{} + } + x = 1 / frac + } + return rational{} +} + +// mul returns the product of two rationals in lowest terms, and false if the product does not fit +// within the supported range. +func (r rational) mul(o rational) (rational, bool) { + if r.q == 0 || o.q == 0 { + return rational{}, false + } + // Cross-reduce before multiplying to keep the terms small. + g1, g2 := gcd(r.p, o.q), gcd(o.p, r.q) + p1, q2 := r.p/g1, o.q/g1 + p2, q1 := o.p/g2, r.q/g2 + hiP, p := bits.Mul64(p1, p2) + hiQ, q := bits.Mul64(q1, q2) + if hiP != 0 || hiQ != 0 || q > maxRationalDenominator { + return rational{}, false + } + return rational{p: p, q: q}, true +} + +func gcd(a, b uint64) uint64 { + for b != 0 { + a, b = b, a%b + } + if a == 0 { + return 1 + } + return a +} + +// scale computes ⌈x · f⌉: +// +// - the factor is applied as its exact rational form when it has one (see rationalOf), so the +// result is exact for every input, including those above 2^53; +// - an unbounded input stays unbounded for any positive factor; +// - a zero input, or a zero or negative factor, yields zero; a NaN factor yields ⊤, so that an +// invalid factor cannot make a quantity free. +func scale(x uint64, f float64, r rational) uint64 { + switch { + case math.IsNaN(f): + return math.MaxUint64 + case f <= 0 || x == 0: + return 0 + case x == math.MaxUint64 || math.IsInf(f, 1): + return math.MaxUint64 + case r.q == 0: + return SafeMultiplyByFactor(x, f) + } + hi, lo := bits.Mul64(x, r.p) + if hi >= r.q { + return math.MaxUint64 + } + quo, rem := bits.Div64(hi, lo, r.q) + if rem != 0 { + if quo == math.MaxUint64 { + return math.MaxUint64 + } + quo++ + } + return quo +} + +// normalize moves scale factors outward so that each product and each uniformly scaled sum is +// rounded once: +// +// Scale(Scale(a, f), g) -> Scale(a, f·g) +// Mul(Scale(a, f), Scale(b, g), c) -> Scale(Mul(a, b, c), f·g) +// Sum(Scale(a, f), Scale(b, f)) -> Scale(Sum(a, b), f) +// +// Factors are combined as exact rationals. A combination which has no exact form within the +// supported range is left in place. +func normalize(e QuantityExpr) QuantityExpr { + if e == nil { + return nil + } + switch x := e.(type) { + case scaleExpr: + inner := normalize(x.expr) + if s, ok := inner.(scaleExpr); ok { + if r, ok := x.rat.mul(s.rat); ok { + return scaleExpr{expr: s.expr, factor: x.factor * s.factor, rat: r} + } + } + return scaleExpr{expr: inner, factor: x.factor, rat: x.rat} + case mulExpr: + terms := make([]QuantityExpr, 0, len(x.terms)) + for _, t := range x.terms { + t = normalize(t) + if m, ok := t.(mulExpr); ok { + terms = append(terms, m.terms...) + continue + } + terms = append(terms, t) + } + factor, rat, hoisted := 1.0, rational{p: 1, q: 1}, false + plain := make([]QuantityExpr, 0, len(terms)) + for _, t := range terms { + if s, ok := t.(scaleExpr); ok { + if r, ok := rat.mul(s.rat); ok { + factor, rat, hoisted = factor*s.factor, r, true + plain = append(plain, s.expr) + continue + } + } + plain = append(plain, t) + } + if hoisted { + return scaleExpr{expr: mulExpr{terms: plain}, factor: factor, rat: rat} + } + return mulExpr{terms: plain} + case addExpr: + terms := make([]QuantityExpr, len(x.terms)) + for i, t := range x.terms { + terms[i] = normalize(t) + } + if len(terms) > 1 { + if first, ok := terms[0].(scaleExpr); ok && first.rat.q != 0 { + inner := make([]QuantityExpr, len(terms)) + same := true + for i, t := range terms { + s, ok := t.(scaleExpr) + if !ok || s.rat != first.rat { + same = false + break + } + inner[i] = s.expr + } + if same { + return scaleExpr{expr: addExpr{terms: inner}, factor: first.factor, rat: first.rat} + } + } + } + return addExpr{terms: terms} + case subExpr: + return subExpr{lhs: normalize(x.lhs), rhs: normalize(x.rhs)} + case minExpr: + return minExpr{lhs: normalize(x.lhs), rhs: normalize(x.rhs)} + case maxExpr: + return maxExpr{lhs: normalize(x.lhs), rhs: normalize(x.rhs)} + case unionExpr: + terms := make([]QuantityExpr, len(x.terms)) + for i, t := range x.terms { + terms[i] = normalize(t) + } + return unionExpr{terms: terms} + case rangedExpr: + return rangedExpr{minExpr: normalize(x.minExpr), maxExpr: normalize(x.maxExpr)} + case atLeastOneExpr: + return atLeastOneExpr{expr: normalize(x.expr)} + case listExpr: + return listExpr{lenExpr: normalize(x.lenExpr), elemExpr: normalize(x.elemExpr)} + case mapExpr: + return mapExpr{sizeExpr: normalize(x.sizeExpr), keyExpr: normalize(x.keyExpr), valExpr: normalize(x.valExpr)} + case optionalExpr: + return optionalExpr{valueExpr: normalize(x.valueExpr)} + default: + // Atoms and projections contain no scale factors. + return e + } +} + +// carriesElements reports whether an expression may denote a container, and so whether an absent +// element or key size on its estimate means "unknown" rather than "none". +// +// Constants, integer values and totals are scalars. Arg, Target and Result may be containers, +// unless the checker typed the argument or receiver as something which has no elements, such as a +// string. The element and key projections may be containers, as may any combinator with such an +// operand. +func carriesElements(ctx EstimateContext, e QuantityExpr) bool { + switch x := e.(type) { + case argExpr: + t, ok := ctx.ArgType(x.index) + return !ok || mayBeContainerType(t) + case targetExpr: + t, ok := ctx.TargetType() + return !ok || mayBeContainerType(t) + case resultExpr, elemExpr, keyExpr, listExpr, mapExpr, optionalExpr: + return true + case subExpr: + return carriesElements(ctx, x.lhs) + case scaleExpr: + return carriesElements(ctx, x.expr) + case atLeastOneExpr: + return carriesElements(ctx, x.expr) + case minExpr: + return carriesElements(ctx, x.lhs) || carriesElements(ctx, x.rhs) + case maxExpr: + return carriesElements(ctx, x.lhs) || carriesElements(ctx, x.rhs) + case rangedExpr: + return carriesElements(ctx, x.minExpr) || carriesElements(ctx, x.maxExpr) + case addExpr: + return anyCarriesElements(ctx, x.terms) + case mulExpr: + return anyCarriesElements(ctx, x.terms) + case unionExpr: + return anyCarriesElements(ctx, x.terms) + default: + return false + } +} + +func anyCarriesElements(ctx EstimateContext, terms []QuantityExpr) bool { + for _, t := range terms { + if carriesElements(ctx, t) { + return true + } + } + return false +} + +// mayBeContainerType reports whether a value of the checked type may hold elements or keys. Only +// the kinds which cannot, such as strings, bytes and numbers, are excluded; an unknown type may be +// anything. +func mayBeContainerType(t *types.Type) bool { + if t == nil { + return true + } + k := t.Kind() + return !hasUnitLength(k) && k != types.StringKind && k != types.BytesKind +} + +// mergeMeta returns the union of the operands' key and element sizes. +// +// Metadata is attached only when some operand states it. When one does, an operand which may be a +// non-empty container but states no metadata contributes an unknown size, so the union cannot be +// narrower than what that operand may hold. Scalar operands, and empty containers, contribute +// nothing. +func mergeMeta(ctx EstimateContext, exprs []QuantityExpr, ests []SizeEstimate) (key, elem *SizeEstimate) { + anyKey, anyElem := false, false + for _, s := range ests { + anyKey = anyKey || s.Key != nil + anyElem = anyElem || s.Elem != nil + } + if !anyKey && !anyElem { + return nil, nil + } + for i, s := range ests { + // An operand which may be a non-empty container but states nothing about its contents may + // hold anything. One which states an element size but no key size is a list, which has no + // keys. + nonEmpty := mayHoldElements(ctx, s) + unstated := nonEmpty && s.Key == nil && s.Elem == nil && carriesElements(ctx, exprs[i]) + if anyElem { + e := s.Elem + if e == nil && (unstated || (s.Key != nil && nonEmpty)) { + e = &unknownSizeEstimate + } + elem = mergeSizeEstimatePtr(elem, e) + } + if anyKey { + k := s.Key + if k == nil && unstated { + k = &unknownSizeEstimate + } + key = mergeSizeEstimatePtr(key, k) + } + } + return key, elem +} + +// combineMeta attaches the operands' metadata, as mergeMeta merges it, to a combined estimate. +func combineMeta(ctx EstimateContext, size SizeEstimate, exprs []QuantityExpr, ests []SizeEstimate) SizeEstimate { + size.Key, size.Elem = mergeMeta(ctx, exprs, ests) + return size +} + +// mayHoldElements reports whether a container with the given size estimate may be non-empty under +// the context's sizing strategy. An empty container has size 0 under the default strategy and size +// 1 under the aggregate strategy. +func mayHoldElements(ctx EstimateContext, s SizeEstimate) bool { + if _, aggregate := strategyOf(ctx).(*aggregateSizingStrategy); aggregate { + return s.Max > 1 + } + return s.Max > 0 +} + +// aggregateResultSize raises the upper bound of a result size estimated under the aggregate +// strategy to at least 1. That strategy sizes an empty string, bytes value, list or map as 1, so a +// model whose result may be empty, such as a substring which drops the whole receiver, could +// otherwise report an upper bound of 0. Raising an upper bound is sound for any value. +func aggregateResultSize(strategy SizingStrategy, sz SizeEstimate) SizeEstimate { + if _, aggregate := strategy.(*aggregateSizingStrategy); aggregate && sz.Max == 0 { + sz.Max = 1 + } + return sz +} + +// containerSize returns the size the context's sizing strategy assigns to a container of n +// entries, each of the given size; see containerSizeFor. +func containerSize(ctx EstimateContext, n, entry SizeEstimate) SizeEstimate { + return containerSizeFor(strategyOf(ctx), n, entry) +} + +// containerSizeFor returns the size a strategy assigns to a container of n entries, each of the +// given size. +// +// The default strategy sizes a container by its length. The aggregate strategy sizes it as 1 plus +// the sizes of its entries, each of which is at least 1. Other strategies define no relationship, +// so the size is unknown. +func containerSizeFor(strategy SizingStrategy, n, entry SizeEstimate) SizeEstimate { + switch strategy.(type) { + case defaultSizingStrategy: + return RangedSizeEstimate(n.Min, n.Max) + case *aggregateSizingStrategy: + e := AtLeastOneSize(entry) + return RangedSizeEstimate( + SafeAdd(1, SafeMultiply(n.Min, e.Min)), + SafeAdd(1, SafeMultiply(n.Max, e.Max)), + ) + default: + return UnknownSizeEstimate() + } +} diff --git a/vendor/cel.dev/cel-go/common/cost/model.go b/vendor/cel.dev/cel-go/common/cost/model.go new file mode 100644 index 0000000000..6273c16157 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/model.go @@ -0,0 +1,1608 @@ +// Copyright 2026 Google LLC +// +// 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 cost + +import ( + "math" + "slices" + "sync" + + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" +) + +// TypeContext provides type information for AST nodes. +type TypeContext interface { + // TargetType returns the deduced type of the receiver/target object, if present. + TargetType() (*types.Type, bool) + + // ArgType returns the deduced type of the argument at the given 0-based index. + ArgType(index int) (*types.Type, bool) +} + +// EstimateContext provides size and argument evaluation during cost estimation. +type EstimateContext interface { + TypeContext + + // Arg returns the size estimate for the argument at the given 0-based index. + Arg(index int) (SizeEstimate, bool) + + // Target returns the size estimate for the receiver/target object, if present. + Target() (SizeEstimate, bool) + + // Result returns the size estimate of the evaluated result, if known. + Result() (SizeEstimate, bool) + + // Estimator returns the user-provided Estimator, if configured. + Estimator() Estimator + + // Size returns the estimated size based on the SizingStrategy configured on the Estimator. + Size(node AstNode) SizeEstimate + + // ArgValue returns the literal/constant uint64 value of the argument at index, or defaultVal. + ArgValue(index int, defaultVal uint64) uint64 + + // TargetValue returns the literal/constant uint64 value of the receiver/target, or defaultVal. + TargetValue(defaultVal uint64) uint64 +} + +// TrackContext provides value size and argument evaluation during runtime cost tracking. +type TrackContext interface { + TypeContext + + // Arg returns the size of the argument at the given 0-based index. + Arg(index int) uint64 + + // Target returns the size of the receiver/target object, if present. + Target() uint64 + + // Result returns the size of the evaluated result, if present. + Result() uint64 + + // Estimator returns the runtime ActualCostEstimator, if configured. + Estimator() ActualCostEstimator + + // Size returns the actual runtime size of a value. + Size(value ref.Val) uint64 + + // ArgValue returns the uint64 value of the argument at index, or defaultVal. + ArgValue(index int, defaultVal uint64) uint64 + + // TargetValue returns the uint64 value of the receiver/target, or defaultVal. + TargetValue(defaultVal uint64) uint64 + + // ArgVal returns the value of the argument at the given 0-based index, if present. + ArgVal(index int) (ref.Val, bool) + + // TargetVal returns the value of the receiver/target object, if present. + TargetVal() (ref.Val, bool) + + // ResultVal returns the evaluated result value, if present. + ResultVal() (ref.Val, bool) +} + +// QuantityExpr represents a computable size or cost equation. +type QuantityExpr interface { + estimate(ctx EstimateContext) SizeEstimate + track(ctx TrackContext) uint64 +} + +// ModelVersionOf reports the cost model version the given Estimator is configured with, or +// math.MaxUint32 if the estimator does not carry version metadata. +func ModelVersionOf(estimator Estimator) uint32 { + if v, ok := estimator.(interface{ modelVersion() uint32 }); ok { + return v.modelVersion() + } + return defaultModelVersion +} + +// targetInspector is an internal interface for expressions that inspect receiver/target presence. +type targetInspector interface { + hasTarget() bool +} + +// hasTarget returns true if the expression or any of its subexpressions references the target object. +func hasTarget(expr QuantityExpr) bool { + if expr == nil { + return false + } + if r, ok := expr.(targetInspector); ok { + return r.hasTarget() + } + return false +} + +// valueSource is an internal interface for expressions which denote runtime values rather than +// only a quantity derived from them. +// +// Element and key projections read the value they project from, so they are defined only over the +// expressions implementing this interface: Arg, Target, Result, and the element and key +// projections ElemOf and KeyOf. An expression may denote more than one value, as the elements of +// a list do. +// +// OverloadModel.Validate reports a projection over any other expression, so a model which cannot +// answer a projection at runtime is rejected when it is registered rather than mispriced when it +// is evaluated. +type valueSource interface { + QuantityExpr + + // eachValue calls fn with each value the expression denotes in the given context. An + // expression which denotes no value in the context makes no calls. + eachValue(ctx TrackContext, fn func(ref.Val)) +} + +// eachValueOf calls fn with each value denoted by expr, and makes no calls if expr does not denote +// a value. +func eachValueOf(expr QuantityExpr, ctx TrackContext, fn func(ref.Val)) { + if src, ok := expr.(valueSource); ok { + src.eachValue(ctx, fn) + } +} + +// eachElement calls fn with each element of a list, each value of a map, or the value an optional +// holds. Values which are not containers have no elements. +func eachElement(val ref.Val, fn func(ref.Val)) { + switch v := val.(type) { + case *types.Optional: + if v.HasValue() { + fn(v.GetValue()) + } + case traits.Lister: + for it := v.Iterator(); it.HasNext() == types.True; { + fn(it.Next()) + } + case traits.Mapper: + for it := v.Iterator(); it.HasNext() == types.True; { + fn(v.Get(it.Next())) + } + } +} + +// eachKey calls fn with each key of a map. Values which are not maps have no keys. +func eachKey(val ref.Val, fn func(ref.Val)) { + if m, ok := val.(traits.Mapper); ok { + for it := m.Iterator(); it.HasNext() == types.True; { + fn(it.Next()) + } + } +} + +// constExpr represents a constant integer quantity. +type constExpr struct { + val uint64 +} + +func (c constExpr) estimate(_ EstimateContext) SizeEstimate { + return FixedSizeEstimate(c.val) +} + +func (c constExpr) track(_ TrackContext) uint64 { + return c.val +} + +func (constExpr) hasTarget() bool { return false } + +// Const creates a constant quantity expression. +func Const(val uint64) QuantityExpr { + return constExpr{val: val} +} + +// argExpr represents the size of a function argument. +type argExpr struct { + index int +} + +func (a argExpr) estimate(ctx EstimateContext) SizeEstimate { + if sz, ok := ctx.Arg(a.index); ok { + return sz + } + return UnknownSizeEstimate() +} + +func (a argExpr) track(ctx TrackContext) uint64 { + return ctx.Arg(a.index) +} + +func (a argExpr) eachValue(ctx TrackContext, fn func(ref.Val)) { + if val, ok := ctx.ArgVal(a.index); ok { + fn(val) + } +} + +func (argExpr) hasTarget() bool { return false } + +// Arg creates an expression referencing the size of the argument at the given index. +func Arg(index int) QuantityExpr { + return argExpr{index: index} +} + +// ArgElem creates an expression referencing the element size of the argument at the given index. +func ArgElem(index int) QuantityExpr { + return ElemOf(Arg(index)) +} + +// ArgKey creates an expression referencing the key size of the argument at the given index. +func ArgKey(index int) QuantityExpr { + return KeyOf(Arg(index)) +} + +// intArgExpr represents the integer value of an argument. +type intArgExpr struct { + index int + defaultVal uint64 +} + +func (a intArgExpr) estimate(ctx EstimateContext) SizeEstimate { + if versionOf(ctx) < 1 { + return FixedSizeEstimate(ctx.ArgValue(a.index, a.defaultVal)) + } + // A literal reports the same value for any default; a non-literal reports the default. + lo, hi := ctx.ArgValue(a.index, 0), ctx.ArgValue(a.index, math.MaxUint64) + if lo != hi { + return UnknownSizeEstimate() + } + return FixedSizeEstimate(lo) +} + +func (a intArgExpr) track(ctx TrackContext) uint64 { + return ctx.ArgValue(a.index, a.defaultVal) +} + +func (intArgExpr) hasTarget() bool { return false } + +// IntArg creates an expression referencing the integer value of the argument at the given index. +// +// At runtime, an argument which is not an integer reads as defaultVal, and a negative integer reads +// as 0. When estimating, a literal argument reads as its value, and a non-literal argument is +// unbounded from model version 1 (or FixedSizeEstimate(defaultVal) at version 0). +func IntArg(index int, defaultVal uint64) QuantityExpr { + return intArgExpr{index: index, defaultVal: defaultVal} +} + +// targetExpr represents the size of the receiver/target object. +type targetExpr struct{} + +func (targetExpr) estimate(ctx EstimateContext) SizeEstimate { + if sz, ok := ctx.Target(); ok { + return sz + } + return UnknownSizeEstimate() +} + +func (targetExpr) track(ctx TrackContext) uint64 { + return ctx.Target() +} + +func (targetExpr) eachValue(ctx TrackContext, fn func(ref.Val)) { + if val, ok := ctx.TargetVal(); ok { + fn(val) + } +} + +func (targetExpr) hasTarget() bool { return true } + +// Target creates an expression referencing the size of the receiver / target object. +func Target() QuantityExpr { + return targetExpr{} +} + +// TargetElem creates an expression referencing the element size of the receiver / target object. +func TargetElem() QuantityExpr { + return ElemOf(Target()) +} + +// elemExpr represents the element size of another quantity expression. +type elemExpr struct { + expr QuantityExpr +} + +func (e elemExpr) estimate(ctx EstimateContext) SizeEstimate { + sz := e.expr.estimate(ctx) + if sz.Elem != nil { + return *sz.Elem + } + return UnknownSizeEstimate() +} + +// track reports the size of the largest element, matching the estimate, whose Max bounds every +// element rather than describing an average one. +// +// A value with no elements, including a scalar, contributes nothing. The cost of the scan is +// linear in the number of elements; see the element projection notes in docs/cost-model.md. +func (e elemExpr) track(ctx TrackContext) uint64 { + largest := uint64(0) + e.eachValue(ctx, func(elem ref.Val) { + largest = max(largest, ctx.Size(elem)) + }) + return largest +} + +func (e elemExpr) eachValue(ctx TrackContext, fn func(ref.Val)) { + eachValueOf(e.expr, ctx, func(val ref.Val) { + eachElement(val, fn) + }) +} + +func (e elemExpr) hasTarget() bool { + return hasTarget(e.expr) +} + +// ElemOf creates an expression referencing the element size of another expression. +func ElemOf(expr QuantityExpr) QuantityExpr { + return elemExpr{expr: expr} +} + +// elemTotalExpr represents the summed size of the elements of another quantity expression. +type elemTotalExpr struct { + expr QuantityExpr +} + +func (e elemTotalExpr) estimate(ctx EstimateContext) SizeEstimate { + sz := e.expr.estimate(ctx) + return totalEstimate(ctx, e.expr, sz, sz.Elem, isListOperand(ctx, e.expr, sz)) +} + +// singleValueOf resolves the value an ElemTotal, KeyTotal or Length operand denotes. Validate +// restricts those operands to Arg, Target and Result. +func singleValueOf(expr QuantityExpr, ctx TrackContext) (ref.Val, bool) { + switch x := expr.(type) { + case argExpr: + return ctx.ArgVal(x.index) + case targetExpr: + return ctx.TargetVal() + case resultExpr: + return ctx.ResultVal() + } + return nil, false +} + +// sumSizes totals the sizes of the parts which each enumerates in the operand's value. +func sumSizes(ctx TrackContext, operand QuantityExpr, each func(ref.Val, func(ref.Val))) uint64 { + total := uint64(0) + if val, ok := singleValueOf(operand, ctx); ok { + each(val, func(part ref.Val) { + total = SafeAdd(total, ctx.Size(part)) + }) + } + return total +} + +func (e elemTotalExpr) track(ctx TrackContext) uint64 { + return sumSizes(ctx, e.expr, eachElement) +} + +func (e elemTotalExpr) hasTarget() bool { + return hasTarget(e.expr) +} + +// ElemTotal creates an expression referencing the combined size of every element of a list, or +// every value of a map, under the sizing strategy in effect: the length of a flattened list under +// the default strategy, or the content size of a list under the aggregate strategy. See KeyTotal +// for the keys of a map. +// +// The operand must be Arg, Target or Result; see OverloadModel.Validate. The estimate is derived +// from the operand's size under the sizing strategy; see totalEstimate. At runtime this reports +// the exact total. +func ElemTotal(expr QuantityExpr) QuantityExpr { + return elemTotalExpr{expr: expr} +} + +// keyTotalExpr represents the summed size of the keys of another quantity expression. +type keyTotalExpr struct { + expr QuantityExpr +} + +func (k keyTotalExpr) estimate(ctx EstimateContext) SizeEstimate { + sz := k.expr.estimate(ctx) + return totalEstimate(ctx, k.expr, sz, sz.Key, false) +} + +func (k keyTotalExpr) track(ctx TrackContext) uint64 { + return sumSizes(ctx, k.expr, eachKey) +} + +func (k keyTotalExpr) hasTarget() bool { + return hasTarget(k.expr) +} + +// KeyTotal creates an expression referencing the combined size of every key of a map. A value +// which is not a map has no keys. +// +// The operand must be Arg, Target or Result; see OverloadModel.Validate. The estimate is derived +// from the operand's size under the sizing strategy; see totalEstimate. At runtime this reports +// the exact total. +func KeyTotal(expr QuantityExpr) QuantityExpr { + return keyTotalExpr{expr: expr} +} + +// lengthExpr represents the shallow top-level length of a single value (its CEL size()): the +// number of code points of a string, the number of bytes of a bytes value, the number of top-level +// elements of a list or entries of a map, and 1 for any other value. +type lengthExpr struct { + expr QuantityExpr +} + +// Length creates an expression referencing the shallow top-level length of a single value (its CEL +// size() / ActualSize), independent of the sizing strategy: the number of code points of a string, +// bytes of a bytes value, top-level elements of a list or entries of a map, and 1 for any other +// value. Unlike Arg(i), Target(), or Result(), which report the depth-based total content size +// under AggregateSizingStrategy, Length always reports only the top-level container or value +// length. +// +// The operand must be Arg, Target or Result; see OverloadModel.Validate. Length is a scalar and +// carries no element or key size. +// +// Sizes follow the sizing strategy, so under the aggregate strategy Target() of a string is its +// UTF-8 byte count and Target() of a list is its depth-based aggregate content size. Length lets a +// model charge by top-level length under every strategy while still describing its result's size +// through List and Map. +func Length(expr QuantityExpr) QuantityExpr { + return lengthExpr{expr: expr} +} + +// estimate reports the exact length of a literal operand, as ActualSize counts it at runtime, or +// bounds the operand's length from its estimated size under the sizing strategy. +// +// Because track returns ActualSize(val)—which is 0 for empty strings, bytes, and containers, and 1 +// for fixed-width scalars—the returned range is [1, 1] for fixed-width scalars and [lo, hi] within +// [0, MaxUint64] for variable-length values. For soundness (est.Min <= actual), lo must be 0 +// whenever the operand may be empty at runtime: +// +// - Default strategy: the size is the length ([sz.Min, sz.Max]). +// - Aggregate strategy: every value has an aggregate size >= 1 even when its length is 0 (a +// string's size is max(1, UTF-8 byte count) with 1–4 bytes per code point; a bytes value's size +// is max(1, byte length); a container's size is 1 + entry sizes, see countBounds); any other +// value has length 1. An aggregate size with Min <= 1 therefore yields lo = 0. +// - Other strategies: [0, MaxUint64], except for scalars whose length is always [1, 1]. +// +// The kind of value comes from the operand's checked type, or, for a result whose type is not +// known, from its metadata: an estimate which states element or key sizes is a container. +func (l lengthExpr) estimate(ctx EstimateContext) SizeEstimate { + if lit, ok := operandLiteral(ctx, l.expr); ok { + return FixedSizeEstimate(ActualSize(lit)) + } + sz := l.expr.estimate(ctx) + kind, known := operandKind(ctx, l.expr) + if known && hasUnitLength(kind) { + return FixedSizeEstimate(1) + } + switch strategyOf(ctx).(type) { + case defaultSizingStrategy: + return RangedSizeEstimate(sz.Min, sz.Max) + case *aggregateSizingStrategy: + switch { + case known && kind == types.StringKind: + // Size <= 1 may be "" (length 0); n > 1 UTF-8 bytes hold [ceil(n/4), n] code points. + lo := uint64(0) + if sz.Min > 1 { + lo = sz.Min/4 + min(sz.Min%4, 1) + } + return RangedSizeEstimate(lo, sz.Max) + case known && kind == types.BytesKind: + // Size <= 1 may be b"" (length 0). + lo := uint64(0) + if sz.Min > 1 { + lo = sz.Min + } + return RangedSizeEstimate(lo, sz.Max) + case (known && (kind == types.ListKind || kind == types.MapKind)) || sz.Elem != nil || sz.Key != nil: + return countBounds(strategyOf(ctx), sz) + default: + // Any value: empty strings/bytes/containers have length 0, and length never exceeds size (>= 1). + return RangedSizeEstimate(0, max(sz.Max, 1)) + } + default: + return UnknownSizeEstimate() + } +} + +func (l lengthExpr) track(ctx TrackContext) uint64 { + val, ok := singleValueOf(l.expr, ctx) + // A call which fails produces an error rather than a result, which has no length. + if !ok || types.IsUnknownOrError(val) { + return 0 + } + // An optional has the length of the value it holds, as it is estimated. + if inner, isOpt := optionalValueOf(val); isOpt { + if inner == nil { + return 0 + } + val = inner + } + return ActualSize(val) +} + +func (l lengthExpr) hasTarget() bool { + return hasTarget(l.expr) +} + +// TargetKey creates an expression referencing the key size of the receiver / target object. +func TargetKey() QuantityExpr { + return KeyOf(Target()) +} + +// intTargetExpr represents the integer value of the receiver/target object. +type intTargetExpr struct { + defaultVal uint64 +} + +func (t intTargetExpr) estimate(ctx EstimateContext) SizeEstimate { + if versionOf(ctx) < 1 { + return FixedSizeEstimate(ctx.TargetValue(t.defaultVal)) + } + lo, hi := ctx.TargetValue(0), ctx.TargetValue(math.MaxUint64) + if lo != hi { + return UnknownSizeEstimate() + } + return FixedSizeEstimate(lo) +} + +func (t intTargetExpr) track(ctx TrackContext) uint64 { + return ctx.TargetValue(t.defaultVal) +} + +func (intTargetExpr) hasTarget() bool { return true } + +// IntTarget creates an expression referencing the integer value of the receiver/target object, +// with the same runtime and estimation rules as IntArg. +func IntTarget(defaultVal uint64) QuantityExpr { + return intTargetExpr{defaultVal: defaultVal} +} + +// keyExpr represents the key size of another quantity expression. +type keyExpr struct { + expr QuantityExpr +} + +func (k keyExpr) estimate(ctx EstimateContext) SizeEstimate { + sz := k.expr.estimate(ctx) + if sz.Key != nil { + return *sz.Key + } + // An absent key size is unknown rather than single-byte: map keys may be strings or bytes of + // any length. Strategies which know the key type is fixed-width populate Key themselves. + return UnknownSizeEstimate() +} + +// track reports the size of the largest key, matching the estimate, whose Max bounds every key +// rather than describing an average one. +// +// A value with no keys, including a list or a scalar, contributes nothing. The cost of the scan is +// linear in the number of entries; see the element projection notes in docs/cost-model.md. +func (k keyExpr) track(ctx TrackContext) uint64 { + largest := uint64(0) + k.eachValue(ctx, func(key ref.Val) { + largest = max(largest, ctx.Size(key)) + }) + return largest +} + +func (k keyExpr) eachValue(ctx TrackContext, fn func(ref.Val)) { + eachValueOf(k.expr, ctx, func(val ref.Val) { + eachKey(val, fn) + }) +} + +func (k keyExpr) hasTarget() bool { + return hasTarget(k.expr) +} + +// KeyOf creates an expression referencing the key size of another expression. +func KeyOf(expr QuantityExpr) QuantityExpr { + return keyExpr{expr: expr} +} + +// resultExpr represents the size of the evaluated result. +type resultExpr struct{} + +func (resultExpr) estimate(ctx EstimateContext) SizeEstimate { + if sz, ok := ctx.Result(); ok { + return sz + } + return UnknownSizeEstimate() +} + +func (resultExpr) track(ctx TrackContext) uint64 { + return ctx.Result() +} + +func (resultExpr) eachValue(ctx TrackContext, fn func(ref.Val)) { + if val, ok := ctx.ResultVal(); ok { + fn(val) + } +} + +func (resultExpr) hasTarget() bool { return false } + +// Result creates an expression referencing the size of the result. +func Result() QuantityExpr { + return resultExpr{} +} + +// addExpr represents the sum of multiple quantity expressions. +type addExpr struct { + terms []QuantityExpr +} + +func (a addExpr) estimate(ctx EstimateContext) SizeEstimate { + if len(a.terms) == 0 { + return FixedSizeEstimate(0) + } + return foldEstimates(ctx, a.terms, SizeEstimate.Add) +} + +func (a addExpr) track(ctx TrackContext) uint64 { + sum := uint64(0) + for _, term := range a.terms { + sum = SafeAdd(sum, term.track(ctx)) + } + return sum +} + +func (a addExpr) hasTarget() bool { + return slices.ContainsFunc(a.terms, hasTarget) +} + +// Sum creates an expression representing the sum of the given terms. +func Sum(terms ...QuantityExpr) QuantityExpr { + return addExpr{terms: slices.Clone(terms)} +} + +// subExpr represents the subtraction of two quantity expressions. +type subExpr struct { + lhs, rhs QuantityExpr +} + +func (s subExpr) estimate(ctx EstimateContext) SizeEstimate { + lhsVal := s.lhs.estimate(ctx) + rhsVal := s.rhs.estimate(ctx) + diff := lhsVal.Subtract(rhsVal) + // A difference holds some of the minuend's elements, never the subtrahend's. + diff.Key, diff.Elem = lhsVal.Key, lhsVal.Elem + return diff +} + +func (s subExpr) track(ctx TrackContext) uint64 { + return SafeSubtract(s.lhs.track(ctx), s.rhs.track(ctx)) +} + +func (s subExpr) hasTarget() bool { + return hasTarget(s.lhs) || hasTarget(s.rhs) +} + +// Sub creates an expression representing lhs - rhs, saturated at zero. +func Sub(lhs, rhs QuantityExpr) QuantityExpr { + return subExpr{lhs: lhs, rhs: rhs} +} + +// mulExpr represents the product of multiple quantity expressions. +type mulExpr struct { + terms []QuantityExpr +} + +func (m mulExpr) estimate(ctx EstimateContext) SizeEstimate { + if len(m.terms) == 0 { + return FixedSizeEstimate(1) + } + return foldEstimates(ctx, m.terms, SizeEstimate.Multiply) +} + +func (m mulExpr) track(ctx TrackContext) uint64 { + if len(m.terms) == 0 { + return 1 + } + prod := m.terms[0].track(ctx) + for _, term := range m.terms[1:] { + prod = SafeMultiply(prod, term.track(ctx)) + } + return prod +} + +func (m mulExpr) hasTarget() bool { + return slices.ContainsFunc(m.terms, hasTarget) +} + +// Mul creates an expression representing the product of the given terms. +func Mul(terms ...QuantityExpr) QuantityExpr { + return mulExpr{terms: slices.Clone(terms)} +} + +// scaleExpr represents an expression scaled by a constant factor. +type scaleExpr struct { + expr QuantityExpr + factor float64 + // rat is the exact rational form of factor; see rationalOf. + rat rational +} + +func (s scaleExpr) estimate(ctx EstimateContext) SizeEstimate { + val := s.expr.estimate(ctx) + res := RangedSizeEstimate( + scale(val.Min, s.factor, s.rat), + scale(val.Max, s.factor, s.rat), + ) + res.Key = val.Key + res.Elem = val.Elem + return res +} + +func (s scaleExpr) track(ctx TrackContext) uint64 { + return scale(s.expr.track(ctx), s.factor, s.rat) +} + +func (s scaleExpr) hasTarget() bool { + return hasTarget(s.expr) +} + +// Scale creates an expression that scales another expression by a constant factor, rounding up. +// +// Factors are constant so that a model's runtime charge depends only on the sizes reported by the +// sizing strategy. A cost which differs by argument type should be modeled with one OverloadModel +// per overload ID, since CEL already dispatches overloads by type. The factor must be finite and +// positive; Validate rejects any other. +// +// The factor is applied as the simplest rational with the same float64 value, so that 0.1 scales by +// exactly 1/10, and the product is computed exactly; an unbounded quantity stays unbounded; and +// when a model is compiled, factors are moved outward so that each product is rounded once. +func Scale(expr QuantityExpr, factor float64) QuantityExpr { + return scaleExpr{expr: expr, factor: factor, rat: rationalOf(factor)} +} + +// Square creates an expression representing the square of another expression. +func Square(expr QuantityExpr) QuantityExpr { + return Mul(expr, expr) +} + +// minExpr represents the minimum of two quantity expressions. +type minExpr struct { + lhs, rhs QuantityExpr +} + +func (m minExpr) estimate(ctx EstimateContext) SizeEstimate { + return foldEstimates(ctx, []QuantityExpr{m.lhs, m.rhs}, minBounds) +} + +func (m minExpr) track(ctx TrackContext) uint64 { + return min(m.lhs.track(ctx), m.rhs.track(ctx)) +} + +func (m minExpr) hasTarget() bool { + return hasTarget(m.lhs) || hasTarget(m.rhs) +} + +// Min creates an expression representing the minimum of two quantities. +func Min(lhs, rhs QuantityExpr) QuantityExpr { + return minExpr{lhs: lhs, rhs: rhs} +} + +// maxExpr represents the maximum of two quantity expressions. +type maxExpr struct { + lhs, rhs QuantityExpr +} + +func (m maxExpr) estimate(ctx EstimateContext) SizeEstimate { + return foldEstimates(ctx, []QuantityExpr{m.lhs, m.rhs}, maxBounds) +} + +func (m maxExpr) track(ctx TrackContext) uint64 { + return max(m.lhs.track(ctx), m.rhs.track(ctx)) +} + +func (m maxExpr) hasTarget() bool { + return hasTarget(m.lhs) || hasTarget(m.rhs) +} + +// Max creates an expression representing the maximum of two quantities. +func Max(lhs, rhs QuantityExpr) QuantityExpr { + return maxExpr{lhs: lhs, rhs: rhs} +} + +// unionExpr represents the union interval of multiple quantity expressions. +type unionExpr struct { + terms []QuantityExpr +} + +func (u unionExpr) estimate(ctx EstimateContext) SizeEstimate { + if len(u.terms) == 0 { + return FixedSizeEstimate(0) + } + return foldEstimates(ctx, u.terms, SizeEstimate.Union) +} + +func (u unionExpr) track(ctx TrackContext) uint64 { + res := uint64(0) + for _, term := range u.terms { + res = max(res, term.track(ctx)) + } + return res +} + +func (u unionExpr) hasTarget() bool { + return slices.ContainsFunc(u.terms, hasTarget) +} + +// Union creates an expression representing the union interval of multiple expressions. +func Union(terms ...QuantityExpr) QuantityExpr { + return unionExpr{terms: slices.Clone(terms)} +} + +// rangedExpr represents a quantity bounded by minExpr on the bottom and maxExpr on top. +type rangedExpr struct { + minExpr QuantityExpr + maxExpr QuantityExpr +} + +func (r rangedExpr) estimate(ctx EstimateContext) SizeEstimate { + return foldEstimates(ctx, []QuantityExpr{r.minExpr, r.maxExpr}, rangedBounds) +} + +// foldEstimates estimates the operands and combines the estimates from left to right with op, +// attaching the operands' metadata as combineMeta describes. The estimates of up to four operands, +// as many as the models in this repository use, are held on the stack. +func foldEstimates(ctx EstimateContext, operands []QuantityExpr, op func(SizeEstimate, SizeEstimate) SizeEstimate) SizeEstimate { + var buf [4]SizeEstimate + ests := buf[:0] + for _, operand := range operands { + ests = append(ests, operand.estimate(ctx)) + } + res := ests[0] + for _, est := range ests[1:] { + res = op(res, est) + } + return combineMeta(ctx, RangedSizeEstimate(res.Min, res.Max), operands, ests) +} + +func minBounds(lhs, rhs SizeEstimate) SizeEstimate { + return RangedSizeEstimate(min(lhs.Min, rhs.Min), min(lhs.Max, rhs.Max)) +} + +func maxBounds(lhs, rhs SizeEstimate) SizeEstimate { + return RangedSizeEstimate(max(lhs.Min, rhs.Min), max(lhs.Max, rhs.Max)) +} + +// rangedBounds takes the upper bound from hi and the lower bound from lo, capped by the upper bound +// since a lower bound above it would describe an empty interval. +func rangedBounds(lo, hi SizeEstimate) SizeEstimate { + return RangedSizeEstimate(min(lo.Min, hi.Max), hi.Max) +} + +func (r rangedExpr) track(ctx TrackContext) uint64 { + return r.maxExpr.track(ctx) +} + +func (r rangedExpr) hasTarget() bool { + return hasTarget(r.minExpr) || hasTarget(r.maxExpr) +} + +// Ranged creates an expression where the lower bound is taken from minExpr and the upper bound from maxExpr. +func Ranged(minExpr, maxExpr QuantityExpr) QuantityExpr { + return rangedExpr{minExpr: minExpr, maxExpr: maxExpr} +} + +// AtMost creates an expression representing a quantity bounded between 0 and the upper bound of maxExpr. +func AtMost(maxExpr QuantityExpr) QuantityExpr { + return Ranged(Const(0), maxExpr) +} + +// atLeastOneExpr represents a quantity guaranteed to be at least 1. +type atLeastOneExpr struct { + expr QuantityExpr +} + +func (a atLeastOneExpr) estimate(ctx EstimateContext) SizeEstimate { + return AtLeastOneSize(a.expr.estimate(ctx)) +} + +func (a atLeastOneExpr) track(ctx TrackContext) uint64 { + val := a.expr.track(ctx) + if val == 0 { + return 1 + } + return val +} + +func (a atLeastOneExpr) hasTarget() bool { + return hasTarget(a.expr) +} + +// AtLeastOneQuantity creates an expression ensuring the quantity is at least 1. +func AtLeastOneQuantity(expr QuantityExpr) QuantityExpr { + return atLeastOneExpr{expr: expr} +} + +// StringScan creates an expression representing the cost of scanning a string. +func StringScan(expr QuantityExpr) QuantityExpr { + return Scale(expr, StringTraversalCostFactor) +} + +// ListAlloc creates an expression representing list allocation cost with base cost and scaled element count. +func ListAlloc(elemCount QuantityExpr, costFactor float64) QuantityExpr { + return Sum(Const(ListCreateBaseCost), Scale(elemCount, costFactor)) +} + +// AllocList creates an expression representing the cost of a call that allocates a list: +// CallCost + ListCreateBaseCost plus the given work terms. +func AllocList(terms ...QuantityExpr) QuantityExpr { + all := make([]QuantityExpr, 0, len(terms)+1) + all = append(all, Const(CallCost+ListCreateBaseCost)) + all = append(all, terms...) + return Sum(all...) +} + +// Traversal creates an expression representing the traversal and optional allocation cost over an expression. +func Traversal(expr QuantityExpr, costFactor float64, allocCost uint64) QuantityExpr { + if allocCost == 0 { + return Scale(expr, costFactor) + } + return Sum(Const(allocCost), Scale(expr, costFactor)) +} + +// listExpr represents a list size estimate composed of length and element size expressions. +type listExpr struct { + lenExpr QuantityExpr + elemExpr QuantityExpr +} + +func (l listExpr) estimate(ctx EstimateContext) SizeEstimate { + lenSize := l.lenExpr.estimate(ctx) + elemSize := l.elemExpr.estimate(ctx) + size := containerSize(ctx, lenSize, elemSize) + size.Key = nil + size.Elem = &elemSize + return size +} + +func (l listExpr) track(ctx TrackContext) uint64 { + return l.lenExpr.track(ctx) +} + +func (l listExpr) hasTarget() bool { + return hasTarget(l.lenExpr) || hasTarget(l.elemExpr) +} + +// List creates an expression representing a list with the given length and element size. +// +// The estimate is the size the sizing strategy assigns to such a list: its length under the default +// strategy, and 1 plus the length times the element size under the aggregate strategy. The track is +// the length. +func List(lenExpr, elemExpr QuantityExpr) QuantityExpr { + return listExpr{lenExpr: lenExpr, elemExpr: elemExpr} +} + +// mapExpr represents a map size estimate composed of size, key size, and value size expressions. +type mapExpr struct { + sizeExpr QuantityExpr + keyExpr QuantityExpr + valExpr QuantityExpr +} + +func (m mapExpr) estimate(ctx EstimateContext) SizeEstimate { + mapSize := m.sizeExpr.estimate(ctx) + keySize := m.keyExpr.estimate(ctx) + valSize := m.valExpr.estimate(ctx) + size := containerSize(ctx, mapSize, AtLeastOneSize(keySize).Add(AtLeastOneSize(valSize))) + size.Key = &keySize + size.Elem = &valSize + return size +} + +func (m mapExpr) track(ctx TrackContext) uint64 { + return m.sizeExpr.track(ctx) +} + +func (m mapExpr) hasTarget() bool { + return hasTarget(m.sizeExpr) || hasTarget(m.keyExpr) || hasTarget(m.valExpr) +} + +// Map creates an expression representing a map with the given entry count, key size and value size. +// +// The estimate is the size the sizing strategy assigns to such a map: its entry count under the +// default strategy, and 1 plus the entry count times the key and value sizes under the aggregate +// strategy. The track is the entry count. +func Map(sizeExpr, keyExpr, valExpr QuantityExpr) QuantityExpr { + return mapExpr{sizeExpr: sizeExpr, keyExpr: keyExpr, valExpr: valExpr} +} + +// optionalExpr represents the size of an optional which holds a value of the given size. +type optionalExpr struct { + valueExpr QuantityExpr +} + +func (o optionalExpr) estimate(ctx EstimateContext) SizeEstimate { + if versionOf(ctx) < 1 { + return FixedSizeEstimate(1) + } + return optionalSizeOf(o.valueExpr.estimate(ctx)) +} + +func (o optionalExpr) track(ctx TrackContext) uint64 { + if trackVersionOf(ctx) < 1 { + return 1 + } + return SafeAdd(1, o.valueExpr.track(ctx)) +} + +func (o optionalExpr) hasTarget() bool { + return hasTarget(o.valueExpr) +} + +// Optional creates an expression representing an optional which holds a value of the given size. +// +// From cost model version 1 an optional is 1 plus the size of the value it holds, under every +// sizing strategy: 1 plus the value's length under the default strategy, and 1 plus its aggregate +// size under the aggregate strategy. An empty optional is 1, which Optional(Const(0)) describes. +// The value is the optional's element, which ElemOf reads, so that value() and orValue() recover its +// size. Version 0 sizes every optional as 1, as cel-go v0.32.0 did. +func Optional(valueExpr QuantityExpr) QuantityExpr { + return optionalExpr{valueExpr: valueExpr} +} + +// OverloadModel pairs an overload ID with its abstract cost and result size expressions. +// +// An OverloadModel is a value built by Overload or MemberOverload, and is not modified afterwards: +// estimators and trackers are compiled from it on request. Validate reports a model which cannot +// be priced, and cel.CostModel and Model call it when the model is registered. +type OverloadModel struct { + ID string + Cost QuantityExpr + Size QuantityExpr + hasSize bool + IsMember bool + manual bool + manualEstimator bool + // argumentsOnly marks a short-circuiting operator, whose cost is that of the arguments it + // evaluates, and which is therefore exempt from the minimum call cost; see minCallCost. + argumentsOnly bool + estimator FunctionEstimator + tracker FunctionTracker + priors []priorOverload +} + +// priorOverload is the model which priced an overload at revisions earlier than before. +type priorOverload struct { + before uint32 + model OverloadModel +} + +// priorForVersion selects the prior with the smallest before which still exceeds version, so +// that each prior covers the revisions from the previous prior's before up to its own. +func priorForVersion(priors []priorOverload, version uint32) (OverloadModel, bool) { + var chosen *priorOverload + for i, p := range priors { + if version < p.before && (chosen == nil || p.before < chosen.before) { + chosen = &priors[i] + } + } + if chosen == nil { + return OverloadModel{}, false + } + return chosen.model, true +} + +// OverloadModelOption functional options for configuring an OverloadModel. +type OverloadModelOption func(*OverloadModel) + +// EvalCost sets the evaluation cost expression for the overload model. +func EvalCost(cost QuantityExpr) OverloadModelOption { + return func(m *OverloadModel) { + m.Cost = cost + } +} + +// ResultSize sets the result size expression for the overload model. Passing nil in a +// BeforeVersion entry clears any result size inherited from the enclosing OverloadModel. +func ResultSize(size QuantityExpr) OverloadModelOption { + return func(m *OverloadModel) { + m.Size = size + m.hasSize = true + } +} + +// ManualCost sets a custom FunctionEstimator and FunctionTracker for an overload whose cost or +// result size cannot be expressed declaratively with EvalCost and ResultSize. +// +// Both functions are required; Validate reports a nil one. ManualCost cannot be combined with +// EvalCost, ResultSize, or ManualEstimator on the same OverloadModel or BeforeVersion entry. +func ManualCost(estimator FunctionEstimator, tracker FunctionTracker) OverloadModelOption { + return func(m *OverloadModel) { + m.manual = true + m.estimator = estimator + m.tracker = tracker + } +} + +// ManualEstimator sets a custom FunctionEstimator for an overload (or BeforeVersion entry) whose +// static estimate cannot be expressed declaratively with EvalCost and ResultSize, while retaining +// the OverloadModel's declarative EvalCost for runtime tracking. +// +// ManualEstimator requires a non-nil FunctionEstimator and cannot be combined with ManualCost or +// ResultSize on the same OverloadModel or BeforeVersion entry. +func ManualEstimator(estimator FunctionEstimator) OverloadModelOption { + return func(m *OverloadModel) { + m.manualEstimator = true + m.estimator = estimator + } +} + +// BeforeVersion records the options that priced the overload before the given model revision. +// +// At revisions earlier than version, the overload is configured by opts (such as EvalCost, +// ResultSize, ManualCost, or ManualEstimator), inheriting the enclosing OverloadModel's ID, +// receiver kind, and any unset EvalCost or ResultSize. +func BeforeVersion(version uint32, opts ...OverloadModelOption) OverloadModelOption { + return func(m *OverloadModel) { + m.priors = append(m.priors, priorOverload{ + before: version, + model: newOverloadModel(m.ID, m.IsMember, opts), + }) + } +} + +// resolvePrior returns prior with any unset Cost or Size inherited from m. +func (m OverloadModel) resolvePrior(prior OverloadModel) OverloadModel { + if prior.manual { + return prior + } + if prior.Cost == nil { + prior.Cost = m.Cost + } + if !prior.manualEstimator && !prior.hasSize { + prior.Size = m.Size + prior.hasSize = m.hasSize + } + return prior +} + +// Overload creates a global function OverloadModel with functional options. +func Overload(id string, opts ...OverloadModelOption) OverloadModel { + return newOverloadModel(id, false, opts) +} + +// MemberOverload creates a member function OverloadModel with functional options. +func MemberOverload(id string, opts ...OverloadModelOption) OverloadModel { + return newOverloadModel(id, true, opts) +} + +func newOverloadModel(id string, isMember bool, opts []OverloadModelOption) OverloadModel { + m := OverloadModel{ID: id, IsMember: isMember} + for _, opt := range opts { + opt(&m) + } + return m +} + +func (m OverloadModel) hasTarget() bool { + return m.IsMember || hasTarget(m.Cost) || hasTarget(m.Size) +} + +var estimatorCtxPool = sync.Pool{ + New: func() any { + return &estimatorEvalContext{} + }, +} + +var trackerCtxPool = sync.Pool{ + New: func() any { + return &trackerEvalContext{} + }, +} + +// FunctionEstimator returns a FunctionEstimator implementing the cost model. +func (m OverloadModel) FunctionEstimator() FunctionEstimator { + return m.buildEstimator(defaultSizing, defaultModelVersion) +} + +// FunctionEstimatorWithOptions returns a FunctionEstimator implementing the cost model, configured +// by the supplied options. Unset options take their defaults: the default SizingStrategy and the +// latest model revision. +func (m OverloadModel) FunctionEstimatorWithOptions(opts ...ModelOption) FunctionEstimator { + resolved := newModelOptions(opts...) + return m.buildEstimator(resolved.strategy, resolved.version) +} + +func (m OverloadModel) buildEstimator(strategy SizingStrategy, version uint32) FunctionEstimator { + if prior, ok := priorForVersion(m.priors, version); ok { + return m.resolvePrior(prior).buildEstimator(strategy, version) + } + if m.manual || m.manualEstimator { + return m.estimator + } + hasTarget := m.hasTarget() + cost := normalize(m.Cost) + size := normalize(m.Size) + floor := m.hasCallFloor(version) + return func(estimator Estimator, target *AstNode, args []AstNode) *CallEstimate { + if hasTarget && target == nil { + return nil + } + ctx := estimatorCtxPool.Get().(*estimatorEvalContext) + if ve, ok := estimator.(*versionedEstimator); ok { + ctx.coster = ve.coster + } + ctx.estimator = estimator + ctx.strategy = strategy + ctx.version = version + ctx.target = target + ctx.args = args + ctx.hasTarget = hasTarget + var resSize *SizeEstimate + if size != nil { + sz := aggregateResultSize(strategy, size.estimate(ctx)) + resSize = &sz + // The result size is available to the cost through Result(). + ctx.result = resSize + } + costEst := cost.estimate(ctx) + *ctx = estimatorEvalContext{} + estimatorCtxPool.Put(ctx) + if floor { + costEst.Min, costEst.Max = max(costEst.Min, minCallCost), max(costEst.Max, minCallCost) + } + return NewCallEstimate(CostEstimate{Min: costEst.Min, Max: costEst.Max}, resSize) + } +} + +// FunctionTracker returns a FunctionTracker implementing the cost model. +func (m OverloadModel) FunctionTracker() FunctionTracker { + return m.buildTracker(defaultSizing, defaultModelVersion) +} + +// FunctionTrackerWithOptions returns a FunctionTracker implementing the cost model, configured by +// the supplied options. +// +// ModelVersion applies to tracking as it does to estimation, so that a call's estimate and its +// charge are computed by the same rules. +func (m OverloadModel) FunctionTrackerWithOptions(opts ...ModelOption) FunctionTracker { + resolved := newModelOptions(opts...) + return m.buildTracker(resolved.strategy, resolved.version) +} + +func (m OverloadModel) buildTracker(strategy SizingStrategy, version uint32) FunctionTracker { + if prior, ok := priorForVersion(m.priors, version); ok { + return m.resolvePrior(prior).buildTracker(strategy, version) + } + if m.manual { + return m.tracker + } + isMember := m.hasTarget() + cost := normalize(m.Cost) + floor := m.hasCallFloor(version) + return func(args []ref.Val, result ref.Val) *uint64 { + ctx := trackerCtxPool.Get().(*trackerEvalContext) + ctx.strategy = strategy + ctx.version = version + ctx.args = args + ctx.result = result + ctx.isMember = isMember + costVal := cost.track(ctx) + *ctx = trackerEvalContext{} + trackerCtxPool.Put(ctx) + if floor { + costVal = max(costVal, minCallCost) + } + return &costVal + } +} + +// versionOf reports the cost model version of an EstimateContext. +func versionOf(ctx EstimateContext) uint32 { + if ctx == nil { + return defaultModelVersion + } + if e, ok := ctx.(*estimatorEvalContext); ok && (e.estimator == nil || e.coster != nil) { + return e.version + } + return ModelVersionOf(ctx.Estimator()) +} + +// estimatorEvalContext provides evaluation context for cost estimation. +type estimatorEvalContext struct { + coster *coster + estimator Estimator + strategy SizingStrategy + version uint32 + target *AstNode + args []AstNode + hasTarget bool + // result is the estimated result size, available to the cost through Result(). + result *SizeEstimate +} + +// sizingStrategy implements sizingStrategyContext. +func (e *estimatorEvalContext) sizingStrategy() SizingStrategy { + return e.strategy +} + +// resultType implements resultTypeContext from the estimator, which knows the call being +// estimated. +func (e *estimatorEvalContext) resultType() (*types.Type, bool) { + if rc, ok := e.estimator.(resultTypeContext); ok { + return rc.resultType() + } + return nil, false +} + +// operandNode implements operandNodeContext for Arg and Target operands. +func (e *estimatorEvalContext) operandNode(q QuantityExpr) (AstNode, bool) { + switch x := q.(type) { + case argExpr: + if x.index >= 0 && x.index < len(e.args) { + return e.args[x.index], true + } + case targetExpr: + if e.target != nil { + return *e.target, true + } + } + return nil, false +} + +// Arg returns the size estimate for the argument at index. +func (e *estimatorEvalContext) Arg(index int) (SizeEstimate, bool) { + if index < len(e.args) { + return e.Size(e.args[index]), true + } + return UnknownSizeEstimate(), false +} + +// Target returns the size estimate for the receiver/target object. +func (e *estimatorEvalContext) Target() (SizeEstimate, bool) { + if e.target != nil { + return e.Size(*e.target), true + } + return UnknownSizeEstimate(), false +} + +// Result returns the size estimate of the result, if the model's result size has been estimated. +func (e *estimatorEvalContext) Result() (SizeEstimate, bool) { + if e.result != nil { + return *e.result, true + } + return UnknownSizeEstimate(), false +} + +// Estimator returns the underlying Estimator. +func (e *estimatorEvalContext) Estimator() Estimator { + return e.estimator +} + +// Size returns the estimated size of an AST node. +func (e *estimatorEvalContext) Size(node AstNode) SizeEstimate { + if node == nil { + return UnknownSizeEstimate() + } + if sz := node.ComputedSize(); sz != nil { + return *sz + } + if e.coster != nil && node.Expr() != nil { + if sz := e.coster.computeSize(node.Expr()); sz != nil { + return *sz + } + } + if sz, ok := e.strategy.EstimateSize(e, node); ok { + return sz + } + if e.estimator != nil { + if sz := e.estimator.EstimateSize(node); sz != nil { + return *sz + } + } + return UnknownSizeEstimate() +} + +// TargetType returns the type of the receiver/target object. +func (e *estimatorEvalContext) TargetType() (*types.Type, bool) { + if e.target != nil && (*e.target) != nil { + return (*e.target).Type(), true + } + return nil, false +} + +// ArgType returns the type of the argument at index. +func (e *estimatorEvalContext) ArgType(index int) (*types.Type, bool) { + if index < len(e.args) && e.args[index] != nil { + return e.args[index].Type(), true + } + return nil, false +} + +// ArgValue returns the uint64 value of the argument at index, or defaultVal if not a literal int/uint. +func (e *estimatorEvalContext) ArgValue(index int, defaultVal uint64) uint64 { + if index < len(e.args) && e.args[index] != nil { + return NodeAsUintValue(e.args[index], defaultVal) + } + return defaultVal +} + +// TargetValue returns the uint64 value of the receiver/target, or defaultVal if not a literal int/uint. +func (e *estimatorEvalContext) TargetValue(defaultVal uint64) uint64 { + if e.target != nil && (*e.target) != nil { + return NodeAsUintValue(*e.target, defaultVal) + } + return defaultVal +} + +// trackerEvalContext provides evaluation context for runtime cost tracking. +type trackerEvalContext struct { + estimator ActualCostEstimator + strategy SizingStrategy + version uint32 + args []ref.Val + result ref.Val + isMember bool +} + +// valueAsUint returns the non-negative uint64 value of ref.Val (int or uint), or defaultVal. +func valueAsUint(val ref.Val, defaultVal uint64) uint64 { + if val == nil { + return defaultVal + } + switch v := val.(type) { + case types.Int: + if v < 0 { + return 0 + } + return uint64(v) + case types.Uint: + return uint64(v) + default: + return defaultVal + } +} + +// ArgValue returns the uint64 value of the argument at index, or defaultVal. +func (t *trackerEvalContext) ArgValue(index int, defaultVal uint64) uint64 { + idx := index + if t.isMember { + idx = index + 1 + } + if idx < len(t.args) { + return valueAsUint(t.args[idx], defaultVal) + } + return defaultVal +} + +// TargetValue returns the uint64 value of the receiver/target object, or defaultVal. +func (t *trackerEvalContext) TargetValue(defaultVal uint64) uint64 { + if t.isMember && len(t.args) > 0 { + return valueAsUint(t.args[0], defaultVal) + } + return defaultVal +} + +// TargetType returns the type of the receiver/target object. +func (t *trackerEvalContext) TargetType() (*types.Type, bool) { + if t.isMember && len(t.args) > 0 && t.args[0] != nil { + if tp, ok := t.args[0].Type().(*types.Type); ok { + return tp, true + } + } + return nil, false +} + +// ArgType returns the type of the argument at index. +func (t *trackerEvalContext) ArgType(index int) (*types.Type, bool) { + idx := index + if t.isMember { + idx = index + 1 + } + if idx < len(t.args) && t.args[idx] != nil { + if tp, ok := t.args[idx].Type().(*types.Type); ok { + return tp, true + } + } + return nil, false +} + +// Estimator returns the runtime ActualCostEstimator. +func (t *trackerEvalContext) Estimator() ActualCostEstimator { + return t.estimator +} + +// Size returns the actual runtime size of a value. +func (t *trackerEvalContext) Size(value ref.Val) uint64 { + if value == nil { + return 0 + } + // Inlines defaultSizingStrategy.TrackSize, avoiding an interface call and boxing the context. + if t.strategy == defaultSizing { + if opt, isOpt := value.(*types.Optional); isOpt { + return optionalLength(t.version, opt) + } + return ActualSize(value) + } + if sz, ok := t.strategy.TrackSize(t, value); ok { + return sz + } + return ActualSize(value) +} + +// ArgVal returns the value of the argument at index. +func (t *trackerEvalContext) ArgVal(index int) (ref.Val, bool) { + idx := index + if t.isMember { + idx = index + 1 + } + if idx < len(t.args) && t.args[idx] != nil { + return t.args[idx], true + } + return nil, false +} + +// TargetVal returns the value of the receiver/target object. +func (t *trackerEvalContext) TargetVal() (ref.Val, bool) { + if t.isMember && len(t.args) > 0 && t.args[0] != nil { + return t.args[0], true + } + return nil, false +} + +// ResultVal returns the evaluated result value. +func (t *trackerEvalContext) ResultVal() (ref.Val, bool) { + if t.result != nil { + return t.result, true + } + return nil, false +} + +// Arg returns the runtime size of the argument at index. +func (t *trackerEvalContext) Arg(index int) uint64 { + if val, ok := t.ArgVal(index); ok { + return t.Size(val) + } + return 0 +} + +// Target returns the runtime size of the receiver/target object. +func (t *trackerEvalContext) Target() uint64 { + if val, ok := t.TargetVal(); ok { + return t.Size(val) + } + return 0 +} + +// Result returns the runtime size of the result. +func (t *trackerEvalContext) Result() uint64 { + if val, ok := t.ResultVal(); ok { + return t.Size(val) + } + return 0 +} + +// modelVersion implements trackVersionContext. +func (t *trackerEvalContext) modelVersion() uint32 { + return t.version +} + +// minCallCost is the least a call priced by an OverloadModel costs from cost model version 1, both +// estimated and tracked: a call does at least a unit of work, even over empty arguments, as +// comparing two empty strings does. The short-circuiting operators, ||, && and ?:, and the optional +// or() and orValue(), are exempt, as their cost is that of the arguments they evaluate. +// +// Version 0 reproduces cel-go v0.32.0, which estimated and charged such calls 0. +const minCallCost = uint64(1) + +// hasCallFloor reports whether the model's declarative cost is raised to minCallCost at version. +func (m OverloadModel) hasCallFloor(version uint32) bool { + return version >= 1 && !m.argumentsOnly +} + +// argumentsOnly marks the model of a short-circuiting operator, which is exempt from minCallCost. +func argumentsOnly() OverloadModelOption { + return func(m *OverloadModel) { + m.argumentsOnly = true + } +} diff --git a/vendor/cel.dev/cel-go/common/cost/standard.go b/vendor/cel.dev/cel-go/common/cost/standard.go new file mode 100644 index 0000000000..bceb25c15d --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/standard.go @@ -0,0 +1,278 @@ +// Copyright 2026 Google LLC +// +// 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 cost + +import "cel.dev/cel-go/common/overloads" + +// StandardOverloadModels defines the cost models for standard CEL functions. +var StandardOverloadModels = []OverloadModel{ + // O(1) container index operations + Overload(overloads.IndexList, + EvalCost(Const(1)), + ResultSize(ArgElem(0)), + ), + Overload(overloads.IndexMap, + EvalCost(Const(1)), + ResultSize(ArgElem(0)), + ), + + // O(n) prefix/suffix functions + MemberOverload(overloads.StartsWithString, + EvalCost(Scale(Arg(0), StringTraversalCostFactor)), + ), + MemberOverload(overloads.EndsWithString, + EvalCost(Scale(Arg(0), StringTraversalCostFactor)), + ), + + // O(n) conversion & format functions + Overload(overloads.StringToBytes, + EvalCost(Scale(Arg(0), StringTraversalCostFactor)), + ResultSize(Ranged(Arg(0), Scale(Arg(0), 4.0))), + ), + Overload(overloads.BytesToString, + EvalCost(Scale(Arg(0), StringTraversalCostFactor)), + ResultSize(Ranged(Scale(Arg(0), 0.25), Arg(0))), + ), + Overload(overloads.ExtQuoteString, + EvalCost(Scale(Arg(0), StringTraversalCostFactor)), + ResultSize(Ranged(Sum(Arg(0), Const(2)), Sum(Scale(Arg(0), 2.0), Const(2)))), + ), + MemberOverload(overloads.ExtFormatString, + EvalCost(Scale(Target(), StringTraversalCostFactor)), + ), + + // O(n) containment + Overload(overloads.InList, EvalCost(Arg(1))), + + // Short-circuiting optional selection. The planner rewrites these calls into a branch which + // evaluates the alternative only when the receiver is empty, and which is not charged at + // runtime, so the model reports no cost for the dispatch itself. The alternative's cost is + // bounded by calculateArgCost. + // + // From version 1 the result is whichever of the two is present: or() returns one of the two + // optionals, and orValue() the receiver's value or the alternative. Before the revision these + // were unmodeled calls, which v0.32.0 estimated at 1 with no result size, although it charged + // them nothing. + MemberOverload(overloads.OptionalOrOptional, + EvalCost(Const(0)), + argumentsOnly(), + ResultSize(Union(Target(), Arg(0))), + BeforeVersion(1, ManualEstimator(estimateUnmodeledCall)), + ), + MemberOverload(overloads.OptionalOrValueValue, + EvalCost(Const(0)), + argumentsOnly(), + ResultSize(Union(ElemOf(Target()), Arg(0))), + BeforeVersion(1, ManualEstimator(estimateUnmodeledCall)), + ), + + // Creating, wrapping and unwrapping an optional. These cost what an unmodeled call costs; they + // are modeled from version 1 so that the wrapped value's size survives the round trip, with an + // optional sized as 1 plus the value it holds (see Optional). Without them an estimate dies at + // optional.of(x) and everything downstream of the optional is unbounded. + Overload(overloads.OptionalNone, + EvalCost(Const(1)), + ResultSize(Optional(Const(0))), + BeforeVersion(1, ResultSize(nil)), + ), + Overload(overloads.OptionalOf, + EvalCost(Const(1)), + ResultSize(Optional(Arg(0))), + BeforeVersion(1, ResultSize(nil)), + ), + // ofNonZeroValue is empty for a zero value, so it holds a value of at most the argument's size. + Overload(overloads.OptionalOfNonZeroValue, + EvalCost(Const(1)), + ResultSize(Optional(AtMost(Arg(0)))), + BeforeVersion(1, ResultSize(nil)), + ), + MemberOverload(overloads.OptionalValue, + EvalCost(Const(1)), + ResultSize(ElemOf(Target())), + BeforeVersion(1, ResultSize(nil)), + ), + + // O(min(m, n)) comparison / equality. Before version 1 the estimate keeps the v0.32.0 bounds of + // estimateComparisonV0; the charge is the same at every version. + Overload(overloads.LessString, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + Overload(overloads.GreaterString, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + Overload(overloads.LessEqualsString, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + Overload(overloads.GreaterEqualsString, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + Overload(overloads.LessBytes, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + Overload(overloads.GreaterBytes, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + Overload(overloads.LessEqualsBytes, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + Overload(overloads.GreaterEqualsBytes, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + Overload(overloads.Equals, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + Overload(overloads.NotEquals, + EvalCost(Scale(Min(Arg(0), Arg(1)), StringTraversalCostFactor)), + BeforeVersion(1, ManualEstimator(estimateComparisonV0)), + ), + + // O(m+n) string & bytes concatenation + Overload(overloads.AddString, + EvalCost(Scale(Sum(Arg(0), Arg(1)), StringTraversalCostFactor)), + ResultSize(Sum(Arg(0), Arg(1))), + ), + Overload(overloads.AddBytes, + EvalCost(Scale(Sum(Arg(0), Arg(1)), StringTraversalCostFactor)), + ResultSize(Sum(Arg(0), Arg(1))), + ), + + // O(1) list concatenation with size tracking + Overload(overloads.AddList, + EvalCost(Const(1)), + ResultSize(Sum(Arg(0), Arg(1))), + ), + + // O(nm) regex matches + Overload(overloads.Matches, + EvalCost(Mul( + Scale(Sum(Arg(0), Const(1)), StringTraversalCostFactor), + Scale(Arg(1), RegexStringLengthCostFactor), + )), + BeforeVersion(1, EvalCost(Mul( + roundScale(Sum(Arg(0), Const(1)), StringTraversalCostFactor), + roundScale(Arg(1), RegexStringLengthCostFactor), + ))), + ), + MemberOverload(overloads.MatchesString, + EvalCost(Mul( + Scale(Sum(Target(), Const(1)), StringTraversalCostFactor), + Scale(Arg(0), RegexStringLengthCostFactor), + )), + BeforeVersion(1, EvalCost(Mul( + roundScale(Sum(Target(), Const(1)), StringTraversalCostFactor), + roundScale(Arg(0), RegexStringLengthCostFactor), + ))), + ), + + // O(nm) substring contains + MemberOverload(overloads.ContainsString, + EvalCost(Mul( + Scale(Target(), StringTraversalCostFactor), + Scale(Arg(0), StringTraversalCostFactor), + )), + BeforeVersion(1, EvalCost(Mul( + roundScale(Target(), StringTraversalCostFactor), + roundScale(Arg(0), StringTraversalCostFactor), + ))), + ), + + // The arg cost for logical and conditional operators is special-cased for + // short-circuiting (see CalculateArgCost in estimator.go), so the arg cost is 0. + + // Logical short-circuiting operators + Overload(overloads.LogicalOr, EvalCost(Const(0)), argumentsOnly()), + Overload(overloads.LogicalAnd, EvalCost(Const(0)), argumentsOnly()), + + // Conditional operator + Overload(overloads.Conditional, + EvalCost(Const(0)), + argumentsOnly(), + ResultSize(Union(Arg(1), Arg(2))), + ), +} + +// roundScale scales e by f and rounds before any outer multiplication, reproducing the version 0 +// rounding of products of scaled factors. +func roundScale(e QuantityExpr, f float64) QuantityExpr { + s := Scale(e, f) + return Ranged(s, s) +} + +// StandardOverloadEstimators returns the map of FunctionEstimator instances for standard overloads. +func StandardOverloadEstimators() map[string]FunctionEstimator { + return StandardOverloadEstimatorsWithOptions() +} + +// StandardOverloadEstimatorsWithOptions returns the map of FunctionEstimator instances for standard +// overloads, configured by the supplied options. +func StandardOverloadEstimatorsWithOptions(opts ...ModelOption) map[string]FunctionEstimator { + estimators := make(map[string]FunctionEstimator, len(StandardOverloadModels)) + for _, m := range StandardOverloadModels { + estimators[m.ID] = m.FunctionEstimatorWithOptions(opts...) + } + return estimators +} + +// StandardOverloadTrackers returns the map of FunctionTracker instances for standard overloads. +func StandardOverloadTrackers() map[string]FunctionTracker { + return StandardOverloadTrackersWithOptions() +} + +// StandardOverloadTrackersWithOptions returns the map of FunctionTracker instances for standard +// overloads, configured by the supplied options. +// +// The models are tracked under the configured revision, so that each charge is computed by the same +// rules as its estimate. +func StandardOverloadTrackersWithOptions(opts ...ModelOption) map[string]FunctionTracker { + trackers := make(map[string]FunctionTracker, len(StandardOverloadModels)) + for _, m := range StandardOverloadModels { + trackers[m.ID] = m.FunctionTrackerWithOptions(opts...) + } + return trackers +} + +// estimateUnmodeledCall estimates a call as the estimator does a call it has no model for: a cost +// of 1, with no result size. +func estimateUnmodeledCall(Estimator, *AstNode, []AstNode) *CallEstimate { + return NewCallEstimate(CallCostEstimate, nil) +} + +// estimateComparisonV0 estimates a string, bytes or equality comparison as cel-go v0.32.0 did: +// ceil(0.1 * [m, min(lhs.Max, rhs.Max)]), where m is 1 when the smaller maximum is non-zero, and 0 +// otherwise. +// +// The lower bound is the charge of comparing any non-empty operands, whatever their minimum sizes, +// where the version 1 model reports ceil(0.1 * min(lhs.Min, rhs.Min)). The upper bound scales an +// unknown size like any other, where the version 1 model saturates it at math.MaxUint64. +func estimateComparisonV0(estimator Estimator, _ *AstNode, args []AstNode) *CallEstimate { + if len(args) != 2 { + return nil + } + smallestMax := min(EstimateSize(estimator, args[0]).Max, EstimateSize(estimator, args[1]).Max) + lo := uint64(0) + if smallestMax > 0 { + lo = 1 + } + return NewCallEstimate(CostEstimate{Min: lo, Max: smallestMax}.MultiplyByCostFactor(StringTraversalCostFactor), nil) +} diff --git a/vendor/cel.dev/cel-go/common/cost/strategy.go b/vendor/cel.dev/cel-go/common/cost/strategy.go new file mode 100644 index 0000000000..fb5b0f58aa --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/strategy.go @@ -0,0 +1,29 @@ +// Copyright 2026 Google LLC +// +// 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 cost + +import ( + "cel.dev/cel-go/common/types/ref" +) + +// SizingStrategy defines how sizes and container element sizes are estimated and tracked. +type SizingStrategy interface { + // EstimateSize computes the size estimate for an AST node during cost estimation. + // For lists and maps, the returned SizeEstimate can recursively include Elem and Key sizes. + EstimateSize(ctx EstimateContext, node AstNode) (SizeEstimate, bool) + + // TrackSize computes the actual runtime size of a value during cost tracking. + TrackSize(ctx TrackContext, value ref.Val) (uint64, bool) +} diff --git a/vendor/cel.dev/cel-go/common/cost/tracker.go b/vendor/cel.dev/cel-go/common/cost/tracker.go new file mode 100644 index 0000000000..3e72ba8411 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/tracker.go @@ -0,0 +1,297 @@ +// Copyright 2026 Google LLC +// +// 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 cost + +import ( + "cel.dev/cel-go/common/types/ref" + "fmt" +) + +// WARNING: Any changes to cost calculations in this file require a corresponding change in estimator.go + +// ActualCostEstimator provides function call cost estimations at runtime. +// +// CallCost returns an estimated cost for the function overload invocation with the given args, or nil if it has no +// estimate to provide. CEL attempts to provide reasonable estimates for its standard function library, so CallCost +// should typically not need to provide an estimate for CELs standard function. +type ActualCostEstimator interface { + CallCost(function, overloadID string, args []ref.Val, result ref.Val) *uint64 +} + +// FunctionTracker computes the actual cost of evaluating the functions with the given arguments and result. +type FunctionTracker func(args []ref.Val, result ref.Val) *uint64 + +// Call represents an invocable function with a name and overload ID. +type Call interface { + // Function returns the name of the function being called. + Function() string + + // OverloadID returns the specific overload ID being invoked. + OverloadID() string +} + +// TrackerOption configures the behavior of CostTracker objects. +type TrackerOption interface { + applyTracker(*trackerBuilder) error +} + +type trackerOption func(*Tracker) error + +func (opt trackerOption) applyTracker(b *trackerBuilder) error { + return opt(b.tracker) +} + +type trackerBuilderOption func(*trackerBuilder) error + +func (opt trackerBuilderOption) applyTracker(b *trackerBuilder) error { + return opt(b) +} + +// trackerBuilder holds the configuration which matters only while NewTracker builds a Tracker. +// +// It is kept out of the Tracker, which is copied for every evaluation by Clone, so that the +// per-evaluation copy carries only what pricing a call reads. +type trackerBuilder struct { + tracker *Tracker + modelRules + overloadTrackers overloadTable[FunctionTracker] +} + +// TrackerLimit sets the runtime limit on the evaluation cost during execution and will terminate the expression +// evaluation if the limit is exceeded. +func TrackerLimit(limit uint64) TrackerOption { + return trackerOption(func(tracker *Tracker) error { + tracker.Limit = &limit + return nil + }) +} + +// TrackerPresenceTestHasCost determines whether presence testing has a cost of one or zero. +// Defaults to presence test has a cost of one. +func TrackerPresenceTestHasCost(hasCost bool) TrackerOption { + return trackerOption(func(tracker *Tracker) error { + tracker.presenceTestHasCost = hasCost + return nil + }) +} + +// TrackerLimitExceededHandler sets a custom handler invoked when the cost limit is exceeded. +func TrackerLimitExceededHandler(handler func()) TrackerOption { + return trackerOption(func(tracker *Tracker) error { + tracker.limitExceededHandler = handler + return nil + }) +} + +// OverloadTracker binds an overload ID to a runtime FunctionTracker implementation. +// +// OverloadTracker instances augment or override ActualCostEstimator decisions, allowing for +// versioned and/or optional cost tracking changes. +func OverloadTracker(overloadID string, fnTracker FunctionTracker) TrackerOption { + return trackerBuilderOption(func(b *trackerBuilder) error { + if fnTracker == nil { + return fmt.Errorf("OverloadTracker(%q) requires a FunctionTracker", overloadID) + } + b.overloadTrackers.mutable()[overloadID] = fnTracker + return nil + }) +} + +// LimitExceededError indicates that the actual cost limit was exceeded during evaluation. +type LimitExceededError struct { + Message string +} + +// Error returns the error message for LimitExceededError. +func (e LimitExceededError) Error() string { + return e.Message +} + +// Tracker represents the information needed for tracking runtime cost. +type Tracker struct { + Estimator ActualCostEstimator + overloadTrackers map[string]FunctionTracker + standardOverloadTrackers map[string]FunctionTracker + Limit *uint64 + limitExceededHandler func() + cost uint64 + presenceTestHasCost bool + modelVersion uint32 +} + +// NewTracker creates a new Tracker with a given estimator and a set of functional TrackerOption values. +// +// The Tracker's configuration is fixed once it is returned; only its accumulated cost changes. +func NewTracker(estimator ActualCostEstimator, opts ...TrackerOption) (*Tracker, error) { + b := &trackerBuilder{ + tracker: &Tracker{Estimator: estimator, presenceTestHasCost: true}, + modelRules: defaultModelRules(), + } + for _, opt := range opts { + if mo, ok := opt.(ModelOption); ok { + b.modelRules.override(mo) + } + } + for _, opt := range opts { + if err := opt.applyTracker(b); err != nil { + return nil, err + } + } + tracker := b.tracker + tracker.modelVersion = b.modelVersion + tracker.overloadTrackers = b.overloadTrackers.fns + // The package-level trackers are compiled under the default rules. + tracker.standardOverloadTrackers = stdOverloadTrackers + if !b.modelRules.isDefault() { + tracker.standardOverloadTrackers = StandardOverloadTrackersWithOptions(b.modelRules.modelOptions()...) + } + return tracker, nil +} + +// Clone makes a shallow copy of the tracker with no accumulated cost. +// The different clones can be used independently from each other: they share only configuration, +// which is not modified after NewTracker returns. +func (c *Tracker) Clone() (*Tracker, error) { + tracker := *c + tracker.cost = 0 + return &tracker, nil +} + +// ActualCost returns the runtime cost. +func (c *Tracker) ActualCost() uint64 { + return c.cost +} + +// PresenceTestHasCost returns whether presence testing has a cost. +func (c *Tracker) PresenceTestHasCost() bool { + return c.presenceTestHasCost +} + +// ModelVersion returns the cost model version configured on the tracker. +func (c *Tracker) ModelVersion() uint32 { + if c == nil { + return defaultModelVersion + } + return c.modelVersion +} + +// CreateList records list literal construction cost. +func (c *Tracker) CreateList(id int64, res ref.Val) { + c.cost = SafeAdd(c.cost, ListCreateBaseCost) + c.checkLimit() +} + +// CreateMap records map literal construction cost. +func (c *Tracker) CreateMap(id int64, res ref.Val) { + c.cost = SafeAdd(c.cost, MapCreateBaseCost) + c.checkLimit() +} + +// CreateStruct records struct/object construction cost. +func (c *Tracker) CreateStruct(id int64, res ref.Val) { + c.cost = SafeAdd(c.cost, StructCreateBaseCost) + c.checkLimit() +} + +// EvalAttribute records attribute resolution cost (ident / select). +func (c *Tracker) EvalAttribute(id int64, isTestOnly bool, res ref.Val) { + if !isTestOnly || c.presenceTestHasCost { + c.cost = SafeAdd(c.cost, SelectAndIdentCost) + c.checkLimit() + } +} + +// Qualify records qualifier cost. +func (c *Tracker) Qualify(id int64) { + c.cost = SafeAdd(c.cost, 1) + c.checkLimit() +} + +func (c *Tracker) recordCallCost(call Call, args []ref.Val, result ref.Val) { + c.cost = SafeAdd(c.cost, c.CostCall(call, args, result)) + c.checkLimit() +} + +// EvalZeroArity records the cost for a 0-arity call expression. +func (c *Tracker) EvalZeroArity(vars any, id int64, call Call, result ref.Val) { + c.recordCallCost(call, nil, result) +} + +// EvalUnary records the cost for a unary call expression. +func (c *Tracker) EvalUnary(vars any, id int64, call Call, arg ref.Val, result ref.Val) { + var buf [1]ref.Val + buf[0] = arg + c.recordCallCost(call, buf[:], result) +} + +// EvalBinary records the cost for a binary call expression. +func (c *Tracker) EvalBinary(vars any, id int64, call Call, lhs, rhs ref.Val, result ref.Val) { + var buf [2]ref.Val + buf[0] = lhs + buf[1] = rhs + c.recordCallCost(call, buf[:], result) +} + +// EvalVarArgs records the cost for a variadic call expression. +func (c *Tracker) EvalVarArgs(vars any, id int64, call Call, args []ref.Val, result ref.Val) { + c.recordCallCost(call, args, result) +} + +func (c *Tracker) checkLimit() { + if c.Limit != nil && c.cost > *c.Limit { + if c.limitExceededHandler != nil { + c.limitExceededHandler() + } + panic(LimitExceededError{Message: "operation cancelled: actual cost limit exceeded"}) + } +} + +// CostCall calculates the runtime cost for a function call. +func (c *Tracker) CostCall(call Call, args []ref.Val, result ref.Val) uint64 { + var total uint64 + if tracker, found := c.overloadTrackers[call.OverloadID()]; found { + callCost := tracker(args, result) + if callCost != nil { + total = SafeAdd(total, *callCost) + return total + } + } + if c.Estimator != nil { + callCost := c.Estimator.CallCost(call.Function(), call.OverloadID(), args, result) + if callCost != nil { + total = SafeAdd(total, *callCost) + return total + } + } + if tracker, found := c.standardOverloadTrackers[call.OverloadID()]; found { + callCost := tracker(args, result) + if callCost != nil { + total = SafeAdd(total, *callCost) + return total + } + } + // The following operations are assumed to have O(1) complexity. + // - AddList due to the implementation. Index lookup can be O(c) the + // number of concatenated lists, but we don't track that in cost calculations. + // - Conversions, since none perform a traversal of a type of unbound length. + // - Computing the size of strings, byte sequences, lists and maps. + // - Logical operations and all operators on fixed width scalars (comparisons, equality) + // - Any functions that don't have a declared cost either here or in provided ActualCostEstimator. + return SafeAdd(total, 1) +} + +var ( + stdOverloadTrackers = StandardOverloadTrackers() +) diff --git a/vendor/cel.dev/cel-go/common/cost/validate.go b/vendor/cel.dev/cel-go/common/cost/validate.go new file mode 100644 index 0000000000..f9ecd3f5d1 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/validate.go @@ -0,0 +1,275 @@ +// Copyright 2026 Google LLC +// +// 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 cost + +import ( + "errors" + "fmt" + "math" +) + +// Validate reports whether the model is well-formed. +// +// A model is checked when it is registered, rather than when it is evaluated, because neither of +// the two evaluation paths can report a problem: an estimator has nowhere to return an error, and +// a tracker which cannot answer an expression would have to choose between charging nothing and +// charging the maximum, one of which lets an expression through and the other of which fails every +// evaluation that sets a cost limit. +// +// The checks apply at every model version, because every model they reject is mispriced at every +// version. They are: +// - the overload has an ID, and an evaluation cost expression; +// - every Arg and IntArg index is non-negative; +// - every element or key projection is applied to an expression which denotes a value; +// - every ElemTotal, KeyTotal and Length is applied to Arg, Target or Result; +// - a global overload does not reference the receiver; +// - every Scale factor is finite and positive; +// - no Ranged has constant bounds in the wrong order; +// - the result size expression does not reference Result(). +// +// Projections read the value they project from, so ElemOf, KeyOf and the ArgElem, ArgKey, +// TargetElem and TargetKey shorthands are defined over Arg, Target, Result, and the ElemOf and +// KeyOf projections of those. A projection of a computed quantity, such as +// ElemOf(Sum(Arg(0), Arg(1))), has an estimate but no runtime counterpart, and is reported here. +// ElemTotal, KeyTotal and Length estimate a quantity from the size of a single value, so they are +// defined over Arg, Target and Result only. +func (m OverloadModel) Validate() error { + return m.validate(false) +} + +func (m OverloadModel) validate(inPrior bool) error { + if m.ID == "" { + return errors.New("overload model requires an ID") + } + if m.manual && m.manualEstimator { + return fmt.Errorf("overload %q cannot combine ManualCost with ManualEstimator", m.ID) + } + if m.manual && (m.Cost != nil || m.hasSize) { + return fmt.Errorf("overload %q cannot combine ManualCost with EvalCost or ResultSize", m.ID) + } + if m.manual && (m.estimator == nil || m.tracker == nil) { + return fmt.Errorf("overload %q ManualCost requires both a FunctionEstimator and a FunctionTracker", m.ID) + } + if m.manualEstimator && m.hasSize { + return fmt.Errorf("overload %q cannot combine ManualEstimator with ResultSize", m.ID) + } + if m.manualEstimator && m.estimator == nil { + return fmt.Errorf("overload %q ManualEstimator requires a FunctionEstimator", m.ID) + } + if !m.manual && m.Cost == nil && !(inPrior && (m.manualEstimator || m.hasSize)) { + return fmt.Errorf("overload %q requires an EvalCost expression or ManualCost", m.ID) + } + if m.Cost != nil { + if err := validateQuantityExpr(m.Cost); err != nil { + return fmt.Errorf("overload %q eval cost: %w", m.ID, err) + } + } + if m.Size != nil || (m.hasSize && !inPrior) { + if err := validateQuantityExpr(m.Size); err != nil { + return fmt.Errorf("overload %q result size: %w", m.ID, err) + } + } + if !m.IsMember && (hasTarget(m.Cost) || hasTarget(m.Size)) { + return fmt.Errorf("overload %q is global but its model references the receiver; use MemberOverload", m.ID) + } + if m.Size != nil && references(m.Size, func(e QuantityExpr) bool { _, ok := e.(resultExpr); return ok }) { + return fmt.Errorf("overload %q result size references Result()", m.ID) + } + return validatePriors(m) +} + +func validatePriors(m OverloadModel) error { + seen := make(map[uint32]struct{}, len(m.priors)) + for _, p := range m.priors { + if p.before == 0 { + return fmt.Errorf("overload %q: BeforeVersion requires a version >= 1, got 0", m.ID) + } + if _, dup := seen[p.before]; dup { + return fmt.Errorf("overload %q: duplicate BeforeVersion(%d)", m.ID, p.before) + } + seen[p.before] = struct{}{} + if err := p.model.validate(true); err != nil { + return fmt.Errorf("overload %q before version %d: %w", m.ID, p.before, err) + } + resolved := m.resolvePrior(p.model) + if !resolved.manual && resolved.Cost == nil { + return fmt.Errorf("overload %q before version %d: overload %q requires an EvalCost expression or ManualCost", m.ID, p.before, m.ID) + } + } + return nil +} + +// references reports whether pred holds for the expression or any of its operands. +func references(expr QuantityExpr, pred func(QuantityExpr) bool) bool { + if pred(expr) { + return true + } + _, operands := describeQuantityExpr(expr) + for _, operand := range operands { + if references(operand, pred) { + return true + } + } + return false +} + +// ValidateOverloadModels reports the first model which is not well-formed. +func ValidateOverloadModels(models ...OverloadModel) error { + for _, m := range models { + if err := m.Validate(); err != nil { + return err + } + } + return nil +} + +// validateQuantityExpr reports the first operand of an expression tree which cannot be evaluated. +// +// A nil operand is reported here so that it fails registration rather than panicking when an +// estimate or a charge is first computed. +func validateQuantityExpr(expr QuantityExpr) error { + if expr == nil { + return errors.New("nil quantity expression") + } + label, operands := describeQuantityExpr(expr) + switch e := expr.(type) { + case argExpr: + if e.index < 0 { + return fmt.Errorf("Arg index must be non-negative, got %d", e.index) + } + case intArgExpr: + if e.index < 0 { + return fmt.Errorf("IntArg index must be non-negative, got %d", e.index) + } + case scaleExpr: + if math.IsNaN(e.factor) || math.IsInf(e.factor, 0) || e.factor <= 0 { + return fmt.Errorf("Scale factor must be finite and positive, got %v", e.factor) + } + case rangedExpr: + lo, loConst := e.minExpr.(constExpr) + hi, hiConst := e.maxExpr.(constExpr) + if loConst && hiConst && lo.val > hi.val { + return fmt.Errorf("Ranged lower bound %d exceeds upper bound %d", lo.val, hi.val) + } + } + // A nil operand is left to the recursion below to report. + if _, isProjection := expr.(projection); isProjection && operands[0] != nil { + if _, ok := operands[0].(valueSource); !ok { + operandLabel, _ := describeQuantityExpr(operands[0]) + return fmt.Errorf( + "%s is not defined over %s: element and key projections apply to Arg, Target, Result, and ElemOf or KeyOf of those", + label, operandLabel) + } + } + if _, single := expr.(singleValueProjection); single { + switch operands[0].(type) { + case argExpr, targetExpr, resultExpr: + default: + operandLabel, _ := describeQuantityExpr(operands[0]) + return fmt.Errorf( + "%s is not defined over %s: it applies to Arg, Target and Result, whose size bounds it", + label, operandLabel) + } + } + for _, operand := range operands { + if err := validateQuantityExpr(operand); err != nil { + return fmt.Errorf("%s: %w", label, err) + } + } + return nil +} + +// projection marks the expressions which read the elements or keys of the value they are applied +// to, and so constrain what that operand may be. +type projection interface { + QuantityExpr + projects() +} + +func (elemExpr) projects() {} +func (keyExpr) projects() {} +func (elemTotalExpr) projects() {} +func (keyTotalExpr) projects() {} +func (lengthExpr) projects() {} + +// singleValueProjection marks the projections whose estimate is derived from the size of a single +// value, so the operand must denote exactly one value: a total or length of ElemOf(X) would range +// over every element of X, which no single size estimate bounds. +type singleValueProjection interface { + projection + singleValue() +} + +func (elemTotalExpr) singleValue() {} +func (keyTotalExpr) singleValue() {} +func (lengthExpr) singleValue() {} + +// describeQuantityExpr reports the constructor name of a quantity expression and its operands. +// +// Every expression type must be listed: an omission makes an expression's operands invisible to +// validation, and reports an unhelpful name in the error message. TestDescribeQuantityExpr covers +// each constructor. +func describeQuantityExpr(expr QuantityExpr) (string, []QuantityExpr) { + switch e := expr.(type) { + case constExpr: + return "Const", nil + case argExpr: + return "Arg", nil + case intArgExpr: + return "IntArg", nil + case targetExpr: + return "Target", nil + case intTargetExpr: + return "IntTarget", nil + case resultExpr: + return "Result", nil + case elemExpr: + return "ElemOf", []QuantityExpr{e.expr} + case keyExpr: + return "KeyOf", []QuantityExpr{e.expr} + case elemTotalExpr: + return "ElemTotal", []QuantityExpr{e.expr} + case keyTotalExpr: + return "KeyTotal", []QuantityExpr{e.expr} + case lengthExpr: + return "Length", []QuantityExpr{e.expr} + case addExpr: + return "Sum", e.terms + case subExpr: + return "Sub", []QuantityExpr{e.lhs, e.rhs} + case mulExpr: + return "Mul", e.terms + case scaleExpr: + return "Scale", []QuantityExpr{e.expr} + case minExpr: + return "Min", []QuantityExpr{e.lhs, e.rhs} + case maxExpr: + return "Max", []QuantityExpr{e.lhs, e.rhs} + case unionExpr: + return "Union", e.terms + case rangedExpr: + return "Ranged", []QuantityExpr{e.minExpr, e.maxExpr} + case atLeastOneExpr: + return "AtLeastOneQuantity", []QuantityExpr{e.expr} + case listExpr: + return "List", []QuantityExpr{e.lenExpr, e.elemExpr} + case mapExpr: + return "Map", []QuantityExpr{e.sizeExpr, e.keyExpr, e.valExpr} + case optionalExpr: + return "Optional", []QuantityExpr{e.valueExpr} + default: + return fmt.Sprintf("%T", expr), nil + } +} diff --git a/vendor/cel.dev/cel-go/common/cost/version.go b/vendor/cel.dev/cel-go/common/cost/version.go new file mode 100644 index 0000000000..5b4b45bd7a --- /dev/null +++ b/vendor/cel.dev/cel-go/common/cost/version.go @@ -0,0 +1,299 @@ +// Copyright 2025 Google LLC +// +// 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 +// +// https://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 cost + +import ( + "maps" + "math" + "slices" + "sync" +) + +const defaultModelVersion uint32 = math.MaxUint32 + +// ModelOption configures how OverloadModels, cost estimators, and cost trackers are built and +// evaluated. +// +// A ModelOption implements both Option (for Cost) and TrackerOption (for NewTracker), and may also +// be passed when compiling models directly via FunctionEstimatorWithOptions, +// FunctionTrackerWithOptions, StandardOverloadEstimatorsWithOptions, and +// StandardOverloadTrackersWithOptions. +type ModelOption func(*modelOptions) + +// modelRules are the sizing strategy and model revision under which an estimator or a tracker +// prices calls. Both are fixed once the estimator or tracker has been configured. +type modelRules struct { + sizingStrategy SizingStrategy + modelVersion uint32 +} + +func defaultModelRules() modelRules { + return modelRules{sizingStrategy: defaultSizing, modelVersion: defaultModelVersion} +} + +// isDefault reports whether the rules are those the package-level and per-model-set caches are +// compiled under, so that the cached functions may be shared rather than recompiled. +func (r modelRules) isDefault() bool { + return r.sizingStrategy == defaultSizing && r.modelVersion == defaultModelVersion +} + +func (r modelRules) modelOptions() []ModelOption { + return []ModelOption{WithSizingStrategy(r.sizingStrategy), ModelVersion(r.modelVersion)} +} + +// override replaces the rules the option sets, leaving the others in place. +func (r *modelRules) override(opt ModelOption) { + o := newModelOptions(opt) + if o.hasStrategy { + r.sizingStrategy = o.strategy + } + if o.hasVersion { + r.modelVersion = o.version + } +} + +// compiledModelSet is the immutable product of a Model option: the models, the result of +// validating them, and, built on first use and shared by every estimator and tracker configured +// with the option, the functions the models compile to under the default rules. +type compiledModelSet struct { + models []OverloadModel + err error + estOnce sync.Once + defaultEstimators map[string]FunctionEstimator + trkOnce sync.Once + defaultTrackers map[string]FunctionTracker +} + +func newCompiledModelSet(models []OverloadModel) *compiledModelSet { + return &compiledModelSet{ + models: models, + err: ValidateOverloadModels(models...), + } +} + +func (cm *compiledModelSet) estimators() map[string]FunctionEstimator { + cm.estOnce.Do(func() { + var t overloadTable[FunctionEstimator] + t.compile(cm.models, estimatorCompiler()) + cm.defaultEstimators = t.fns + }) + return cm.defaultEstimators +} + +func (cm *compiledModelSet) trackers() map[string]FunctionTracker { + cm.trkOnce.Do(func() { + var t overloadTable[FunctionTracker] + t.compile(cm.models, trackerCompiler()) + cm.defaultTrackers = t.fns + }) + return cm.defaultTrackers +} + +// overloadTable maps overload IDs to the FunctionEstimators or FunctionTrackers which price them. +// +// Options populate a table while an estimator or tracker is configured; it is read-only after. +// A table configured with a single model set under the default rules refers to the set's cached +// functions rather than copying them, and is copied before its first write. +type overloadTable[F any] struct { + fns map[string]F + shared bool +} + +func (t *overloadTable[F]) mutable() map[string]F { + if t.shared { + t.fns, t.shared = maps.Clone(t.fns), false + } else if t.fns == nil { + t.fns = map[string]F{} + } + return t.fns +} + +// compile binds each model's function in order, so a later model replaces an earlier one with the +// same ID. +func (t *overloadTable[F]) compile(models []OverloadModel, compile func(OverloadModel) F) { + fns := t.mutable() + for _, m := range models { + fns[m.ID] = compile(m) + } +} + +// addModelSet binds the functions the models of cm compile to under the given rules. +func (t *overloadTable[F]) addModelSet(cm *compiledModelSet, rules modelRules, + cached func() map[string]F, compile func(...ModelOption) func(OverloadModel) F) error { + if cm.err != nil { + return cm.err + } + if !rules.isDefault() { + t.compile(cm.models, compile(rules.modelOptions()...)) + return nil + } + if t.fns == nil { + t.fns, t.shared = cached(), true + return nil + } + t.compile(cm.models, compile()) + return nil +} + +func estimatorCompiler(opts ...ModelOption) func(OverloadModel) FunctionEstimator { + return func(m OverloadModel) FunctionEstimator { + return m.FunctionEstimatorWithOptions(opts...) + } +} + +func trackerCompiler(opts ...ModelOption) func(OverloadModel) FunctionTracker { + return func(m OverloadModel) FunctionTracker { + return m.FunctionTrackerWithOptions(opts...) + } +} + +// modelOptions is the resolved configuration for compiling an OverloadModel or configuring an +// estimator or tracker. +type modelOptions struct { + strategy SizingStrategy + hasStrategy bool + version uint32 + hasVersion bool + modelSets []*compiledModelSet +} + +// A ModelOption is applied in two passes by Cost and NewTracker. The first, over every ModelOption +// before any other option, settles the rules, so that models are compiled under the final rules +// whatever the option order. The second registers the model sets in order with the other options, +// so that a later registration of an overload ID overrides an earlier one. + +func (opt ModelOption) applyCoster(c *coster) error { + for _, cm := range newModelOptions(opt).modelSets { + if err := c.overloadEstimators.addModelSet(cm, c.modelRules, cm.estimators, estimatorCompiler); err != nil { + return err + } + } + return nil +} + +func (opt ModelOption) applyTracker(b *trackerBuilder) error { + for _, cm := range newModelOptions(opt).modelSets { + if err := b.overloadTrackers.addModelSet(cm, b.modelRules, cm.trackers, trackerCompiler); err != nil { + return err + } + } + return nil +} + +// newModelOptions resolves the supplied options over the defaults. +func newModelOptions(opts ...ModelOption) *modelOptions { + resolved := &modelOptions{ + strategy: defaultSizing, + version: defaultModelVersion, + } + for _, opt := range opts { + opt(resolved) + } + return resolved +} + +// Model registers one or more OverloadModels for both cost estimation and runtime cost tracking. +// +// Models are validated when the option is applied to Cost or NewTracker and resolved after all +// options have run, so they observe the WithSizingStrategy and ModelVersion configured on the call +// regardless of option order. +func Model(models ...OverloadModel) ModelOption { + cm := newCompiledModelSet(slices.Clone(models)) + return func(o *modelOptions) { + o.modelSets = append(o.modelSets, cm) + } +} + +// WithSizingStrategy sets the SizingStrategy used to resolve sizes during both cost estimation and +// runtime cost tracking. +// +// A nil strategy is ignored, leaving the default in place. +func WithSizingStrategy(strategy SizingStrategy) ModelOption { + return func(o *modelOptions) { + o.hasStrategy = true + if strategy != nil { + o.strategy = strategy + } + } +} + +// ModelVersion pins the revision of the cost model's estimation and runtime tracking rules. +// +// If this option is not set, the latest cost model version is used. Revisions exist so that +// corrections to the model can land without silently moving numbers that existing deployments +// budget against. A caller holding estimates recorded under an earlier release can pin to the +// revision those estimates were produced under, review the delta at leisure, and adopt the +// correction deliberately. +// +// Revisions apply to both estimation and runtime tracking, so that an estimate and the charge it +// predicts are always computed by the same rules. Pinning a version therefore holds both stable. +// +// Caveat: Pinning to version 0 preserves legacy behavior from v0.32.0 and earlier, which contains +// known soundness gaps where static estimates can underestimate actual runtime cost (for example, +// when a caller's Estimator overrides computed loop variable sizes via bare "@items" paths, when +// selecting or indexing into computed containers, or when evaluating non-literal integer bounds). +// Callers are strongly encouraged to switch to ModelVersion(1) or higher (or leave the version +// unset to use the latest revision) for improved soundness between estimated bounds and tracked +// runtime cost. +// +// Version 1: +// - Min() is computed as the exact minimum of its operands' intervals, where v0.32.0 reported a +// lower bound of 1 for any interval whose upper bound is non-zero. The change moves only the +// lower bound of an estimate, never a charge, so it applies at every revision, including when +// pinned to version 0. +// - A value inside an optional keeps its size. optional.of, optional.ofNonZeroValue and value() +// report the size they wrap or unwrap, the two `or` forms report the union of the receiver and +// the alternative, and the optional index forms record the same `@items` and `@values` field +// path their non-optional counterparts do. +// - Optional field and index qualifiers (`m.?k`, `l[?0]`) charge 1 at runtime even when the +// field or index is absent, matching static estimation and non-optional qualification. +// - Selecting or indexing into a computed expression (such as `[1, 2][0]` or `{"a": 1}.a`) +// charges the attribute traversal cost of 1 during estimation to match runtime tracking. +// - Comprehension loop variables over computed (pathless) ranges retain their propagated element +// or key sizes rather than recording bare `@items`, `@indices`, `@keys`, or `@values` paths +// that a caller's Estimator could override with a smaller bound. +// - The default sizing strategy skips `@items`, `@keys`, and `@values` child size hints when a +// container's maximum size is 0. +// - Extension estimators in ext/lists (distinct, sort, sortBy, slice, range, flatten), +// ext/strings (join, split, substring, replace), and ext/regex (extract, extractAll, replace) +// align their Min/Max cost and result-size bounds with their runtime cost trackers. +// - Scale applies its factor as the simplest rational with the same float64 value (0.1 is 1/10) +// and computes the product exactly; it keeps an unbounded quantity unbounded; and when a model +// is compiled, factors are moved outward so that each product is rounded once. The standard +// contains and matches costs become ⌈0.01·m·n⌉ and ⌈0.025·(m+1)·n⌉. +// - Ranged never reports a lower bound above its upper bound. +// - Combinators keep an unknown element or key size unknown, treating constants and integer +// values as scalars; Sub carries only its minuend's metadata. +// - The result size is estimated first and is available to the cost through Result(). +// - A non-literal IntArg or IntTarget estimates as unbounded rather than as its default. +// - List and Map report the size the sizing strategy assigns to the container they describe. +// Under the aggregate strategy, a comprehension iterates once per element of its range rather +// than once per unit of content size, and sizes its result as an aggregate container. +// - Runtime tracking honors the revision, as estimation does. +// - Every ext overload with a cost estimator is priced by a model, which charges by Length what +// its tracker charged and states result sizes in the units of the sizing strategy; flatten(depth) +// follows the strategy in its estimator. An Arg or Target typed as a value without elements, +// such as a string, carries no unknown element size. +// - The value bound by cel.bind counts toward the minimum cost only when the result must read +// it, since the binding is lazy. +// - A list or map literal's minimum size counts only its required elements or entries, and an +// optional element written as optional.none() or optional.of(x) contributes nothing or the +// size of x. +func ModelVersion(version uint32) ModelOption { + return func(o *modelOptions) { + o.hasVersion = true + o.version = version + } +} diff --git a/vendor/github.com/google/cel-go/common/debug/BUILD.bazel b/vendor/cel.dev/cel-go/common/debug/BUILD.bazel similarity index 88% rename from vendor/github.com/google/cel-go/common/debug/BUILD.bazel rename to vendor/cel.dev/cel-go/common/debug/BUILD.bazel index 724ed34045..07fed42715 100644 --- a/vendor/github.com/google/cel-go/common/debug/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/debug/BUILD.bazel @@ -10,7 +10,7 @@ go_library( srcs = [ "debug.go", ], - importpath = "github.com/google/cel-go/common/debug", + importpath = "cel.dev/cel-go/common/debug", deps = [ "//common:go_default_library", "//common/ast:go_default_library", diff --git a/vendor/github.com/google/cel-go/common/debug/debug.go b/vendor/cel.dev/cel-go/common/debug/debug.go similarity index 98% rename from vendor/github.com/google/cel-go/common/debug/debug.go rename to vendor/cel.dev/cel-go/common/debug/debug.go index fbc847f0c1..67593c9968 100644 --- a/vendor/github.com/google/cel-go/common/debug/debug.go +++ b/vendor/cel.dev/cel-go/common/debug/debug.go @@ -22,9 +22,9 @@ import ( "strconv" "strings" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // Adorner returns debug metadata that will be tacked on to the string diff --git a/vendor/github.com/google/cel-go/common/decls/BUILD.bazel b/vendor/cel.dev/cel-go/common/decls/BUILD.bazel similarity index 95% rename from vendor/github.com/google/cel-go/common/decls/BUILD.bazel rename to vendor/cel.dev/cel-go/common/decls/BUILD.bazel index bd3f9ae70e..85c7d5c41d 100644 --- a/vendor/github.com/google/cel-go/common/decls/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/decls/BUILD.bazel @@ -10,7 +10,7 @@ go_library( srcs = [ "decls.go", ], - importpath = "github.com/google/cel-go/common/decls", + importpath = "cel.dev/cel-go/common/decls", deps = [ "//checker/decls:go_default_library", "//common:go_default_library", diff --git a/vendor/github.com/google/cel-go/common/decls/decls.go b/vendor/cel.dev/cel-go/common/decls/decls.go similarity index 89% rename from vendor/github.com/google/cel-go/common/decls/decls.go rename to vendor/cel.dev/cel-go/common/decls/decls.go index 5c50b8e99e..f46e975072 100644 --- a/vendor/github.com/google/cel-go/common/decls/decls.go +++ b/vendor/cel.dev/cel-go/common/decls/decls.go @@ -20,12 +20,12 @@ import ( "fmt" "strings" - chkdecls "github.com/google/cel-go/checker/decls" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + chkdecls "cel.dev/cel-go/checker/decls" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" ) @@ -322,12 +322,29 @@ func (f *FunctionDecl) HasSingletonBinding() bool { return f.singleton != nil } +// IsAsync returns true if the function has an async binding. +func (f *FunctionDecl) IsAsync() bool { + if f == nil { + return false + } + if f.singleton != nil && f.singleton.Async != nil { + return true + } + for _, oID := range f.overloadOrdinals { + o := f.overloads[oID] + if o.IsAsync() { + return true + } + } + return false +} + // HasLateBinding returns true if the function has late bindings. A function cannot mix late bindings with other bindings. func (f *FunctionDecl) HasLateBinding() bool { if f == nil { return false } - if f.singleton != nil && f.singleton.Async != nil { + if f.singleton != nil && f.singleton.LateBound { return true } for _, oID := range f.overloadOrdinals { @@ -350,28 +367,26 @@ func (f *FunctionDecl) Bindings() ([]*functions.Overload, error) { hasLateBinding := false for _, oID := range f.overloadOrdinals { o := f.overloads[oID] - hasLateBinding = hasLateBinding || o.HasLateBinding() - if o.HasBinding() { - overload := &functions.Overload{ - Operator: o.ID(), - Unary: o.guardedUnaryOp(f.Name(), f.disableTypeGuards), - Binary: o.guardedBinaryOp(f.Name(), f.disableTypeGuards), - Function: o.guardedFunctionOp(f.Name(), f.disableTypeGuards), - Async: o.guardedAsyncOp(f.Name(), f.disableTypeGuards), - OperandTrait: o.OperandTrait(), - NonStrict: o.IsNonStrict(), - } - overloads = append(overloads, overload) - nonStrict = nonStrict || o.IsNonStrict() + // An overload is either bound at declaration time or late-bound from the activation. + // The two are mutually exclusive, so each is configured independently. + switch { + case o.HasLateBinding(): + hasLateBinding = true + overloads = append(overloads, o.lateBoundBinding(f.disableTypeGuards)) + case o.HasBinding(): + overloads = append(overloads, o.binding(f.Name(), f.disableTypeGuards)) + default: + continue } + nonStrict = nonStrict || o.IsNonStrict() } if f.singleton != nil { - if len(overloads) != 0 { - return nil, fmt.Errorf("singleton function incompatible with specialized overloads: %s", f.Name()) - } if hasLateBinding { return nil, fmt.Errorf("singleton function incompatible with late bindings: %s", f.Name()) } + if len(overloads) != 0 { + return nil, fmt.Errorf("singleton function incompatible with specialized overloads: %s", f.Name()) + } overloads = []*functions.Overload{ { Operator: f.Name(), @@ -379,6 +394,7 @@ func (f *FunctionDecl) Bindings() ([]*functions.Overload, error) { Binary: f.singleton.Binary, Function: f.singleton.Function, Async: f.singleton.Async, + LateBound: f.singleton.LateBound, OperandTrait: f.singleton.OperandTrait, }, } @@ -392,14 +408,19 @@ func (f *FunctionDecl) Bindings() ([]*functions.Overload, error) { if overloads[0].Operator == f.Name() { return overloads, nil } + named := *overloads[0] + named.Operator = f.Name() + return append(overloads, &named), nil + } + if hasLateBinding { + // Late-bound implementations are resolved from the activation by function name, so the + // top-level entry dispatches over the declared overloads to determine which signature + // the runtime arguments satisfy. return append(overloads, &functions.Overload{ - Operator: f.Name(), - Unary: overloads[0].Unary, - Binary: overloads[0].Binary, - Function: overloads[0].Function, - Async: overloads[0].Async, - NonStrict: overloads[0].NonStrict, - OperandTrait: overloads[0].OperandTrait, + Operator: f.Name(), + LateBound: true, + LateBoundDispatch: f.lateBoundDispatcher(), + NonStrict: nonStrict, }), nil } // All of the defined overloads are wrapped into a top-level function which @@ -716,12 +737,20 @@ func (o *OverloadDecl) IsNonStrict() bool { return o.nonStrict } -// HasLateBinding returns whether the overload has a binding which is not known at compile time. +// IsAsync returns whether the overload has an asynchronous binding. +func (o *OverloadDecl) IsAsync() bool { + if o == nil { + return false + } + return o.asyncOp != nil +} + +// HasLateBinding returns whether the overload has a late binding which is resolved at runtime. func (o *OverloadDecl) HasLateBinding() bool { if o == nil { return false } - return o.hasLateBinding || o.asyncOp != nil + return o.hasLateBinding } // OperandTrait returns the trait mask of the first operand to the overload call, e.g. @@ -852,6 +881,67 @@ func (o *OverloadDecl) guardedAsyncOp(funcName string, disableTypeGuards bool) f } } +// binding returns the runtime binding for an overload whose implementation is provided at +// declaration time. +// +// Each implementation is wrapped in an invocation guard which ensures runtime type agreement +// between the overload signature and the argument values. +func (o *OverloadDecl) binding(funcName string, disableTypeGuards bool) *functions.Overload { + return &functions.Overload{ + Operator: o.ID(), + Unary: o.guardedUnaryOp(funcName, disableTypeGuards), + Binary: o.guardedBinaryOp(funcName, disableTypeGuards), + Function: o.guardedFunctionOp(funcName, disableTypeGuards), + Async: o.guardedAsyncOp(funcName, disableTypeGuards), + OperandTrait: o.OperandTrait(), + NonStrict: o.IsNonStrict(), + } +} + +// lateBoundBinding returns the runtime binding for an overload whose implementation is supplied +// by the activation at evaluation time. +// +// There is no implementation to wrap in an invocation guard, so the signature check is instead +// exposed to the interpreter which applies it to the implementation it resolves. +func (o *OverloadDecl) lateBoundBinding(disableTypeGuards bool) *functions.Overload { + return &functions.Overload{ + Operator: o.ID(), + LateBound: true, + LateBoundDispatch: o.lateBoundDispatcher(disableTypeGuards), + OperandTrait: o.OperandTrait(), + NonStrict: o.IsNonStrict(), + } +} + +// lateBoundDispatcher creates the runtime signature check for a late-bound overload. +func (o *OverloadDecl) lateBoundDispatcher(disableTypeGuards bool) functions.LateBoundDispatcher { + return func(memberStyle bool, args ...ref.Val) (string, bool) { + if memberStyle != o.IsMemberFunction() || !o.matchesRuntimeSignature(disableTypeGuards, args...) { + return "", false + } + return o.ID(), true + } +} + +// lateBoundDispatcher creates a runtime dispatcher over the late-bound overloads of the function. +// +// This mirrors the dynamic dispatch performed for functions with multiple eager overloads: the +// first overload whose receiver style and signature agree with the runtime arguments wins. +func (f *FunctionDecl) lateBoundDispatcher() functions.LateBoundDispatcher { + return func(memberStyle bool, args ...ref.Val) (string, bool) { + for _, oID := range f.overloadOrdinals { + o := f.overloads[oID] + if !o.HasLateBinding() || memberStyle != o.IsMemberFunction() { + continue + } + if o.matchesRuntimeSignature(f.disableTypeGuards, args...) { + return o.ID(), true + } + } + return "", false + } +} + // matchesRuntimeUnarySignature indicates whether the argument type is runtime assiganble to the overload's expected argument. func (o *OverloadDecl) matchesRuntimeUnarySignature(disableTypeGuards bool, arg ref.Val) bool { return matchRuntimeArgType(o.IsNonStrict(), disableTypeGuards, o.ArgTypes()[0], arg) && @@ -882,15 +972,10 @@ func (o *OverloadDecl) matchesRuntimeSignature(disableTypeGuards bool, args ...r } func matchRuntimeArgType(nonStrict, disableTypeGuards bool, argType *types.Type, arg ref.Val) bool { - if nonStrict && (disableTypeGuards || types.IsUnknownOrError(arg)) { + if disableTypeGuards || argType.IsAssignableRuntimeType(arg) { return true } - // Note, early returns and unknown aggregation happen in the interpretable.go file; however, this check is here - // for defense in depth or for scenarios where someone manipulates bindings to offer their own dispatch logic. - if types.IsUnknownOrError(arg) { - return false - } - return disableTypeGuards || argType.IsAssignableRuntimeType(arg) + return nonStrict && types.IsUnknownOrError(arg) } func matchOperandTrait(trait int, arg ref.Val) bool { @@ -995,6 +1080,9 @@ func wrapAsyncOp(fn functions.BlockingAsyncOp) functions.AsyncOp { // LateFunctionBinding indicates that the function has a binding which is not known at compile time. // This is useful for functions which have side-effects or are not deterministically computable. +// +// The implementation is supplied at evaluation time as a functions.LateBoundOp within the function +// namespace of the activation, and is subject to the same runtime type-guard as an eager binding. func LateFunctionBinding() OverloadOpt { return func(o *OverloadDecl) (*OverloadDecl, error) { if o.HasBinding() { diff --git a/vendor/github.com/google/cel-go/common/doc.go b/vendor/cel.dev/cel-go/common/doc.go similarity index 100% rename from vendor/github.com/google/cel-go/common/doc.go rename to vendor/cel.dev/cel-go/common/doc.go diff --git a/vendor/github.com/google/cel-go/common/env/BUILD.bazel b/vendor/cel.dev/cel-go/common/env/BUILD.bazel similarity index 94% rename from vendor/github.com/google/cel-go/common/env/BUILD.bazel rename to vendor/cel.dev/cel-go/common/env/BUILD.bazel index 261da924d4..2dc1af513f 100644 --- a/vendor/github.com/google/cel-go/common/env/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/env/BUILD.bazel @@ -22,10 +22,11 @@ package( go_library( name = "go_default_library", srcs = [ + "catalog.go", "env.go", "io.go", ], - importpath = "github.com/google/cel-go/common/env", + importpath = "cel.dev/cel-go/common/env", deps = [ "//common:go_default_library", "//common/decls:go_default_library", @@ -38,6 +39,7 @@ go_test( name = "go_default_test", size = "small", srcs = [ + "catalog_test.go", "env_test.go", "io_test.go", ], diff --git a/vendor/cel.dev/cel-go/common/env/catalog.go b/vendor/cel.dev/cel-go/common/env/catalog.go new file mode 100644 index 0000000000..aed5ac42f8 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/env/catalog.go @@ -0,0 +1,294 @@ +// Copyright 2026 Google LLC +// +// 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 env + +import ( + "math" + "sort" + "strings" +) + +// SymbolKind indicates the kind of declaration provided in an environment. +type SymbolKind string + +const ( + // FunctionKind represents a function declaration. + FunctionKind SymbolKind = "function" + + // MacroKind represents a macro declaration. + MacroKind SymbolKind = "macro" + + // TypeKind represents a type declaration. + TypeKind SymbolKind = "type" + + // NamespaceKind represents a namespace declaration. + NamespaceKind SymbolKind = "namespace" + + // VariableKind represents a variable declaration. + VariableKind SymbolKind = "variable" +) + +// CatalogSymbol represents a symbol in the environment catalog. +type CatalogSymbol struct { + Name string `yaml:"name" json:"name"` + Kind SymbolKind `yaml:"kind" json:"kind"` + Library string `yaml:"library,omitempty" json:"library,omitempty"` + Option string `yaml:"option,omitempty" json:"option,omitempty"` + MinVersion uint32 `yaml:"min_version,omitempty" json:"minVersion,omitempty"` +} + +// Catalog holds an index of symbols from the active environment and available libraries. +type Catalog struct { + symbols []*CatalogSymbol + byName map[string]*CatalogSymbol +} + +// NewCatalog creates a new Catalog initialized with the given symbols. +func NewCatalog(symbols ...*CatalogSymbol) *Catalog { + c := &Catalog{ + symbols: make([]*CatalogSymbol, 0, len(symbols)), + byName: make(map[string]*CatalogSymbol, len(symbols)), + } + for _, sym := range symbols { + c.Add(sym) + } + return c +} + +// Add adds one or more symbols to the catalog. +func (c *Catalog) Add(syms ...*CatalogSymbol) { + for _, sym := range syms { + if sym == nil || sym.Name == "" { + continue + } + c.symbols = append(c.symbols, sym) + c.byName[sym.Name] = sym + } +} + +// Find searches for symbols in the catalog matching the given name. +// +// If an exact match exists, a single-element slice containing that symbol is returned. +// Otherwise, candidate symbols matching the namespace structure (namespaced vs non-namespaced) +// are evaluated using Damerau-Levenshtein edit distance within the following thresholds: +// - length <= 3: max distance 1 +// - 4 <= length <= 8: max distance 2 +// - length > 8: max distance length / 3 +// +// If candidates meet the edit distance threshold, up to two entries with the lowest edit distance +// are returned, ordered from shortest to longest suggestion (and alphabetically on tie). +// +// If no edit distance matches are found, prefix matching is performed as a fallback. When a prefix +// matches multiple symbols, up to two candidates are returned, ordered from shortest to longest. +func (c *Catalog) Find(name string) []*CatalogSymbol { + if c == nil || name == "" { + return nil + } + if sym, ok := c.byName[name]; ok { + return []*CatalogSymbol{sym} + } + if len(c.symbols) == 0 { + return nil + } + + hasDot := strings.Contains(name, ".") + maxDist := 2 + if len(name) <= 3 { + maxDist = 1 + } else if len(name) > 8 { + maxDist = len(name) / 3 + } + + type match struct { + sym *CatalogSymbol + dist int + } + var editMatches []match + minDist := math.MaxInt32 + seen := make(map[string]bool) + + for _, sym := range c.symbols { + if seen[sym.Name] { + continue + } + // If the input might be namespaced, only consider other namespaced symbols. + if strings.Contains(sym.Name, ".") != hasDot { + continue + } + seen[sym.Name] = true + dist := EditDistance(name, sym.Name) + if dist <= maxDist { + editMatches = append(editMatches, match{sym: sym, dist: dist}) + if dist < minDist { + minDist = dist + } + } + } + + if len(editMatches) > 0 { + var best []match + for _, m := range editMatches { + if m.dist == minDist { + best = append(best, m) + } + } + sort.Slice(best, func(i, j int) bool { + if len(best[i].sym.Name) != len(best[j].sym.Name) { + return len(best[i].sym.Name) < len(best[j].sym.Name) + } + return best[i].sym.Name < best[j].sym.Name + }) + resultCount := min(len(best), 2) + res := make([]*CatalogSymbol, resultCount) + for i := range res { + res[i] = best[i].sym + } + return res + } + + // Fallback: prefix match (require at least 2 characters) + if len(name) >= 2 { + seenPrefix := make(map[string]bool) + var prefixMatches []*CatalogSymbol + for _, sym := range c.symbols { + if seenPrefix[sym.Name] { + continue + } + if strings.Contains(sym.Name, ".") != hasDot { + continue + } + if strings.HasPrefix(sym.Name, name) { + seenPrefix[sym.Name] = true + prefixMatches = append(prefixMatches, sym) + } + } + + if len(prefixMatches) > 0 { + sort.Slice(prefixMatches, func(i, j int) bool { + if len(prefixMatches[i].Name) != len(prefixMatches[j].Name) { + return len(prefixMatches[i].Name) < len(prefixMatches[j].Name) + } + return prefixMatches[i].Name < prefixMatches[j].Name + }) + if len(prefixMatches) > 2 { + prefixMatches = prefixMatches[:2] + } + return prefixMatches + } + } + + return nil +} + +const ( + maxEditDistanceIterations = 64 * 64 +) + +// EditDistance calculates the Damerau-Levenshtein distance between two strings, +// taking into account insertions, deletions, substitutions, and adjacent transpositions. +// +// When evaluating string similarity for suggestions, the following distance thresholds are recommended: +// - length <= 3: max distance 1 +// - 4 <= length <= 8: max distance 2 +// - length > 8: max distance length / 3 +func EditDistance(a, b string) int { + ra, rb := []rune(a), []rune(b) + la, lb := len(ra), len(rb) + if la == 0 { + return lb + } + if lb == 0 { + return la + } + if la >= 16 && la*2 >= lb*3 { + return la - lb + } + if lb >= 16 && lb*2 >= la*3 { + return lb - la + } + if la*lb > maxEditDistanceIterations { + return math.MaxInt32 + } + + maxLen := max(la, lb) + threshold := maxLen / 3 + + d := make([][]int, la+1) + for i := range d { + d[i] = make([]int, lb+1) + d[i][0] = i + } + for j := 0; j <= lb; j++ { + d[0][j] = j + } + + for i := 1; i <= la; i++ { + rowMin := d[i][0] + for j := 1; j <= lb; j++ { + cost := 1 + if ra[i-1] == rb[j-1] { + cost = 0 + } + d[i][j] = min( + d[i-1][j]+1, // deletion + d[i][j-1]+1, // insertion + d[i-1][j-1]+cost, // substitution + ) + if i > 1 && j > 1 && ra[i-1] == rb[j-2] && ra[i-2] == rb[j-1] { + d[i][j] = min(d[i][j], d[i-2][j-2]+1) // transposition + } + if d[i][j] < rowMin { + rowMin = d[i][j] + } + } + if rowMin > threshold { + return math.MaxInt32 + } + } + return d[la][lb] +} + +// ToCatalog converts the Config to a Catalog containing its functions, variables, container, and imports. +func (c *Config) ToCatalog() *Catalog { + cat := NewCatalog() + if c == nil { + return cat + } + for _, v := range c.Variables { + cat.Add(&CatalogSymbol{ + Name: v.Name, + Kind: VariableKind, + }) + } + for _, f := range c.Functions { + cat.Add(&CatalogSymbol{ + Name: f.Name, + Kind: FunctionKind, + }) + } + if c.Container != "" { + cat.Add(&CatalogSymbol{ + Name: c.Container, + Kind: NamespaceKind, + }) + } + for _, imp := range c.Imports { + cat.Add(&CatalogSymbol{ + Name: imp.Name, + Kind: NamespaceKind, + }) + } + return cat +} diff --git a/vendor/github.com/google/cel-go/common/env/env.go b/vendor/cel.dev/cel-go/common/env/env.go similarity index 86% rename from vendor/github.com/google/cel-go/common/env/env.go rename to vendor/cel.dev/cel-go/common/env/env.go index 936036ed21..433724ce48 100644 --- a/vendor/github.com/google/cel-go/common/env/env.go +++ b/vendor/cel.dev/cel-go/common/env/env.go @@ -22,11 +22,11 @@ import ( "strconv" "strings" - "github.com/google/cel-go/common/decls" - "github.com/google/cel-go/common/types" + "cel.dev/cel-go/common/decls" + "cel.dev/cel-go/common/types" ) -// NewConfig creates an instance of a YAML serializable CEL environment configuration. +// NewConfig creates an instance of a YAML/JSON serializable CEL environment configuration. func NewConfig(name string) *Config { return &Config{ Name: name, @@ -39,18 +39,18 @@ func NewConfig(name string) *Config { // considered part of the core CEL environment configuration and should be managed separately // until a common convention for such settings is developed. type Config struct { - Name string `yaml:"name,omitempty"` - Description string `yaml:"description,omitempty"` - Container string `yaml:"container,omitempty"` - Imports []*Import `yaml:"imports,omitempty"` - StdLib *LibrarySubset `yaml:"stdlib,omitempty"` - Extensions []*Extension `yaml:"extensions,omitempty"` - ContextVariable *ContextVariable `yaml:"context_variable,omitempty"` - Variables []*Variable `yaml:"variables,omitempty"` - Functions []*Function `yaml:"functions,omitempty"` - Validators []*Validator `yaml:"validators,omitempty"` - Features []*Feature `yaml:"features,omitempty"` - Limits []*Limit `yaml:"limits,omitempty"` + Name string `yaml:"name,omitempty" json:"name,omitempty"` + Description string `yaml:"description,omitempty" json:"description,omitempty"` + Container string `yaml:"container,omitempty" json:"container,omitempty" jsonschema_description:"Protobuf container namespace for type resolution"` + Imports []*Import `yaml:"imports,omitempty" json:"imports,omitempty" jsonschema_description:"Fully qualified type names imported by simple name"` + StdLib *LibrarySubset `yaml:"stdlib,omitempty" json:"stdlib,omitempty" jsonschema_description:"Standard library macro and function subset configuration"` + Extensions []*Extension `yaml:"extensions,omitempty" json:"extensions,omitempty"` + ContextVariable *ContextVariable `yaml:"context_variable,omitempty" json:"contextVariable,omitempty" jsonschema_description:"Protobuf message type whose fields are exposed as top-level variables"` + Variables []*Variable `yaml:"variables,omitempty" json:"variables,omitempty"` + Functions []*Function `yaml:"functions,omitempty" json:"functions,omitempty"` + Validators []*Validator `yaml:"validators,omitempty" json:"validators,omitempty"` + Features []*Feature `yaml:"features,omitempty" json:"features,omitempty"` + Limits []*Limit `yaml:"limits,omitempty" json:"limits,omitempty"` } // Validate validates the whole configuration is well-formed. @@ -226,7 +226,7 @@ func NewImport(name string) *Import { // Import represents a type name that will be appreviated by its simple name using // the cel.Abbrevs() option. type Import struct { - Name string `yaml:"name"` + Name string `yaml:"name" json:"name" jsonschema_description:"Fully qualified protobuf message or enum name"` } // Validate validates the import configuration is well-formed. @@ -253,15 +253,15 @@ func NewVariableWithDoc(name string, t *TypeDesc, doc string) *Variable { // Variable represents a typed variable declaration which will be published via the // cel.VariableDecls() option. type Variable struct { - Name string `yaml:"name"` - Description string `yaml:"description,omitempty"` + Name string `yaml:"name" json:"name"` + Description string `yaml:"description,omitempty" json:"description,omitempty"` // Type represents the type declaration for the variable. // // When serialized, 'type' is used for shorthand specifier string. // // Use GetType() for getting the effective type. - Type *TypeDesc `yaml:"type,omitempty"` + Type *TypeDesc `yaml:"type,omitempty" json:"type,omitempty" jsonschema_description:"Type specifier formatted as TypeName or namespace.TypeName with optional type parameters in angle brackets <>"` // TypeDesc is an embedded set of fields allowing for the specification of the Variable type. *TypeDesc `yaml:",inline"` @@ -323,7 +323,7 @@ func NewContextVariable(typeName string) *ContextVariable { type ContextVariable struct { // TypeName represents the fully qualified typename of the context variable. // Currently, only protobuf types are supported. - TypeName string `yaml:"type_name"` + TypeName string `yaml:"type_name" json:"typeName" jsonschema_description:"Fully qualified protobuf message type name"` } // Validate validates the context-variable configuration is well-formed. @@ -349,9 +349,9 @@ func NewFunctionWithDoc(name, doc string, overloads ...*Overload) *Function { // Function represents the serializable format of a function and its overloads. type Function struct { - Name string `yaml:"name"` - Description string `yaml:"description,omitempty"` - Overloads []*Overload `yaml:"overloads,omitempty"` + Name string `yaml:"name" json:"name" jsonschema_description:"camelCase function name, either standalone or namespace.functionName"` + Description string `yaml:"description,omitempty" json:"description,omitempty"` + Overloads []*Overload `yaml:"overloads,omitempty" json:"overloads,omitempty"` } // Validate validates the function configuration is well-formed. @@ -405,11 +405,11 @@ func NewMemberOverload(id string, target *TypeDesc, args []*TypeDesc, ret *TypeD // Overload represents the serializable format of a function overload. type Overload struct { - ID string `yaml:"id"` - Examples []string `yaml:"examples,omitempty"` - Target *TypeDesc `yaml:"target,omitempty"` - Args []*TypeDesc `yaml:"args,omitempty"` - Return *TypeDesc `yaml:"return,omitempty"` + ID string `yaml:"id" json:"id" jsonschema_description:"Overload ID formatted as function_name_type1_..._typeN or target_type_function_name_type1_..._typeN"` + Examples []string `yaml:"examples,omitempty" json:"examples,omitempty"` + Target *TypeDesc `yaml:"target,omitempty" json:"target,omitempty" jsonschema_description:"Receiver type specifier for member functions"` + Args []*TypeDesc `yaml:"args,omitempty" json:"args,omitempty"` + Return *TypeDesc `yaml:"return,omitempty" json:"return,omitempty"` } // Validate validates the overload configuration is well-formed. @@ -458,14 +458,16 @@ func (od *Overload) AsFunctionOption(tp types.Provider) (decls.FunctionOpt, erro if od.Target != nil { t, err := od.Target.AsCELType(tp) if err != nil { - return nil, errors.Join(append(errs, err)...) + errs = append(errs, err) } args = append([]*types.Type{t}, args...) - return decls.MemberOverload(od.ID, args, result), nil } if len(errs) != 0 { return nil, errors.Join(errs...) } + if od.Target != nil { + return decls.MemberOverload(od.ID, args, result, decls.OverloadExamples(od.Examples...)), nil + } return decls.Overload(od.ID, args, result, decls.OverloadExamples(od.Examples...)), nil } @@ -484,10 +486,10 @@ func NewExtension(name string, version uint32) *Extension { // Extension represents a named and optionally versioned extension library configured in the environment. type Extension struct { // Name is either the LibraryName() or some short-hand simple identifier which is understood by the config-handler. - Name string `yaml:"name"` + Name string `yaml:"name" json:"name"` // Version may either be an unsigned long value or the string 'latest'. If empty, the value is treated as '0'. - Version string `yaml:"version,omitempty"` + Version string `yaml:"version,omitempty" json:"version,omitempty" jsonschema_description:"Extension version number or 'latest'"` } // Validate validates the extension configuration is well-formed. @@ -526,28 +528,28 @@ func NewLibrarySubset() *LibrarySubset { type LibrarySubset struct { // Disabled indicates whether the library has been disabled, typically only used for // default-enabled libraries like stdlib. - Disabled bool `yaml:"disabled,omitempty"` + Disabled bool `yaml:"disabled,omitempty" json:"disabled,omitempty"` // DisableMacros disables macros for the given library. - DisableMacros bool `yaml:"disable_macros,omitempty"` + DisableMacros bool `yaml:"disable_macros,omitempty" json:"disableMacros,omitempty"` // IncludeMacros specifies a set of macro function names to include in the subset. - IncludeMacros []string `yaml:"include_macros,omitempty"` + IncludeMacros []string `yaml:"include_macros,omitempty" json:"includeMacros,omitempty"` // ExcludeMacros specifies a set of macro function names to exclude from the subset. // Note: if IncludeMacros is non-empty, then ExcludeFunctions is ignored. - ExcludeMacros []string `yaml:"exclude_macros,omitempty"` + ExcludeMacros []string `yaml:"exclude_macros,omitempty" json:"excludeMacros,omitempty"` // IncludeFunctions specifies a set of functions to include in the subset. // // Note: the overloads specified in the subset need only specify their ID. // Note: if IncludeFunctions is non-empty, then ExcludeFunctions is ignored. - IncludeFunctions []*Function `yaml:"include_functions,omitempty"` + IncludeFunctions []*Function `yaml:"include_functions,omitempty" json:"includeFunctions,omitempty" jsonschema_description:"Functions and optional overload IDs to include"` // ExcludeFunctions specifies the set of functions to exclude from the subset. // // Note: the overloads specified in the subset need only specify their ID. - ExcludeFunctions []*Function `yaml:"exclude_functions,omitempty"` + ExcludeFunctions []*Function `yaml:"exclude_functions,omitempty" json:"excludeFunctions,omitempty" jsonschema_description:"Functions and optional overload IDs to exclude"` } // Validate validates the library configuration is well-formed. @@ -699,8 +701,8 @@ func NewValidator(name string) *Validator { // Note: the map-keys must directly correspond to the internal representation of the original // validator, and should only use primitive scalar types as values at this time. type Validator struct { - Name string `yaml:"name"` - Config map[string]any `yaml:"config,omitempty"` + Name string `yaml:"name" json:"name"` + Config map[string]any `yaml:"config,omitempty" json:"config,omitempty"` } // Validate validates the configuration of the validator object. @@ -736,8 +738,8 @@ func NewFeature(name string, enabled bool) *Feature { // Feature represents a named boolean feature flag supported by CEL. type Feature struct { - Name string `yaml:"name"` - Enabled bool `yaml:"enabled"` + Name string `yaml:"name" json:"name"` + Enabled bool `yaml:"enabled" json:"enabled"` } // Validate validates whether the feature is well-configured. @@ -754,8 +756,8 @@ func (feat *Feature) Validate() error { // Limit represents a named limit in the CEL environment. This is used to control // the complexity tolerated before failing parsing, type checking, or planning. type Limit struct { - Name string `yaml:"name"` - Value int `yaml:"value"` + Name string `yaml:"name" json:"name"` + Value int `yaml:"value" json:"value"` } // NewLimit creates a new limit. @@ -786,9 +788,9 @@ func NewTypeParam(paramName string) *TypeDesc { // TypeDesc represents the serializable format of a CEL *types.Type value. type TypeDesc struct { - TypeName string `yaml:"type_name"` - Params []*TypeDesc `yaml:"params,omitempty"` - IsTypeParam bool `yaml:"is_type_param,omitempty"` + TypeName string `yaml:"type_name" json:"typeName"` + Params []*TypeDesc `yaml:"params,omitempty" json:"params,omitempty"` + IsTypeParam bool `yaml:"is_type_param,omitempty" json:"isTypeParam,omitempty"` } // String implements the strings.Stringer interface method. @@ -950,9 +952,8 @@ func (td *TypeDesc) AsCELType(tp types.Provider) (*types.Type, error) { if !found { return nil, fmt.Errorf("undefined type name: %q", td.TypeName) } - _, ok := t.(*types.Type) - if ok && len(td.Params) == 0 { - return t.(*types.Type), nil + if celType, ok := t.(*types.Type); ok && len(td.Params) == 0 { + return celType, nil } params := make([]*types.Type, len(td.Params)) for i, p := range td.Params { diff --git a/vendor/cel.dev/cel-go/common/env/io.go b/vendor/cel.dev/cel-go/common/env/io.go new file mode 100644 index 0000000000..621ee305fd --- /dev/null +++ b/vendor/cel.dev/cel-go/common/env/io.go @@ -0,0 +1,528 @@ +// Copyright 2026 Google LLC +// +// 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 env + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "reflect" + "strings" + + "go.yaml.in/yaml/v3" +) + +// YAML and JSON Serialization Methodology: +// +// Several Config sub-types support both structured object representations and shorthand/alias +// forms when decoding (e.g., TypeDesc specifier strings like "map", scalar Overload +// IDs, "type" aliases on ContextVariable, and inline vs nested TypeDesc fields on Variable), while +// normalizing to canonical shorthand representations when encoding. +// +// To keep YAML and JSON handling symmetric while satisfying each library's canonical interfaces: +// +// 1. Unmarshaling: Each customized type implements an internal `unmarshal(func(any) error) error` +// method that decodes into a parallel internal struct (avoiding recursive Unmarshaler loops). +// - `UnmarshalYAML(unmarshal func(any) error) error` passes the active `yaml.v3` decoder +// closure directly to `unmarshal(...)`. Using the `func(any) error` signature (rather than +// `UnmarshalYAML(*yaml.Node)`) preserves the outer `yaml.Decoder`'s `KnownFields` setting +// when `StrictDecoding(true)` is enabled, whereas `(*yaml.Node).Decode` constructs a fresh +// decoder with `KnownFields` disabled. +// - `UnmarshalJSON(data []byte) error` satisfies `encoding/json.Unmarshaler` and adapts +// `json.Unmarshal` to the same `func(any) error` signature via `jsonUnmarshaler(data)`. +// +// 2. Marshaling: Types that require custom output formatting (`Variable` and `TypeDesc`) implement +// an internal `marshal() any` method returning the canonical value to serialize: +// - `MarshalYAML() (any, error)` returns `marshal(), nil` for `yaml.v3` to encode. +// - `MarshalJSON() ([]byte, error)` encodes `marshal()` via `marshalJSONNoEscape` so type +// specifier brackets (`<`, `>`) are not HTML-escaped. +// - `Variable` requires an explicit marshaler because it embeds `*TypeDesc` (`yaml:",inline"`), +// and `yaml.v3` omits inlined structs that implement `Unmarshaler` during `yaml.Marshal` +// (while `encoding/json` would otherwise promote `TypeDesc.MarshalJSON` to `Variable`). +// Delegating `Variable.marshal()` to `&internalVariable{..., Type: v.GetType()}` allows both +// `yaml.v3` and `encoding/json` to invoke `TypeDesc`'s respective marshaler on `Type`. + +type internalContextVariable struct { + Type string `yaml:"type,omitempty" json:"type,omitempty"` + TypeName string `yaml:"type_name,omitempty" json:"typeName,omitempty"` +} + +type internalOverload Overload + +type internalTypeDesc TypeDesc + +// Embedding TypeDesc in variable causes issues with customizing +// unmarshalling / marshalling. Work around with a parallel type. +type internalVariable struct { + Name string `yaml:"name" json:"name"` + Description string `yaml:"description,omitempty" json:"description,omitempty"` + Type *TypeDesc `yaml:"type,omitempty" json:"type,omitempty"` + TypeName string `yaml:"type_name,omitempty" json:"typeName,omitempty"` + Params []*TypeDesc `yaml:"params,omitempty" json:"params,omitempty"` + IsTypeParam bool `yaml:"is_type_param,omitempty" json:"isTypeParam,omitempty"` +} + +type internalValidator Validator + +func jsonUnmarshaler(data []byte) func(any) error { + return func(v any) error { + return json.Unmarshal(data, v) + } +} + +func (ctx *ContextVariable) unmarshal(unmarshal func(any) error) error { + var buf internalContextVariable + if err := unmarshal(&buf); err != nil { + return err + } + if buf.TypeName != "" { + ctx.TypeName = buf.TypeName + } else if buf.Type != "" { + ctx.TypeName = buf.Type + } + return nil +} + +// UnmarshalYAML implements yaml.Unmarshaler. +func (ctx *ContextVariable) UnmarshalYAML(unmarshal func(any) error) error { + return ctx.unmarshal(unmarshal) +} + +// UnmarshalJSON implements json.Unmarshaler. +func (ctx *ContextVariable) UnmarshalJSON(data []byte) error { + return ctx.unmarshal(jsonUnmarshaler(data)) +} + +func (od *Overload) unmarshal(unmarshal func(any) error) error { + var id string + if err := unmarshal(&id); err == nil { + od.ID = id + return nil + } + var buf internalOverload + if err := unmarshal(&buf); err != nil { + return fmt.Errorf("unsupported overload encoding: %w", err) + } + *od = Overload(buf) + return nil +} + +// UnmarshalYAML implements yaml.Unmarshaler. +func (od *Overload) UnmarshalYAML(unmarshal func(any) error) error { + return od.unmarshal(unmarshal) +} + +// UnmarshalJSON implements json.Unmarshaler. +func (od *Overload) UnmarshalJSON(data []byte) error { + return od.unmarshal(jsonUnmarshaler(data)) +} + +func (v *Variable) unmarshal(unmarshal func(any) error) error { + var buf internalVariable + if err := unmarshal(&buf); err != nil { + return err + } + v.Name = buf.Name + v.Description = buf.Description + if buf.TypeName != "" { + v.TypeDesc = &TypeDesc{ + TypeName: buf.TypeName, + Params: buf.Params, + IsTypeParam: buf.IsTypeParam, + } + } else if buf.Type != nil { + v.TypeDesc = buf.Type + } + return nil +} + +// UnmarshalYAML implements yaml.Unmarshaler. +func (v *Variable) UnmarshalYAML(unmarshal func(any) error) error { + return v.unmarshal(unmarshal) +} + +// UnmarshalJSON implements json.Unmarshaler. +func (v *Variable) UnmarshalJSON(data []byte) error { + return v.unmarshal(jsonUnmarshaler(data)) +} + +func (v *Variable) marshal() any { + return &internalVariable{ + Name: v.Name, + Description: v.Description, + Type: v.GetType(), + } +} + +// MarshalYAML implements yaml.Marshaler. +func (v *Variable) MarshalYAML() (any, error) { + return v.marshal(), nil +} + +// MarshalJSON implements json.Marshaler. +func (v *Variable) MarshalJSON() ([]byte, error) { + return marshalJSONNoEscape(v.marshal(), "") +} + +func (td *TypeDesc) unmarshal(unmarshal func(any) error) error { + var str string + if err := unmarshal(&str); err == nil { + o, err := ParseTypeDesc(str) + if err != nil { + return err + } + *td = *o + return nil + } + var buf internalTypeDesc + if err := unmarshal(&buf); err != nil { + return fmt.Errorf("unsupported type description encoding: %w", err) + } + *td = TypeDesc(buf) + return nil +} + +// UnmarshalYAML implements yaml.Unmarshaler. +func (td *TypeDesc) UnmarshalYAML(unmarshal func(any) error) error { + return td.unmarshal(unmarshal) +} + +// UnmarshalJSON implements json.Unmarshaler. +func (td *TypeDesc) UnmarshalJSON(data []byte) error { + return td.unmarshal(jsonUnmarshaler(data)) +} + +func (td *TypeDesc) marshal() any { + if td == nil { + return nil + } + return td.SpecifierFormat() +} + +// MarshalYAML implements yaml.Marshaler. +func (td *TypeDesc) MarshalYAML() (any, error) { + return td.marshal(), nil +} + +// MarshalJSON implements json.Marshaler. +func (td *TypeDesc) MarshalJSON() ([]byte, error) { + return marshalJSONNoEscape(td.marshal(), "") +} + +func (v *Validator) unmarshal(unmarshal func(any) error) error { + var buf internalValidator + if err := unmarshal(&buf); err != nil { + return err + } + for k, val := range buf.Config { + if num, ok := val.(float64); ok && num == float64(int(num)) { + buf.Config[k] = int(num) + } + } + *v = Validator(buf) + return nil +} + +// UnmarshalYAML implements yaml.Unmarshaler. +func (v *Validator) UnmarshalYAML(unmarshal func(any) error) error { + return v.unmarshal(unmarshal) +} + +// UnmarshalJSON implements json.Unmarshaler. +func (v *Validator) UnmarshalJSON(data []byte) error { + return v.unmarshal(jsonUnmarshaler(data)) +} + +type typeDescParser struct { + text string + pos int + length int +} + +// ParseTypeDesc parses a TypeDesc from the type specifier format: "map" +func ParseTypeDesc(text string) (*TypeDesc, error) { + p := &typeDescParser{text: text, length: len(text)} + res, err := p.parseTypeElem() + if err != nil { + return nil, fmt.Errorf("failed to parse type %q: %v", text, err) + } + p.skipWhitespace() + if p.pos < p.length { + return nil, fmt.Errorf("unexpected character %q at position %d in %q", p.text[p.pos], p.pos, text) + } + return res, nil +} + +func (p *typeDescParser) parseConcreteType() (*TypeDesc, error) { + id, err := p.parseNamespaceIdentifier() + if err != nil { + return nil, err + } + if p.pos < p.length && p.text[p.pos] == '<' { + p.pos++ // consume '<' + var params []*TypeDesc + for { + p.skipWhitespace() + param, err := p.parseTypeElem() + if err != nil { + return nil, err + } + params = append(params, param) + p.skipWhitespace() + if p.pos < p.length && p.text[p.pos] == ',' { + p.pos++ // consume ',' + continue + } + if p.pos < p.length && p.text[p.pos] == '>' { + p.pos++ // consume '>' + break + } + return nil, fmt.Errorf("expected ',' or '>' at position %d", p.pos) + } + return NewTypeDesc(id, params...), nil + } + return NewTypeDesc(id), nil +} + +func (p *typeDescParser) parseTypeElem() (*TypeDesc, error) { + p.skipWhitespace() + if p.pos < p.length && p.text[p.pos] == '~' { + p.pos++ // consume '~' + id, err := p.parseTypeParamIdent() + if err != nil { + return nil, err + } + return NewTypeParam(id), nil + } + return p.parseConcreteType() +} + +func (p *typeDescParser) parseNamespaceIdentifier() (string, error) { + p.skipWhitespace() + var id string + for p.pos < p.length && p.text[p.pos] != '<' { + c := p.text[p.pos] + if c == '.' { + id += "." + p.pos++ // consume '.' + } + ident, err := p.parseIdentifier() + if err != nil { + return "", err + } + id += ident + p.skipWhitespace() + if p.pos < p.length && p.text[p.pos] != '.' { + break + } + } + if id == "" { + return "", fmt.Errorf("missing identifier at position %d", p.pos) + } + return id, nil +} + +func (p *typeDescParser) parseIdentifier() (string, error) { + p.skipWhitespace() + if p.pos >= p.length { + return "", fmt.Errorf("unexpected end of input") + } + start := p.pos + c := p.text[p.pos] + if !isAlpha(c) && c != '_' { + return "", fmt.Errorf("identifier is expected, but %q was found at position %d", c, p.pos) + } + p.pos++ + for p.pos < p.length { + c := p.text[p.pos] + if !isAlphaNumeric(c) && c != '_' { + break + } + p.pos++ + } + return p.text[start:p.pos], nil +} + +func (p *typeDescParser) parseTypeParamIdent() (string, error) { + p.skipWhitespace() + if p.pos >= p.length { + return "", fmt.Errorf("unexpected end of input") + } + c := p.text[p.pos] + if !isAlpha(c) { + return "", fmt.Errorf("invalid type parameter identifier %q at position %d, must be a single character from A-Z", c, p.pos) + } + p.pos++ + if p.pos < p.length && isAlpha(p.text[p.pos]) { + return "", fmt.Errorf("invalid type param, must have a single alphabetic character at position %d", p.pos) + } + return string(c), nil +} + +func (p *typeDescParser) skipWhitespace() { + for p.pos < p.length && isWhitespace(p.text[p.pos]) { + p.pos++ + } +} + +func isWhitespace(c byte) bool { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' +} + +func isAlpha(c byte) bool { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') +} + +func isAlphaNumeric(c byte) bool { + return isAlpha(c) || (c >= '0' && c <= '9') +} + +// DecodeOption configures how an environment Config is decoded from YAML or JSON. +type DecodeOption func(*decodeOptions) + +type decodeOptions struct { + strict bool +} + +// StrictDecoding configures whether unknown fields in the YAML or JSON input cause a decoding error. +// By default, unknown fields are ignored. +func StrictDecoding(strict bool) DecodeOption { + return func(opts *decodeOptions) { + opts.strict = strict + } +} + +func validateStrictJSON(v any, t reflect.Type) error { + for t.Kind() == reflect.Pointer { + t = t.Elem() + } + switch val := v.(type) { + case []any: + if t.Kind() == reflect.Slice { + for _, elem := range val { + if err := validateStrictJSON(elem, t.Elem()); err != nil { + return err + } + } + } + case map[string]any: + switch t { + case reflect.TypeFor[ContextVariable](): + t = reflect.TypeFor[internalContextVariable]() + case reflect.TypeFor[Variable](): + t = reflect.TypeFor[internalVariable]() + } + if t.Kind() != reflect.Struct { + return nil + } + for k, child := range val { + ft, ok := jsonFieldType(t, k) + if !ok { + return fmt.Errorf("json: unknown field %q", k) + } + if err := validateStrictJSON(child, ft); err != nil { + return err + } + } + } + return nil +} + +func jsonFieldType(t reflect.Type, name string) (reflect.Type, bool) { + for i := range t.NumField() { + f := t.Field(i) + tag, _, _ := strings.Cut(f.Tag.Get("json"), ",") + if tag == name { + return f.Type, true + } + } + return nil, false +} + +// ConfigFromYAML returns a config from YAML source. +// +// Adds custom parsing logic for normalizing shorthand for specifiying some fields +// in a YAML document (mainly the type-specifier shorthand). +// +// Using yaml.Unmarshal with any implementation should be sufficient for most +// cases. +func ConfigFromYAML(data []byte, opts ...DecodeOption) (*Config, error) { + dOpts := &decodeOptions{} + for _, opt := range opts { + opt(dOpts) + } + c := &Config{} + dec := yaml.NewDecoder(bytes.NewReader(data)) + dec.KnownFields(dOpts.strict) + if err := dec.Decode(c); err != nil && !errors.Is(err, io.EOF) { + return nil, err + } + return c, nil +} + +// ConfigToYAML returns the config serialized to YAML +// +// Provided as a convenience wrapper around a tested YAML Marshaler. +func ConfigToYAML(c *Config) ([]byte, error) { + return yaml.Marshal(c) +} + +// ConfigFromJSON returns a config from JSON source. +// +// Adds custom parsing logic for normalizing shorthand for specifying some fields +// in a JSON document (mainly the type-specifier shorthand). +// +// Using json.Unmarshal with any implementation should be sufficient for most +// cases. +func ConfigFromJSON(data []byte, opts ...DecodeOption) (*Config, error) { + dOpts := &decodeOptions{} + for _, opt := range opts { + opt(dOpts) + } + c := &Config{} + if err := json.Unmarshal(data, c); err != nil { + return nil, err + } + if dOpts.strict { + var raw any + _ = json.Unmarshal(data, &raw) + if err := validateStrictJSON(raw, reflect.TypeFor[Config]()); err != nil { + return nil, err + } + } + return c, nil +} + +// ConfigToJSON returns the config serialized to JSON +// +// Provided as a convenience wrapper around a tested JSON Marshaler. +func ConfigToJSON(c *Config) ([]byte, error) { + return marshalJSONNoEscape(c, " ") +} + +func marshalJSONNoEscape(v any, indent string) ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if indent != "" { + enc.SetIndent("", indent) + } + if err := enc.Encode(v); err != nil { + return nil, err + } + return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil +} diff --git a/vendor/github.com/google/cel-go/common/error.go b/vendor/cel.dev/cel-go/common/error.go similarity index 100% rename from vendor/github.com/google/cel-go/common/error.go rename to vendor/cel.dev/cel-go/common/error.go diff --git a/vendor/github.com/google/cel-go/common/errors.go b/vendor/cel.dev/cel-go/common/errors.go similarity index 100% rename from vendor/github.com/google/cel-go/common/errors.go rename to vendor/cel.dev/cel-go/common/errors.go diff --git a/vendor/github.com/google/cel-go/common/functions/BUILD.bazel b/vendor/cel.dev/cel-go/common/functions/BUILD.bazel similarity index 83% rename from vendor/github.com/google/cel-go/common/functions/BUILD.bazel rename to vendor/cel.dev/cel-go/common/functions/BUILD.bazel index 3cc27d60ce..4511d06f7e 100644 --- a/vendor/github.com/google/cel-go/common/functions/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/functions/BUILD.bazel @@ -10,7 +10,7 @@ go_library( srcs = [ "functions.go", ], - importpath = "github.com/google/cel-go/common/functions", + importpath = "cel.dev/cel-go/common/functions", deps = [ "//common/types/ref:go_default_library", ], diff --git a/vendor/github.com/google/cel-go/common/functions/functions.go b/vendor/cel.dev/cel-go/common/functions/functions.go similarity index 64% rename from vendor/github.com/google/cel-go/common/functions/functions.go rename to vendor/cel.dev/cel-go/common/functions/functions.go index 0c00781d9c..bc48e33ee9 100644 --- a/vendor/github.com/google/cel-go/common/functions/functions.go +++ b/vendor/cel.dev/cel-go/common/functions/functions.go @@ -18,7 +18,7 @@ package functions import ( "context" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // Overload defines a named overload of a function, indicating an operand trait @@ -51,11 +51,28 @@ type Overload struct { // Async defines the overload with an AsyncOp implementation. May be nil. Async AsyncOp + // LateBound specifies whether the Overload has a late-binding that will be resolved + // at runtime from the activation. + LateBound bool + + // LateBoundDispatch validates the runtime arguments of a late-bound call against the + // declared overload signatures and reports the id of the matching overload. May be nil, + // in which case the arguments are not validated against the declaration. + LateBoundDispatch LateBoundDispatcher + // NonStrict specifies whether the Overload will tolerate arguments that // are types.Err or types.Unknown. NonStrict bool } +// LateBoundDispatcher reports the id of the declared overload whose signature matches the +// receiver style and runtime arguments of a call, or false if no declared overload matches. +// +// Late-bound implementations are supplied by the activation rather than the declaration, so this +// is the only opportunity to enforce agreement between a call and the signature it was checked +// against. +type LateBoundDispatcher func(memberStyle bool, args ...ref.Val) (string, bool) + // UnaryOp is a function that takes a single value and produces an output. type UnaryOp func(ref.Val) ref.Val @@ -66,6 +83,19 @@ type BinaryOp func(ref.Val, ref.Val) ref.Val // a value or error as a result. type FunctionOp func(...ref.Val) ref.Val +// LateBoundOp is the implementation of a function whose binding is supplied at evaluation time +// rather than at declaration time. +// +// Late-bound implementations are resolved from the activation by function name, in a namespace +// which is separate from variables, so a function with multiple overloads is served by a single +// implementation. The id of the overload which matched the call is provided so that such an +// implementation may distinguish between them. +// +// The activation is deliberately not an input to the call. Bindings are supplied for a single +// evaluation alongside the variables of that evaluation, so an implementation which depends on +// evaluation context should capture it in a closure when the activation is constructed. +type LateBoundOp func(overloadID string, args ...ref.Val) ref.Val + // AsyncOp is a function that accepts zero or more arguments and produces // a value or error asynchronously via a channel. // diff --git a/vendor/github.com/google/cel-go/common/location.go b/vendor/cel.dev/cel-go/common/location.go similarity index 100% rename from vendor/github.com/google/cel-go/common/location.go rename to vendor/cel.dev/cel-go/common/location.go diff --git a/vendor/github.com/google/cel-go/common/operators/BUILD.bazel b/vendor/cel.dev/cel-go/common/operators/BUILD.bazel similarity index 80% rename from vendor/github.com/google/cel-go/common/operators/BUILD.bazel rename to vendor/cel.dev/cel-go/common/operators/BUILD.bazel index b5b67f0623..21776cecc3 100644 --- a/vendor/github.com/google/cel-go/common/operators/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/operators/BUILD.bazel @@ -10,5 +10,5 @@ go_library( srcs = [ "operators.go", ], - importpath = "github.com/google/cel-go/common/operators", + importpath = "cel.dev/cel-go/common/operators", ) diff --git a/vendor/github.com/google/cel-go/common/operators/operators.go b/vendor/cel.dev/cel-go/common/operators/operators.go similarity index 100% rename from vendor/github.com/google/cel-go/common/operators/operators.go rename to vendor/cel.dev/cel-go/common/operators/operators.go diff --git a/vendor/github.com/google/cel-go/common/overloads/BUILD.bazel b/vendor/cel.dev/cel-go/common/overloads/BUILD.bazel similarity index 80% rename from vendor/github.com/google/cel-go/common/overloads/BUILD.bazel rename to vendor/cel.dev/cel-go/common/overloads/BUILD.bazel index e46e2f4830..1f1eaa094a 100644 --- a/vendor/github.com/google/cel-go/common/overloads/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/overloads/BUILD.bazel @@ -10,5 +10,5 @@ go_library( srcs = [ "overloads.go", ], - importpath = "github.com/google/cel-go/common/overloads", + importpath = "cel.dev/cel-go/common/overloads", ) diff --git a/vendor/github.com/google/cel-go/common/overloads/overloads.go b/vendor/cel.dev/cel-go/common/overloads/overloads.go similarity index 91% rename from vendor/github.com/google/cel-go/common/overloads/overloads.go rename to vendor/cel.dev/cel-go/common/overloads/overloads.go index 0e3a724495..78c9c8ea01 100644 --- a/vendor/github.com/google/cel-go/common/overloads/overloads.go +++ b/vendor/cel.dev/cel-go/common/overloads/overloads.go @@ -166,6 +166,31 @@ const ( ExtFormatString = "string_format" ) +// Optional function overloads which short-circuit, and so need to be referenced in cost +// computations. +const ( + OptionalOrOptional = "optional_or_optional" + OptionalOrValueValue = "optional_orValue_value" +) + +// Optional function overloads which create, wrap or unwrap a value, and so need to be referenced in +// cost computations to carry the wrapped value's size through the optional. +const ( + OptionalNone = "optional_none" + OptionalOf = "optional_of" + OptionalOfNonZeroValue = "optional_ofNonZeroValue" + OptionalValue = "optional_value" +) + +// Optional index overloads, which qualify their operand in the same way as the non-optional index +// operations and so extend a field path during cost estimation. +const ( + OptIndexList = "list_optindex_optional_int" + OptIndexOptionalList = "optional_list_optindex_optional_int" + OptIndexMap = "map_optindex_optional_value" + OptIndexOptionalMap = "optional_map_optindex_optional_value" +) + // Time-based functions. const ( TimeGetFullYear = "getFullYear" diff --git a/vendor/github.com/google/cel-go/common/runes/BUILD.bazel b/vendor/cel.dev/cel-go/common/runes/BUILD.bazel similarity index 87% rename from vendor/github.com/google/cel-go/common/runes/BUILD.bazel rename to vendor/cel.dev/cel-go/common/runes/BUILD.bazel index bb30242cfa..0674eaed1b 100644 --- a/vendor/github.com/google/cel-go/common/runes/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/runes/BUILD.bazel @@ -10,7 +10,7 @@ go_library( srcs = [ "buffer.go", ], - importpath = "github.com/google/cel-go/common/runes", + importpath = "cel.dev/cel-go/common/runes", ) go_test( diff --git a/vendor/github.com/google/cel-go/common/runes/buffer.go b/vendor/cel.dev/cel-go/common/runes/buffer.go similarity index 100% rename from vendor/github.com/google/cel-go/common/runes/buffer.go rename to vendor/cel.dev/cel-go/common/runes/buffer.go diff --git a/vendor/github.com/google/cel-go/common/source.go b/vendor/cel.dev/cel-go/common/source.go similarity index 99% rename from vendor/github.com/google/cel-go/common/source.go rename to vendor/cel.dev/cel-go/common/source.go index 9187e9b5c3..73237edf98 100644 --- a/vendor/github.com/google/cel-go/common/source.go +++ b/vendor/cel.dev/cel-go/common/source.go @@ -15,7 +15,7 @@ package common import ( - "github.com/google/cel-go/common/runes" + "cel.dev/cel-go/common/runes" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" ) diff --git a/vendor/github.com/google/cel-go/common/stdlib/BUILD.bazel b/vendor/cel.dev/cel-go/common/stdlib/BUILD.bazel similarity index 91% rename from vendor/github.com/google/cel-go/common/stdlib/BUILD.bazel rename to vendor/cel.dev/cel-go/common/stdlib/BUILD.bazel index 124dbea819..dd34ac1e50 100644 --- a/vendor/github.com/google/cel-go/common/stdlib/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/stdlib/BUILD.bazel @@ -10,7 +10,7 @@ go_library( srcs = [ "standard.go", ], - importpath = "github.com/google/cel-go/common/stdlib", + importpath = "cel.dev/cel-go/common/stdlib", deps = [ "//common:go_default_library", "//common/decls:go_default_library", diff --git a/vendor/github.com/google/cel-go/common/stdlib/standard.go b/vendor/cel.dev/cel-go/common/stdlib/standard.go similarity index 98% rename from vendor/github.com/google/cel-go/common/stdlib/standard.go rename to vendor/cel.dev/cel-go/common/stdlib/standard.go index 3a151462ed..8542937695 100644 --- a/vendor/github.com/google/cel-go/common/stdlib/standard.go +++ b/vendor/cel.dev/cel-go/common/stdlib/standard.go @@ -20,25 +20,27 @@ import ( "math" "strconv" "strings" + "sync" "time" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/decls" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/decls" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" ) var ( - stdFunctions []*decls.FunctionDecl - stdTypes []*decls.VariableDecl - utcTZ = types.String("UTC") + initStandardOnce sync.Once + stdFunctions []*decls.FunctionDecl + stdTypes []*decls.VariableDecl + utcTZ = types.String("UTC") ) -func init() { +func initStandard() { paramA := types.NewTypeParamType("A") paramB := types.NewTypeParamType("B") listOfA := types.NewListType(paramA) @@ -116,11 +118,13 @@ func init() { // Comprehension short-circuiting related function function(operators.NotStrictlyFalse, + decls.DisableTypeGuards(true), decls.Overload(overloads.NotStrictlyFalse, argTypes(types.BoolType), types.BoolType, decls.OverloadIsNonStrict(), decls.UnaryBinding(notStrictlyFalse))), // Deprecated: __not_strictly_false__ function(operators.OldNotStrictlyFalse, + decls.DisableTypeGuards(true), decls.DisableDeclaration(true), // safe deprecation decls.Overload(operators.OldNotStrictlyFalse, argTypes(types.BoolType), types.BoolType, decls.OverloadIsNonStrict(), @@ -902,11 +906,13 @@ func init() { // Functions returns the set of standard library function declarations and definitions for CEL. func Functions() []*decls.FunctionDecl { + initStandardOnce.Do(initStandard) return stdFunctions } // Types returns the set of standard library types for CEL. func Types() []*decls.VariableDecl { + initStandardOnce.Do(initStandard) return stdTypes } diff --git a/vendor/github.com/google/cel-go/common/types/BUILD.bazel b/vendor/cel.dev/cel-go/common/types/BUILD.bazel similarity index 94% rename from vendor/github.com/google/cel-go/common/types/BUILD.bazel rename to vendor/cel.dev/cel-go/common/types/BUILD.bazel index 4ecc40031d..da3231ba46 100644 --- a/vendor/github.com/google/cel-go/common/types/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/types/BUILD.bazel @@ -8,6 +8,7 @@ package( go_library( name = "go_default_library", srcs = [ + "aggregate_sizer.go", "any_value.go", "bool.go", "bytes.go", @@ -21,6 +22,7 @@ go_library( "format.go", "list.go", "map.go", + "memory_tracker.go", "native.go", "null.go", "object.go", @@ -28,6 +30,7 @@ go_library( "overflow.go", "provider.go", "regex.go", + "size_calc.go", "string.go", "struct.go", "timestamp.go", @@ -36,7 +39,7 @@ go_library( "unknown.go", "util.go", ], - importpath = "github.com/google/cel-go/common/types", + importpath = "cel.dev/cel-go/common/types", deps = [ "//checker/decls:go_default_library", "//common/overloads:go_default_library", @@ -70,12 +73,14 @@ go_test( "json_struct_test.go", "list_test.go", "map_test.go", + "memory_tracker_test.go", "native_test.go", "null_test.go", "object_test.go", "optional_test.go", "provider_test.go", "regex_test.go", + "size_calc_test.go", "string_test.go", "timestamp_test.go", "types_test.go", diff --git a/vendor/cel.dev/cel-go/common/types/aggregate_sizer.go b/vendor/cel.dev/cel-go/common/types/aggregate_sizer.go new file mode 100644 index 0000000000..d56b8bc4db --- /dev/null +++ b/vendor/cel.dev/cel-go/common/types/aggregate_sizer.go @@ -0,0 +1,43 @@ +// Copyright 2026 Google LLC +// +// 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 types + +// AggregateSizer calculates the recursive element size of values. +type AggregateSizer interface { + // AggregateSize returns the size of the input value, if known. + // Otherwise, a unit size of 1 is returned. + AggregateSize(val any) uint32 +} + +// AggregateSizeVisitor interface for ref.Val implementations capable of returning +// their total recursive element count. +type AggregateSizeVisitor interface { + // AggregateSize returns the total count of nested atomic elements (capped at math.MaxUint32). + AggregateSize(sizer AggregateSizer) uint32 +} + +// Helper for computing aggregate sizes of traits.Foldable types. +type foldableAggregateSizer struct { + sizer AggregateSizer + total uint32 +} + +// FoldEntry implements the traits.FoldEntry interface method and counts the aggregate size +// keys and values. +func (f *foldableAggregateSizer) FoldEntry(k, v any) bool { + f.total = safeAddUint32(f.total, f.sizer.AggregateSize(k)) + f.total = safeAddUint32(f.total, f.sizer.AggregateSize(v)) + return true +} diff --git a/vendor/github.com/google/cel-go/common/types/any_value.go b/vendor/cel.dev/cel-go/common/types/any_value.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/any_value.go rename to vendor/cel.dev/cel-go/common/types/any_value.go diff --git a/vendor/github.com/google/cel-go/common/types/bool.go b/vendor/cel.dev/cel-go/common/types/bool.go similarity index 98% rename from vendor/github.com/google/cel-go/common/types/bool.go rename to vendor/cel.dev/cel-go/common/types/bool.go index 5f1e4573e1..d16964cdb1 100644 --- a/vendor/github.com/google/cel-go/common/types/bool.go +++ b/vendor/cel.dev/cel-go/common/types/bool.go @@ -20,7 +20,7 @@ import ( "strconv" "strings" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" diff --git a/vendor/github.com/google/cel-go/common/types/bytes.go b/vendor/cel.dev/cel-go/common/types/bytes.go similarity index 99% rename from vendor/github.com/google/cel-go/common/types/bytes.go rename to vendor/cel.dev/cel-go/common/types/bytes.go index 2eefb5d7f7..206dd3bc5f 100644 --- a/vendor/github.com/google/cel-go/common/types/bytes.go +++ b/vendor/cel.dev/cel-go/common/types/bytes.go @@ -22,7 +22,7 @@ import ( "strings" "unicode/utf8" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" diff --git a/vendor/github.com/google/cel-go/common/types/compare.go b/vendor/cel.dev/cel-go/common/types/compare.go similarity index 97% rename from vendor/github.com/google/cel-go/common/types/compare.go rename to vendor/cel.dev/cel-go/common/types/compare.go index e196826180..caad97b941 100644 --- a/vendor/github.com/google/cel-go/common/types/compare.go +++ b/vendor/cel.dev/cel-go/common/types/compare.go @@ -17,7 +17,7 @@ package types import ( "math" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) func compareDoubleInt(d Double, i Int) Int { diff --git a/vendor/github.com/google/cel-go/common/types/doc.go b/vendor/cel.dev/cel-go/common/types/doc.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/doc.go rename to vendor/cel.dev/cel-go/common/types/doc.go diff --git a/vendor/github.com/google/cel-go/common/types/double.go b/vendor/cel.dev/cel-go/common/types/double.go similarity index 99% rename from vendor/github.com/google/cel-go/common/types/double.go rename to vendor/cel.dev/cel-go/common/types/double.go index 02abfee2dc..729fc1ec41 100644 --- a/vendor/github.com/google/cel-go/common/types/double.go +++ b/vendor/cel.dev/cel-go/common/types/double.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" diff --git a/vendor/github.com/google/cel-go/common/types/duration.go b/vendor/cel.dev/cel-go/common/types/duration.go similarity index 98% rename from vendor/github.com/google/cel-go/common/types/duration.go rename to vendor/cel.dev/cel-go/common/types/duration.go index 2207147734..cd3efa1cec 100644 --- a/vendor/github.com/google/cel-go/common/types/duration.go +++ b/vendor/cel.dev/cel-go/common/types/duration.go @@ -21,8 +21,8 @@ import ( "strings" "time" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" dpb "google.golang.org/protobuf/types/known/durationpb" diff --git a/vendor/github.com/google/cel-go/common/types/err.go b/vendor/cel.dev/cel-go/common/types/err.go similarity index 98% rename from vendor/github.com/google/cel-go/common/types/err.go rename to vendor/cel.dev/cel-go/common/types/err.go index 3216ff1c4a..354906a9fd 100644 --- a/vendor/github.com/google/cel-go/common/types/err.go +++ b/vendor/cel.dev/cel-go/common/types/err.go @@ -19,7 +19,7 @@ import ( "fmt" "reflect" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // Error interface which allows types types.Err values to be treated as error values. @@ -36,7 +36,7 @@ type Err struct { var ( // ErrType singleton. - ErrType = NewOpaqueType("error") + ErrType = ErrorType // errDivideByZero is an error indicating a division by zero of an integer value. errDivideByZero = errors.New("division by zero") diff --git a/vendor/github.com/google/cel-go/common/types/format.go b/vendor/cel.dev/cel-go/common/types/format.go similarity index 91% rename from vendor/github.com/google/cel-go/common/types/format.go rename to vendor/cel.dev/cel-go/common/types/format.go index 174a2bd040..3b2c06f0a9 100644 --- a/vendor/github.com/google/cel-go/common/types/format.go +++ b/vendor/cel.dev/cel-go/common/types/format.go @@ -4,8 +4,8 @@ import ( "fmt" "strings" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" ) type formattable interface { diff --git a/vendor/github.com/google/cel-go/common/types/int.go b/vendor/cel.dev/cel-go/common/types/int.go similarity index 99% rename from vendor/github.com/google/cel-go/common/types/int.go rename to vendor/cel.dev/cel-go/common/types/int.go index 60d5a71606..82dbb1738e 100644 --- a/vendor/github.com/google/cel-go/common/types/int.go +++ b/vendor/cel.dev/cel-go/common/types/int.go @@ -22,7 +22,7 @@ import ( "strings" "time" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" diff --git a/vendor/github.com/google/cel-go/common/types/iterator.go b/vendor/cel.dev/cel-go/common/types/iterator.go similarity index 94% rename from vendor/github.com/google/cel-go/common/types/iterator.go rename to vendor/cel.dev/cel-go/common/types/iterator.go index 98e9147b6e..77fc90f428 100644 --- a/vendor/github.com/google/cel-go/common/types/iterator.go +++ b/vendor/cel.dev/cel-go/common/types/iterator.go @@ -18,8 +18,8 @@ import ( "fmt" "reflect" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" ) var ( diff --git a/vendor/github.com/google/cel-go/common/types/json_value.go b/vendor/cel.dev/cel-go/common/types/json_value.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/json_value.go rename to vendor/cel.dev/cel-go/common/types/json_value.go diff --git a/vendor/cel.dev/cel-go/common/types/list.go b/vendor/cel.dev/cel-go/common/types/list.go new file mode 100644 index 0000000000..64ed61dbfd --- /dev/null +++ b/vendor/cel.dev/cel-go/common/types/list.go @@ -0,0 +1,1401 @@ +// Copyright 2018 Google LLC +// +// 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 types + +import ( + "bytes" + "fmt" + "reflect" + "strings" + "sync" + "sync/atomic" + "unsafe" + + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" + + anypb "google.golang.org/protobuf/types/known/anypb" + structpb "google.golang.org/protobuf/types/known/structpb" +) + +// NewDynamicList returns a traits.Lister with heterogenous elements. +// value should be an array of "native" types, i.e. any type that +// NativeToValue() can convert to a ref.Val. +func NewDynamicList(adapter Adapter, value any) traits.Lister { + if value == nil { + return NewList[any](adapter, nil) + } + switch v := value.(type) { + case []string: + return NewList(adapter, v) + case []ref.Val: + return NewList(adapter, v) + case []int: + return NewList(adapter, v) + case []int64: + return NewList(adapter, v) + case []int32: + return NewList(adapter, v) + case []uint: + return NewList(adapter, v) + case []uint64: + return NewList(adapter, v) + case []uint32: + return NewList(adapter, v) + case []float64: + return NewList(adapter, v) + case []float32: + return NewList(adapter, v) + case []bool: + return NewList(adapter, v) + case []any: + return NewList(adapter, v) + case [][]byte: + return NewList(adapter, v) + } + rt := reflect.TypeOf(value) + if meta := getDynamicSliceMeta(rt); meta.supported { + sh := (*unsafeSlice)(anyDataPtr(value)) + isNil := sh == nil || sh.Data == nil + qualifyRaw := canQualifyRawVal(adapter, meta.sliceType.Elem(), meta.qualifyRawVal) + if meta.isPtrElem { + var elems []unsafe.Pointer + if sh != nil && sh.Len > 0 { + elems = unsafe.Slice((*unsafe.Pointer)(sh.Data), sh.Len) + } + return &sliceList[unsafe.Pointer]{ + Adapter: adapter, + elems: elems, + elemTypePtr: meta.elemTypePtr, + meta: meta, + qualifyRawVal: qualifyRaw, + isNilSlice: isNil, + } + } + var elems []byte + if sh != nil && sh.Len > 0 { + elems = unsafe.Slice((*byte)(sh.Data), sh.Len*int(meta.elemStride)) + } + return &sliceList[byte]{ + Adapter: adapter, + elems: elems, + elemTypePtr: meta.elemTypePtr, + meta: meta, + qualifyRawVal: qualifyRaw, + isNilSlice: isNil, + } + } + refValue := reflect.ValueOf(value) + return &baseList{ + Adapter: adapter, + value: value, + size: refValue.Len(), + get: func(i int) any { + return refValue.Index(i).Interface() + }, + } +} + +// NewList returns a traits.Lister backed by a typed Go slice []T. +func NewList[T any](adapter Adapter, elems []T) traits.Lister { + return &sliceList[T]{ + Adapter: adapter, + elems: elems, + elemTypePtr: elemTypePtrFor[T](), + qualifyRawVal: isQualifyRawStructFor[T](adapter), + } +} + +// NewStringList returns a traits.Lister containing only strings. +func NewStringList(adapter Adapter, elems []string) traits.Lister { + return NewList(adapter, elems) +} + +// NewRefValList returns a traits.Lister with ref.Val elements. +// +// This type specialization is used with list literals within CEL expressions. +func NewRefValList(adapter Adapter, elems []ref.Val) traits.Lister { + return &sliceList[ref.Val]{ + Adapter: adapter, + elems: elems, + } +} + +// NewProtoList returns a traits.Lister based on a pb.List instance. +func NewProtoList(adapter Adapter, list protoreflect.List) traits.Lister { + return &baseList{ + Adapter: adapter, + value: list, + size: list.Len(), + get: func(i int) any { return list.Get(i).Interface() }, + } +} + +// NewJSONList returns a traits.Lister based on structpb.ListValue instance. +func NewJSONList(adapter Adapter, l *structpb.ListValue) traits.Lister { + vals := l.GetValues() + return &baseList{ + Adapter: adapter, + value: l, + size: len(vals), + get: func(i int) any { return vals[i] }, + } +} + +// NewMutableList creates a new mutable list whose internal state can be modified. +func NewMutableList(adapter Adapter) traits.MutableLister { + return &mutableList{ + sliceList: &sliceList[ref.Val]{ + Adapter: adapter, + }, + } +} + +// MaybeSliceList attempts to sub-slice a traits.Lister using its underlying native slice representation +// via reflection, preserving the original element type. If the underlying representation is not a slice +// or the indices are invalid, it returns (nil, false). +func MaybeSliceList(adapter Adapter, list traits.Lister, start, end int) (traits.Lister, bool) { + if list == nil { + return nil, false + } + if _, isConcat := list.(*concatList); isConcat { + return nil, false + } + val := list.Value() + if val == nil { + return nil, false + } + rv := reflect.ValueOf(val) + if rv.Kind() != reflect.Slice { + return nil, false + } + if start < 0 || end < 0 || start > end || end > rv.Len() { + return nil, false + } + adapter = maybeCustomAdapter(adapter, list) + sub := rv.Slice(start, end).Interface() + return NewDynamicList(adapter, sub), true +} + +// MaybeReverseList attempts to reverse a traits.Lister using its underlying native slice representation, +// preserving the original element type. If the underlying representation is not a slice, it returns (nil, false). +func MaybeReverseList(adapter Adapter, list traits.Lister) (traits.Lister, bool) { + if list == nil { + return nil, false + } + if _, isConcat := list.(*concatList); isConcat { + return nil, false + } + val := list.Value() + if val == nil { + return nil, false + } + rv := reflect.ValueOf(val) + if rv.Kind() != reflect.Slice { + return nil, false + } + n := rv.Len() + if n <= 1 { + return list, true + } + adapter = maybeCustomAdapter(adapter, list) + out := reflect.MakeSlice(rv.Type(), n, n) + for i := range n { + out.Index(n - 1 - i).Set(rv.Index(i)) + } + return NewDynamicList(adapter, out.Interface()), true +} + +type listAdapter interface { + listAdapter() Adapter +} + +func maybeCustomAdapter(adapter Adapter, list traits.Lister) Adapter { + if la, ok := list.(listAdapter); ok { + if listAdapt := la.listAdapter(); listAdapt != nil && !isStandardAdapter(listAdapt) { + return listAdapt + } + } + return adapter +} + +// baseList points to a list containing elements of any type. +// The `value` is an array of native values, and refValue is its reflection object. +// The `Adapter` enables native type to CEL type conversions. +type baseList struct { + Adapter + value any + size int + // aggSize memoizes the aggregate size computed by the first completed sizing of this + // list. Accessed atomically since immutable lists may be shared across concurrent + // evaluations; zero means not yet computed. See the SizeCalculator documentation for + // the memoization contract. + aggSize uint32 + get func(int) any +} + +func (l *baseList) listAdapter() Adapter { + return l.Adapter +} + +// Add implements the traits.Adder interface method. +func (l *baseList) Add(other ref.Val) ref.Val { + otherList, ok := other.(traits.Lister) + if !ok { + return MaybeNoSuchOverloadErr(other) + } + return newConcatList(l.Adapter, l, otherList) +} + +// Contains implements the traits.Container interface method. +func (l *baseList) Contains(elem ref.Val) ref.Val { + for i := 0; i < l.size; i++ { + val := l.NativeToValue(l.get(i)) + cmp := elem.Equal(val) + b, ok := cmp.(Bool) + if ok && b == True { + return True + } + } + return False +} + +// ConvertToNative implements the ref.Val interface method. +func (l *baseList) ConvertToNative(typeDesc reflect.Type) (any, error) { + return convertListToNative(l, l.value, typeDesc) +} + +func convertListToNative(l traits.Lister, val any, typeDesc reflect.Type) (any, error) { + if typeDesc == reflect.TypeFor[any]() { + typeDesc = reflect.TypeFor[[]any]() + } + // If the underlying list value is assignable to the reflected type return it. + if val != nil && reflect.TypeOf(val).AssignableTo(typeDesc) { + return val, nil + } + // If the list wrapper is assignable to the desired type return it. + if reflect.TypeOf(l).AssignableTo(typeDesc) { + return l, nil + } + // Attempt to convert the list to a set of well known protobuf types. + switch typeDesc { + case anyValueType: + json, err := l.ConvertToNative(JSONListType) + if err != nil { + return nil, err + } + return anypb.New(json.(proto.Message)) + case JSONValueType, JSONListType: + jsonValues, err := + l.ConvertToNative(reflect.TypeFor[[]*structpb.Value]()) + if err != nil { + return nil, err + } + jsonList := &structpb.ListValue{Values: jsonValues.([]*structpb.Value)} + if typeDesc == JSONListType { + return jsonList, nil + } + return structpb.NewListValue(jsonList), nil + } + // Non-list conversion. + if typeDesc.Kind() != reflect.Slice && typeDesc.Kind() != reflect.Array { + return nil, fmt.Errorf("type conversion error from list to '%v'", typeDesc) + } + + // List conversion. + // Allow the element ConvertToNative() function to determine whether conversion is possible. + otherElemType := typeDesc.Elem() + elemCount := int(l.Size().(Int)) + var nativeList reflect.Value + if typeDesc.Kind() == reflect.Array { + nativeList = reflect.New(reflect.ArrayOf(elemCount, typeDesc)).Elem().Index(0) + } else { + nativeList = reflect.MakeSlice(typeDesc, elemCount, elemCount) + } + for i := range elemCount { + elem := l.Get(Int(i)) + nativeElemVal, err := elem.ConvertToNative(otherElemType) + if err != nil { + return nil, err + } + nativeList.Index(i).Set(reflect.ValueOf(nativeElemVal)) + } + return nativeList.Interface(), nil +} + +// ConvertToType implements the ref.Val interface method. +func (l *baseList) ConvertToType(typeVal ref.Type) ref.Val { + switch typeVal { + case ListType: + return l + case TypeType: + return ListType + } + return NewErr("type conversion error from '%s' to '%s'", ListType, typeVal) +} + +// Equal implements the ref.Val interface method. +func (l *baseList) Equal(other ref.Val) ref.Val { + otherList, ok := other.(traits.Lister) + if !ok { + return False + } + if l.Size() != otherList.Size() { + return False + } + for i := IntZero; i < l.Size().(Int); i++ { + thisElem := l.Get(i) + otherElem := otherList.Get(i) + elemEq := Equal(thisElem, otherElem) + if elemEq == False { + return False + } + } + return True +} + +// Get implements the traits.Indexer interface method. +func (l *baseList) Get(index ref.Val) ref.Val { + ind, err := GetOrError(index) + if err != nil { + return ValOrErr(index, "%v", err) + } + if ind < 0 || ind >= l.size { + return NewErr("index '%d' out of range in list size '%d'", ind, l.Size()) + } + return l.NativeToValue(l.get(ind)) +} + +// IsZeroValue returns true if the list is empty. +func (l *baseList) IsZeroValue() bool { + return l.size == 0 +} + +// Fold calls the FoldEntry method for each (index, value) pair in the list. +func (l *baseList) Fold(f traits.Folder) { + get := l.get + if !isStandardAdapter(l.Adapter) { + get = func(i int) any { + return l.Adapter.NativeToValue(l.get(i)) + } + } + for i := 0; i < l.size; i++ { + if !f.FoldEntry(i, get(i)) { + break + } + } +} + +// Iterator implements the traits.Iterable interface method. +func (l *baseList) Iterator() traits.Iterator { + return newListIterator(l) +} + +// Size implements the traits.Sizer interface method. +func (l *baseList) Size() ref.Val { + return Int(l.size) +} + +// AggregateSize implements the AggregateSizeVisitor interface method. +func (l *baseList) AggregateSize(sizer AggregateSizer) uint32 { + if sz := atomic.LoadUint32(&l.aggSize); sz != 0 { + return sz + } + var total uint32 + if l.value != nil { + if t, ok := getSliceElementsAggregateSize(sizer, l.value); ok { + total = t + } + } + if total == 0 { + total = uint32(1) + for i := range l.size { + total = safeAddUint32(total, sizer.AggregateSize(l.get(i))) + } + } + if cacheableAggregateSize(sizer) { + atomic.StoreUint32(&l.aggSize, total) + } + return total +} + +// Type implements the ref.Val interface method. +func (l *baseList) Type() ref.Type { + return ListType +} + +// Value implements the ref.Val interface method. +func (l *baseList) Value() any { + return l.value +} + +// String converts the list to a human readable string form. +func (l *baseList) String() string { + var sb strings.Builder + sb.WriteString("[") + for i := 0; i < l.size; i++ { + sb.WriteString(fmt.Sprintf("%v", l.get(i))) + if i != l.size-1 { + sb.WriteString(", ") + } + } + sb.WriteString("]") + return sb.String() +} + +func formatList(l traits.Lister, sb *strings.Builder) { + sb.WriteString("[") + n, _ := l.Size().(Int) + for i := 0; i < int(n); i++ { + formatTo(sb, l.Get(Int(i))) + if i != int(n)-1 { + sb.WriteString(", ") + } + } + sb.WriteString("]") +} + +func (l *baseList) format(sb *strings.Builder) { + formatList(l, sb) +} + +// mutableList aggregates values into its internal storage. For use with internal CEL variables only. +type mutableList struct { + *sliceList[ref.Val] +} + +// Add copies elements from the other list into the internal storage of the mutable list. +// The ref.Val returned by Add is the receiver. +func (l *mutableList) Add(other ref.Val) ref.Val { + switch otherList := other.(type) { + case *mutableList: + l.elems = append(l.elems, otherList.elems...) + atomic.StoreUint32(&l.aggSize, 0) + case traits.Lister: + for i := IntZero; i < otherList.Size().(Int); i++ { + l.elems = append(l.elems, otherList.Get(i)) + } + atomic.StoreUint32(&l.aggSize, 0) + default: + return MaybeNoSuchOverloadErr(otherList) + } + return l +} + +// ToImmutableList returns an immutable list based on the internal storage of the mutable list. +// It transfers ownership of the underlying buffer to the returned immutable list and clears +// internal elements to prevent subsequent modifications from aliasing. +func (l *mutableList) ToImmutableList() traits.Lister { + elems := l.elems + l.elems = nil + atomic.StoreUint32(&l.aggSize, 0) + return NewRefValList(l.Adapter, elems) +} + +// concatList combines two list implementations together into a view. +// The `Adapter` enables native type to CEL type conversions. +type concatList struct { + Adapter + value any + valueOnce sync.Once + prevList traits.Lister + nextList traits.Lister + cachedSize ref.Val + aggSize uint32 +} + +func newConcatList(adapter Adapter, prevList, nextList traits.Lister) ref.Val { + prevSize := prevList.Size().(Int) + nextSize := nextList.Size().(Int) + if prevSize == IntZero { + return nextList.(ref.Val) + } + if nextSize == IntZero { + return prevList.(ref.Val) + } + return &concatList{ + Adapter: adapter, + prevList: prevList, + nextList: nextList, + cachedSize: prevSize.Add(nextSize), + } +} + +// Add implements the traits.Adder interface method. +func (l *concatList) Add(other ref.Val) ref.Val { + otherList, ok := other.(traits.Lister) + if !ok { + return MaybeNoSuchOverloadErr(other) + } + return newConcatList(l.Adapter, l, otherList) +} + +// Contains implements the traits.Container interface method. +func (l *concatList) Contains(elem ref.Val) ref.Val { + // The concat list relies on the IsErrorOrUnknown checks against the input element to be + // performed by the `prevList` and/or `nextList`. + prev := l.prevList.Contains(elem) + // Short-circuit the return if the elem was found in the prev list. + if prev == True { + return prev + } + // Return if the elem was found in the next list. + next := l.nextList.Contains(elem) + if next == True { + return next + } + // Handle the case where an error or unknown was encountered before checking next. + if IsUnknownOrError(prev) { + return prev + } + // Otherwise, rely on the next value as the representative result. + return next +} + +// ConvertToNative implements the ref.Val interface method. +func (l *concatList) ConvertToNative(typeDesc reflect.Type) (any, error) { + combined := NewDynamicList(l.Adapter, l.Value()) + return combined.ConvertToNative(typeDesc) +} + +// ConvertToType implements the ref.Val interface method. +func (l *concatList) ConvertToType(typeVal ref.Type) ref.Val { + switch typeVal { + case ListType: + return l + case TypeType: + return ListType + } + return NewErr("type conversion error from '%s' to '%s'", ListType, typeVal) +} + +// Equal implements the ref.Val interface method. +func (l *concatList) Equal(other ref.Val) ref.Val { + otherList, ok := other.(traits.Lister) + if !ok { + return False + } + if l.Size() != otherList.Size() { + return False + } + var maybeErr ref.Val + for i := IntZero; i < l.Size().(Int); i++ { + thisElem := l.Get(i) + otherElem := otherList.Get(i) + elemEq := Equal(thisElem, otherElem) + if elemEq == False { + return False + } + if maybeErr == nil && IsUnknownOrError(elemEq) { + maybeErr = elemEq + } + } + if maybeErr != nil { + return maybeErr + } + return True +} + +// Get implements the traits.Indexer interface method. +func (l *concatList) Get(index ref.Val) ref.Val { + ind, err := GetOrError(index) + if err != nil { + return ValOrErr(index, "%v", err) + } + i := Int(ind) + if i < l.prevList.Size().(Int) { + return l.prevList.Get(i) + } + offset := i - l.prevList.Size().(Int) + return l.nextList.Get(offset) +} + +// IsZeroValue returns true if the list is empty. +func (l *concatList) IsZeroValue() bool { + return l.Size().(Int) == 0 +} + +// Fold calls the FoldEntry method for each (index, value) pair in the list. +func (l *concatList) Fold(f traits.Folder) { + for i := Int(0); i < l.Size().(Int); i++ { + if !f.FoldEntry(i, l.Get(i)) { + break + } + } +} + +// Iterator implements the traits.Iterable interface method. +func (l *concatList) Iterator() traits.Iterator { + return newListIterator(l) +} + +// Size implements the traits.Sizer interface method. +func (l *concatList) Size() ref.Val { + return l.cachedSize +} + +// AggregateSize implements the AggregateSizeVisitor interface method. +func (l *concatList) AggregateSize(sizer AggregateSizer) uint32 { + if sz := atomic.LoadUint32(&l.aggSize); sz != 0 { + return sz + } + total := safeAddUint32(sizer.AggregateSize(l.prevList), sizer.AggregateSize(l.nextList)) + if cacheableAggregateSize(sizer) { + atomic.StoreUint32(&l.aggSize, total) + } + return total +} + +// String converts the concatenated list to a human-readable string. +func (l *concatList) String() string { + var sb strings.Builder + sb.WriteString("[") + for i := Int(0); i < l.Size().(Int); i++ { + sb.WriteString(fmt.Sprintf("%v", l.Get(i))) + if i != l.Size().(Int)-1 { + sb.WriteString(", ") + } + } + sb.WriteString("]") + return sb.String() +} + +// Type implements the ref.Val interface method. +func (l *concatList) Type() ref.Type { + return ListType +} + +// Value implements the ref.Val interface method. +func (l *concatList) Value() any { + l.valueOnce.Do(func() { + merged := make([]ref.Val, l.Size().(Int)) + prevLen := l.prevList.Size().(Int) + for i := Int(0); i < prevLen; i++ { + merged[i] = l.prevList.Get(i) + } + nextLen := l.nextList.Size().(Int) + for j := Int(0); j < nextLen; j++ { + merged[prevLen+j] = l.nextList.Get(j) + } + l.value = merged + }) + return l.value +} + +func newListIterator(listValue traits.Lister) traits.Iterator { + return &listIterator{ + listValue: listValue, + len: listValue.Size().(Int), + } +} + +type listIterator struct { + *baseIterator + listValue traits.Lister + cursor Int + len Int +} + +// HasNext implements the traits.Iterator interface method. +func (it *listIterator) HasNext() ref.Val { + return Bool(it.cursor < it.len) +} + +// Next implements the traits.Iterator interface method. +func (it *listIterator) Next() ref.Val { + if it.HasNext() == True { + index := it.cursor + it.cursor++ + return it.listValue.Get(index) + } + return nil +} + +// GetOrError converts an input index value into either a lossless integer index or an error. +func GetOrError(index ref.Val) (int, error) { + switch iv := index.(type) { + case Int: + return int(iv), nil + case Double: + if ik, ok := doubleToInt64Lossless(float64(iv)); ok { + return int(ik), nil + } + return -1, fmt.Errorf("unsupported index value %v in list", index) + case Uint: + if ik, ok := uint64ToInt64Lossless(uint64(iv)); ok { + return int(ik), nil + } + return -1, fmt.Errorf("unsupported index value %v in list", index) + default: + return -1, fmt.Errorf("unsupported index type '%s' in list", index.Type()) + } +} + +// ToFoldableList will create a Foldable version of a list suitable for key-value pair iteration. +// +// For values which are already Foldable, this call is a no-op. For all other values, the fold is +// driven via the Size() and Get() calls which means that the folding will function, but take a +// performance hit. +func ToFoldableList(l traits.Lister) traits.Foldable { + if f, ok := l.(traits.Foldable); ok { + return f + } + return interopFoldableList{Lister: l} +} + +type interopFoldableList struct { + traits.Lister +} + +// Fold implements the traits.Foldable interface method and performs an iteration over the +// range of elements of the list. +func (l interopFoldableList) Fold(f traits.Folder) { + sz := l.Size().(Int) + for i := Int(0); i < sz; i++ { + if !f.FoldEntry(i, l.Get(i)) { + break + } + } +} + +type sliceList[T any] struct { + Adapter + elems []T + elemTypePtr unsafe.Pointer + meta *dynamicSliceMeta + aggSize uint32 + qualifyRawVal bool + isNilSlice bool +} + +func (l *sliceList[T]) listAdapter() Adapter { + return l.Adapter +} + +func (l *sliceList[T]) len() int { + if l.meta != nil && l.meta.elemStride > 0 { + return len(l.elems) / int(l.meta.elemStride) + } + return len(l.elems) +} + +func (l *sliceList[T]) nativeSliceValue() any { + if l.meta != nil { + n := l.len() + var data unsafe.Pointer + if n > 0 { + data = unsafe.Pointer(unsafe.SliceData(l.elems)) + } else if !l.isNilSlice { + data = unsafe.Pointer(&emptySliceData) + } + hdr := &unsafeSlice{ + Data: data, + Len: n, + Cap: n, + } + return packAny(l.meta.sliceTypePtr, unsafe.Pointer(hdr)) + } + return l.elems +} + +func (l *sliceList[T]) rawElemAt(ind int) (any, bool) { + switch s := any(l).(type) { + case *sliceList[unsafe.Pointer]: + if s.elemTypePtr != nil { + ptr := s.elems[ind] + if ptr == nil { + return NullValue, true + } + return packAny(s.elemTypePtr, ptr), true + } + case *sliceList[uint8]: + if s.meta != nil && s.meta.elemStride > 0 && s.elemTypePtr != nil { + addr := unsafe.Pointer(&s.elems[uintptr(ind)*s.meta.elemStride]) + if !s.qualifyRawVal { + return reflect.NewAt(s.meta.sliceType.Elem(), addr).Elem().Interface(), true + } + return packAny(s.elemTypePtr, addr), true + } + } + if l.qualifyRawVal && l.elemTypePtr != nil { + return packAny(l.elemTypePtr, unsafe.Pointer(&l.elems[ind])), true + } + return nil, false +} + +func (l *sliceList[T]) getElem(ind int) ref.Val { + switch s := any(l).(type) { + case *sliceList[string]: + return String(s.elems[ind]) + case *sliceList[ref.Val]: + return s.elems[ind] + case *sliceList[int]: + return Int(s.elems[ind]) + case *sliceList[int64]: + return Int(s.elems[ind]) + case *sliceList[int32]: + return Int(s.elems[ind]) + case *sliceList[uint]: + return Uint(s.elems[ind]) + case *sliceList[uint64]: + return Uint(s.elems[ind]) + case *sliceList[uint32]: + return Uint(s.elems[ind]) + case *sliceList[uint8]: + if s.meta == nil { + return Uint(s.elems[ind]) + } + case *sliceList[float64]: + return Double(s.elems[ind]) + case *sliceList[float32]: + return Double(s.elems[ind]) + case *sliceList[bool]: + if s.elems[ind] { + return True + } + return False + case *sliceList[[]byte]: + return Bytes(s.elems[ind]) + } + if raw, ok := l.rawElemAt(ind); ok { + return l.Adapter.NativeToValue(raw) + } + return l.Adapter.NativeToValue(l.elems[ind]) +} + +// GetInt64Index returns the element at ind for fast index qualification in the interpreter. +// For non-proto Go struct elements, it returns the unboxed struct pointer or zero-copy struct +// emptyInterface so subsequent field accesses can read offsets without allocating a nativeObj. +func (l *sliceList[T]) GetInt64Index(ind int64) (any, bool) { + n := l.len() + if ind < 0 || ind >= int64(n) { + return nil, false + } + i := int(ind) + if !l.qualifyRawVal { + return l.getElem(i), true + } + if raw, ok := l.rawElemAt(i); ok { + return raw, true + } + return l.elems[i], true +} + +func (l *sliceList[T]) Add(other ref.Val) ref.Val { + otherList, ok := other.(traits.Lister) + if !ok { + return MaybeNoSuchOverloadErr(other) + } + return newConcatList(l.Adapter, l, otherList) +} + +func (l *sliceList[T]) Contains(elem ref.Val) ref.Val { + switch s := any(l).(type) { + case *sliceList[string]: + if strVal, ok := elem.(String); ok { + str := string(strVal) + for _, e := range s.elems { + if e == str { + return True + } + } + return False + } + case *sliceList[int64]: + if intVal, ok := elem.(Int); ok { + iv := int64(intVal) + for _, e := range s.elems { + if e == iv { + return True + } + } + return False + } + case *sliceList[int]: + if intVal, ok := elem.(Int); ok { + iv := int(intVal) + for _, e := range s.elems { + if e == iv { + return True + } + } + return False + } + case *sliceList[int32]: + if intVal, ok := elem.(Int); ok { + iv := int32(intVal) + if int64(iv) == int64(intVal) { + for _, e := range s.elems { + if e == iv { + return True + } + } + } + return False + } + case *sliceList[uint64]: + if uintVal, ok := elem.(Uint); ok { + uv := uint64(uintVal) + for _, e := range s.elems { + if e == uv { + return True + } + } + return False + } + case *sliceList[uint]: + if uintVal, ok := elem.(Uint); ok { + uv := uint(uintVal) + for _, e := range s.elems { + if e == uv { + return True + } + } + return False + } + case *sliceList[uint32]: + if uintVal, ok := elem.(Uint); ok { + uv := uint32(uintVal) + if uint64(uv) == uint64(uintVal) { + for _, e := range s.elems { + if e == uv { + return True + } + } + } + return False + } + case *sliceList[float64]: + if dblVal, ok := elem.(Double); ok { + dv := float64(dblVal) + for _, e := range s.elems { + if e == dv { + return True + } + } + return False + } + case *sliceList[bool]: + if boolVal, ok := elem.(Bool); ok { + bv := bool(boolVal) + for _, e := range s.elems { + if e == bv { + return True + } + } + return False + } + } + n := l.len() + for i := 0; i < n; i++ { + cmp := elem.Equal(l.getElem(i)) + if b, ok := cmp.(Bool); ok && b == True { + return True + } + } + return False +} + +func (l *sliceList[T]) ConvertToNative(typeDesc reflect.Type) (any, error) { + if l.meta == nil && typeDesc == reflect.TypeFor[[]T]() { + return l.elems, nil + } + val := l.nativeSliceValue() + if l.meta != nil && l.meta.sliceType == typeDesc { + return val, nil + } + return convertListToNative(l, val, typeDesc) +} + +func (l *sliceList[T]) ConvertToType(typeVal ref.Type) ref.Val { + switch typeVal { + case ListType: + return l + case TypeType: + return ListType + } + return NewErr("type conversion error from '%s' to '%s'", ListType, typeVal) +} + +func (l *sliceList[T]) Equal(other ref.Val) ref.Val { + otherList, ok := other.(traits.Lister) + if !ok { + return False + } + if l.Size() != otherList.Size() { + return False + } + n := l.len() + if otherSlice, ok := other.(*sliceList[T]); ok && l.meta == otherSlice.meta { + switch s := any(l).(type) { + case *sliceList[string]: + o := any(otherSlice).(*sliceList[string]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[int64]: + o := any(otherSlice).(*sliceList[int64]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[int]: + o := any(otherSlice).(*sliceList[int]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[int32]: + o := any(otherSlice).(*sliceList[int32]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[uint64]: + o := any(otherSlice).(*sliceList[uint64]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[uint]: + o := any(otherSlice).(*sliceList[uint]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[uint32]: + o := any(otherSlice).(*sliceList[uint32]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[float64]: + o := any(otherSlice).(*sliceList[float64]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[float32]: + o := any(otherSlice).(*sliceList[float32]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[bool]: + o := any(otherSlice).(*sliceList[bool]) + for i := range n { + if s.elems[i] != o.elems[i] { + return False + } + } + return True + case *sliceList[[]byte]: + o := any(otherSlice).(*sliceList[[]byte]) + for i := range n { + if !bytes.Equal(s.elems[i], o.elems[i]) { + return False + } + } + return True + } + for i := range n { + if Equal(l.getElem(i), otherSlice.getElem(i)) == False { + return False + } + } + return True + } + for i := range n { + thisElem := l.getElem(i) + otherElem := otherList.Get(Int(i)) + if Equal(thisElem, otherElem) == False { + return False + } + } + return True +} + +func (l *sliceList[T]) Get(index ref.Val) ref.Val { + ind, err := GetOrError(index) + if err != nil { + return ValOrErr(index, "%v", err) + } + n := l.len() + if ind < 0 || ind >= n { + return NewErr("index '%d' out of range in list size '%d'", ind, n) + } + return l.getElem(ind) +} + +func (l *sliceList[T]) IsZeroValue() bool { + return l.len() == 0 +} + +func (l *sliceList[T]) foldElems(f traits.Folder) { + for i := range l.len() { + if !f.FoldEntry(i, l.getElem(i)) { + break + } + } +} + +func (l *sliceList[T]) Fold(f traits.Folder) { + switch s := any(l).(type) { + case *sliceList[string]: + for i, e := range s.elems { + if !f.FoldEntry(i, String(e)) { + break + } + } + case *sliceList[ref.Val]: + for i, e := range s.elems { + if !f.FoldEntry(i, e) { + break + } + } + case *sliceList[int]: + for i, e := range s.elems { + if !f.FoldEntry(i, Int(e)) { + break + } + } + case *sliceList[int64]: + for i, e := range s.elems { + if !f.FoldEntry(i, Int(e)) { + break + } + } + case *sliceList[int32]: + for i, e := range s.elems { + if !f.FoldEntry(i, Int(e)) { + break + } + } + case *sliceList[uint]: + for i, e := range s.elems { + if !f.FoldEntry(i, Uint(e)) { + break + } + } + case *sliceList[uint64]: + for i, e := range s.elems { + if !f.FoldEntry(i, Uint(e)) { + break + } + } + case *sliceList[uint32]: + for i, e := range s.elems { + if !f.FoldEntry(i, Uint(e)) { + break + } + } + case *sliceList[uint8]: + if s.meta != nil && s.meta.elemStride > 0 && s.elemTypePtr != nil { + if !s.qualifyRawVal { + s.foldElems(f) + return + } + stride := s.meta.elemStride + n := len(s.elems) / int(stride) + for i := 0; i < n; i++ { + if !f.FoldEntry(i, packAny(s.elemTypePtr, unsafe.Pointer(&s.elems[uintptr(i)*stride]))) { + break + } + } + return + } + for i, e := range s.elems { + if !f.FoldEntry(i, Uint(e)) { + break + } + } + case *sliceList[float64]: + for i, e := range s.elems { + if !f.FoldEntry(i, Double(e)) { + break + } + } + case *sliceList[float32]: + for i, e := range s.elems { + if !f.FoldEntry(i, Double(e)) { + break + } + } + case *sliceList[bool]: + for i, e := range s.elems { + val := False + if e { + val = True + } + if !f.FoldEntry(i, val) { + break + } + } + case *sliceList[[]byte]: + for i, e := range s.elems { + if !f.FoldEntry(i, Bytes(e)) { + break + } + } + case *sliceList[unsafe.Pointer]: + if s.elemTypePtr != nil { + if !s.qualifyRawVal { + s.foldElems(f) + return + } + for i, ptr := range s.elems { + if ptr == nil { + if !f.FoldEntry(i, NullValue) { + break + } + continue + } + if !f.FoldEntry(i, packAny(s.elemTypePtr, ptr)) { + break + } + } + return + } + default: + if l.qualifyRawVal && l.elemTypePtr != nil { + for i := range l.elems { + if !f.FoldEntry(i, packAny(l.elemTypePtr, unsafe.Pointer(&l.elems[i]))) { + break + } + } + return + } + if !l.qualifyRawVal && (!isStandardAdapter(l.Adapter) || l.elemTypePtr != nil) { + l.foldElems(f) + return + } + for i, e := range l.elems { + if !f.FoldEntry(i, e) { + break + } + } + } +} + +func (l *sliceList[T]) Iterator() traits.Iterator { + return &sliceListIterator[T]{ + list: l, + len: l.len(), + } +} + +func (l *sliceList[T]) Size() ref.Val { + return Int(l.len()) +} + +func (l *sliceList[T]) AggregateSize(sizer AggregateSizer) uint32 { + if sz := atomic.LoadUint32(&l.aggSize); sz != 0 { + return sz + } + var total uint32 + if l.meta == nil && l.elemTypePtr == nil { + if t, ok := getSliceElementsAggregateSize(sizer, l.elems); ok { + total = t + } + } + if total == 0 { + total = uint32(1) + n := l.len() + for i := 0; i < n; i++ { + total = safeAddUint32(total, sizer.AggregateSize(l.getElem(i))) + } + } + if cacheableAggregateSize(sizer) { + atomic.StoreUint32(&l.aggSize, total) + } + return total +} + +func (l *sliceList[T]) Type() ref.Type { + return ListType +} + +func (l *sliceList[T]) Value() any { + return l.nativeSliceValue() +} + +func (l *sliceList[T]) String() string { + var sb strings.Builder + sb.WriteString("[") + n := l.len() + for i := 0; i < n; i++ { + if l.meta != nil { + sb.WriteString(fmt.Sprintf("%v", l.getElem(i).Value())) + } else { + sb.WriteString(fmt.Sprintf("%v", l.elems[i])) + } + if i != n-1 { + sb.WriteString(", ") + } + } + sb.WriteString("]") + return sb.String() +} + +func (l *sliceList[T]) format(sb *strings.Builder) { + formatList(l, sb) +} + +type sliceListIterator[T any] struct { + *baseIterator + list *sliceList[T] + cursor int + len int +} + +func (it *sliceListIterator[T]) HasNext() ref.Val { + if it.cursor < it.len { + return True + } + return False +} + +func (it *sliceListIterator[T]) Next() ref.Val { + if it.cursor < it.len { + ind := it.cursor + it.cursor++ + return it.list.getElem(ind) + } + return nil +} + +var emptySliceData byte diff --git a/vendor/github.com/google/cel-go/common/types/map.go b/vendor/cel.dev/cel-go/common/types/map.go similarity index 60% rename from vendor/github.com/google/cel-go/common/types/map.go rename to vendor/cel.dev/cel-go/common/types/map.go index e4d6f76574..73d61f8a5c 100644 --- a/vendor/github.com/google/cel-go/common/types/map.go +++ b/vendor/cel.dev/cel-go/common/types/map.go @@ -16,17 +16,21 @@ package types import ( "fmt" + "maps" + "math" "reflect" "sort" "strings" + "sync/atomic" "unicode" + "unsafe" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "github.com/google/cel-go/common/types/pb" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/types/pb" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" @@ -43,6 +47,16 @@ func NewDynamicMap(adapter Adapter, value any) traits.Mapper { } } +// NewMap returns a traits.Mapper backed by a typed Go map[K]V. +func NewMap[K comparable, V any](adapter Adapter, value map[K]V) traits.Mapper { + return &nativeMap[K, V]{ + Adapter: adapter, + mapVal: value, + valTypePtr: elemTypePtrFor[V](), + qualifyRawVal: isQualifyRawStructFor[V](adapter), + } +} + // NewJSONStruct creates a traits.Mapper implementation backed by a JSON struct that has been // encoded in protocol buffer form. // @@ -59,32 +73,17 @@ func NewJSONStruct(adapter Adapter, value *structpb.Struct) traits.Mapper { // NewRefValMap returns a specialized traits.Mapper with CEL valued keys and values. func NewRefValMap(adapter Adapter, value map[ref.Val]ref.Val) traits.Mapper { - return &baseMap{ - Adapter: adapter, - mapAccessor: newRefValMapAccessor(value), - value: value, - size: len(value), - } + return NewMap(adapter, value) } // NewStringInterfaceMap returns a specialized traits.Mapper with string keys and interface values. func NewStringInterfaceMap(adapter Adapter, value map[string]any) traits.Mapper { - return &baseMap{ - Adapter: adapter, - mapAccessor: newStringIfaceMapAccessor(adapter, value), - value: value, - size: len(value), - } + return NewMap(adapter, value) } // NewStringStringMap returns a specialized traits.Mapper with string keys and values. func NewStringStringMap(adapter Adapter, value map[string]string) traits.Mapper { - return &baseMap{ - Adapter: adapter, - mapAccessor: newStringMapAccessor(value), - value: value, - size: len(value), - } + return NewMap(adapter, value) } // NewProtoMap returns a specialized traits.Mapper for handling protobuf map values. @@ -101,16 +100,12 @@ func NewMutableMap(adapter Adapter, mutableValues map[ref.Val]ref.Val) traits.Mu for k, v := range mutableValues { mutableCopy[k] = v } - m := &mutableMap{ - baseMap: &baseMap{ - Adapter: adapter, - mapAccessor: newRefValMapAccessor(mutableCopy), - value: mutableCopy, - size: len(mutableCopy), + return &mutableMap{ + nativeMap: &nativeMap[ref.Val, ref.Val]{ + Adapter: adapter, + mapVal: mutableCopy, }, - mutableValues: mutableCopy, } - return m } // mapAccessor is a private interface for finding values within a map and iterating over the keys. @@ -142,8 +137,13 @@ type baseMap struct { // value is the native Go value upon which the map type operators. value any - // size is the number of entries in the map. size int + + // aggSize memoizes the aggregate size computed by the first completed sizing of this + // map. Accessed atomically since immutable maps may be shared across concurrent + // evaluations; zero means not yet computed. See the SizeCalculator documentation for + // the memoization contract. + aggSize uint32 } // Contains implements the traits.Container interface method. @@ -154,13 +154,17 @@ func (m *baseMap) Contains(index ref.Val) ref.Val { // ConvertToNative implements the ref.Val interface method. func (m *baseMap) ConvertToNative(typeDesc reflect.Type) (any, error) { + return convertMapToNative(m, m.value, typeDesc) +} + +func convertMapToNative(m traits.Mapper, val any, typeDesc reflect.Type) (any, error) { // If the map is already assignable to the desired type return it, e.g. interfaces and // maps with the same key value types. if typeDesc == reflect.TypeFor[any]() { typeDesc = reflect.TypeFor[map[any]any]() } - if reflect.TypeOf(m.value).AssignableTo(typeDesc) { - return m.value, nil + if val != nil && reflect.TypeOf(val).AssignableTo(typeDesc) { + return val, nil } if reflect.TypeOf(m).AssignableTo(typeDesc) { return m, nil @@ -200,7 +204,7 @@ func (m *baseMap) ConvertToNative(typeDesc reflect.Type) (any, error) { case reflect.Map: otherKey := typeDesc.Key() otherElem := typeDesc.Elem() - nativeMap := reflect.MakeMapWithSize(typeDesc, m.size) + nativeMap := reflect.MakeMapWithSize(typeDesc, int(m.Size().(Int))) it := m.Iterator() for it.HasNext() == True { key := it.Next() @@ -303,6 +307,28 @@ func (m *baseMap) Size() ref.Val { return Int(m.size) } +// AggregateSize implements the AggregateSizeVisitor interface method. +func (m *baseMap) AggregateSize(sizer AggregateSizer) uint32 { + if sz := atomic.LoadUint32(&m.aggSize); sz != 0 { + return sz + } + var total uint32 + if m.value != nil { + if t, ok := getMapElementsAggregateSize(sizer, m.value); ok { + total = t + } + } + if total == 0 { + f := foldableAggregateSizer{sizer: sizer, total: 1} + m.Fold(&f) + total = f.total + } + if cacheableAggregateSize(sizer) { + atomic.StoreUint32(&m.aggSize, total) + } + return total +} + // String converts the map into a human-readable string. func (m *baseMap) String() string { var sb strings.Builder @@ -312,7 +338,7 @@ func (m *baseMap) String() string { for it.HasNext() == True { k := it.Next() v, _ := m.Find(k) - sb.WriteString(fmt.Sprintf("%v: %v", k, v)) + fmt.Fprintf(&sb, "%v: %v", k, v) if i != m.size-1 { sb.WriteString(", ") } @@ -369,8 +395,7 @@ func (m *baseMap) Value() any { // mutableMap holds onto a set of mutable values which are used for intermediate computations. type mutableMap struct { - *baseMap - mutableValues map[ref.Val]ref.Val + *nativeMap[ref.Val, ref.Val] } // Insert implements the traits.MutableMapper interface method, returning true if the key insertion @@ -379,14 +404,17 @@ func (m *mutableMap) Insert(k, v ref.Val) ref.Val { if _, found := m.Find(k); found { return NewErr("insert failed: key %v already exists", k) } - m.mutableValues[k] = v + m.mapVal[k] = v + atomic.StoreUint32(&m.aggSize, 0) return m } // ToImmutableMap implements the traits.MutableMapper interface method, converting a mutable map // an immutable map implementation. func (m *mutableMap) ToImmutableMap() traits.Mapper { - return NewRefValMap(m.Adapter, m.mutableValues) + copyMap := make(map[ref.Val]ref.Val, len(m.mapVal)) + maps.Copy(copyMap, m.mapVal) + return NewRefValMap(m.Adapter, copyMap) } func newJSONStructAccessor(adapter Adapter, st map[string]*structpb.Value) mapAccessor { @@ -518,6 +546,14 @@ func (m *reflectMapAccessor) Iterator() traits.Iterator { // Fold calls the FoldEntry method for each (key, value) pair in the map. func (m *reflectMapAccessor) Fold(f traits.Folder) { mapRange := m.refValue.MapRange() + if !isStandardAdapter(m.Adapter) { + for mapRange.Next() { + if !f.FoldEntry(m.NativeToValue(mapRange.Key().Interface()), m.NativeToValue(mapRange.Value().Interface())) { + break + } + } + return + } for mapRange.Next() { if !f.FoldEntry(mapRange.Key().Interface(), mapRange.Value().Interface()) { break @@ -525,171 +561,581 @@ func (m *reflectMapAccessor) Fold(f traits.Folder) { } } -func newRefValMapAccessor(mapVal map[ref.Val]ref.Val) mapAccessor { - return &refValMapAccessor{mapVal: mapVal} +func toInt64Key(key ref.Val) (int64, bool) { + switch k := key.(type) { + case Int: + return int64(k), true + case Uint: + return uint64ToInt64Lossless(uint64(k)) + case Double: + return doubleToInt64Lossless(float64(k)) + default: + return 0, false + } +} + +func toUint64Key(key ref.Val) (uint64, bool) { + switch k := key.(type) { + case Uint: + return uint64(k), true + case Int: + return int64ToUint64Lossless(int64(k)) + case Double: + return doubleToUint64Lossless(float64(k)) + default: + return 0, false + } } -type refValMapAccessor struct { - mapVal map[ref.Val]ref.Val +type nativeMap[K comparable, V any] struct { + Adapter + mapVal map[K]V + valTypePtr unsafe.Pointer + qualifyRawVal bool + aggSize uint32 +} + +func (m *nativeMap[K, V]) keyToRefVal(k K) ref.Val { + switch any((*K)(nil)).(type) { + case *string: + return String(*(*string)(unsafe.Pointer(&k))) + case *ref.Val: + return *(*ref.Val)(unsafe.Pointer(&k)) + case *int64: + return Int(*(*int64)(unsafe.Pointer(&k))) + case *int: + return Int(*(*int)(unsafe.Pointer(&k))) + case *int32: + return Int(*(*int32)(unsafe.Pointer(&k))) + case *uint64: + return Uint(*(*uint64)(unsafe.Pointer(&k))) + case *uint: + return Uint(*(*uint)(unsafe.Pointer(&k))) + case *uint32: + return Uint(*(*uint32)(unsafe.Pointer(&k))) + case *bool: + if *(*bool)(unsafe.Pointer(&k)) { + return True + } + return False + default: + return m.Adapter.NativeToValue(k) + } +} + +func (m *nativeMap[K, V]) valToRefVal(v V) ref.Val { + switch any((*V)(nil)).(type) { + case *string: + return String(*(*string)(unsafe.Pointer(&v))) + case *ref.Val: + return *(*ref.Val)(unsafe.Pointer(&v)) + case *int64: + return Int(*(*int64)(unsafe.Pointer(&v))) + case *int: + return Int(*(*int)(unsafe.Pointer(&v))) + case *int32: + return Int(*(*int32)(unsafe.Pointer(&v))) + case *uint64: + return Uint(*(*uint64)(unsafe.Pointer(&v))) + case *uint: + return Uint(*(*uint)(unsafe.Pointer(&v))) + case *uint32: + return Uint(*(*uint32)(unsafe.Pointer(&v))) + case *float64: + return Double(*(*float64)(unsafe.Pointer(&v))) + case *float32: + return Double(*(*float32)(unsafe.Pointer(&v))) + case *bool: + if *(*bool)(unsafe.Pointer(&v)) { + return True + } + return False + case *[]byte: + return Bytes(*(*[]byte)(unsafe.Pointer(&v))) + default: + if m.qualifyRawVal && m.valTypePtr != nil { + return m.Adapter.NativeToValue(packAny(m.valTypePtr, unsafe.Pointer(heapCopy(v)))) + } + return m.Adapter.NativeToValue(v) + } } -// Find uses native map accesses to find the key, returning (value, true) if present. -// -// If the key is not found the function returns (nil, false). -func (a *refValMapAccessor) Find(key ref.Val) (ref.Val, bool) { - if len(a.mapVal) == 0 { +func (m *nativeMap[K, V]) rawValToAny(v V) any { + if m.valTypePtr != nil { + return packAny(m.valTypePtr, unsafe.Pointer(heapCopy(v))) + } + if m.qualifyRawVal && anyDataPtr(v) == nil { + return NullValue + } + return v +} + +func (m *nativeMap[K, V]) keyToFoldAny(k K) any { + switch any((*K)(nil)).(type) { + case *string: + return String(*(*string)(unsafe.Pointer(&k))) + case *ref.Val: + return *(*ref.Val)(unsafe.Pointer(&k)) + case *int64: + return Int(*(*int64)(unsafe.Pointer(&k))) + case *int: + return Int(*(*int)(unsafe.Pointer(&k))) + case *int32: + return Int(*(*int32)(unsafe.Pointer(&k))) + case *uint64: + return Uint(*(*uint64)(unsafe.Pointer(&k))) + case *uint: + return Uint(*(*uint)(unsafe.Pointer(&k))) + case *uint32: + return Uint(*(*uint32)(unsafe.Pointer(&k))) + case *bool: + if *(*bool)(unsafe.Pointer(&k)) { + return True + } + return False + default: + return k + } +} + +func (m *nativeMap[K, V]) valToFoldAny(v V) any { + switch any((*V)(nil)).(type) { + case *string: + return String(*(*string)(unsafe.Pointer(&v))) + case *ref.Val: + return *(*ref.Val)(unsafe.Pointer(&v)) + case *int64: + return Int(*(*int64)(unsafe.Pointer(&v))) + case *int: + return Int(*(*int)(unsafe.Pointer(&v))) + case *int32: + return Int(*(*int32)(unsafe.Pointer(&v))) + case *uint64: + return Uint(*(*uint64)(unsafe.Pointer(&v))) + case *uint: + return Uint(*(*uint)(unsafe.Pointer(&v))) + case *uint32: + return Uint(*(*uint32)(unsafe.Pointer(&v))) + case *float64: + return Double(*(*float64)(unsafe.Pointer(&v))) + case *float32: + return Double(*(*float32)(unsafe.Pointer(&v))) + case *bool: + if *(*bool)(unsafe.Pointer(&v)) { + return True + } + return False + case *[]byte: + return Bytes(*(*[]byte)(unsafe.Pointer(&v))) + default: + return m.rawValToAny(v) + } +} + +func (m *nativeMap[K, V]) Find(key ref.Val) (ref.Val, bool) { + v, found := m.findVal(key) + if !found { return nil, false } - if keyVal, found := a.mapVal[key]; found { - return keyVal, true + return m.valToRefVal(v), true +} + +// findVal resolves key to the stored native value without converting it to a ref.Val, so that +// presence tests (`in`, has(), optional selection) do not pay for value conversion. +func (m *nativeMap[K, V]) findVal(key ref.Val) (v V, found bool) { + if len(m.mapVal) == 0 { + return v, false } - switch k := key.(type) { + var k K + switch any((*K)(nil)).(type) { + case *string: + sk, ok := key.(String) + if !ok { + return v, false + } + k = *(*K)(unsafe.Pointer(&sk)) + case *int64: + ik, ok := toInt64Key(key) + if !ok { + return v, false + } + k = *(*K)(unsafe.Pointer(&ik)) + case *int: + ik, ok := toInt64Key(key) + if !ok || ik < math.MinInt || ik > math.MaxInt { + return v, false + } + iv := int(ik) + k = *(*K)(unsafe.Pointer(&iv)) + case *int32: + ik, ok := toInt64Key(key) + if !ok || ik < math.MinInt32 || ik > math.MaxInt32 { + return v, false + } + iv := int32(ik) + k = *(*K)(unsafe.Pointer(&iv)) + case *uint64: + uk, ok := toUint64Key(key) + if !ok { + return v, false + } + k = *(*K)(unsafe.Pointer(&uk)) + case *uint: + uk, ok := toUint64Key(key) + if !ok || uk > math.MaxUint { + return v, false + } + uv := uint(uk) + k = *(*K)(unsafe.Pointer(&uv)) + case *uint32: + uk, ok := toUint64Key(key) + if !ok || uk > math.MaxUint32 { + return v, false + } + uv := uint32(uk) + k = *(*K)(unsafe.Pointer(&uv)) + case *bool: + bk, ok := key.(Bool) + if !ok { + return v, false + } + bv := bool(bk) + k = *(*K)(unsafe.Pointer(&bv)) + case *ref.Val: + return m.findRefValKey(key) + default: + rawK, err := key.ConvertToNative(reflect.TypeFor[K]()) + if err != nil { + return v, false + } + typedK, ok := rawK.(K) + if !ok { + return v, false + } + k = typedK + } + v, found = m.mapVal[k] + return v, found +} + +// findRefValKey looks up a key in a map whose key type is ref.Val, falling back to numerically +// equivalent keys of other numeric types (e.g. 1.0 -> 1 -> 1u) when there is no exact match. +func (m *nativeMap[K, V]) findRefValKey(key ref.Val) (v V, found bool) { + if v, found = m.lookupRefVal(key); found { + return v, true + } + switch kv := key.(type) { case Double: - if ik, ok := doubleToInt64Lossless(float64(k)); ok { - if keyVal, found := a.mapVal[Int(ik)]; found { - return keyVal, found + if ik, ok := doubleToInt64Lossless(float64(kv)); ok { + if v, found = m.lookupRefVal(Int(ik)); found { + return v, true } } - if uk, ok := doubleToUint64Lossless(float64(k)); ok { - keyVal, found := a.mapVal[Uint(uk)] - return keyVal, found + if uk, ok := doubleToUint64Lossless(float64(kv)); ok { + return m.lookupRefVal(Uint(uk)) } - // map keys of type double are not supported. case Int: - if uk, ok := int64ToUint64Lossless(int64(k)); ok { - keyVal, found := a.mapVal[Uint(uk)] - return keyVal, found + if uk, ok := int64ToUint64Lossless(int64(kv)); ok { + return m.lookupRefVal(Uint(uk)) } case Uint: - if ik, ok := uint64ToInt64Lossless(uint64(k)); ok { - keyVal, found := a.mapVal[Int(ik)] - return keyVal, found + if ik, ok := uint64ToInt64Lossless(uint64(kv)); ok { + return m.lookupRefVal(Int(ik)) } } - return nil, false + return v, false } -// Iterator produces a new traits.Iterator which iterates over the map keys via Golang reflection. -func (a *refValMapAccessor) Iterator() traits.Iterator { - return &mapIterator{ - Adapter: DefaultTypeAdapter, - mapKeys: reflect.ValueOf(a.mapVal).MapRange(), - len: len(a.mapVal), +// lookupRefVal performs a direct map lookup for maps whose key type K is ref.Val. +func (m *nativeMap[K, V]) lookupRefVal(rk ref.Val) (V, bool) { + v, found := m.mapVal[*(*K)(unsafe.Pointer(&rk))] + return v, found +} + +func (m *nativeMap[K, V]) valToQualifyAny(v V) any { + if m.qualifyRawVal { + return m.rawValToAny(v) } + return m.valToRefVal(v) } -// Fold calls the FoldEntry method for each (key, value) pair in the map. -func (a *refValMapAccessor) Fold(f traits.Folder) { - for k, v := range a.mapVal { - if !f.FoldEntry(k, v) { - break +func (m *nativeMap[K, V]) FindStringKey(s string) (any, bool) { + switch any((*K)(nil)).(type) { + case *string: + v, found := m.mapVal[*(*K)(unsafe.Pointer(&s))] + if !found { + return nil, false + } + return m.valToQualifyAny(v), true + case *ref.Val: + var rk ref.Val = String(s) + v, found := m.mapVal[*(*K)(unsafe.Pointer(&rk))] + if !found { + return nil, false } + return m.valToQualifyAny(v), true + default: + return nil, false } } -func newStringMapAccessor(strMap map[string]string) mapAccessor { - return &stringMapAccessor{mapVal: strMap} +func (m *nativeMap[K, V]) FindInt64Key(ik int64) (any, bool) { + switch any((*K)(nil)).(type) { + case *int64: + v, found := m.mapVal[*(*K)(unsafe.Pointer(&ik))] + if !found { + return nil, false + } + return m.valToQualifyAny(v), true + case *int: + if ik < math.MinInt || ik > math.MaxInt { + return nil, false + } + iv := int(ik) + v, found := m.mapVal[*(*K)(unsafe.Pointer(&iv))] + if !found { + return nil, false + } + return m.valToQualifyAny(v), true + case *int32: + if ik < math.MinInt32 || ik > math.MaxInt32 { + return nil, false + } + iv := int32(ik) + v, found := m.mapVal[*(*K)(unsafe.Pointer(&iv))] + if !found { + return nil, false + } + return m.valToQualifyAny(v), true + case *ref.Val: + var rk ref.Val = Int(ik) + v, found := m.mapVal[*(*K)(unsafe.Pointer(&rk))] + if found { + return m.valToQualifyAny(v), true + } + if ik >= 0 { + rk = Uint(ik) + v, found = m.mapVal[*(*K)(unsafe.Pointer(&rk))] + if found { + return m.valToQualifyAny(v), true + } + } + return nil, false + default: + return nil, false + } } -type stringMapAccessor struct { - mapVal map[string]string +func (m *nativeMap[K, V]) FindNative(key any) (any, bool) { + switch k := key.(type) { + case String: + return m.FindStringKey(string(k)) + case string: + return m.FindStringKey(k) + case Int: + return m.FindInt64Key(int64(k)) + case int64: + return m.FindInt64Key(k) + case int: + return m.FindInt64Key(int64(k)) + } + if rv, ok := key.(ref.Val); ok { + return m.Find(rv) + } + return nil, false } -// Find uses native map accesses to find the key, returning (value, true) if present. -// -// If the key is not found the function returns (nil, false). -func (a *stringMapAccessor) Find(key ref.Val) (ref.Val, bool) { - strKey, ok := key.(String) - if !ok { - return nil, false +func (m *nativeMap[K, V]) Contains(index ref.Val) ref.Val { + _, found := m.findVal(index) + return Bool(found) +} + +func (m *nativeMap[K, V]) ConvertToNative(typeDesc reflect.Type) (any, error) { + if typeDesc == reflect.TypeFor[map[K]V]() { + return m.mapVal, nil } - keyVal, found := a.mapVal[string(strKey)] - if !found { - return nil, false + return convertMapToNative(m, m.mapVal, typeDesc) +} + +func (m *nativeMap[K, V]) ConvertToType(typeVal ref.Type) ref.Val { + switch typeVal { + case MapType: + return m + case TypeType: + return MapType } - return String(keyVal), true + return NewErr("type conversion error from '%s' to '%s'", MapType, typeVal) } -// Iterator creates a new traits.Iterator from the string key set of the map. -func (a *stringMapAccessor) Iterator() traits.Iterator { - // Copy the keys to make their order stable. - mapKeys := make([]string, len(a.mapVal)) - i := 0 - for k := range a.mapVal { - mapKeys[i] = k - i++ +func (m *nativeMap[K, V]) Equal(other ref.Val) ref.Val { + otherMap, ok := other.(traits.Mapper) + if !ok { + return False } - return &stringKeyIterator{ - mapKeys: mapKeys, - len: len(mapKeys), + if m.Size() != otherMap.Size() { + return False + } + if otherNative, ok := other.(*nativeMap[K, V]); ok { + for k, v := range m.mapVal { + if otherV, found := otherNative.mapVal[k]; found { + if Equal(m.valToRefVal(v), otherNative.valToRefVal(otherV)) == False { + return False + } + continue + } + otherVal, found := otherNative.Find(m.keyToRefVal(k)) + if !found || Equal(m.valToRefVal(v), otherVal) == False { + return False + } + } + return True } + for k, v := range m.mapVal { + otherVal, found := otherMap.Find(m.keyToRefVal(k)) + if !found { + return False + } + if Equal(m.valToRefVal(v), otherVal) == False { + return False + } + } + return True } -// Fold calls the FoldEntry method for each (key, value) pair in the map. -func (a *stringMapAccessor) Fold(f traits.Folder) { - for k, v := range a.mapVal { - if !f.FoldEntry(k, v) { +func (m *nativeMap[K, V]) Get(key ref.Val) ref.Val { + v, found := m.Find(key) + if !found { + return ValOrErr(v, "no such key: %v", key) + } + return v +} + +func (m *nativeMap[K, V]) IsZeroValue() bool { + return len(m.mapVal) == 0 +} + +func (m *nativeMap[K, V]) Fold(f traits.Folder) { + if kf, ok := f.(interface{ FoldKeyOnly() bool }); ok && kf.FoldKeyOnly() { + if !isStandardAdapter(m.Adapter) { + for k := range m.mapVal { + if !f.FoldEntry(m.keyToRefVal(k), nil) { + break + } + } + return + } + for k := range m.mapVal { + if !f.FoldEntry(m.keyToFoldAny(k), nil) { + break + } + } + return + } + if !m.qualifyRawVal && !isStandardAdapter(m.Adapter) { + for k, v := range m.mapVal { + if !f.FoldEntry(m.keyToRefVal(k), m.valToRefVal(v)) { + break + } + } + return + } + for k, v := range m.mapVal { + if !f.FoldEntry(m.keyToFoldAny(k), m.valToFoldAny(v)) { break } } } -func newStringIfaceMapAccessor(adapter Adapter, mapVal map[string]any) mapAccessor { - return &stringIfaceMapAccessor{ - Adapter: adapter, - mapVal: mapVal, +type nativeMapKeyIterator[K comparable, V any] struct { + *baseIterator + m *nativeMap[K, V] + keys []K + cursor int +} + +func (it *nativeMapKeyIterator[K, V]) HasNext() ref.Val { + if it.cursor < len(it.keys) { + return True } + return False } -type stringIfaceMapAccessor struct { - Adapter - mapVal map[string]any +func (it *nativeMapKeyIterator[K, V]) Next() ref.Val { + if it.cursor < len(it.keys) { + k := it.keys[it.cursor] + it.cursor++ + return it.m.keyToRefVal(k) + } + return nil } -// Find uses native map accesses to find the key, returning (value, true) if present. -// -// If the key is not found the function returns (nil, false). -func (a *stringIfaceMapAccessor) Find(key ref.Val) (ref.Val, bool) { - strKey, ok := key.(String) - if !ok { - return nil, false +func (m *nativeMap[K, V]) Iterator() traits.Iterator { + keys := make([]K, 0, len(m.mapVal)) + for k := range m.mapVal { + keys = append(keys, k) } - keyVal, found := a.mapVal[string(strKey)] - if !found { - return nil, false + return &nativeMapKeyIterator[K, V]{ + m: m, + keys: keys, } - return a.NativeToValue(keyVal), true } -// Iterator creates a new traits.Iterator from the string key set of the map. -func (a *stringIfaceMapAccessor) Iterator() traits.Iterator { - // Copy the keys to make their order stable. - mapKeys := make([]string, len(a.mapVal)) - i := 0 - for k := range a.mapVal { - mapKeys[i] = k - i++ +func (m *nativeMap[K, V]) Size() ref.Val { + return Int(len(m.mapVal)) +} + +func (m *nativeMap[K, V]) AggregateSize(sizer AggregateSizer) uint32 { + if sz := atomic.LoadUint32(&m.aggSize); sz != 0 { + return sz } - return &stringKeyIterator{ - mapKeys: mapKeys, - len: len(mapKeys), + var total uint32 + if t, ok := getMapElementsAggregateSize(sizer, m.mapVal); ok { + total = t + } + if total == 0 { + f := foldableAggregateSizer{sizer: sizer, total: 1} + m.Fold(&f) + total = f.total } + if cacheableAggregateSize(sizer) { + atomic.StoreUint32(&m.aggSize, total) + } + return total } -// Fold calls the FoldEntry method for each (key, value) pair in the map. -func (a *stringIfaceMapAccessor) Fold(f traits.Folder) { - for k, v := range a.mapVal { - if !f.FoldEntry(k, v) { - break +func (m *nativeMap[K, V]) String() string { + var sb strings.Builder + sb.WriteString("{") + i := 0 + for k, v := range m.mapVal { + fmt.Fprintf(&sb, "%v: %v", m.keyToRefVal(k), m.valToRefVal(v)) + if i != len(m.mapVal)-1 { + sb.WriteString(", ") } + i++ } + sb.WriteString("}") + return sb.String() +} + +func (m *nativeMap[K, V]) format(sb *strings.Builder) { + formatMap(m, sb) +} + +func (m *nativeMap[K, V]) Type() ref.Type { + return MapType +} + +func (m *nativeMap[K, V]) Value() any { + return m.mapVal } // protoMap is a specialized, separate implementation of the traits.Mapper interfaces tailored to // accessing protoreflect.Map values. type protoMap struct { Adapter - value *pb.Map + value *pb.Map + aggSize uint32 } // Contains returns whether the map contains the given key. @@ -909,6 +1355,26 @@ func (m *protoMap) Size() ref.Val { return Int(m.value.Len()) } +// AggregateSize implements the AggregateSizeVisitor interface method. +func (m *protoMap) AggregateSize(sizer AggregateSizer) uint32 { + if m.value == nil { + return 1 + } + if sz := atomic.LoadUint32(&m.aggSize); sz != 0 { + return sz + } + total := uint32(1) + m.value.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { + total = safeAddUint32(total, sizer.AggregateSize(k)) + total = safeAddUint32(total, sizer.AggregateSize(v)) + return true + }) + if cacheableAggregateSize(sizer) { + atomic.StoreUint32(&m.aggSize, total) + } + return total +} + // Type implements the ref.Val interface method. func (m *protoMap) Type() ref.Type { return MapType @@ -1006,6 +1472,14 @@ type interopFoldableMap struct { func (m interopFoldableMap) Fold(f traits.Folder) { it := m.Iterator() + if kf, ok := f.(interface{ FoldKeyOnly() bool }); ok && kf.FoldKeyOnly() { + for it.HasNext() == True { + if !f.FoldEntry(it.Next(), nil) { + break + } + } + return + } for it.HasNext() == True { k := it.Next() if !f.FoldEntry(k, m.Get(k)) { @@ -1068,3 +1542,11 @@ func isDelim(r rune) bool { func isLower(r rune) bool { return r >= 'a' && r <= 'z' } + +// heapCopy returns a pointer to a fresh heap copy of v. Taking &v directly would move the parameter +// to the heap on every call of the enclosing generic function, including calls that never box v. +func heapCopy[V any](v V) *V { + p := new(V) + *p = v + return p +} diff --git a/vendor/cel.dev/cel-go/common/types/memory_tracker.go b/vendor/cel.dev/cel-go/common/types/memory_tracker.go new file mode 100644 index 0000000000..ffa9fc15de --- /dev/null +++ b/vendor/cel.dev/cel-go/common/types/memory_tracker.go @@ -0,0 +1,181 @@ +// Copyright 2026 Google LLC +// +// 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 types + +import ( + "cel.dev/cel-go/common/types/ref" +) + +const ( + defaultMemoryTrackerSampleInterval = 1 +) + +// MemoryTrackerOption configures a MemoryTracker instance. +type MemoryTrackerOption func(*MemoryTracker) + +// MemoryTrackerLimit sets a limit on the peak aggregate memory observed during tracking. +// +// The tracker does not enforce the limit itself; callers should consult ExceedsLimit after +// tracking observations and terminate evaluation as appropriate. +func MemoryTrackerLimit(limit uint32) MemoryTrackerOption { + return func(t *MemoryTracker) { + t.limit = limit + t.hasLimit = true + } +} + +// MemoryTrackerSampleInterval configures how frequently Sample observations compute a size. +// +// An interval of N means every Nth call to Sample performs a size computation; intervening +// calls are skipped. Values less than 1 are treated as 1, meaning every sample is computed. +// Sampling bounds the tracking overhead for high-frequency observation points such as +// comprehension loops and bind initializers. +func MemoryTrackerSampleInterval(interval uint32) MemoryTrackerOption { + return func(t *MemoryTracker) { + if interval < 1 { + interval = 1 + } + t.sampleInterval = interval + } +} + +// MemoryTrackerSizeCalculator overrides the SizeCalculator used to compute value sizes. +func MemoryTrackerSizeCalculator(calc *SizeCalculator) MemoryTrackerOption { + return func(t *MemoryTracker) { + t.calc = calc + } +} + +// MemoryTracker records the peak aggregate memory observed during an evaluation. +// +// Memory is measured in aggregate element counts as computed by a SizeCalculator, with all +// arithmetic saturating at math.MaxUint32. The tracker is independent of any interpreter +// implementation; evaluators feed it observations at the points where values materialize +// during evaluation, such as resolved attributes, call results, constructed aggregates, and +// values built up within comprehensions or bind initializers. +// +// The peak is the largest single observation, where one Track call observes a value +// as a watermark. +// +// A MemoryTracker is stateful and intended for use by a single evaluation at a time; it is +// not safe for concurrent use. +type MemoryTracker struct { + version int + calc *SizeCalculator + limit uint32 + hasLimit bool + sampleInterval uint32 + + sampleCounts map[int64]uint32 + peak uint32 + calcLimitExceeded bool +} + +// NewMemoryTracker returns a new MemoryTracker configured with optional MemoryTrackerOption +// settings, using a default SizeCalculator when one is not provided. +func NewMemoryTracker(opts ...MemoryTrackerOption) *MemoryTracker { + t := &MemoryTracker{ + version: 0, + sampleInterval: defaultMemoryTrackerSampleInterval, + } + for _, opt := range opts { + opt(t) + } + if t.calc == nil { + t.calc = NewSizeCalculator() + } + return t +} + +// Version returns the tracking version. +func (t *MemoryTracker) Version() int { + return t.version +} + +// Track observes a value as a watermark, returning its aggregate size with saturation at math.MaxUint32. +func (t *MemoryTracker) Track(val ref.Val) uint32 { + if val == nil { + return 0 + } + switch v := val.(type) { + case Bool, Int, Uint, Double, Duration, Timestamp, Null, *Type, *Err, *Unknown: + if 1 > t.peak { + t.peak = 1 + } + return 1 + case String: + sz := t.calc.stringSize(len(v)) + if sz > t.peak { + t.peak = sz + } + return sz + case Bytes: + sz := t.calc.stringSize(len(v)) + if sz > t.peak { + t.peak = sz + } + return sz + } + + est := t.calc.ApproximateAggregateSize(val) + if est.LimitExceeded { + t.calcLimitExceeded = true + } + if est.Size > t.peak { + t.peak = est.Size + } + return est.Size +} + +// Sample observes a value for a specific node ID subject to the tracker's sample interval, +// returning the value's aggregate size when computed, or zero when the observation is skipped. +// +// The first observation of any node ID is always tracked; subsequent observations are sampled +// at multiples of the sample interval. +// +// Sample is intended for high-frequency observation points, such as accumulator values built +// up by comprehension loops or bind initializers, where sizing every iteration would be +// prohibitively expensive. +func (t *MemoryTracker) Sample(id int64, val ref.Val) uint32 { + if t.sampleCounts == nil { + t.sampleCounts = make(map[int64]uint32) + } + t.sampleCounts[id]++ + count := t.sampleCounts[id] + if count == 1 || t.sampleInterval <= 1 || count%t.sampleInterval == 0 { + return t.Track(val) + } + return 0 +} + +// Peak returns the largest single watermark observed, saturating at math.MaxUint32. +func (t *MemoryTracker) Peak() uint32 { + return t.peak +} + +// ExceedsLimit indicates whether the peak observed memory exceeds the configured limit. +// When no limit is configured, ExceedsLimit always returns false. +func (t *MemoryTracker) ExceedsLimit() bool { + return t.hasLimit && t.peak > t.limit +} + +// CalculationLimitExceeded indicates whether any tracked value was too expensive to size, +// causing the size computation to abort at the SizeCalculator's depth or traversal limits. +// +// Such observations saturate to math.MaxUint32; this signal distinguishes values which were +// too costly to measure from values whose measured size genuinely saturated uint32. +func (t *MemoryTracker) CalculationLimitExceeded() bool { + return t.calcLimitExceeded +} diff --git a/vendor/cel.dev/cel-go/common/types/native.go b/vendor/cel.dev/cel-go/common/types/native.go new file mode 100644 index 0000000000..31e51cf646 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/types/native.go @@ -0,0 +1,1668 @@ +// Copyright 2022 Google LLC +// +// 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 me. +// limitations under the License. + +package types + +import ( + "errors" + "fmt" + "reflect" + "strings" + "sync/atomic" + "time" + "unsafe" + + "google.golang.org/protobuf/reflect/protoreflect" + + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" + + structpb "google.golang.org/protobuf/types/known/structpb" +) + +var ( + nativeObjTraitMask = traits.FieldTesterType | traits.IndexerType + jsonValueType = reflect.TypeFor[*structpb.Value]() + jsonStructType = reflect.TypeFor[*structpb.Struct]() + + pbMsgInterfaceType = reflect.TypeFor[protoreflect.ProtoMessage]() + refValType = reflect.TypeFor[ref.Val]() + timestampType = reflect.TypeFor[time.Time]() + durationType = reflect.TypeFor[time.Duration]() + + errDuplicatedFieldName = errors.New("field name already exists in struct") +) + +// NewNativeType constructs a NativeType instance for a Go struct reflect.Type. +func NewNativeType(rawType reflect.Type, opts ...NativeTypeOption) (*NativeType, error) { + tpOptions := NativeTypeOptions{} + for _, opt := range opts { + if err := opt(&tpOptions); err != nil { + return nil, err + } + } + return newNativeType(rawType, tpOptions) +} + +// NativeTypesFieldNameHandler is a handler for mapping a reflect.StructField to a CEL field name. +// This can be used to override the default Go struct field to CEL field name mapping. +type NativeTypesFieldNameHandler = func(field reflect.StructField) string + +// NativeTypeOptions holds options for native types. +type NativeTypeOptions struct { + fieldNameHandler NativeTypesFieldNameHandler + typeName string + adapter Adapter +} + +// NativeTypeOption is a functional option for configuring handling of native types. +type NativeTypeOption func(*NativeTypeOptions) error + +// NativeTypeAdapter sets the TypeAdapter to use when adapting nested dynamic fields for a NativeType. +func NativeTypeAdapter(adapter Adapter) NativeTypeOption { + return func(opts *NativeTypeOptions) error { + opts.adapter = adapter + return nil + } +} + +// NativeTypeAlias configures a custom CEL type name (alias) for a native type. +func NativeTypeAlias(alias string) NativeTypeOption { + return func(opts *NativeTypeOptions) error { + opts.typeName = alias + return nil + } +} + +// NativeTypeDesc describes a native Go struct type for registration with CEL. +type NativeTypeDesc struct { + refType reflect.Type + options []NativeTypeOption +} + +// ReflectType returns the reflect.Type wrapped by this descriptor. +func (d *NativeTypeDesc) ReflectType() reflect.Type { + return d.refType +} + +// Options returns the NativeTypeOption slice for this descriptor. +func (d *NativeTypeDesc) Options() []NativeTypeOption { + return d.options +} + +// NativeTypeFor constructs a NativeTypeDesc for a Go struct type T with the given options. +func NativeTypeFor[T any](opts ...NativeTypeOption) *NativeTypeDesc { + return &NativeTypeDesc{ + refType: reflect.TypeFor[T](), + options: opts, + } +} + +// ParseStructTags configures if native types field names should be overridable by CEL struct tags. +// This is equivalent to ParseStructTag("cel"). +// +// A tag starting with "-" (e.g. `cel:"-"` or `cel:"-,"`) marks the field as skipped. +// A literal "-" can be specified by single-quoting the name (e.g. `cel:"'-'"`). +// +// Skipping an embedded struct also skips the fields promoted from it, so they cannot be +// reached through the enclosing struct. +// +// The configured tag only governs what is visible to CEL expressions. Serialization, whether +// via `ConvertToNative` to a protobuf `Struct`/`Value` or via the `json.encode` and +// `yaml.encode` extension functions, is governed by the `json` tag. A field tagged +// `cel:"-"` is therefore still serialized unless it is also tagged `json:"-"`, and a field +// tagged `json:"-"` is still visible to CEL unless it is also tagged `cel:"-"`. +// Configuring ParseStructTag("json") makes CEL visibility and serialization agree. +func ParseStructTags(enabled bool) NativeTypeOption { + if enabled { + return ParseStructTag("cel") + } + return ParseStructField(nil) +} + +// ParseStructTag configures the struct tag to parse. The 0th item in the tag is used as the name of the CEL field. +// +// A tag starting with "-" (e.g. `cel:"-"` or `cel:"-,"`) marks the field as skipped. +// A literal "-" can be specified by single-quoting the name (e.g. `cel:"'-'"`). +// +// Skipping an embedded struct also skips the fields promoted from it, so they cannot be +// reached through the enclosing struct. +// +// The configured tag only governs what is visible to CEL expressions; serialization is always +// governed by the `json` tag. See ParseStructTags for details. +func ParseStructTag(tag string) NativeTypeOption { + return ParseStructField(fieldNameByTag(tag)) +} + +// ParseStructField configures how to parse Go struct fields. It can be used to customize struct field parsing. +func ParseStructField(handler NativeTypesFieldNameHandler) NativeTypeOption { + return func(opts *NativeTypeOptions) error { + opts.fieldNameHandler = handler + return nil + } +} + +func fieldNameByTag(structTagToParse string) func(field reflect.StructField) string { + return func(field reflect.StructField) string { + tagInfo := parseStructTag(field, structTagToParse, field.Name) + if tagInfo.Skip { + return "-" + } + return tagInfo.Name + } +} + +func isSkippedFieldName(name string) bool { + return name == "" || name == "-" +} + +type nativeJSONField struct { + index []int + jsonName string + omitEmpty bool + hasTag bool +} + +// NativeType represents a CEL struct type descriptor generated from a native Go struct. +type NativeType struct { + typeName string + refType reflect.Type + fieldsByName map[string]reflect.StructField + jsonFields []nativeJSONField + adapter Adapter +} + +// Clone creates a copy of the NativeType with optional configuration overrides. +func (t *NativeType) Clone(opts ...NativeTypeOption) (*NativeType, error) { + if t == nil { + return nil, nil + } + if len(opts) == 0 { + cpy := *t + return &cpy, nil + } + tpOptions := NativeTypeOptions{ + typeName: t.typeName, + adapter: t.adapter, + } + for _, opt := range opts { + if err := opt(&tpOptions); err != nil { + return nil, err + } + } + if tpOptions.fieldNameHandler == nil { + return &NativeType{ + typeName: tpOptions.typeName, + refType: t.refType, + fieldsByName: t.fieldsByName, + jsonFields: t.jsonFields, + adapter: tpOptions.adapter, + }, nil + } + return newNativeType(t.refType, tpOptions) +} + +// ReflectType implements StructTypeDescriptor. +func (t *NativeType) ReflectType() reflect.Type { + return t.refType +} + +// Adapt implements StructTypeDescriptor. +func (t *NativeType) Adapt(adapter Adapter, value any) ref.Val { + if value == nil { + return NullValue + } + refVal := reflect.ValueOf(value) + var structPtr unsafe.Pointer + if refVal.Kind() == reflect.Ptr { + if refVal.IsNil() { + return NullValue + } + structPtr = unsafe.Pointer(refVal.Pointer()) + refVal = refVal.Elem() + } else if refVal.Kind() == reflect.Struct { + if !isDirectIface(t.refType) { + structPtr = anyDataPtr(value) + } else { + ptr := reflect.New(t.refType) + ptr.Elem().Set(refVal) + structPtr = unsafe.Pointer(ptr.Pointer()) + } + } + return &nativeObj{ + adapter: adapter, + val: value, + valType: t, + refValue: refVal, + structPtr: structPtr, + } +} + +// ConvertToNative implements ref.Val.ConvertToNative. +func (t *NativeType) ConvertToNative(typeDesc reflect.Type) (any, error) { + return nil, fmt.Errorf("type conversion error for type to '%v'", typeDesc) +} + +// ConvertToType implements ref.Val.ConvertToType. +func (t *NativeType) ConvertToType(typeVal ref.Type) ref.Val { + switch typeVal { + case TypeType: + return TypeType + } + return NewErr("type conversion error from '%s' to '%s'", TypeType, typeVal) +} + +// Equal returns true if both type names are equal to each other. +func (t *NativeType) Equal(other ref.Val) ref.Val { + otherType, ok := other.(ref.Type) + return Bool(ok && t.TypeName() == otherType.TypeName()) +} + +// HasTrait implements the ref.Type interface method. +func (t *NativeType) HasTrait(trait int) bool { + return nativeObjTraitMask&trait == trait +} + +// String implements the fmt.Stringer interface method. +func (t *NativeType) String() string { + return t.typeName +} + +// Type implements the ref.Val interface method. +func (t *NativeType) Type() ref.Type { + return TypeType +} + +// TypeName implements the ref.Type interface method. +func (t *NativeType) TypeName() string { + return t.typeName +} + +// Value implements the ref.Val interface method. +func (t *NativeType) Value() any { + return t.typeName +} + +// NativeToValue implements the ref.TypeAdapter interface method. +func (t *NativeType) NativeToValue(value any) ref.Val { + return t.adapterFrom(nil).NativeToValue(value) +} + +func (t *NativeType) hasField(fieldName string) (reflect.StructField, bool) { + f, found := t.fieldsByName[fieldName] + if !found { + return reflect.StructField{}, false + } + return f, true +} + +// FieldNames provides the list of field names for this type. +func (t *NativeType) FieldNames() []string { + fields := make([]string, 0, len(t.fieldsByName)) + for fieldName := range t.fieldsByName { + fields = append(fields, fieldName) + } + return fields +} + +// FindFieldType looks up a field by name and provides the type and accessors. +func (t *NativeType) FindFieldType(fieldName string) (*FieldType, bool) { + refField, found := t.hasField(fieldName) + if !found { + return nil, false + } + celType, ok := convertToCelType(refField.Type) + if !ok { + return nil, false + } + return &FieldType{ + Type: celType, + IsSet: t.makeFieldTester(refField), + GetFrom: t.makeFieldGetter(refField), + }, true +} + +// NewValue constructs a new native Go struct instance populated with given field values. +func (t *NativeType) NewValue(adapter Adapter, fields map[string]ref.Val) ref.Val { + refPtr := reflect.New(t.refType) + refVal := refPtr.Elem() + for fieldName, val := range fields { + refFieldDef, isDefined := t.hasField(fieldName) + if !isDefined { + return NewErr("no such field: %s", fieldName) + } + fieldVal, err := val.ConvertToNative(refFieldDef.Type) + if err != nil { + return NewErrFromString(err.Error()) + } + refField := safeSetFieldByIndex(refVal, refFieldDef.Index) + if !refField.IsValid() { + return NewErr("cannot set field: %s", fieldName) + } + refField.Set(reflect.ValueOf(fieldVal)) + } + return adapter.NativeToValue(refPtr.Interface()) +} + +type nativeObj struct { + adapter Adapter + val any + valType *NativeType + refValue reflect.Value + structPtr unsafe.Pointer + aggSize uint32 +} + +func (o *nativeObj) ConvertToNative(typeDesc reflect.Type) (any, error) { + if o.refValue.Type() == typeDesc { + if reflect.TypeOf(o.val) == typeDesc { + return o.val, nil + } + return o.refValue.Interface(), nil + } + if typeDesc.Kind() == reflect.Pointer && o.refValue.Type() == typeDesc.Elem() { + if reflect.TypeOf(o.val) == typeDesc { + return o.val, nil + } + ptr := reflect.New(o.refValue.Type()) + ptr.Elem().Set(o.refValue) + return ptr.Interface(), nil + } + switch typeDesc { + case jsonValueType: + jsonStruct, err := o.ConvertToNative(jsonStructType) + if err != nil { + return nil, err + } + return structpb.NewStructValue(jsonStruct.(*structpb.Struct)), nil + case jsonStructType: + refVal := reflect.Indirect(o.refValue) + fields := make(map[string]*structpb.Value, len(o.valType.jsonFields)) + for _, jf := range o.valType.jsonFields { + fieldValue := safeGetFieldByIndex(refVal, jf.index) + if !fieldValue.IsValid() { + continue + } + if fieldValue.IsZero() { + if !jf.hasTag || jf.omitEmpty || fieldValue.Kind() == reflect.Pointer || fieldValue.Kind() == reflect.Slice || fieldValue.Kind() == reflect.Map || fieldValue.Kind() == reflect.Interface { + continue + } + } + fieldCELVal := o.NativeToValue(fieldValue.Interface()) + fieldJSONVal, err := fieldCELVal.ConvertToNative(jsonValueType) + if err != nil { + return nil, err + } + fields[jf.jsonName] = fieldJSONVal.(*structpb.Value) + } + return &structpb.Struct{Fields: fields}, nil + } + return nil, fmt.Errorf("type conversion error from '%v' to '%v'", o.Type(), typeDesc) +} + +// NativeToValue implements the ref.TypeAdapter interface method. +func (o *nativeObj) NativeToValue(value any) ref.Val { + return o.adapterFrom().NativeToValue(value) +} + +type structTagInfo struct { + Name string + OmitEmpty bool + Skip bool + HasTag bool +} + +// parseStructTag parses a struct field's tag for the given tagName (e.g. "cel" or "json"). +// +// If the tag name or leading comma-separated segment is "-" (such as `json:"-"` or `json:"-,"`), +// the field is marked as skipped. To specify a literal "-" as the field name, single quotes +// can be used, such as `json:"'-'"`. +func parseStructTag(field reflect.StructField, tagName, defaultName string) structTagInfo { + tag, found := field.Tag.Lookup(tagName) + if !found { + return structTagInfo{Name: defaultName} + } + parts := strings.Split(tag, ",") + if parts[0] == "-" { + return structTagInfo{Skip: true, HasTag: true} + } + name := strings.Trim(parts[0], "'") + if name == "" { + name = defaultName + } + omitEmpty := false + for _, opt := range parts[1:] { + if opt == "omitempty" { + omitEmpty = true + } + } + return structTagInfo{ + Name: name, + OmitEmpty: omitEmpty, + HasTag: true, + } +} + +func (o *nativeObj) ConvertToType(typeVal ref.Type) ref.Val { + switch typeVal { + case TypeType: + return o.valType + default: + if typeVal.TypeName() == o.valType.typeName { + return o + } + } + return NewErr("type conversion error from '%s' to '%s'", o.Type(), typeVal) +} + +func (o *nativeObj) Equal(other ref.Val) ref.Val { + otherNtv, ok := other.(*nativeObj) + if !ok { + return False + } + val := o.val + otherVal := otherNtv.val + if reflect.TypeOf(val).Kind() != reflect.TypeOf(otherVal).Kind() { + val = o.refValue.Interface() + otherVal = otherNtv.refValue.Interface() + } + return Bool(reflect.DeepEqual(val, otherVal)) +} + +func (o *nativeObj) IsZeroValue() bool { + return o.refValue.IsZero() +} + +func (o *nativeObj) IsSet(field ref.Val) ref.Val { + refField, refErr := o.getReflectedField(field) + if refErr != nil { + return refErr + } + return Bool(refField.IsValid() && !refField.IsZero()) +} + +func (o *nativeObj) Get(field ref.Val) ref.Val { + refField, refErr := o.getReflectedField(field) + if refErr != nil { + return refErr + } + return adaptFieldValue(o.adapterFrom(), refField) +} + +func (o *nativeObj) adapterFrom() Adapter { + if o.adapter != nil { + return o.adapter + } + return o.valType.adapterFrom(nil) +} + +func (o *nativeObj) getReflectedField(field ref.Val) (reflect.Value, ref.Val) { + fieldName, ok := field.(String) + if !ok { + return reflect.Value{}, MaybeNoSuchOverloadErr(field) + } + fieldNameStr := string(fieldName) + refField, isDefined := o.valType.hasField(fieldNameStr) + if !isDefined { + return reflect.Value{}, NewErr("no such field: %s", fieldName) + } + refVal := reflect.Indirect(o.refValue) + return safeGetFieldByIndex(refVal, refField.Index), nil +} + +func (o *nativeObj) Type() ref.Type { + return o.valType +} + +func (o *nativeObj) Value() any { + return o.val +} + +// AggregateSize implements the AggregateSizeVisitor interface method. +func (o *nativeObj) AggregateSize(sizer AggregateSizer) uint32 { + if sz := atomic.LoadUint32(&o.aggSize); sz != 0 { + return sz + } + refVal := reflect.Indirect(o.refValue) + if !refVal.IsValid() { + return 1 + } + total := uint32(1) + for _, fieldType := range o.valType.fieldsByName { + fieldValue := safeGetFieldByIndex(refVal, fieldType.Index) + if !fieldValue.IsValid() || fieldValue.IsZero() { + continue + } + total = safeAddUint32(total, sizer.AggregateSize(fieldValue)) + } + if cacheableAggregateSize(sizer) { + atomic.StoreUint32(&o.aggSize, total) + } + return total +} + +func getNativeTypeName(refType reflect.Type, customName string) string { + if customName != "" { + return customName + } + return fmt.Sprintf("%s.%s", simplePkgAlias(refType.PkgPath()), refType.Name()) +} + +func newNativeTypes(rawType reflect.Type, options NativeTypeOptions) ([]*NativeType, error) { + nt, err := newNativeType(rawType, options) + if err != nil { + return nil, err + } + result := []*NativeType{nt} + + unwrappedRaw := rawType + if unwrappedRaw.Kind() == reflect.Pointer { + unwrappedRaw = unwrappedRaw.Elem() + } + alreadySeen := map[string]struct{}{ + unwrappedRaw.String(): {}, + } + var iterateStructMembers func(reflect.Type) + iterateStructMembers = func(t reflect.Type) { + if t.Implements(reflect.TypeFor[ref.Val]()) { + return + } + k := t.Kind() + if k == reflect.Pointer || k == reflect.Slice || k == reflect.Array { + iterateStructMembers(t.Elem()) + return + } + if k == reflect.Map { + iterateStructMembers(t.Key()) + iterateStructMembers(t.Elem()) + return + } + if t.Kind() != reflect.Struct { + return + } + if _, seen := alreadySeen[t.String()]; seen { + return + } + alreadySeen[t.String()] = struct{}{} + // Nested member structs use fieldNameHandler only (custom typeName applies to root rawType) + nestedOpts := NativeTypeOptions{ + fieldNameHandler: options.fieldNameHandler, + adapter: options.adapter, + } + nt, ntErr := newNativeType(t, nestedOpts) + if ntErr != nil { + err = ntErr + return + } + result = append(result, nt) + + for _, field := range reflect.VisibleFields(t) { + if !field.IsExported() || !isSupportedType(field.Type) { + continue + } + iterateStructMembers(field.Type) + } + } + for _, field := range reflect.VisibleFields(unwrappedRaw) { + if !field.IsExported() || !isSupportedType(field.Type) { + continue + } + iterateStructMembers(field.Type) + } + + return result, err +} + +func toFieldName(f reflect.StructField, fieldNameHandler NativeTypesFieldNameHandler) string { + if fieldNameHandler == nil { + return f.Name + } + return fieldNameHandler(f) +} + +func newNativeType(rawType reflect.Type, options NativeTypeOptions) (*NativeType, error) { + refType := rawType + if refType.Kind() == reflect.Pointer { + refType = refType.Elem() + } + if !isValidObjectType(refType) { + return nil, fmt.Errorf("unsupported reflect.Type %v, must be reflect.Struct", rawType) + } + fieldsByName, err := celFieldsByName(refType, options.fieldNameHandler) + if err != nil { + return nil, err + } + return &NativeType{ + typeName: getNativeTypeName(refType, options.typeName), + refType: refType, + fieldsByName: fieldsByName, + jsonFields: jsonFieldsOf(refType, options.fieldNameHandler), + adapter: options.adapter, + }, nil +} + +// celFieldsByName determines the fields of a struct which are visible to CEL authors, keyed by +// their CEL field name. +// +// A field is visible unless it is skipped according to the configured field name handler, which +// consults the configured struct tag (e.g. `cel:"-"`). +func celFieldsByName(refType reflect.Type, handler NativeTypesFieldNameHandler) (map[string]reflect.StructField, error) { + skipped := func(f reflect.StructField) bool { + return isSkippedFieldName(toFieldName(f, handler)) + } + fieldsByName := make(map[string]reflect.StructField) + for _, field := range visibleFields(refType, skipped) { + fieldName := toFieldName(field, handler) + if _, found := fieldsByName[fieldName]; found { + return nil, fmt.Errorf("invalid field name `%s` in struct `%s`: %w", fieldName, refType.Name(), errDuplicatedFieldName) + } + fieldsByName[fieldName] = field + } + return fieldsByName, nil +} + +// jsonFieldsOf determines the fields of a struct which are included when serializing to JSON +// (and by extension YAML), along with their serialized names. +// +// A field is serialized unless it is skipped according to the `json` struct tag (`json:"-"`). +// Embedded structs follow encoding/json conventions: those without a json name are serialized +// inline via their promoted fields, those with a json name are serialized as a nested object. +// The serialized name is the json tag name when present, otherwise the CEL field name. +func jsonFieldsOf(refType reflect.Type, handler NativeTypesFieldNameHandler) []nativeJSONField { + skipped := func(f reflect.StructField) bool { + return parseStructTag(f, "json", "").Skip + } + var jsonFields []nativeJSONField + for _, field := range visibleFields(refType, skipped) { + if field.Anonymous && !hasJSONName(field) { + continue + } + if isPromotedThroughNamedJSONField(refType, field) { + continue + } + defaultName := toFieldName(field, handler) + if isSkippedFieldName(defaultName) { + defaultName = field.Name + } + tagInfo := parseStructTag(field, "json", defaultName) + jsonFields = append(jsonFields, nativeJSONField{ + index: field.Index, + jsonName: tagInfo.Name, + omitEmpty: tagInfo.OmitEmpty, + hasTag: tagInfo.HasTag, + }) + } + return jsonFields +} + +// visibleFields returns the exported, supported fields of a struct which are not skipped. +// +// A field is skipped when the predicate holds for the field itself or for any embedded struct +// through which the field is promoted, so that a skipped embedded struct cannot be reached via +// its members. +func visibleFields(refType reflect.Type, skipped func(reflect.StructField) bool) []reflect.StructField { + var fields []reflect.StructField + for _, field := range reflect.VisibleFields(refType) { + if !field.IsExported() || !isSupportedType(field.Type) { + continue + } + if isSkippedField(refType, field, skipped) { + continue + } + fields = append(fields, field) + } + return fields +} + +// isSkippedField reports whether the field, or any embedded struct through which it is +// promoted, satisfies the skip predicate. +func isSkippedField(refType reflect.Type, field reflect.StructField, skipped func(reflect.StructField) bool) bool { + if skipped(field) { + return true + } + for _, parent := range embeddedAncestors(refType, field) { + if skipped(parent) { + return true + } + } + return false +} + +// embeddedAncestors returns the chain of embedded struct fields through which a promoted +// field is reached, from outermost to innermost. The result is empty for direct fields. +func embeddedAncestors(refType reflect.Type, field reflect.StructField) []reflect.StructField { + if len(field.Index) <= 1 { + return nil + } + ancestors := make([]reflect.StructField, 0, len(field.Index)-1) + cur := refType + for _, idx := range field.Index[:len(field.Index)-1] { + if cur.Kind() == reflect.Pointer { + cur = cur.Elem() + } + if cur.Kind() != reflect.Struct || idx >= cur.NumField() { + return ancestors + } + parent := cur.Field(idx) + ancestors = append(ancestors, parent) + cur = parent.Type + } + return ancestors +} + +// hasJSONName reports whether the field carries a json tag with an explicit name. +func hasJSONName(field reflect.StructField) bool { + tagInfo := parseStructTag(field, "json", "") + return tagInfo.HasTag && tagInfo.Name != "" +} + +// isPromotedThroughNamedJSONField reports whether a promoted field is reached through an +// embedded struct with a json name, in which case the field is serialized within that +// struct's nested object rather than inline. +func isPromotedThroughNamedJSONField(refType reflect.Type, field reflect.StructField) bool { + for _, parent := range embeddedAncestors(refType, field) { + if hasJSONName(parent) { + return true + } + } + return false +} + +func adaptFieldValue(adapter Adapter, refField reflect.Value) ref.Val { + return adapter.NativeToValue(getFieldValue(adapter, refField)) +} + +func safeSetFieldByIndex(v reflect.Value, index []int) reflect.Value { + for _, i := range index { + if v.Kind() == reflect.Pointer { + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + v = v.Elem() + } + if v.Kind() != reflect.Struct || i >= v.NumField() { + return reflect.Value{} + } + v = v.Field(i) + } + return v +} + +func safeGetFieldByIndex(v reflect.Value, index []int) reflect.Value { + if v.Kind() == reflect.Pointer { + if v.IsNil() { + return reflect.Value{} + } + v = v.Elem() + } + if len(index) == 1 { + if v.Kind() != reflect.Struct || index[0] >= v.NumField() { + return reflect.Value{} + } + return v.Field(index[0]) + } + for _, i := range index { + if v.Kind() == reflect.Pointer { + if v.IsNil() { + v = reflect.Zero(v.Type().Elem()) + } else { + v = v.Elem() + } + } + if v.Kind() != reflect.Struct || i >= v.NumField() { + return reflect.Value{} + } + v = v.Field(i) + } + return v +} + +func structFieldOffset(rootType reflect.Type, index []int) (uintptr, bool) { + var offset uintptr + cur := rootType + for i, idx := range index { + if cur.Kind() != reflect.Struct || idx >= cur.NumField() { + return 0, false + } + sf := cur.Field(idx) + offset += sf.Offset + if i < len(index)-1 { + cur = sf.Type + } + } + return offset, true +} + +func (t *NativeType) expectedTypePtrs() (ptrTyp, structTyp unsafe.Pointer) { + ptrTyp = runtimeTypePtr(reflect.PointerTo(t.refType)) + if !isDirectIface(t.refType) { + structTyp = runtimeTypePtr(t.refType) + } + return ptrTyp, structTyp +} + +func (t *NativeType) structPtrFrom(obj any, expectedPtrTyp, expectedStructTyp unsafe.Pointer) (unsafe.Pointer, bool) { + e := unpackAny(obj) + if e.typ == expectedPtrTyp { + return e.ptr, e.ptr != nil + } + if expectedStructTyp != nil && e.typ == expectedStructTyp { + return e.ptr, e.ptr != nil + } + if no, ok := obj.(*nativeObj); ok && no.valType == t { + return no.structPtr, no.structPtr != nil + } + return nil, false +} + +func unwrapStruct(obj any) reflect.Value { + if no, ok := obj.(*nativeObj); ok { + return no.refValue + } + if rv, ok := obj.(ref.Val); ok { + obj = rv.Value() + } + return reflect.ValueOf(obj) +} + +func fieldTesterFor[T comparable](t *NativeType, refField reflect.StructField, offset uintptr, expectedPtrTyp, expectedStructTyp unsafe.Pointer) func(obj any) bool { + var zero T + return func(obj any) bool { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return *(*T)(unsafe.Add(ptr, offset)) != zero + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return refFieldVal.IsValid() && !refFieldVal.IsZero() + } +} + +func intFieldGetter[T ~int | ~int32 | ~int64](t *NativeType, refField reflect.StructField, offset uintptr, expectedPtrTyp, expectedStructTyp unsafe.Pointer) func(obj any) (any, error) { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return Int(*(*T)(unsafe.Add(ptr, offset))), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return Int(refFieldVal.Int()), nil + } +} + +func uintFieldGetter[T ~uint | ~uint32 | ~uint64](t *NativeType, refField reflect.StructField, offset uintptr, expectedPtrTyp, expectedStructTyp unsafe.Pointer) func(obj any) (any, error) { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return Uint(*(*T)(unsafe.Add(ptr, offset))), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return Uint(refFieldVal.Uint()), nil + } +} + +func floatFieldGetter[T ~float32 | ~float64](t *NativeType, refField reflect.StructField, offset uintptr, expectedPtrTyp, expectedStructTyp unsafe.Pointer) func(obj any) (any, error) { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return Double(*(*T)(unsafe.Add(ptr, offset))), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return Double(refFieldVal.Float()), nil + } +} + +func (t *NativeType) adapterFrom(obj any) Adapter { + if no, ok := obj.(*nativeObj); ok && no.adapter != nil { + return no.adapter + } + if t != nil && t.adapter != nil { + return t.adapter + } + return DefaultTypeAdapter +} + +func sliceFieldGetter[T any](t *NativeType, refField reflect.StructField, offset uintptr, expectedPtrTyp, expectedStructTyp unsafe.Pointer) func(obj any) (any, error) { + return func(obj any) (any, error) { + adapter := t.adapterFrom(obj) + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return NewList(adapter, *(*[]T)(unsafe.Add(ptr, offset))), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return NewList(adapter, refFieldVal.Interface().([]T)), nil + } +} + +func mapFieldGetter[K comparable, V any](t *NativeType, refField reflect.StructField, offset uintptr, expectedPtrTyp, expectedStructTyp unsafe.Pointer) func(obj any) (any, error) { + return func(obj any) (any, error) { + adapter := t.adapterFrom(obj) + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return NewMap(adapter, *(*map[K]V)(unsafe.Add(ptr, offset))), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return NewMap(adapter, refFieldVal.Interface().(map[K]V)), nil + } +} + +func (t *NativeType) makeFieldTester(refField reflect.StructField) func(obj any) bool { + if offset, ok := structFieldOffset(t.refType, refField.Index); ok { + expectedPtrTyp, expectedStructTyp := t.expectedTypePtrs() + switch refField.Type.Kind() { + case reflect.Bool: + return fieldTesterFor[bool](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Int: + return fieldTesterFor[int](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Int32: + return fieldTesterFor[int32](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Int64: + return fieldTesterFor[int64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Uint: + return fieldTesterFor[uint](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Uint32, reflect.Float32: + return fieldTesterFor[uint32](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Uint64, reflect.Float64: + return fieldTesterFor[uint64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.String: + return fieldTesterFor[string](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Pointer, reflect.Map, reflect.Slice, reflect.Chan, reflect.Func, reflect.UnsafePointer, reflect.Interface: + return fieldTesterFor[unsafe.Pointer](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Struct: + if refField.Type == timestampType { + return func(obj any) bool { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return !(*time.Time)(unsafe.Add(ptr, offset)).IsZero() + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return refFieldVal.IsValid() && !refFieldVal.IsZero() + } + } + return func(obj any) bool { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return !reflect.NewAt(refField.Type, unsafe.Add(ptr, offset)).Elem().IsZero() + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return refFieldVal.IsValid() && !refFieldVal.IsZero() + } + } + } + return func(obj any) bool { + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return refFieldVal.IsValid() && !refFieldVal.IsZero() + } +} + +func (t *NativeType) makeFieldGetter(refField reflect.StructField) func(obj any) (any, error) { + if offset, ok := structFieldOffset(t.refType, refField.Index); ok { + expectedPtrTyp, expectedStructTyp := t.expectedTypePtrs() + switch refField.Type.Kind() { + case reflect.Bool: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + if *(*bool)(unsafe.Add(ptr, offset)) { + return True, nil + } + return False, nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + if refFieldVal.Bool() { + return True, nil + } + return False, nil + } + case reflect.Int, reflect.Int32, reflect.Int64: + if refField.Type == durationType { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return Duration{Duration: *(*time.Duration)(unsafe.Add(ptr, offset))}, nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return Duration{Duration: time.Duration(refFieldVal.Int())}, nil + } + } + switch refField.Type.Kind() { + case reflect.Int: + return intFieldGetter[int](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Int32: + return intFieldGetter[int32](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Int64: + return intFieldGetter[int64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + } + case reflect.Uint, reflect.Uint32, reflect.Uint64: + switch refField.Type.Kind() { + case reflect.Uint: + return uintFieldGetter[uint](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Uint32: + return uintFieldGetter[uint32](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Uint64: + return uintFieldGetter[uint64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + } + case reflect.Float32: + return floatFieldGetter[float32](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.Float64: + return floatFieldGetter[float64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.String: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return String(*(*string)(unsafe.Add(ptr, offset))), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return String(refFieldVal.String()), nil + } + case reflect.Slice: + if refField.Type.Elem() == reflect.TypeOf(byte(0)) { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return Bytes(*(*[]byte)(unsafe.Add(ptr, offset))), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return Bytes(refFieldVal.Bytes()), nil + } + } + switch refField.Type { + case reflect.TypeFor[[]string](): + return sliceFieldGetter[string](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]ref.Val](): + return sliceFieldGetter[ref.Val](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]int](): + return sliceFieldGetter[int](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]int64](): + return sliceFieldGetter[int64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]float64](): + return sliceFieldGetter[float64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]bool](): + return sliceFieldGetter[bool](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]int32](): + return sliceFieldGetter[int32](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]uint](): + return sliceFieldGetter[uint](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]uint64](): + return sliceFieldGetter[uint64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]uint32](): + return sliceFieldGetter[uint32](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]float32](): + return sliceFieldGetter[float32](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]time.Time](): + return sliceFieldGetter[time.Time](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]time.Duration](): + return sliceFieldGetter[time.Duration](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[[]any](): + return sliceFieldGetter[any](t, refField, offset, expectedPtrTyp, expectedStructTyp) + default: + if meta := getDynamicSliceMeta(refField.Type); meta.supported { + elemType := meta.sliceType.Elem() + if meta.isPtrElem { + return func(obj any) (any, error) { + adapter := t.adapterFrom(obj) + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elems := *(*[]unsafe.Pointer)(unsafe.Add(ptr, offset)) + return &sliceList[unsafe.Pointer]{ + Adapter: adapter, + elems: elems, + elemTypePtr: meta.elemTypePtr, + meta: meta, + qualifyRawVal: canQualifyRawVal(adapter, elemType, meta.qualifyRawVal), + isNilSlice: elems == nil, + }, nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return NewDynamicList(adapter, refFieldVal.Interface()), nil + } + } + return func(obj any) (any, error) { + adapter := t.adapterFrom(obj) + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + hdr := *(*unsafeSlice)(unsafe.Add(ptr, offset)) + var bytes []byte + if hdr.Data != nil && hdr.Len > 0 { + bytes = unsafe.Slice((*byte)(hdr.Data), uintptr(hdr.Len)*meta.elemStride) + } + return &sliceList[byte]{ + Adapter: adapter, + elems: bytes, + elemTypePtr: meta.elemTypePtr, + meta: meta, + qualifyRawVal: canQualifyRawVal(adapter, elemType, meta.qualifyRawVal), + isNilSlice: hdr.Data == nil, + }, nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + if !refFieldVal.IsValid() { + return nil, nil + } + return NewDynamicList(adapter, refFieldVal.Interface()), nil + } + } + } + case reflect.Map: + switch refField.Type { + case reflect.TypeFor[map[string]string](): + return mapFieldGetter[string, string](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[map[string]any](): + return mapFieldGetter[string, any](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[map[ref.Val]ref.Val](): + return mapFieldGetter[ref.Val, ref.Val](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[map[int64]bool](): + return mapFieldGetter[int64, bool](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[map[string]int64](): + return mapFieldGetter[string, int64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[map[string]int](): + return mapFieldGetter[string, int](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[map[string]bool](): + return mapFieldGetter[string, bool](t, refField, offset, expectedPtrTyp, expectedStructTyp) + case reflect.TypeFor[map[string]float64](): + return mapFieldGetter[string, float64](t, refField, offset, expectedPtrTyp, expectedStructTyp) + } + case reflect.Struct: + if refField.Type == timestampType { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + tm := *(*time.Time)(unsafe.Add(ptr, offset)) + if tm.IsZero() { + return Timestamp{Time: time.Unix(0, 0)}, nil + } + return Timestamp{Time: tm}, nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + if !refField.Type.Implements(refValType) && !refField.Type.Implements(pbMsgInterfaceType) { + expectedFieldPtrTyp := runtimeTypePtr(reflect.PointerTo(refField.Type)) + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return packAny(expectedFieldPtrTyp, unsafe.Add(ptr, offset)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + case reflect.Pointer: + elemType := refField.Type.Elem() + switch elemType.Kind() { + case reflect.Bool: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil || !*(*bool)(elemPtr) { + return False, nil + } + return True, nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + case reflect.Int, reflect.Int32, reflect.Int64: + if elemType == durationType { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return Duration{Duration: 0}, nil + } + return Duration{Duration: *(*time.Duration)(elemPtr)}, nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + switch elemType.Kind() { + case reflect.Int: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return IntZero, nil + } + return Int(*(*int)(elemPtr)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + case reflect.Int32: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return IntZero, nil + } + return Int(*(*int32)(elemPtr)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + case reflect.Int64: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return IntZero, nil + } + return Int(*(*int64)(elemPtr)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + case reflect.Uint, reflect.Uint32, reflect.Uint64: + switch elemType.Kind() { + case reflect.Uint: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return Uint(0), nil + } + return Uint(*(*uint)(elemPtr)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + case reflect.Uint32: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return Uint(0), nil + } + return Uint(*(*uint32)(elemPtr)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + case reflect.Uint64: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return Uint(0), nil + } + return Uint(*(*uint64)(elemPtr)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + case reflect.Float32, reflect.Float64: + if elemType.Kind() == reflect.Float32 { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return Double(0), nil + } + return Double(*(*float32)(elemPtr)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return Double(0), nil + } + return Double(*(*float64)(elemPtr)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + case reflect.String: + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return String(""), nil + } + return String(*(*string)(elemPtr)), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + case reflect.Struct: + if elemType == timestampType { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return Timestamp{Time: time.Unix(0, 0)}, nil + } + tm := *(*time.Time)(elemPtr) + if tm.IsZero() { + return Timestamp{Time: time.Unix(0, 0)}, nil + } + return Timestamp{Time: tm}, nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + if !refField.Type.Implements(refValType) { + expectedFieldPtrTyp := runtimeTypePtr(refField.Type) + var zeroFieldPtr any + if isNullZeroPointerType(refField.Type) { + zeroFieldPtr = NullValue + } else { + zeroFieldPtr = reflect.New(elemType).Interface() + } + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + elemPtr := *(*unsafe.Pointer)(unsafe.Add(ptr, offset)) + if elemPtr == nil { + return zeroFieldPtr, nil + } + return packAny(expectedFieldPtrTyp, elemPtr), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + } + case reflect.Interface: + if refField.Type == reflect.TypeFor[any]() { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + val := *(*any)(unsafe.Add(ptr, offset)) + return t.adapterFrom(obj).NativeToValue(val), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + if refField.Type.Implements(refValType) { + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + val := *(*ref.Val)(unsafe.Add(ptr, offset)) + if val == nil { + return NullValue, nil + } + return val, nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + return func(obj any) (any, error) { + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + val := reflect.NewAt(refField.Type, unsafe.Add(ptr, offset)).Elem().Interface() + return t.adapterFrom(obj).NativeToValue(val), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(t.adapterFrom(obj), refFieldVal), nil + } + } + return func(obj any) (any, error) { + adapter := t.adapterFrom(obj) + if ptr, ok := t.structPtrFrom(obj, expectedPtrTyp, expectedStructTyp); ok { + return getFieldValue(adapter, reflect.NewAt(refField.Type, unsafe.Add(ptr, offset)).Elem()), nil + } + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(adapter, refFieldVal), nil + } + } + return func(obj any) (any, error) { + adapter := t.adapterFrom(obj) + refVal := unwrapStruct(obj) + refFieldVal := safeGetFieldByIndex(refVal, refField.Index) + return getFieldValue(adapter, refFieldVal), nil + } +} + +func isNullZeroPointerType(t reflect.Type) bool { + switch t { + case boolWrapperType, byteWrapperType, doubleWrapperType, floatWrapperType, + int32WrapperType, int64WrapperType, stringWrapperType, uint32WrapperType, + uint64WrapperType, jsonValueType, anyValueType: + return true + default: + return false + } +} + +func getFieldValue(adapter Adapter, refField reflect.Value) any { + if adapter == nil { + adapter = DefaultTypeAdapter + } + if !refField.IsValid() { + return nil + } + switch refField.Kind() { + case reflect.Bool: + if refField.Bool() { + return True + } + return False + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if refField.Type() == durationType { + return Duration{Duration: time.Duration(refField.Int())} + } + return Int(refField.Int()) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return Uint(refField.Uint()) + case reflect.Float32, reflect.Float64: + return Double(refField.Float()) + case reflect.String: + return String(refField.String()) + case reflect.Slice: + if refField.Type().Elem() == reflect.TypeOf(byte(0)) { + return Bytes(refField.Bytes()) + } + if refField.Type() == reflect.TypeFor[[]string]() { + return NewStringList(adapter, refField.Interface().([]string)) + } + if refField.Type() == reflect.TypeFor[[]ref.Val]() { + return NewRefValList(adapter, refField.Interface().([]ref.Val)) + } + case reflect.Map: + if refField.Type() == reflect.TypeFor[map[string]string]() { + return NewStringStringMap(adapter, refField.Interface().(map[string]string)) + } + if refField.Type() == reflect.TypeFor[map[string]any]() { + return NewStringInterfaceMap(adapter, refField.Interface().(map[string]any)) + } + if refField.Type() == reflect.TypeFor[map[ref.Val]ref.Val]() { + return NewRefValMap(adapter, refField.Interface().(map[ref.Val]ref.Val)) + } + case reflect.Struct: + if refField.Type() == timestampType { + if refField.IsZero() { + return Timestamp{Time: time.Unix(0, 0)} + } + return Timestamp{Time: refField.Interface().(time.Time)} + } + case reflect.Pointer: + if refField.IsZero() { + if isNullZeroPointerType(refField.Type()) { + return NullValue + } + elemType := refField.Type().Elem() + switch elemType.Kind() { + case reflect.Bool: + return False + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if elemType == durationType { + return Duration{Duration: 0} + } + return IntZero + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return Uint(0) + case reflect.Float32, reflect.Float64: + return Double(0) + case reflect.String: + return String("") + case reflect.Struct: + if elemType == timestampType { + return Timestamp{Time: time.Unix(0, 0)} + } + } + return reflect.New(elemType).Interface() + } + elemType := refField.Type().Elem() + switch elemType.Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64, reflect.String: + return getFieldValue(adapter, refField.Elem()) + case reflect.Struct: + if elemType == timestampType { + return getFieldValue(adapter, refField.Elem()) + } + } + case reflect.Interface: + if refField.IsNil() { + return NullValue + } + return adapter.NativeToValue(refField.Interface()) + } + return refField.Interface() +} + +func simplePkgAlias(pkgPath string) string { + paths := strings.Split(pkgPath, "/") + return paths[len(paths)-1] +} + +func isValidObjectType(refType reflect.Type) bool { + return refType.Kind() == reflect.Struct +} + +func isSupportedType(refType reflect.Type) bool { + switch refType.Kind() { + case reflect.Chan, reflect.Complex64, reflect.Complex128, reflect.Func, reflect.UnsafePointer, reflect.Uintptr: + return false + case reflect.Array, reflect.Slice: + return isSupportedType(refType.Elem()) + case reflect.Map: + return isSupportedType(refType.Key()) && isSupportedType(refType.Elem()) + } + return true +} + +func convertToCelType(refType reflect.Type) (*Type, bool) { + switch refType.Kind() { + case reflect.Bool: + return BoolType, true + case reflect.Float32, reflect.Float64: + return DoubleType, true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if refType == durationType { + return DurationType, true + } + return IntType, true + case reflect.String: + return StringType, true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return UintType, true + case reflect.Array, reflect.Slice: + refElem := refType.Elem() + if refElem.Kind() == reflect.Uint8 { + return BytesType, true + } + elemType, ok := convertToCelType(refElem) + if !ok { + return nil, false + } + return NewListType(elemType), true + case reflect.Map: + keyType, ok := convertToCelType(refType.Key()) + if !ok { + return nil, false + } + elemType, ok := convertToCelType(refType.Elem()) + if !ok { + return nil, false + } + return NewMapType(keyType, elemType), true + case reflect.Struct: + if refType == timestampType { + return TimestampType, true + } + if refType.Implements(refValType) { + emptyCelVal := reflect.New(refType).Elem().Interface().(ref.Val) + return emptyCelVal.Type().(*Type), true + } + return NewObjectType(getNativeTypeName(refType, "")), true + case reflect.Pointer: + if refType.Implements(refValType) { + emptyCelVal := reflect.New(refType.Elem()).Interface().(ref.Val) + return emptyCelVal.Type().(*Type), true + } + if refType.Implements(pbMsgInterfaceType) { + pbMsg := reflect.New(refType.Elem()).Interface().(protoreflect.ProtoMessage) + return NewObjectType(string(pbMsg.ProtoReflect().Descriptor().FullName())), true + } + return convertToCelType(refType.Elem()) + case reflect.Interface: + return DynType, true + } + return nil, false +} diff --git a/vendor/github.com/google/cel-go/common/types/null.go b/vendor/cel.dev/cel-go/common/types/null.go similarity index 98% rename from vendor/github.com/google/cel-go/common/types/null.go rename to vendor/cel.dev/cel-go/common/types/null.go index 671e1ee5c0..990609c695 100644 --- a/vendor/github.com/google/cel-go/common/types/null.go +++ b/vendor/cel.dev/cel-go/common/types/null.go @@ -21,7 +21,7 @@ import ( "google.golang.org/protobuf/proto" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" diff --git a/vendor/github.com/google/cel-go/common/types/object.go b/vendor/cel.dev/cel-go/common/types/object.go similarity index 89% rename from vendor/github.com/google/cel-go/common/types/object.go rename to vendor/cel.dev/cel-go/common/types/object.go index bb2a09e879..82bc3e330d 100644 --- a/vendor/github.com/google/cel-go/common/types/object.go +++ b/vendor/cel.dev/cel-go/common/types/object.go @@ -19,13 +19,14 @@ import ( "reflect" "sort" "strings" + "sync/atomic" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "github.com/google/cel-go/common/types/pb" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/pb" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" @@ -36,6 +37,7 @@ type protoObj struct { value proto.Message typeDesc *pb.TypeDescription typeValue ref.Val + aggSize uint32 } // NewObject returns an object based on a proto.Message value which handles @@ -167,9 +169,23 @@ func (o *protoObj) Value() any { return o.value } -type protoObjField struct { - fd protoreflect.FieldDescriptor - v protoreflect.Value +// AggregateSize implements the AggregateSizeVisitor interface method. +func (o *protoObj) AggregateSize(sizer AggregateSizer) uint32 { + if o.value == nil { + return 1 + } + if sz := atomic.LoadUint32(&o.aggSize); sz != 0 { + return sz + } + total := uint32(1) + o.value.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + total = safeAddUint32(total, sizer.AggregateSize(v)) + return true + }) + if cacheableAggregateSize(sizer) { + atomic.StoreUint32(&o.aggSize, total) + } + return total } func (o *protoObj) format(sb *strings.Builder) { diff --git a/vendor/github.com/google/cel-go/common/types/optional.go b/vendor/cel.dev/cel-go/common/types/optional.go similarity index 88% rename from vendor/github.com/google/cel-go/common/types/optional.go rename to vendor/cel.dev/cel-go/common/types/optional.go index 0d861823d2..71e9b5cab9 100644 --- a/vendor/github.com/google/cel-go/common/types/optional.go +++ b/vendor/cel.dev/cel-go/common/types/optional.go @@ -20,7 +20,7 @@ import ( "reflect" "strings" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) var ( @@ -120,3 +120,14 @@ func (o *Optional) Value() any { } return o.value.Value() } + +// AggregateSize implements the AggregateSizeVisitor interface method. +// +// An empty optional has size 1, as every value does, so that the aggregate size of a container +// is at least 1 plus the number of entries it holds. +func (o *Optional) AggregateSize(sizer AggregateSizer) uint32 { + if !o.HasValue() { + return 1 + } + return safeAddUint32(1, sizer.AggregateSize(o.value)) +} diff --git a/vendor/github.com/google/cel-go/common/types/overflow.go b/vendor/cel.dev/cel-go/common/types/overflow.go similarity index 97% rename from vendor/github.com/google/cel-go/common/types/overflow.go rename to vendor/cel.dev/cel-go/common/types/overflow.go index dcb66ef596..49b15377fc 100644 --- a/vendor/github.com/google/cel-go/common/types/overflow.go +++ b/vendor/cel.dev/cel-go/common/types/overflow.go @@ -427,3 +427,24 @@ func uint64ToInt64Lossless(v uint64) (int64, bool) { i, err := uint64ToInt64Checked(v) return i, err == nil } + +func safeAddUint32(a, b uint32) uint32 { + if math.MaxUint32-a < b { + return math.MaxUint32 + } + return a + b +} + +func safeUint32FromInt(n int) uint32 { + if n < 0 || uint64(n) > math.MaxUint32 { + return math.MaxUint32 + } + return uint32(n) +} + +func safeUint32FromBoxedInt(v Int) uint32 { + if v < 0 || v > math.MaxUint32 { + return math.MaxUint32 + } + return uint32(v) +} diff --git a/vendor/github.com/google/cel-go/common/types/pb/BUILD.bazel b/vendor/cel.dev/cel-go/common/types/pb/BUILD.bazel similarity index 96% rename from vendor/github.com/google/cel-go/common/types/pb/BUILD.bazel rename to vendor/cel.dev/cel-go/common/types/pb/BUILD.bazel index e2b9d37b56..66d333c368 100644 --- a/vendor/github.com/google/cel-go/common/types/pb/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/types/pb/BUILD.bazel @@ -15,7 +15,7 @@ go_library( "pb.go", "type.go", ], - importpath = "github.com/google/cel-go/common/types/pb", + importpath = "cel.dev/cel-go/common/types/pb", deps = [ "@org_golang_google_genproto_googleapis_api//expr/v1alpha1:go_default_library", "@org_golang_google_protobuf//encoding/protowire:go_default_library", diff --git a/vendor/github.com/google/cel-go/common/types/pb/checked.go b/vendor/cel.dev/cel-go/common/types/pb/checked.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/pb/checked.go rename to vendor/cel.dev/cel-go/common/types/pb/checked.go diff --git a/vendor/github.com/google/cel-go/common/types/pb/enum.go b/vendor/cel.dev/cel-go/common/types/pb/enum.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/pb/enum.go rename to vendor/cel.dev/cel-go/common/types/pb/enum.go diff --git a/vendor/github.com/google/cel-go/common/types/pb/equal.go b/vendor/cel.dev/cel-go/common/types/pb/equal.go similarity index 95% rename from vendor/github.com/google/cel-go/common/types/pb/equal.go rename to vendor/cel.dev/cel-go/common/types/pb/equal.go index 76893d85ea..275a2a61c9 100644 --- a/vendor/github.com/google/cel-go/common/types/pb/equal.go +++ b/vendor/cel.dev/cel-go/common/types/pb/equal.go @@ -29,10 +29,10 @@ import ( // // - Messages must share the same instance of the type descriptor // - Known set fields are compared using semantics equality -// - Bytes are compared using bytes.Equal -// - Scalar values are compared with operator == -// - List and map types are equal if they have the same length and all elements are equal -// - Messages are equal if they share the same descriptor and all set fields are equal +// - Bytes are compared using bytes.Equal +// - Scalar values are compared with operator == +// - List and map types are equal if they have the same length and all elements are equal +// - Messages are equal if they share the same descriptor and all set fields are equal // - Unknown fields are compared using byte equality // - NaN values are not equal to each other // - google.protobuf.Any values are unpacked before comparison diff --git a/vendor/github.com/google/cel-go/common/types/pb/file.go b/vendor/cel.dev/cel-go/common/types/pb/file.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/pb/file.go rename to vendor/cel.dev/cel-go/common/types/pb/file.go diff --git a/vendor/github.com/google/cel-go/common/types/pb/pb.go b/vendor/cel.dev/cel-go/common/types/pb/pb.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/pb/pb.go rename to vendor/cel.dev/cel-go/common/types/pb/pb.go diff --git a/vendor/github.com/google/cel-go/common/types/pb/type.go b/vendor/cel.dev/cel-go/common/types/pb/type.go similarity index 93% rename from vendor/github.com/google/cel-go/common/types/pb/type.go rename to vendor/cel.dev/cel-go/common/types/pb/type.go index 8d7d1b299f..92c2a2d362 100644 --- a/vendor/github.com/google/cel-go/common/types/pb/type.go +++ b/vendor/cel.dev/cel-go/common/types/pb/type.go @@ -258,21 +258,31 @@ func (fd *FieldDescription) Documentation() string { // This function implements the FieldType.IsSet function contract which can be used to operate on // more than just protobuf field accesses; however, the target here must be a protobuf.Message. func (fd *FieldDescription) IsSet(target any) bool { + var pbRef protoreflect.Message switch v := target.(type) { case proto.Message: - pbRef := v.ProtoReflect() - pbDesc := pbRef.Descriptor() - if pbDesc == fd.desc.ContainingMessage() { - // When the target protobuf shares the same message descriptor instance as the field - // descriptor, use the cached field descriptor value. - return pbRef.Has(fd.desc) - } - // Otherwise, fallback to a dynamic lookup of the field descriptor from the target - // instance as an attempt to use the cached field descriptor will result in a panic. - return pbRef.Has(pbDesc.Fields().ByName(protoreflect.Name(fd.Name()))) + pbRef = v.ProtoReflect() + case protoreflect.Message: + pbRef = v default: return false } + if pbRef == nil || !pbRef.IsValid() { + return false + } + pbDesc := pbRef.Descriptor() + if pbDesc == fd.desc.ContainingMessage() || (fd.desc.IsExtension() && pbDesc.FullName() == fd.desc.ContainingMessage().FullName()) { + // When the target protobuf shares the same message descriptor instance as the field + // descriptor, use the cached field descriptor value. + return pbRef.Has(fd.desc) + } + // Otherwise, fallback to a dynamic lookup of the field descriptor from the target + // instance as an attempt to use the cached field descriptor will result in a panic. + f := pbDesc.Fields().ByName(protoreflect.Name(fd.Name())) + if f == nil { + return false + } + return pbRef.Has(f) } // GetFrom returns the accessor method associated with the field on the proto generated struct. @@ -282,22 +292,33 @@ func (fd *FieldDescription) IsSet(target any) bool { // This function implements the FieldType.GetFrom function contract which can be used to operate // on more than just protobuf field accesses; however, the target here must be a protobuf.Message. func (fd *FieldDescription) GetFrom(target any) (any, error) { - v, ok := target.(proto.Message) - if !ok { + var pbRef protoreflect.Message + switch v := target.(type) { + case proto.Message: + pbRef = v.ProtoReflect() + case protoreflect.Message: + pbRef = v + default: + return nil, fmt.Errorf("unsupported field selection target: (%T)%v", target, target) + } + if pbRef == nil { return nil, fmt.Errorf("unsupported field selection target: (%T)%v", target, target) } - pbRef := v.ProtoReflect() pbDesc := pbRef.Descriptor() - var fieldVal any - if pbDesc == fd.desc.ContainingMessage() { + var f protoreflect.FieldDescriptor + if pbDesc == fd.desc.ContainingMessage() || (fd.desc.IsExtension() && pbDesc.FullName() == fd.desc.ContainingMessage().FullName()) { // When the target protobuf shares the same message descriptor instance as the field // descriptor, use the cached field descriptor value. - fieldVal = pbRef.Get(fd.desc).Interface() + f = fd.desc } else { // Otherwise, fallback to a dynamic lookup of the field descriptor from the target // instance as an attempt to use the cached field descriptor will result in a panic. - fieldVal = pbRef.Get(pbDesc.Fields().ByName(protoreflect.Name(fd.Name()))).Interface() + f = pbDesc.Fields().ByName(protoreflect.Name(fd.Name())) + if f == nil { + return nil, fmt.Errorf("unsupported field selection target: (%T)%v", target, target) + } } + fieldVal := pbRef.Get(f).Interface() switch fv := fieldVal.(type) { // Fast-path return for primitive types. case bool, []byte, float32, float64, int32, int64, string, uint32, uint64, protoreflect.List: diff --git a/vendor/github.com/google/cel-go/common/types/provider.go b/vendor/cel.dev/cel-go/common/types/provider.go similarity index 77% rename from vendor/github.com/google/cel-go/common/types/provider.go rename to vendor/cel.dev/cel-go/common/types/provider.go index 2321828d8a..cd3721c401 100644 --- a/vendor/github.com/google/cel-go/common/types/provider.go +++ b/vendor/cel.dev/cel-go/common/types/provider.go @@ -15,18 +15,21 @@ package types import ( + "encoding/json" "fmt" "maps" "reflect" + "sync" "sync/atomic" "time" + "unsafe" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "github.com/google/cel-go/common/types/pb" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/types/pb" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" anypb "google.golang.org/protobuf/types/known/anypb" @@ -242,6 +245,20 @@ func (p *Registry) ensureMutable() { p.revTypeMap = maps.Clone(p.revTypeMap) p.structTypes = maps.Clone(p.structTypes) p.reflectTypes = maps.Clone(p.reflectTypes) + for k, st := range p.structTypes { + if nt, isNative := st.(*NativeType); isNative { + cloned, _ := nt.Clone(NativeTypeAdapter(p)) + p.structTypes[k] = cloned + if rt := cloned.ReflectType(); rt != nil { + p.reflectTypes[rt] = cloned + if rt.Kind() == reflect.Ptr { + p.reflectTypes[rt.Elem()] = cloned + } else { + p.reflectTypes[reflect.PointerTo(rt)] = cloned + } + } + } + } p.pbdb = p.pbdb.Copy() p.shared.Store(false) } @@ -386,6 +403,9 @@ func (p *Registry) FindIdent(identName string) (ref.Val, bool) { if t, found := p.revTypeMap[identName]; found { return t, true } + if t, found := p.revTypeMap[sanitizeStructTypeName(identName)]; found { + return t, true + } if enumVal, found := p.pbdb.DescribeEnum(identName); found { return Int(enumVal.Value()), true } @@ -495,7 +515,8 @@ func (p *Registry) RegisterMessage(message proto.Message) error { // to CEL, even when they're not based on protobuf types. func (p *Registry) RegisterType(types ...ref.Type) error { for _, t := range types { - existing, found := p.revTypeMap[t.TypeName()] + typeName := sanitizeStructTypeName(t.TypeName()) + existing, found := p.revTypeMap[typeName] celType := maybeForeignType(t) if found { if !existing.IsEquivalentType(celType) { @@ -510,10 +531,17 @@ func (p *Registry) RegisterType(types ...ref.Type) error { } p.ensureMutable() - typeName := t.TypeName() p.revTypeMap[typeName] = celType if st, ok := t.(StructTypeDescriptor); ok { // Conflicts are gated above so if we see a struct here, it's safe to register. + if nt, isNative := t.(*NativeType); isNative { + cloned, err := nt.Clone(NativeTypeAdapter(p)) + if err != nil { + return err + } + t = cloned + st = cloned + } p.structTypes[typeName] = st if rt := st.ReflectType(); rt != nil { p.reflectTypes[rt] = st @@ -529,8 +557,16 @@ func (p *Registry) RegisterType(types ...ref.Type) error { } // RegisterNativeType creates nativeType instances for the given reflect.Type and registers them. -func (p *Registry) RegisterNativeType(refType reflect.Type) error { - result, err := newNativeTypes(refType, p.nativeOptions.fieldNameHandler) +func (p *Registry) RegisterNativeType(refType reflect.Type, opts ...NativeTypeOption) error { + nativeOpts := p.nativeOptions + // Note: consider cloning NativeType instances so that the registry may be reset if the type is copied to another registry. + nativeOpts.adapter = p + for _, opt := range opts { + if err := opt(&nativeOpts); err != nil { + return err + } + } + result, err := newNativeTypes(refType, nativeOpts) if err != nil { return err } @@ -542,6 +578,14 @@ func (p *Registry) RegisterNativeType(refType reflect.Type) error { return nil } +// RegisterNativeTypeDesc creates nativeType instances for a NativeTypeDesc and registers them. +func (p *Registry) RegisterNativeTypeDesc(desc *NativeTypeDesc) error { + if desc == nil { + return nil + } + return p.RegisterNativeType(desc.ReflectType(), desc.Options()...) +} + func (p *Registry) findStructDescriptorByReflectType(rt reflect.Type) (StructTypeDescriptor, bool) { if rt == nil { return nil, false @@ -663,20 +707,66 @@ func (p *Registry) NativeToValue(value any) ref.Val { if v != nil { return Uint(*v) } + case json.Number: + if i, err := v.Int64(); err == nil { + return Int(i) + } + if f, err := v.Float64(); err == nil { + return Double(f) + } + case json.RawMessage: + var rawVal any + if err := json.Unmarshal(v, &rawVal); err == nil { + return p.NativeToValue(rawVal) + } case []byte: return Bytes(v) // specializations for common lists types. case []string: - return NewStringList(p, v) + return NewList(p, v) case []ref.Val: - return NewRefValList(p, v) + return NewList(p, v) + case []int: + return NewList(p, v) + case []int64: + return NewList(p, v) + case []int32: + return NewList(p, v) + case []uint: + return NewList(p, v) + case []uint64: + return NewList(p, v) + case []uint32: + return NewList(p, v) + case []float64: + return NewList(p, v) + case []float32: + return NewList(p, v) + case []bool: + return NewList(p, v) + case []any: + return NewList(p, v) // specializations for common map types. case map[string]string: - return NewStringStringMap(p, v) + return NewMap(p, v) case map[string]any: - return NewStringInterfaceMap(p, v) + return NewMap(p, v) case map[ref.Val]ref.Val: - return NewRefValMap(p, v) + return NewMap(p, v) + case map[int64]bool: + return NewMap(p, v) + case map[string]int64: + return NewMap(p, v) + case map[string]int: + return NewMap(p, v) + case map[string]bool: + return NewMap(p, v) + case map[string]float64: + return NewMap(p, v) + case map[int64]string: + return NewMap(p, v) + case map[int]string: + return NewMap(p, v) // additional specializations may be added upon request / need. case *anypb.Any: if v == nil { @@ -728,6 +818,9 @@ func (p *Registry) NativeToValue(value any) ref.Val { case protoreflect.List: return NewProtoList(p, v) case protoreflect.Message: + if v == nil { + return UnsupportedRefValConversionErr(v) + } return p.NativeToValue(v.Interface()) case protoreflect.Value: return p.NativeToValue(v.Interface()) @@ -842,13 +935,15 @@ func registerTypeItem(r *Registry, t any) error { return r.RegisterNativeType(v) case reflect.Value: return r.RegisterNativeType(v.Type()) + case *NativeTypeDesc: + return r.RegisterNativeTypeDesc(v) case NativeTypeOption: return v(&r.nativeOptions) case RegistryOption: _, err := v(r) return err default: - return fmt.Errorf("unsupported type: %v (%T) must be reflect.Type or reflect.Value", t, t) + return fmt.Errorf("unsupported type: %v (%T) must be reflect.Type, reflect.Value, or NativeTypeDesc", t, t) } } @@ -1008,6 +1103,203 @@ func fieldTypeConversionError(field *pb.FieldDescription, err error) error { return fmt.Errorf("field type conversion error for %v.%v value type: %v", msgName, field.Name(), err) } +// emptyInterface mirrors Go runtime's internal eface representation: +// +// type eface struct { +// _type *_type +// data unsafe.Pointer +// } +// +// It is used exclusively for zero-copy qualification and direct type extraction. +type emptyInterface struct { + typ unsafe.Pointer + ptr unsafe.Pointer +} + +// packAny constructs an empty interface value from a raw runtime *_type pointer and data pointer. +func packAny(typ, ptr unsafe.Pointer) any { + var a any + e := (*emptyInterface)(unsafe.Pointer(&a)) + e.typ = typ + e.ptr = ptr + return a +} + +// unpackAny extracts the raw runtime *_type and data pointers from an empty interface value. +func unpackAny(v any) emptyInterface { + return *(*emptyInterface)(unsafe.Pointer(&v)) +} + +// anyDataPtr returns the data pointer word from an empty interface value. +func anyDataPtr(v any) unsafe.Pointer { + return (*emptyInterface)(unsafe.Pointer(&v)).ptr +} + +// runtimeTypePtr returns the Go runtime *_type pointer for the given reflect.Type. +func runtimeTypePtr(rt reflect.Type) unsafe.Pointer { + return unpackAny(reflect.Zero(rt).Interface()).typ +} + +// elemTypePtrFor returns the runtime *_type pointer for T if and only if T is a non-empty +// raw struct type suitable for zero-copy boxing via packAny(typ, unsafe.Pointer(&elem)). +// +// For indirect-interface structs, data points to the struct value and typ is T's *_type. +// For single-pointer direct-interface structs, data holds the pointer directly at offset 0, +// so &elem has the exact representation of a *T in an emptyInterface and typ is *T's *_type. +func elemTypePtrFor[T any]() unsafe.Pointer { + t := reflect.TypeFor[T]() + if t.Kind() != reflect.Struct || t.Size() == 0 || !isQualifyRawStructType(t) { + return nil + } + var z T + if e := unpackAny(z); e.ptr != nil { + return e.typ + } + var zp *T + return unpackAny(zp).typ +} + +// elemTypePtrForType is the reflect.Type equivalent of elemTypePtrFor. +func elemTypePtrForType(elemType reflect.Type) unsafe.Pointer { + if elemType == nil || elemType.Kind() != reflect.Struct || elemType.Size() == 0 || !isQualifyRawStructType(elemType) { + return nil + } + if isDirectIface(elemType) { + return runtimeTypePtr(reflect.PointerTo(elemType)) + } + return runtimeTypePtr(elemType) +} + +// isDirectIface determines whether a type's values fit directly into an interface's data word +// according to Go runtime conventions (pointers, single-pointer structs/arrays, maps, funcs, chans). +func isDirectIface(t reflect.Type) bool { + switch t.Kind() { + case reflect.Pointer, reflect.UnsafePointer, reflect.Chan, reflect.Map, reflect.Func: + return true + case reflect.Struct: + return t.NumField() == 1 && isDirectIface(t.Field(0).Type) + case reflect.Array: + return t.Len() == 1 && isDirectIface(t.Elem()) + default: + return false + } +} + +type unsafeSlice struct { + Data unsafe.Pointer + Len int + Cap int +} + +type dynamicSliceMeta struct { + sliceType reflect.Type + sliceTypePtr unsafe.Pointer + elemTypePtr unsafe.Pointer + elemValTypePtr unsafe.Pointer + elemStride uintptr + qualifyRawVal bool + isDirectIface bool + isPtrElem bool + supported bool +} + +var dynamicSliceMetaCache sync.Map + +func isStandardAdapter(adapter Adapter) bool { + switch a := adapter.(type) { + case nil, *defaultTypeAdapter: + return true + case *Registry: + return a.adapter == nil + default: + return false + } +} + +func canQualifyRawVal(adapter Adapter, elemType reflect.Type, metaQualifyRaw bool) bool { + if !metaQualifyRaw { + return false + } + if isStandardAdapter(adapter) { + return true + } + if elemType != nil && elemType.Implements(refValType) { + return true + } + if reg, ok := adapter.(*Registry); ok && len(reg.reflectTypes) > 0 { + if st, found := reg.findStructDescriptorByReflectType(elemType); found { + _, isNative := st.(*NativeType) + return isNative + } + } + return false +} + +func isQualifyRawStructFor[T any](adapter Adapter) bool { + rt := reflect.TypeFor[T]() + if !isQualifyRawStructType(rt) { + return false + } + return canQualifyRawVal(adapter, rt, true) +} + +func isQualifyRawStructType(rt reflect.Type) bool { + if rt == nil { + return false + } + elem := rt + if rt.Kind() == reflect.Pointer { + elem = rt.Elem() + } + if elem.Kind() != reflect.Struct || elem == timestampType { + return false + } + return !rt.Implements(refValType) && !rt.Implements(pbMsgInterfaceType) +} + +var unsupportedDynamicSliceMeta = &dynamicSliceMeta{supported: false} + +func getDynamicSliceMeta(rt reflect.Type) *dynamicSliceMeta { + if rt == nil || rt.Kind() != reflect.Slice { + return unsupportedDynamicSliceMeta + } + if v, ok := dynamicSliceMetaCache.Load(rt); ok { + return v.(*dynamicSliceMeta) + } + sliceTypPtr := runtimeTypePtr(rt) + elemType := rt.Elem() + var meta *dynamicSliceMeta + switch elemType.Kind() { + case reflect.Pointer: + meta = &dynamicSliceMeta{ + sliceType: rt, + sliceTypePtr: sliceTypPtr, + elemTypePtr: runtimeTypePtr(elemType), + qualifyRawVal: isQualifyRawStructType(elemType) || elemType.Implements(refValType), + isPtrElem: true, + supported: true, + } + case reflect.Struct: + if elemTyp := elemTypePtrForType(elemType); elemTyp != nil { + meta = &dynamicSliceMeta{ + sliceType: rt, + sliceTypePtr: sliceTypPtr, + elemTypePtr: elemTyp, + elemValTypePtr: runtimeTypePtr(elemType), + elemStride: elemType.Size(), + qualifyRawVal: true, + isDirectIface: isDirectIface(elemType), + supported: true, + } + } + } + if meta != nil && meta.supported { + dynamicSliceMetaCache.Store(rt, meta) + return meta + } + return unsupportedDynamicSliceMeta +} + var ( // ProtoCELPrimitives provides a map from the protoreflect Kind to the equivalent CEL type. ProtoCELPrimitives = map[protoreflect.Kind]*Type{ diff --git a/vendor/github.com/google/cel-go/common/types/ref/BUILD.bazel b/vendor/cel.dev/cel-go/common/types/ref/BUILD.bazel similarity index 89% rename from vendor/github.com/google/cel-go/common/types/ref/BUILD.bazel rename to vendor/cel.dev/cel-go/common/types/ref/BUILD.bazel index 79330c3321..9df5779d8b 100644 --- a/vendor/github.com/google/cel-go/common/types/ref/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/types/ref/BUILD.bazel @@ -11,7 +11,7 @@ go_library( "provider.go", "reference.go", ], - importpath = "github.com/google/cel-go/common/types/ref", + importpath = "cel.dev/cel-go/common/types/ref", deps = [ "@org_golang_google_genproto_googleapis_api//expr/v1alpha1:go_default_library", "@org_golang_google_protobuf//proto:go_default_library", diff --git a/vendor/github.com/google/cel-go/common/types/ref/provider.go b/vendor/cel.dev/cel-go/common/types/ref/provider.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/ref/provider.go rename to vendor/cel.dev/cel-go/common/types/ref/provider.go diff --git a/vendor/github.com/google/cel-go/common/types/ref/reference.go b/vendor/cel.dev/cel-go/common/types/ref/reference.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/ref/reference.go rename to vendor/cel.dev/cel-go/common/types/ref/reference.go diff --git a/vendor/github.com/google/cel-go/common/types/regex.go b/vendor/cel.dev/cel-go/common/types/regex.go similarity index 96% rename from vendor/github.com/google/cel-go/common/types/regex.go rename to vendor/cel.dev/cel-go/common/types/regex.go index 14173eb522..286dd5ee4a 100644 --- a/vendor/github.com/google/cel-go/common/types/regex.go +++ b/vendor/cel.dev/cel-go/common/types/regex.go @@ -26,7 +26,7 @@ func RegexProgramSize(pattern string) (int, error) { if err != nil { return 0, err } - prog, err := syntax.Compile(re) + prog, err := syntax.Compile(re.Simplify()) if err != nil { return 0, err } diff --git a/vendor/cel.dev/cel-go/common/types/size_calc.go b/vendor/cel.dev/cel-go/common/types/size_calc.go new file mode 100644 index 0000000000..6093c80367 --- /dev/null +++ b/vendor/cel.dev/cel-go/common/types/size_calc.go @@ -0,0 +1,600 @@ +// Copyright 2026 Google LLC +// +// 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 types + +import ( + "math" + "reflect" + "sync" + "time" + + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" + + structpb "google.golang.org/protobuf/types/known/structpb" +) + +const ( + defaultSizeCalculatorMaxDepth = 5 + defaultSizeCalculatorMaxTraversal = 10000 + defaultSizeCalculatorStringUnitLength = 10 +) + +// SizeCalculatorOption configures a SizeCalculator instance. +type SizeCalculatorOption func(*SizeCalculator) + +// SizeCalculatorMaxDepth sets the maximum object depth limit before saturating to math.MaxUint32. +func SizeCalculatorMaxDepth(depth int) SizeCalculatorOption { + return func(s *SizeCalculator) { + s.maxDepth = depth + } +} + +// SizeCalculatorMaxTraversal sets the maximum object traversal limit before saturating to math.MaxUint32. +func SizeCalculatorMaxTraversal(traversal int) SizeCalculatorOption { + return func(s *SizeCalculator) { + s.maxTraversal = traversal + } +} + +// SizeCalculatorStringUnitLength sets the number of string or bytes value bytes which count as +// a single element (default 10). Values less than 1 are treated as 1, meaning each byte counts +// as a whole element. +// +// String sizes are measured in bytes rather than characters so that sizing large values is +// O(1) rather than a full UTF-8 scan per observation; byte length is never smaller than the +// character count, so byte-based sizing is conservative for limit enforcement. +func SizeCalculatorStringUnitLength(length int) SizeCalculatorOption { + return func(s *SizeCalculator) { + if length < 1 { + length = 1 + } + s.stringUnitLength = length + } +} + +// SizeCalculator calculates the recursive element size of values. +// +// Aggregate values may memoize their computed size on first calculation as an optimization +// for repeated sizing of shared structures. The memoized size reflects the configuration of +// the calculator which first sized the value; hosts requiring differently configured +// calculators, e.g. distinct depth or traversal limits, should not share value instances +// across them. Memoized totals are also a snapshot of the value's contents at first sizing: +// hosts which mutate data underlying a sized aggregate, e.g. a proto message held as a list +// element, will observe the total computed before the mutation. Sizes computed from +// calculations aborted at the depth or traversal limits are never memoized. +type SizeCalculator struct { + version int + maxDepth int + maxTraversal int + stringUnitLength int +} + +// NewSizeCalculator returns a new SizeCalculator configured with optional SizeCalculatorOption settings. +func NewSizeCalculator(opts ...SizeCalculatorOption) *SizeCalculator { + s := &SizeCalculator{ + version: 0, + maxDepth: defaultSizeCalculatorMaxDepth, + maxTraversal: defaultSizeCalculatorMaxTraversal, + stringUnitLength: defaultSizeCalculatorStringUnitLength, + } + for _, opt := range opts { + opt(s) + } + return s +} + +// Version returns the calculation version. +func (s *SizeCalculator) Version() int { + return s.version +} + +var sizeContextPool = sync.Pool{ + New: func() any { + return &sizeContext{} + }, +} + +type sizeContext struct { + calc *SizeCalculator + depth int + traversalCount int + limitExceeded bool +} + +func (c *sizeContext) visitNode() bool { + c.traversalCount++ + if c.traversalCount > c.calc.maxTraversal || c.depth > c.calc.maxDepth { + c.limitExceeded = true + return false + } + return true +} + +// aggregateSizeStatus exposes whether the in-flight size computation has exceeded the +// calculator's depth or traversal limits. +type aggregateSizeStatus interface { + aggregateSizeLimitExceeded() bool +} + +// aggregateSizeLimitExceeded implements the aggregateSizeStatus interface method. +func (c *sizeContext) aggregateSizeLimitExceeded() bool { + return c.limitExceeded +} + +// cacheableAggregateSize reports whether a size computed with the given sizer is safe to +// memoize on the value. Only totals from computations which verifiably stayed within the +// calculator's depth and traversal limits are stable properties of the value; totals from +// aborted computations depend on where in the traversal the value was encountered and would +// poison the memoized size. +func cacheableAggregateSize(sizer AggregateSizer) bool { + status, ok := sizer.(aggregateSizeStatus) + return ok && !status.aggregateSizeLimitExceeded() +} + +// ApproximateAggregateSize captures the outcome of an aggregate size computation. +// +// The Size saturates at math.MaxUint32 when the accumulated element count overflows uint32. +// LimitExceeded reports the computation was aborted because the value was too expensive to +// traverse (too deep, or too many nodes visited); in that case Size is also math.MaxUint32, +// but the value's true size may be smaller — the two conditions are distinguishable by the flag. +type ApproximateAggregateSize struct { + Size uint32 + LimitExceeded bool +} + +// ApproximateAggregateSize returns the aggregate size of the input value along with an indication +// of whether the computation was aborted due to the calculator's depth or traversal limits. +func (s *SizeCalculator) ApproximateAggregateSize(val any) ApproximateAggregateSize { + ctx := sizeContextPool.Get().(*sizeContext) + ctx.calc = s + est := ctx.estimateAggregateSize(val) + ctx.calc = nil + + sizeContextPool.Put(ctx) + return est +} + +// AggregateSize implements the AggregateSizer interface by returning the computed size. +func (s *SizeCalculator) AggregateSize(val any) uint32 { + return s.ApproximateAggregateSize(val).Size +} + +// stringSize converts a character or byte length to an element count where stringUnitLength +// characters count as a single element, rounding up with a minimum size of 1. +func (s *SizeCalculator) stringSize(length int) uint32 { + if length <= 0 { + return 1 + } + return safeUint32FromInt((length + s.stringUnitLength - 1) / s.stringUnitLength) +} + +// AggregateSize implements the ref.Val interface and allows for the generation of nested +// child context values which are necessary for correct traversal count tracking. +func (c *sizeContext) AggregateSize(val any) uint32 { + c.depth++ + res := c.aggregateSize(val) + c.depth-- + return res +} + +func (c *sizeContext) aggregateSize(val any) uint32 { + if !c.visitNode() { + return math.MaxUint32 + } + switch v := val.(type) { + case String: + return c.calc.stringSize(len(v)) + case Bytes: + return c.calc.stringSize(len(v)) + case AggregateSizeVisitor: + return v.AggregateSize(c) + case traits.Foldable: + f := foldableAggregateSizer{sizer: c, total: 1} + v.Fold(&f) + return f.total + case traits.Mapper: + total := uint32(1) + it := v.Iterator() + for it.HasNext() == True { + key := it.Next() + val, _ := v.Find(key) + total = safeAddUint32(total, c.AggregateSize(key)) + total = safeAddUint32(total, c.AggregateSize(val)) + } + return total + case traits.Lister: + total := uint32(1) + it := v.Iterator() + for it.HasNext() == True { + total = safeAddUint32(total, c.AggregateSize(it.Next())) + } + return total + case traits.Sizer: + return max(1, safeUint32FromBoxedInt(v.Size().(Int))) + case Bool, Int, Uint, Double, Duration, Timestamp, Null, *Type, *Err, *Unknown: + return 1 + case ref.Val: + return c.aggregateSize(v.Value()) + case protoreflect.Value: + return getProtoValueAggregateSize(c, v) + case protoreflect.MapKey: + return getProtoValueAggregateSize(c, v.Value()) + case protoreflect.Message: + return getProtoMessageAggregateSize(c, v) + case protoreflect.List: + return getProtoListAggregateSize(c, v) + case protoreflect.Map: + return getProtoMapAggregateSize(c, v) + case proto.Message: + if v == nil { + return 1 + } + return getProtoMessageAggregateSize(c, v.ProtoReflect()) + case string: + return c.calc.stringSize(len(v)) + case []byte: + return c.calc.stringSize(len(v)) + case int, int8, int16, int32, int64, + uint, uint8, uint16, uint32, uint64, + float32, float64, bool, time.Time, time.Duration, nil: + return 1 + case reflect.Value: + return getReflectValueAggregateSize(c, v) + default: + return getReflectValueAggregateSize(c, reflect.ValueOf(val)) + } +} + +// estimateAggregateSize evaluates the aggregate size using this context and resets state. +func (c *sizeContext) estimateAggregateSize(val any) ApproximateAggregateSize { + c.depth = 0 + c.traversalCount = 0 + c.limitExceeded = false + + size := c.AggregateSize(val) + return ApproximateAggregateSize{Size: size, LimitExceeded: c.limitExceeded} +} + +func getProtoValueAggregateSize(c *sizeContext, v protoreflect.Value) uint32 { + if !v.IsValid() { + return 1 + } + switch val := v.Interface().(type) { + case protoreflect.Message: + return getProtoMessageAggregateSize(c, val) + case protoreflect.List: + return getProtoListAggregateSize(c, val) + case protoreflect.Map: + return getProtoMapAggregateSize(c, val) + case string: + return c.calc.stringSize(len(val)) + case []byte: + return c.calc.stringSize(len(val)) + default: + return 1 + } +} + +func getProtoFieldAggregateSize(c *sizeContext, fd protoreflect.FieldDescriptor, v protoreflect.Value) uint32 { + if !c.visitNode() { + return math.MaxUint32 + } + if fd.IsMap() { + c.depth++ + sz := getProtoMapAggregateSize(c, v.Map()) + c.depth-- + return sz + } + if fd.IsList() { + c.depth++ + sz := getProtoListAggregateSize(c, v.List()) + c.depth-- + return sz + } + if fd.Message() != nil { + return c.AggregateSize(v.Message()) + } + switch fd.Kind() { + case protoreflect.StringKind: + return c.calc.stringSize(len(v.String())) + case protoreflect.BytesKind: + return c.calc.stringSize(len(v.Bytes())) + default: + return 1 + } +} + +func getProtoMessageAggregateSize(c *sizeContext, m protoreflect.Message) uint32 { + if !m.IsValid() { + return 1 + } + if !c.visitNode() { + return math.MaxUint32 + } + total := uint32(1) + m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + total = safeAddUint32(total, getProtoFieldAggregateSize(c, fd, v)) + return true + }) + return total +} + +func getProtoListAggregateSize(c *sizeContext, l protoreflect.List) uint32 { + if !l.IsValid() { + return 1 + } + if !c.visitNode() { + return math.MaxUint32 + } + total := uint32(1) + for i := range l.Len() { + total = safeAddUint32(total, c.AggregateSize(l.Get(i))) + } + return total +} + +func getProtoMapAggregateSize(c *sizeContext, m protoreflect.Map) uint32 { + if !m.IsValid() { + return 1 + } + if !c.visitNode() { + return math.MaxUint32 + } + total := uint32(1) + m.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { + total = safeAddUint32(total, c.AggregateSize(k)) + total = safeAddUint32(total, c.AggregateSize(v)) + return true + }) + return total +} + +// getSliceElementsAggregateSize computes the aggregate size of known slice payloads without reflection. +func getSliceElementsAggregateSize(sizer AggregateSizer, val any) (uint32, bool) { + switch v := val.(type) { + case []byte: + if sc, ok := sizer.(*sizeContext); ok { + return sc.calc.stringSize(len(v)), true + } + return 1, true + case []int: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []int8: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []int16: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []int32: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []int64: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []uint: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []uint16: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []uint32: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []uint64: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []float32: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []float64: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []bool: + return safeAddUint32(1, safeUint32FromInt(len(v))), true + case []string: + total := uint32(1) + for _, s := range v { + total = safeAddUint32(total, sizer.AggregateSize(s)) + } + return total, true + case []ref.Val: + total := uint32(1) + for _, elem := range v { + total = safeAddUint32(total, sizer.AggregateSize(elem)) + } + return total, true + case protoreflect.List: + total := uint32(1) + for i := range v.Len() { + total = safeAddUint32(total, sizer.AggregateSize(v.Get(i))) + } + return total, true + case *structpb.ListValue: + if v == nil { + return 1, true + } + total := uint32(1) + for _, elem := range v.GetValues() { + total = safeAddUint32(total, sizer.AggregateSize(elem)) + } + return total, true + case []any: + total := uint32(1) + for _, elem := range v { + total = safeAddUint32(total, sizer.AggregateSize(elem)) + } + return total, true + default: + return 0, false + } +} + +// getMapElementsAggregateSize computes the aggregate size of a map payload. +func getMapElementsAggregateSize(sizer AggregateSizer, val any) (uint32, bool) { + switch v := val.(type) { + case map[string]string: + total := uint32(1) + for k, val := range v { + total = safeAddUint32(total, sizer.AggregateSize(k)) + total = safeAddUint32(total, sizer.AggregateSize(val)) + } + return total, true + case map[string]any: + total := uint32(1) + for k, val := range v { + total = safeAddUint32(total, sizer.AggregateSize(k)) + total = safeAddUint32(total, sizer.AggregateSize(val)) + } + return total, true + case map[ref.Val]ref.Val: + total := uint32(1) + for k, val := range v { + total = safeAddUint32(total, sizer.AggregateSize(k)) + total = safeAddUint32(total, sizer.AggregateSize(val)) + } + return total, true + case *structpb.Struct: + if v == nil { + return 1, true + } + total := uint32(1) + for k, val := range v.GetFields() { + total = safeAddUint32(total, sizer.AggregateSize(k)) + total = safeAddUint32(total, sizer.AggregateSize(val)) + } + return total, true + default: + return 0, false + } +} + +func getReflectValueAggregateSize(c *sizeContext, fieldVal reflect.Value) uint32 { + if !fieldVal.IsValid() { + return 1 + } + if !c.visitNode() { + return math.MaxUint32 + } + switch fieldVal.Kind() { + case reflect.String: + return c.calc.stringSize(fieldVal.Len()) + case reflect.Slice: + elemType := fieldVal.Type().Elem() + if elemType.Kind() == reflect.Uint8 { + return c.calc.stringSize(fieldVal.Len()) + } + if fieldVal.CanInterface() { + if total, ok := getSliceElementsAggregateSize(c, fieldVal.Interface()); ok { + return total + } + } + total := safeAddUint32(1, safeUint32FromInt(fieldVal.Len())) + switch elemType.Kind() { + case reflect.String, reflect.Struct, reflect.Pointer, reflect.Slice, reflect.Array, reflect.Map, reflect.Interface: + total = 1 + for i := 0; i < fieldVal.Len(); i++ { + total = safeAddUint32(total, c.AggregateSize(fieldVal.Index(i))) + } + } + return total + case reflect.Array: + elemType := fieldVal.Type().Elem() + if elemType.Kind() == reflect.Uint8 { + return c.calc.stringSize(fieldVal.Len()) + } + total := safeAddUint32(1, safeUint32FromInt(fieldVal.Len())) + switch elemType.Kind() { + case reflect.String, reflect.Struct, reflect.Pointer, reflect.Slice, reflect.Array, reflect.Map, reflect.Interface: + total = 1 + for i := 0; i < fieldVal.Len(); i++ { + total = safeAddUint32(total, c.AggregateSize(fieldVal.Index(i))) + } + } + return total + case reflect.Map: + if fieldVal.CanInterface() { + if total, ok := getMapElementsAggregateSize(c, fieldVal.Interface()); ok { + return total + } + } + total := uint32(1) + iter := fieldVal.MapRange() + for iter.Next() { + total = safeAddUint32(total, c.AggregateSize(iter.Key())) + total = safeAddUint32(total, c.AggregateSize(iter.Value())) + } + return total + case reflect.Pointer, reflect.Interface: + if fieldVal.IsNil() { + return 1 + } + if sz, ok := checkCustomSizer(c, fieldVal); ok { + return sz + } + return getReflectValueAggregateSize(c, fieldVal.Elem()) + case reflect.Struct: + if fieldVal.Type() == timestampType || fieldVal.Type() == durationType { + return 1 + } + if sz, ok := checkCustomSizer(c, fieldVal); ok { + return sz + } + total := uint32(1) + t := fieldVal.Type() + numFields := fieldVal.NumField() + for i := range numFields { + if !t.Field(i).IsExported() { + continue + } + fVal := fieldVal.Field(i) + if !fVal.IsValid() || fVal.IsZero() { + continue + } + total = safeAddUint32(total, c.AggregateSize(fVal)) + } + return total + default: + return 1 + } +} + +var ( + aggregateSizeVisitorType = reflect.TypeFor[AggregateSizeVisitor]() + sizerType = reflect.TypeFor[traits.Sizer]() + protoMessageType = reflect.TypeFor[proto.Message]() +) + +func checkCustomSizer(c *sizeContext, fieldVal reflect.Value) (uint32, bool) { + if !fieldVal.IsValid() || !fieldVal.CanInterface() { + return 0, false + } + t := fieldVal.Type() + if t.Implements(aggregateSizeVisitorType) { + if sizer, ok := fieldVal.Interface().(AggregateSizeVisitor); ok { + return sizer.AggregateSize(c), true + } + } + if t.Implements(sizerType) { + if sizer, ok := fieldVal.Interface().(traits.Sizer); ok { + return max(1, safeUint32FromBoxedInt(sizer.Size().(Int))), true + } + } + if t.Implements(protoMessageType) { + if fieldVal.Kind() == reflect.Pointer && fieldVal.IsNil() { + return 1, true + } + if sizer, ok := fieldVal.Interface().(proto.Message); ok { + if sizer == nil { + return 1, true + } + return getProtoMessageAggregateSize(c, sizer.ProtoReflect()), true + } + } + return 0, false +} diff --git a/vendor/github.com/google/cel-go/common/types/string.go b/vendor/cel.dev/cel-go/common/types/string.go similarity index 87% rename from vendor/github.com/google/cel-go/common/types/string.go rename to vendor/cel.dev/cel-go/common/types/string.go index 1335903a7b..e2dde05bd6 100644 --- a/vendor/github.com/google/cel-go/common/types/string.go +++ b/vendor/cel.dev/cel-go/common/types/string.go @@ -22,8 +22,8 @@ import ( "strings" "time" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" @@ -41,7 +41,7 @@ var ( overloads.StartsWith: StringStartsWith, } - stringWrapperType = reflect.TypeOf(&wrapperspb.StringValue{}) + stringWrapperType = reflect.TypeFor[*wrapperspb.StringValue]() ) // Add implements traits.Adder.Add. @@ -59,7 +59,7 @@ func (s String) Compare(other ref.Val) ref.Val { if !ok { return MaybeNoSuchOverloadErr(other) } - return Int(strings.Compare(s.Value().(string), otherString.Value().(string))) + return Int(strings.Compare(string(s), string(otherString))) } // ConvertToNative implements ref.Val.ConvertToNative. @@ -80,7 +80,7 @@ func (s String) ConvertToNative(typeDesc reflect.Type) (any, error) { return wrapperspb.String(string(s)), nil } if typeDesc.Elem().Kind() == reflect.String { - p := s.Value().(string) + p := string(s) return &p, nil } case reflect.Interface: @@ -100,29 +100,29 @@ func (s String) ConvertToNative(typeDesc reflect.Type) (any, error) { func (s String) ConvertToType(typeVal ref.Type) ref.Val { switch typeVal { case IntType: - if n, err := strconv.ParseInt(s.Value().(string), 10, 64); err == nil { + if n, err := strconv.ParseInt(string(s), 10, 64); err == nil { return Int(n) } case UintType: - if n, err := strconv.ParseUint(s.Value().(string), 10, 64); err == nil { + if n, err := strconv.ParseUint(string(s), 10, 64); err == nil { return Uint(n) } case DoubleType: - if n, err := strconv.ParseFloat(s.Value().(string), 64); err == nil { + if n, err := strconv.ParseFloat(string(s), 64); err == nil { return Double(n) } case BoolType: - if b, err := strconv.ParseBool(s.Value().(string)); err == nil { + if b, err := strconv.ParseBool(string(s)); err == nil { return Bool(b) } case BytesType: return Bytes(s) case DurationType: - if d, err := time.ParseDuration(s.Value().(string)); err == nil { + if d, err := time.ParseDuration(string(s)); err == nil { return durationOf(d) } case TimestampType: - str := s.Value().(string) + str := string(s) if !isStrictRFC3339(str) { return NewErr("invalid RFC 3339 timestamp %q", str) } @@ -157,7 +157,7 @@ func (s String) Match(pattern ref.Val) ref.Val { if !ok { return MaybeNoSuchOverloadErr(pattern) } - matched, err := regexp.MatchString(pat.Value().(string), s.Value().(string)) + matched, err := regexp.MatchString(string(pat), string(s)) if err != nil { return &Err{error: err} } @@ -177,7 +177,7 @@ func (s String) Receive(function string, overload string, args []ref.Val) ref.Va // Size implements traits.Sizer.Size. func (s String) Size() ref.Val { - return Int(len([]rune(s.Value().(string)))) + return Int(len([]rune(s))) } // Type implements ref.Val.Type. diff --git a/vendor/github.com/google/cel-go/common/types/struct.go b/vendor/cel.dev/cel-go/common/types/struct.go similarity index 96% rename from vendor/github.com/google/cel-go/common/types/struct.go rename to vendor/cel.dev/cel-go/common/types/struct.go index 61740a70e1..0b50895a52 100644 --- a/vendor/github.com/google/cel-go/common/types/struct.go +++ b/vendor/cel.dev/cel-go/common/types/struct.go @@ -17,7 +17,7 @@ package types import ( "reflect" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // StructTypeDescriptor describes a CEL struct type, providing field metadata and value instantiation. diff --git a/vendor/github.com/google/cel-go/common/types/timestamp.go b/vendor/cel.dev/cel-go/common/types/timestamp.go similarity index 82% rename from vendor/github.com/google/cel-go/common/types/timestamp.go rename to vendor/cel.dev/cel-go/common/types/timestamp.go index aee47f0535..7b316c6d35 100644 --- a/vendor/github.com/google/cel-go/common/types/timestamp.go +++ b/vendor/cel.dev/cel-go/common/types/timestamp.go @@ -15,6 +15,8 @@ package types import ( + "encoding/json" + "errors" "fmt" "reflect" "regexp" @@ -23,8 +25,8 @@ import ( "time" "unicode" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" @@ -258,6 +260,90 @@ func (t Timestamp) format(sb *strings.Builder) { fmt.Fprintf(sb, `timestamp("%s")`, t.Time.UTC().Format(time.RFC3339Nano)) } +// ParseTimestamp attempts to parse a timestamp from various supported types and representations: +// - time.Time, Timestamp, *timestamppb.Timestamp +// - RFC 3339 and RFC 3339Nano formatted strings (e.g. "2023-01-01T00:00:00Z") +// - Unix epoch integers (int, int32, int64) +// - Unix epoch floating-point seconds (float32, float64) +// - json.Number +// - String representations of integers or floating-point epoch seconds +// +// If the parsed timestamp falls outside the supported range [minUnixTime, maxUnixTime], an error is returned. +func ParseTimestamp(val any) (time.Time, error) { + if val == nil { + return time.Time{}, errors.New("invalid timestamp: nil value") + } + switch v := val.(type) { + case time.Time: + return validateTimestampRange(v.UTC()) + case Timestamp: + return validateTimestampRange(v.Time.UTC()) + case *tpb.Timestamp: + if v == nil { + return time.Time{}, nil + } + return validateTimestampRange(v.AsTime().UTC()) + case int: + return validateTimestampRange(time.Unix(int64(v), 0).UTC()) + case int32: + return validateTimestampRange(time.Unix(int64(v), 0).UTC()) + case int64: + return validateTimestampRange(time.Unix(v, 0).UTC()) + case float32: + return unixTimeFromFloat(float64(v)) + case float64: + return unixTimeFromFloat(v) + case json.Number: + if i, err := v.Int64(); err == nil { + return validateTimestampRange(time.Unix(i, 0).UTC()) + } + if f, err := v.Float64(); err == nil { + return unixTimeFromFloat(f) + } + return ParseTimestamp(v.String()) + case string: + s := strings.TrimSpace(v) + if s == "" { + return time.Time{}, errors.New("invalid RFC 3339 timestamp: ''") + } + if isStrictRFC3339(s) { + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return time.Time{}, fmt.Errorf("invalid RFC 3339 timestamp %q", s) + } + return validateTimestampRange(t.UTC()) + } + if i, err := strconv.ParseInt(s, 10, 64); err == nil { + return validateTimestampRange(time.Unix(i, 0).UTC()) + } + if f, err := strconv.ParseFloat(s, 64); err == nil { + return unixTimeFromFloat(f) + } + return time.Time{}, fmt.Errorf("unsupported timestamp format: %q", s) + default: + return time.Time{}, fmt.Errorf("unsupported timestamp type: %T", val) + } +} + +func unixTimeFromFloat(f float64) (time.Time, error) { + sec, err := doubleToInt64Checked(f) + if err != nil { + return time.Time{}, err + } + nsec := int64((f - float64(sec)) * 1e9) + return validateTimestampRange(time.Unix(sec, nsec).UTC()) +} + +func validateTimestampRange(t time.Time) (time.Time, error) { + if t.IsZero() { + return t, nil + } + if t.Unix() < minUnixTime || t.Unix() > maxUnixTime { + return time.Time{}, fmt.Errorf("timestamp overflow: %v", t) + } + return t, nil +} + var ( timestampValueType = reflect.TypeOf(&tpb.Timestamp{}) diff --git a/vendor/github.com/google/cel-go/common/types/traits/BUILD.bazel b/vendor/cel.dev/cel-go/common/types/traits/BUILD.bazel similarity index 89% rename from vendor/github.com/google/cel-go/common/types/traits/BUILD.bazel rename to vendor/cel.dev/cel-go/common/types/traits/BUILD.bazel index b19eb8301e..e2f7d6fdb5 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/BUILD.bazel +++ b/vendor/cel.dev/cel-go/common/types/traits/BUILD.bazel @@ -22,7 +22,7 @@ go_library( "traits.go", "zeroer.go", ], - importpath = "github.com/google/cel-go/common/types/traits", + importpath = "cel.dev/cel-go/common/types/traits", deps = [ "//common/types/ref:go_default_library", ], diff --git a/vendor/github.com/google/cel-go/common/types/traits/comparer.go b/vendor/cel.dev/cel-go/common/types/traits/comparer.go similarity index 95% rename from vendor/github.com/google/cel-go/common/types/traits/comparer.go rename to vendor/cel.dev/cel-go/common/types/traits/comparer.go index b531d9ae2b..83b1395354 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/comparer.go +++ b/vendor/cel.dev/cel-go/common/types/traits/comparer.go @@ -15,7 +15,7 @@ package traits import ( - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // Comparer interface for ordering comparisons between values in order to diff --git a/vendor/github.com/google/cel-go/common/types/traits/container.go b/vendor/cel.dev/cel-go/common/types/traits/container.go similarity index 94% rename from vendor/github.com/google/cel-go/common/types/traits/container.go rename to vendor/cel.dev/cel-go/common/types/traits/container.go index cf5c621ae9..357ccd31d4 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/container.go +++ b/vendor/cel.dev/cel-go/common/types/traits/container.go @@ -14,7 +14,7 @@ package traits -import "github.com/google/cel-go/common/types/ref" +import "cel.dev/cel-go/common/types/ref" // Container interface which permits containment tests such as 'a in b'. type Container interface { diff --git a/vendor/github.com/google/cel-go/common/types/traits/field_tester.go b/vendor/cel.dev/cel-go/common/types/traits/field_tester.go similarity index 95% rename from vendor/github.com/google/cel-go/common/types/traits/field_tester.go rename to vendor/cel.dev/cel-go/common/types/traits/field_tester.go index 816a956523..d80351b40b 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/field_tester.go +++ b/vendor/cel.dev/cel-go/common/types/traits/field_tester.go @@ -15,7 +15,7 @@ package traits import ( - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // FieldTester indicates if a defined field on an object type is set to a diff --git a/vendor/github.com/google/cel-go/common/types/traits/indexer.go b/vendor/cel.dev/cel-go/common/types/traits/indexer.go similarity index 94% rename from vendor/github.com/google/cel-go/common/types/traits/indexer.go rename to vendor/cel.dev/cel-go/common/types/traits/indexer.go index 662c6836c3..2d1f72ae22 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/indexer.go +++ b/vendor/cel.dev/cel-go/common/types/traits/indexer.go @@ -15,7 +15,7 @@ package traits import ( - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // Indexer permits random access of elements by index 'a[b()]'. diff --git a/vendor/github.com/google/cel-go/common/types/traits/iterator.go b/vendor/cel.dev/cel-go/common/types/traits/iterator.go similarity index 97% rename from vendor/github.com/google/cel-go/common/types/traits/iterator.go rename to vendor/cel.dev/cel-go/common/types/traits/iterator.go index 91c10f08fc..f0a0b4cb9f 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/iterator.go +++ b/vendor/cel.dev/cel-go/common/types/traits/iterator.go @@ -15,7 +15,7 @@ package traits import ( - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // Iterable aggregate types permit traversal over their elements. diff --git a/vendor/github.com/google/cel-go/common/types/traits/lister.go b/vendor/cel.dev/cel-go/common/types/traits/lister.go similarity index 95% rename from vendor/github.com/google/cel-go/common/types/traits/lister.go rename to vendor/cel.dev/cel-go/common/types/traits/lister.go index e54781a602..67f32391b0 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/lister.go +++ b/vendor/cel.dev/cel-go/common/types/traits/lister.go @@ -14,7 +14,7 @@ package traits -import "github.com/google/cel-go/common/types/ref" +import "cel.dev/cel-go/common/types/ref" // Lister interface which aggregates the traits of a list. type Lister interface { diff --git a/vendor/github.com/google/cel-go/common/types/traits/mapper.go b/vendor/cel.dev/cel-go/common/types/traits/mapper.go similarity index 96% rename from vendor/github.com/google/cel-go/common/types/traits/mapper.go rename to vendor/cel.dev/cel-go/common/types/traits/mapper.go index d13333f3f6..7a4acedc54 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/mapper.go +++ b/vendor/cel.dev/cel-go/common/types/traits/mapper.go @@ -14,7 +14,7 @@ package traits -import "github.com/google/cel-go/common/types/ref" +import "cel.dev/cel-go/common/types/ref" // Mapper interface which aggregates the traits of a maps. type Mapper interface { diff --git a/vendor/github.com/google/cel-go/common/types/traits/matcher.go b/vendor/cel.dev/cel-go/common/types/traits/matcher.go similarity index 93% rename from vendor/github.com/google/cel-go/common/types/traits/matcher.go rename to vendor/cel.dev/cel-go/common/types/traits/matcher.go index 085dc94ff4..4ea283e908 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/matcher.go +++ b/vendor/cel.dev/cel-go/common/types/traits/matcher.go @@ -14,7 +14,7 @@ package traits -import "github.com/google/cel-go/common/types/ref" +import "cel.dev/cel-go/common/types/ref" // Matcher interface for supporting 'matches()' overloads. type Matcher interface { diff --git a/vendor/github.com/google/cel-go/common/types/traits/math.go b/vendor/cel.dev/cel-go/common/types/traits/math.go similarity index 97% rename from vendor/github.com/google/cel-go/common/types/traits/math.go rename to vendor/cel.dev/cel-go/common/types/traits/math.go index 86d5b9137e..cb6354f7ee 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/math.go +++ b/vendor/cel.dev/cel-go/common/types/traits/math.go @@ -14,7 +14,7 @@ package traits -import "github.com/google/cel-go/common/types/ref" +import "cel.dev/cel-go/common/types/ref" // Adder interface to support '+' operator overloads. type Adder interface { diff --git a/vendor/github.com/google/cel-go/common/types/traits/receiver.go b/vendor/cel.dev/cel-go/common/types/traits/receiver.go similarity index 94% rename from vendor/github.com/google/cel-go/common/types/traits/receiver.go rename to vendor/cel.dev/cel-go/common/types/traits/receiver.go index 8f41db45e8..4760192c68 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/receiver.go +++ b/vendor/cel.dev/cel-go/common/types/traits/receiver.go @@ -14,7 +14,7 @@ package traits -import "github.com/google/cel-go/common/types/ref" +import "cel.dev/cel-go/common/types/ref" // Receiver interface for routing instance method calls within a value. type Receiver interface { diff --git a/vendor/github.com/google/cel-go/common/types/traits/sizer.go b/vendor/cel.dev/cel-go/common/types/traits/sizer.go similarity index 94% rename from vendor/github.com/google/cel-go/common/types/traits/sizer.go rename to vendor/cel.dev/cel-go/common/types/traits/sizer.go index b80d25137a..8e2e3cf926 100644 --- a/vendor/github.com/google/cel-go/common/types/traits/sizer.go +++ b/vendor/cel.dev/cel-go/common/types/traits/sizer.go @@ -15,7 +15,7 @@ package traits import ( - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // Sizer interface for supporting 'size()' overloads. diff --git a/vendor/github.com/google/cel-go/common/types/traits/traits.go b/vendor/cel.dev/cel-go/common/types/traits/traits.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/traits/traits.go rename to vendor/cel.dev/cel-go/common/types/traits/traits.go diff --git a/vendor/github.com/google/cel-go/common/types/traits/zeroer.go b/vendor/cel.dev/cel-go/common/types/traits/zeroer.go similarity index 100% rename from vendor/github.com/google/cel-go/common/types/traits/zeroer.go rename to vendor/cel.dev/cel-go/common/types/traits/zeroer.go diff --git a/vendor/github.com/google/cel-go/common/types/types.go b/vendor/cel.dev/cel-go/common/types/types.go similarity index 96% rename from vendor/github.com/google/cel-go/common/types/types.go rename to vendor/cel.dev/cel-go/common/types/types.go index 78c77a9b5d..ea3fe21421 100644 --- a/vendor/github.com/google/cel-go/common/types/types.go +++ b/vendor/cel.dev/cel-go/common/types/types.go @@ -21,9 +21,9 @@ import ( "google.golang.org/protobuf/proto" - chkdecls "github.com/google/cel-go/checker/decls" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + chkdecls "cel.dev/cel-go/checker/decls" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" celpb "cel.dev/expr" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" @@ -412,12 +412,31 @@ func (t *Type) String() string { return fmt.Sprintf("%s(%s)", t.DeclaredTypeName(), strings.Join(params, ", ")) } +// IsDyn indicates whether the type is dynamic in any way. +func (t *Type) IsDyn() bool { + return t.isDyn() +} + // isDyn indicates whether the type is dynamic in any way. func (t *Type) isDyn() bool { k := t.Kind() return k == DynKind || k == AnyKind || k == TypeParamKind } +// IsErrOrUnknown indicates whether the type is an error or unknown type. +func (t *Type) IsErrOrUnknown() bool { + return t.isErrOrUnknown() +} + +// isErrOrUnknown indicates whether the type is an error or unknown type. +func (t *Type) isErrOrUnknown() bool { + if t == nil { + return false + } + k := t.Kind() + return k == ErrorKind || k == UnknownKind +} + // defaultIsAssignableType provides the standard definition of what it means for one type to be assignable to another // where any of the following may return a true result: // - The from types are the same instance @@ -426,7 +445,11 @@ func (t *Type) isDyn() bool { // // are IsAssignableType() from the parameters of the fromType. func (t *Type) defaultIsAssignableType(fromType *Type) bool { - if t == fromType || t.isDyn() { + if t == fromType { + return true + } + // if t is dynamic, it is assignable to any type except error or unknown + if t.isDyn() && !fromType.isErrOrUnknown() { return true } if t.Kind() != fromType.Kind() || @@ -446,9 +469,12 @@ func (t *Type) defaultIsAssignableType(fromType *Type) bool { // defaultIsAssignableRuntimeType inspects the type and in the case of list and map elements, the key and element types // to determine whether a ref.Val is assignable to the declared type for a function signature. func (t *Type) defaultIsAssignableRuntimeType(val ref.Val) bool { - valType := val.Type() + rawType := val.Type() + if valType, ok := rawType.(*Type); ok && valType.isErrOrUnknown() { + return false + } // If the current type and value type don't agree, then return - if !(t.isDyn() || t.TypeName() == valType.TypeName()) { + if !(t.isDyn() || t.TypeName() == rawType.TypeName()) { return false } switch t.Kind() { diff --git a/vendor/github.com/google/cel-go/common/types/uint.go b/vendor/cel.dev/cel-go/common/types/uint.go similarity index 99% rename from vendor/github.com/google/cel-go/common/types/uint.go rename to vendor/cel.dev/cel-go/common/types/uint.go index 91d5369daa..6c2bef7299 100644 --- a/vendor/github.com/google/cel-go/common/types/uint.go +++ b/vendor/cel.dev/cel-go/common/types/uint.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" anypb "google.golang.org/protobuf/types/known/anypb" structpb "google.golang.org/protobuf/types/known/structpb" diff --git a/vendor/github.com/google/cel-go/common/types/unknown.go b/vendor/cel.dev/cel-go/common/types/unknown.go similarity index 99% rename from vendor/github.com/google/cel-go/common/types/unknown.go rename to vendor/cel.dev/cel-go/common/types/unknown.go index f43aff18e0..96150fc3f2 100644 --- a/vendor/github.com/google/cel-go/common/types/unknown.go +++ b/vendor/cel.dev/cel-go/common/types/unknown.go @@ -23,7 +23,7 @@ import ( "strings" "unicode" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) var ( diff --git a/vendor/github.com/google/cel-go/common/types/util.go b/vendor/cel.dev/cel-go/common/types/util.go similarity index 96% rename from vendor/github.com/google/cel-go/common/types/util.go rename to vendor/cel.dev/cel-go/common/types/util.go index 71662eee31..cb37389f98 100644 --- a/vendor/github.com/google/cel-go/common/types/util.go +++ b/vendor/cel.dev/cel-go/common/types/util.go @@ -15,7 +15,7 @@ package types import ( - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // IsUnknownOrError returns whether the input element ref.Val is an ErrType or UnknownType. diff --git a/vendor/github.com/google/cel-go/interpreter/BUILD.bazel b/vendor/cel.dev/cel-go/interpreter/BUILD.bazel similarity index 93% rename from vendor/github.com/google/cel-go/interpreter/BUILD.bazel rename to vendor/cel.dev/cel-go/interpreter/BUILD.bazel index 40ac2ba696..a1f99a85a8 100644 --- a/vendor/github.com/google/cel-go/interpreter/BUILD.bazel +++ b/vendor/cel.dev/cel-go/interpreter/BUILD.bazel @@ -22,12 +22,14 @@ go_library( "planner.go", "prune.go", "runtimecost.go", + "runtimememory.go", ], - importpath = "github.com/google/cel-go/interpreter", + importpath = "cel.dev/cel-go/interpreter", deps = [ "//common:go_default_library", "//common/ast:go_default_library", "//common/containers:go_default_library", + "//common/cost:go_default_library", "//common/functions:go_default_library", "//common/operators:go_default_library", "//common/overloads:go_default_library", @@ -52,8 +54,10 @@ go_test( "attributes_test.go", "frame_test.go", "interpreter_test.go", + "mutability_test.go", "prune_test.go", "runtimecost_test.go", + "runtimememory_test.go", ], embed = [ ":go_default_library", diff --git a/vendor/github.com/google/cel-go/interpreter/activation.go b/vendor/cel.dev/cel-go/interpreter/activation.go similarity index 50% rename from vendor/github.com/google/cel-go/interpreter/activation.go rename to vendor/cel.dev/cel-go/interpreter/activation.go index bc9296ed4e..9d2c20404b 100644 --- a/vendor/github.com/google/cel-go/interpreter/activation.go +++ b/vendor/cel.dev/cel-go/interpreter/activation.go @@ -18,7 +18,8 @@ import ( "errors" "fmt" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/types/ref" ) // Activation used to resolve identifiers by name and references by id. @@ -43,7 +44,8 @@ func EmptyActivation() Activation { type emptyActivation struct{} func (emptyActivation) ResolveName(string) (any, bool) { return nil, false } -func (emptyActivation) Parent() Activation { return nil } + +func (emptyActivation) Parent() Activation { return nil } // NewActivation returns an activation based on a map-based binding where the map keys are // expected to be qualified names used with ResolveName calls. @@ -75,23 +77,35 @@ func NewActivation(bindings any) (Activation, error) { return &mapActivation{bindings: m}, nil } -// mapActivation which implements Activation and maps of named values. +// mapActivation is the default Activation implementation, which supplies variables by name and, +// where the caller provided them, the implementations of late-bound functions. +// +// Variables and functions occupy separate namespaces, so the same qualified name may refer to +// both. An mapActivation may also delegate to the mapActivation whose bindings it extends, which is +// exposed as its parent so that the hierarchy is visible to all mapActivation traversals. // // Named bindings may lazily supply values by providing a function which accepts no arguments and // produces an interface value. type mapActivation struct { bindings map[string]any + // TODO: validate that the late-bound functions should be applied here if at all. + // Seems like it would be better if populated via setter? + functions map[string]functions.LateBoundOp + parent Activation } // Parent implements the Activation interface method. func (a *mapActivation) Parent() Activation { - return nil + return a.parent } // ResolveName implements the Activation interface method. func (a *mapActivation) ResolveName(name string) (any, bool) { obj, found := a.bindings[name] if !found { + if a.parent != nil { + return a.parent.ResolveName(name) + } return nil, false } fn, isLazy := obj.(func() ref.Val) @@ -107,6 +121,20 @@ func (a *mapActivation) ResolveName(name string) (any, bool) { return obj, found } +// ResolveFunction implements the FunctionActivation interface method. +// +// Only the bindings supplied to this activation are considered. A hierarchy may contain at most +// one activation which supplies late-bound functions, so there is no parent to delegate to. +func (a *mapActivation) ResolveFunction(name string) (functions.LateBoundOp, bool) { + fn, found := a.functions[name] + return fn, found +} + +// AsPartialActivation supports partial evaluation over the activation being extended. +func (a *mapActivation) AsPartialActivation() (PartialActivation, bool) { + return AsPartialActivation(a.parent) +} + // hierarchicalActivation which implements Activation and contains a parent and // child activation. type hierarchicalActivation struct { @@ -122,10 +150,15 @@ func (a *hierarchicalActivation) Parent() Activation { // ResolveName implements the Activation interface method. func (a *hierarchicalActivation) ResolveName(name string) (any, bool) { - if object, found := a.child.ResolveName(name); found { - return object, found + if a.child != nil { + if object, found := a.child.ResolveName(name); found { + return object, found + } + } + if a.parent != nil { + return a.parent.ResolveName(name) } - return a.parent.ResolveName(name) + return nil, false } // Unwrap returns the parent activation, stripping the local child scope. @@ -212,6 +245,9 @@ func (a *partActivation) AsPartialActivation() (PartialActivation, bool) { // AsPartialActivation walks the activation hierarchy and returns the first PartialActivation, if found. func AsPartialActivation(vars Activation) (PartialActivation, bool) { + if vars == nil { + return nil, false + } // Only internal activation instances may implement this interface if pv, ok := vars.(partialActivationConverter); ok { return pv.AsPartialActivation() @@ -222,3 +258,128 @@ func AsPartialActivation(vars Activation) (PartialActivation, bool) { } return nil, false } + +// FunctionActivation extends the Activation interface with late-bound function implementations. +// +// Function bindings occupy a namespace which is separate from variable bindings, so a function +// and a variable may share the same qualified name without ambiguity. +// +// The implementation which applies to an evaluation is located once, before evaluation begins, so +// at most one activation in a hierarchy may implement this interface. An implementation supplied +// by a caller is treated as the sole source of bindings and its parents are not searched. +type FunctionActivation interface { + Activation + + // ResolveFunction returns the implementation of the late-bound function by qualified name, + // or false if the function could not be found. + ResolveFunction(name string) (functions.LateBoundOp, bool) +} + +// NewFunctionActivation returns an Activation which supplies implementations for late-bound +// functions in addition to the variables provided by the `vars` input. +// +// The `vars` value may either be an Activation or any valid input to the NewActivation call, and +// the result is the same kind of activation that NewActivation produces, extended with the +// function bindings. +// +// Each function implementation is invoked with the id of the declared overload which matched the +// call arguments, which permits a single implementation to serve all overloads of the function. +// +// Late-bound functions are bound for the whole of an evaluation rather than for a lexical scope, +// so an error is returned when `vars` already supplies function bindings. Supply the complete set +// of bindings in a single call instead of layering them. +func NewFunctionActivation(vars any, funcs map[string]functions.LateBoundOp) (FunctionActivation, error) { + // Copy the input to ensure the bindings observed during an evaluation cannot be mutated by + // the caller once the activation has been created. + bindings := make(map[string]functions.LateBoundOp, len(funcs)) + for name, fn := range funcs { + if fn == nil { + return nil, fmt.Errorf("function binding must be non-nil: %s", name) + } + bindings[name] = fn + } + if m, isMap := vars.(map[string]any); isMap { + return &mapActivation{bindings: m, functions: bindings}, nil + } + a, err := NewActivation(vars) + if err != nil { + return nil, err + } + if err := checkNoFunctionActivation(a); err != nil { + return nil, err + } + return &mapActivation{functions: bindings, parent: a}, nil +} + +// errNestedFunctionActivation reports a hierarchy which supplies late-bound functions from more +// than one activation, where the bindings which apply would depend on the order in which the +// activations were composed. +var errNestedFunctionActivation = errors.New( + "activation hierarchy may supply late-bound functions from only one activation") + +// checkNoFunctionActivation returns an error if the hierarchy already supplies late-bound +// function implementations. +func checkNoFunctionActivation(vars Activation) error { + found, err := FindFunctionActivation(vars) + if err != nil { + return err + } + if found != nil { + return errNestedFunctionActivation + } + return nil +} + +// FindFunctionActivation returns the activation which supplies the late-bound function +// implementations for a hierarchy, or nil when the hierarchy supplies none. +// +// Late-bound functions are bound for the duration of an evaluation rather than for a lexical +// scope, so a hierarchy may contain at most one activation which supplies them and an error is +// returned when it contains more. Resolving the binding once, before evaluation begins, keeps the +// lookup at a call site independent of how many scopes enclose it. +// +// This must be called before evaluation begins, while the hierarchy is still composed only of +// caller-supplied activations. Scopes introduced during evaluation, such as those of a +// comprehension, report the enclosing frame as their parent rather than the enclosing activation. +func FindFunctionActivation(vars Activation) (FunctionActivation, error) { + return findFunctionActivation(vars, nil) +} + +// findFunctionActivation searches a hierarchy for the activation which supplies late-bound +// functions, carrying the match found so far so that a second match can be reported as an error. +func findFunctionActivation(vars Activation, found FunctionActivation) (FunctionActivation, error) { + if vars == nil { + return found, nil + } + switch a := vars.(type) { + case *mapActivation: + // A default activation only supplies functions when it was created for that purpose. + if a.functions != nil { + if found != nil { + return nil, errNestedFunctionActivation + } + found = a + } + return findFunctionActivation(a.parent, found) + case *hierarchicalActivation: + // Both scopes are caller-supplied, so both must be searched. + found, err := findFunctionActivation(a.parent, found) + if err != nil { + return nil, err + } + return findFunctionActivation(a.child, found) + case *partActivation: + // The wrapped activation is not reachable via Parent. + return findFunctionActivation(a.Activation, found) + default: + // An implementation supplied by the caller is responsible for the scopes it contains, + // so its parents are not searched. + if fa, isFunc := vars.(FunctionActivation); isFunc { + if found != nil { + return nil, errNestedFunctionActivation + } + return fa, nil + } + return findFunctionActivation(vars.Parent(), found) + } +} diff --git a/vendor/github.com/google/cel-go/interpreter/async.go b/vendor/cel.dev/cel-go/interpreter/async.go similarity index 88% rename from vendor/github.com/google/cel-go/interpreter/async.go rename to vendor/cel.dev/cel-go/interpreter/async.go index 4e391196bf..2c40e516ed 100644 --- a/vendor/github.com/google/cel-go/interpreter/async.go +++ b/vendor/cel.dev/cel-go/interpreter/async.go @@ -16,16 +16,14 @@ package interpreter import ( "context" - "encoding/binary" "fmt" - "hash/fnv" "math" "sync" "sync/atomic" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // Async extension function support. @@ -93,7 +91,7 @@ func (fn *evalAsyncFunc) Args() []InterpretableV2 { // Eval implements the Interpretable interface method. func (fn *evalAsyncFunc) Eval(vars Activation) ref.Val { - return fn.Exec(AsFrame(vars)) + return EvalActivation(vars, fn.Exec) } // Exec implements the InterpretableV2 interface method. @@ -108,10 +106,17 @@ func (fn *evalAsyncFunc) Exec(frame *ExecutionFrame) ref.Val { unk, _ = types.MaybeMergeUnknowns(argVals[i], unk) } if unk != nil { + if costs := frame.CostTracker(); costs != nil { + costs.EvalVarArgs(frame, fn.id, fn, argVals, unk) + } return unk } result := frame.ComputeResult(fn.ID(), fn.Function(), fn.OverloadID(), fn.impl, argVals) - return types.LabelErrNode(fn.id, result) + val := types.LabelErrNode(fn.id, result) + if costs := frame.CostTracker(); costs != nil { + costs.EvalVarArgs(frame, fn.id, fn, argVals, val) + } + return val } // asyncCallStateTracker manages async call states across re-evaluations of a single program. @@ -134,15 +139,60 @@ func newAsyncCallStateTracker() *asyncCallStateTracker { } } -var ( - hashZeroMarker = []byte{0} - hashStringMarker = []byte{'s'} - hashBoolTrueMarker = []byte{'b', 1} - hashBoolFalseMarker = []byte{'b', 0} - hashNumberMarker = []byte{'n'} - hashDefaultMarker = []byte{'x'} +const ( + hashMarkerString = 's' + hashMarkerBool = 'b' + hashMarkerNumber = 'n' + hashMarkerDefault = 'x' ) +func hashString(s string) uint64 { + var h uint64 + for i := 0; i < len(s); i++ { + h = 31*h + uint64(s[i]) + } + return h +} + +// numericKey returns the canonical hash contribution for a CEL numeric value. +// +// Int, Uint, and Double all funnel through float64 because CEL numeric equality is +// heterogeneous and exact: any Int/Uint/Double values that compare equal convert to +// identical float64 bits. Values above 2^53 lose precision and may share a bucket, +// which is benign — findInBucket resolves it. +func numericKey(d float64) uint64 { + if math.IsNaN(d) { + // matches treats NaN as equal to NaN for dispatch purposes, so collapse all + // payloads onto one quiet-NaN pattern. + return 0x7ff8000000000000 + } + if d == 0 { + // Normalizes -0.0, which CEL equality treats as 0.0. + return 0 + } + return math.Float64bits(d) +} + +func hashArg(arg ref.Val) uint64 { + switch v := arg.(type) { + case types.String: + return hashMarkerString*31 + hashString(string(v)) + case types.Bool: + if bool(v) { + return hashMarkerBool*31 + 1 + } + return hashMarkerBool * 31 + case types.Int: + return hashMarkerNumber*31 + numericKey(float64(v)) + case types.Uint: + return hashMarkerNumber*31 + numericKey(float64(v)) + case types.Double: + return hashMarkerNumber*31 + numericKey(float64(v)) + default: + return hashMarkerDefault + } +} + // hashCall computes the composite bucket key for an async call. // // Only string, int, double, uint, and bool argument values contribute to the hash. More complex types @@ -150,56 +200,11 @@ var ( // that a byte-level hash cannot capture safely, so they are intentionally excluded from the key // and are instead disambiguated within the bucket by asyncCallState.matches. func hashCall(id int64, overload string, args []ref.Val) uint64 { - h := fnv.New64a() - var idBuf [8]byte - binary.LittleEndian.PutUint64(idBuf[:], uint64(id)) - h.Write(idBuf[:]) - h.Write([]byte(overload)) - h.Write(hashZeroMarker) + result := 31*uint64(id) + hashString(overload) for _, arg := range args { - switch v := arg.(type) { - case types.String: - h.Write(hashStringMarker) - h.Write([]byte(string(v))) - case types.Bool: - if bool(v) { - h.Write(hashBoolTrueMarker) - } else { - h.Write(hashBoolFalseMarker) - } - case types.Int: - h.Write(hashNumberMarker) - var buf [8]byte - binary.LittleEndian.PutUint64(buf[:], math.Float64bits(float64(v))) - h.Write(buf[:]) - case types.Uint: - h.Write(hashNumberMarker) - var buf [8]byte - binary.LittleEndian.PutUint64(buf[:], math.Float64bits(float64(v))) - h.Write(buf[:]) - case types.Double: - h.Write(hashNumberMarker) - if math.IsNaN(float64(v)) { - h.Write([]byte("NaN")) - h.Write(hashZeroMarker) - continue - } - // Normalize -0.0 to 0.0. Go will treat -0.0 as 0.0 at compile time, - // but the function math.Copysign(0.0, -1.0) can be used to test the -0.0 case. - if v == types.Double(0.0) && math.Signbit(float64(v)) { - v = types.Double(0.0) - } - var buf [8]byte - binary.LittleEndian.PutUint64(buf[:], math.Float64bits(float64(v))) - h.Write(buf[:]) - default: - // Value intentionally omitted; bucket membership falls back to matches. - h.Write(hashDefaultMarker) - } - // Separator to avoid cross-argument collisions, e.g. ("a", "bc") vs ("ab", "c"). - h.Write(hashZeroMarker) + result = 31*result + hashArg(arg) } - return h.Sum64() + return result } // findInBucket returns the call state in the bucket matching the same node id and call identity, diff --git a/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go b/vendor/cel.dev/cel-go/interpreter/attribute_patterns.go similarity index 99% rename from vendor/github.com/google/cel-go/interpreter/attribute_patterns.go rename to vendor/cel.dev/cel-go/interpreter/attribute_patterns.go index bbaca52269..8e33ddd236 100644 --- a/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go +++ b/vendor/cel.dev/cel-go/interpreter/attribute_patterns.go @@ -18,9 +18,9 @@ import ( "fmt" "strings" - "github.com/google/cel-go/common/containers" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/containers" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // AttributePattern represents a top-level variable with an optional set of qualifier patterns. diff --git a/vendor/github.com/google/cel-go/interpreter/attributes.go b/vendor/cel.dev/cel-go/interpreter/attributes.go similarity index 87% rename from vendor/github.com/google/cel-go/interpreter/attributes.go rename to vendor/cel.dev/cel-go/interpreter/attributes.go index 26d8eb0f3e..b138aba3b1 100644 --- a/vendor/github.com/google/cel-go/interpreter/attributes.go +++ b/vendor/cel.dev/cel-go/interpreter/attributes.go @@ -18,10 +18,10 @@ import ( "fmt" "strings" - "github.com/google/cel-go/common/containers" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/containers" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" ) // AttributeFactory provides methods creating Attribute and Qualifier values. @@ -141,7 +141,12 @@ func EnableErrorOnBadPresenceTest(value bool) AttrFactoryOption { // NewAttributeFactory returns a default AttributeFactory which is produces Attribute values // capable of resolving types by simple names and qualify the values using the supported qualifier // types: bool, int, string, and uint. +// +// If the adapter is nil, types.DefaultTypeAdapter is used. func NewAttributeFactory(cont *containers.Container, a types.Adapter, p types.Provider, opts ...AttrFactoryOption) AttributeFactory { + if a == nil { + a = types.DefaultTypeAdapter + } fac := &attrFactory{ container: cont, adapter: a, @@ -173,6 +178,18 @@ func (r *attrFactory) AbsoluteAttribute(id int64, names ...string) NamespacedAtt names[idx] = strings.TrimPrefix(name, ".") } } + if len(names) == 1 && !disambiguateNames { + return &identAttribute{ + id: id, + name: names[0], + candidateNames: names, + qualifiers: []Qualifier{}, + adapter: r.adapter, + provider: r.provider, + fac: r, + errorOnBadPresenceTest: r.errorOnBadPresenceTest, + } + } return &absoluteAttribute{ id: id, namespaceNames: names, @@ -238,17 +255,29 @@ func (r *attrFactory) NewQualifier(objType *types.Type, qualID int64, val any, o // Before creating a new qualifier check to see if this is a protobuf message field access. // If so, use the precomputed GetFrom qualification method rather than the standard // stringQualifier. - str, isStr := val.(string) - if isStr && objType != nil && objType.Kind() == types.StructKind { - ft, found := r.provider.FindStructFieldType(objType.TypeName(), str) - if found && ft.IsSet != nil && ft.GetFrom != nil { - return &fieldQualifier{ - id: qualID, - Name: str, - FieldType: ft, - adapter: r.adapter, - optional: opt, - }, nil + var str string + var isStr bool + switch v := val.(type) { + case string: + str, isStr = v, true + case types.String: + str, isStr = string(v), true + } + if isStr && objType != nil { + if objType.Kind() == types.OpaqueKind && objType.TypeName() == "optional_type" && len(objType.Parameters()) == 1 { + objType = objType.Parameters()[0] + } + if objType.Kind() == types.StructKind { + ft, found := r.provider.FindStructFieldType(objType.TypeName(), str) + if found && ft.IsSet != nil && ft.GetFrom != nil { + return &fieldQualifier{ + id: qualID, + Name: str, + FieldType: ft, + adapter: r.adapter, + optional: opt, + }, nil + } } } return newQualifier(r.adapter, qualID, val, opt, r.errorOnBadPresenceTest) @@ -335,7 +364,11 @@ func (a *absoluteAttribute) Resolve(vars Activation) (any, error) { inputVars = vars wrapped, ok := inputVars.(activationWrapper) for ok { - inputVars = wrapped.Unwrap() + next := wrapped.Unwrap() + if next == nil { + break + } + inputVars = next wrapped, ok = inputVars.(activationWrapper) } } @@ -351,6 +384,13 @@ func (a *absoluteAttribute) Resolve(vars Activation) (any, error) { if celErr, ok := obj.(*types.Err); ok { return nil, celErr } + _, isUnknown := obj.(*types.Unknown) + if isUnknown { + return obj, nil + } + if len(a.qualifiers) == 0 { + return obj, nil + } obj, isOpt, err := applyQualifiers(v, obj, a.qualifiers) if err != nil { return nil, err @@ -382,6 +422,102 @@ func (a *absoluteAttribute) Resolve(vars Activation) (any, error) { return nil, missingAttribute(attrNames.String()) } +// identAttribute is a specialized, lightweight attribute for simple, single-name identifiers +// without namespace disambiguation. +type identAttribute struct { + id int64 + name string + candidateNames []string + qualifiers []Qualifier + adapter types.Adapter + provider types.Provider + fac AttributeFactory + errorOnBadPresenceTest bool +} + +// ID implements the Attribute interface method. +func (a *identAttribute) ID() int64 { + qualCount := len(a.qualifiers) + if qualCount == 0 { + return a.id + } + return a.qualifiers[qualCount-1].ID() +} + +// IsOptional returns trivially false for an attribute as the attribute represents a fully +// qualified variable name. If the attribute is used in an optional manner, then an attrQualifier +// is created and marks the attribute as optional. +func (a *identAttribute) IsOptional() bool { + return false +} + +// AddQualifier implements the Attribute interface method. +func (a *identAttribute) AddQualifier(qual Qualifier) (Attribute, error) { + a.qualifiers = append(a.qualifiers, qual) + return a, nil +} + +// CandidateVariableNames implements the NamespacedAttribute interface method. +func (a *identAttribute) CandidateVariableNames() []string { + return a.candidateNames +} + +// Qualifiers returns the list of Qualifier instances associated with the namespaced attribute. +func (a *identAttribute) Qualifiers() []Qualifier { + return a.qualifiers +} + +// Qualify is an implementation of the Qualifier interface method. +func (a *identAttribute) Qualify(vars Activation, obj any) (any, error) { + return attrQualify(a.fac, vars, obj, a) +} + +// QualifyIfPresent is an implementation of the Qualifier interface method. +func (a *identAttribute) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) { + return attrQualifyIfPresent(a.fac, vars, obj, a, presenceOnly) +} + +// String implements the fmt.Stringer interface method. +func (a *identAttribute) String() string { + return fmt.Sprintf("id: %v, names: %v", a.id, a.candidateNames) +} + +// Resolve returns the resolved Attribute value given the Activation, or error if the Attribute +// variable is not found, or if its Qualifiers cannot be applied successfully. +func (a *identAttribute) Resolve(vars Activation) (any, error) { + obj, found := vars.ResolveName(a.name) + if found { + if celErr, ok := obj.(*types.Err); ok { + return nil, celErr + } + if _, isUnknown := obj.(*types.Unknown); isUnknown { + return obj, nil + } + if len(a.qualifiers) == 0 { + return obj, nil + } + obj, isOpt, err := applyQualifiers(vars, obj, a.qualifiers) + if err != nil { + return nil, err + } + if isOpt { + val := a.adapter.NativeToValue(obj) + if types.IsUnknown(val) { + return val, nil + } + return types.OptionalOf(val), nil + } + return obj, nil + } + typ, found := a.provider.FindIdent(a.name) + if found { + if len(a.qualifiers) == 0 { + return typ, nil + } + } + return nil, missingAttribute(a.name) +} + type conditionalAttribute struct { id int64 expr InterpretableV2 @@ -613,12 +749,25 @@ func (a *relativeAttribute) QualifyIfPresent(vars Activation, obj any, presenceO // Resolve expression value and qualifier relative to the expression result. func (a *relativeAttribute) Resolve(vars Activation) (any, error) { + frame, ok := vars.(*ExecutionFrame) + if !ok { + var err error + frame, err = NewExecutionFrame(vars) + if err != nil { + return nil, err + } + defer frame.Close() + vars = frame + } // First, evaluate the operand. - v := a.operand.Eval(vars) - if types.IsError(v) { + v := a.operand.Exec(frame) + if isError(v) { return nil, v.(*types.Err) } - if types.IsUnknown(v) { + if isUnknown(v) { + return v, nil + } + if len(a.qualifiers) == 0 { return v, nil } obj, isOpt, err := applyQualifiers(vars, v, a.qualifiers) @@ -627,7 +776,7 @@ func (a *relativeAttribute) Resolve(vars Activation) (any, error) { } if isOpt { val := a.adapter.NativeToValue(obj) - if types.IsUnknown(val) { + if isUnknown(val) { return val, nil } return types.OptionalOf(val), nil @@ -794,6 +943,12 @@ func newQualifier(adapter types.Adapter, id int64, v any, opt, errorOnBadPresenc if q, ok := v.(Qualifier); ok { return q, nil } + // Values resolved from comprehension variables may be raw native values, such as the + // *structpb.Value elements of a *structpb.ListValue. Adapt them to CEL values and retry. + // Since NativeToValue always returns a ref.Val, at most one retry occurs. + if _, isVal := v.(ref.Val); !isVal { + return newQualifier(adapter, id, adapter.NativeToValue(v), opt, errorOnBadPresenceTest) + } return nil, fmt.Errorf("invalid qualifier type: %T", v) } return qual, nil @@ -905,6 +1060,14 @@ func (q *stringQualifier) qualifyInternal(vars Activation, obj any, presenceTest return obj, true, nil } default: + if nm, ok := obj.(interface{ FindStringKey(string) (any, bool) }); ok { + if v, found := nm.FindStringKey(s); found { + if presenceOnly { + return nil, true, nil + } + return v, true, nil + } + } return refQualify(q.adapter, obj, q.celValue, presenceTest, presenceOnly, q.errorOnBadPresenceTest) } if presenceTest { @@ -981,6 +1144,11 @@ func (q *intQualifier) qualifyInternal(vars Activation, obj any, presenceTest, p if isIndex { return o[i], true, nil } + case []ref.Val: + isIndex := i >= 0 && i < int64(len(o)) + if isIndex { + return o[i], true, nil + } case []string: isIndex := i >= 0 && i < int64(len(o)) if isIndex { @@ -1032,6 +1200,26 @@ func (q *intQualifier) qualifyInternal(vars Activation, obj any, presenceTest, p return o[i], true, nil } default: + if nl, ok := obj.(interface{ GetInt64Index(int64) (any, bool) }); ok { + if v, found := nl.GetInt64Index(i); found { + if presenceOnly { + return nil, true, nil + } + return v, true, nil + } + if presenceTest { + return nil, false, nil + } + return nil, false, missingIndex(q.celValue) + } + if nm, ok := obj.(interface{ FindInt64Key(int64) (any, bool) }); ok { + if v, found := nm.FindInt64Key(i); found { + if presenceOnly { + return nil, true, nil + } + return v, true, nil + } + } return refQualify(q.adapter, obj, q.celValue, presenceTest, presenceOnly, q.errorOnBadPresenceTest) } if presenceTest { @@ -1300,6 +1488,12 @@ func (q *unknownQualifier) Value() ref.Val { } func applyQualifiers(vars Activation, obj any, qualifiers []Qualifier) (any, bool, error) { + // Early return if there's nothing to apply + if len(qualifiers) == 0 { + return obj, false, nil + } + + // Test for an optional select that's on an empty value. optObj, isOpt := obj.(*types.Optional) if isOpt { if !optObj.HasValue() { @@ -1308,6 +1502,7 @@ func applyQualifiers(vars Activation, obj any, qualifiers []Qualifier) (any, boo obj = optObj.GetValue() } + frame, hasFrame := vars.(*ExecutionFrame) var err error for _, qual := range qualifiers { var qualObj any @@ -1315,6 +1510,12 @@ func applyQualifiers(vars Activation, obj any, qualifiers []Qualifier) (any, boo if isOpt { var present bool qualObj, present, err = qual.QualifyIfPresent(vars, obj, false) + if hasFrame { + if costs := frame.CostTracker(); costs != nil && + (present || err != nil || costs.ModelVersion() >= 1) { + costs.Qualify(qual.ID()) + } + } if err != nil { return nil, false, err } @@ -1326,6 +1527,11 @@ func applyQualifiers(vars Activation, obj any, qualifiers []Qualifier) (any, boo } } else { qualObj, err = qual.Qualify(vars, obj) + if hasFrame { + if costs := frame.CostTracker(); costs != nil { + costs.Qualify(qual.ID()) + } + } if err != nil { return nil, false, err } @@ -1376,7 +1582,7 @@ func refQualify(adapter types.Adapter, obj any, idx ref.Val, presenceTest, prese val, found := v.Find(idx) // If the index is of the wrong type for the map, then it is possible // for the Find call to produce an error. - if types.IsError(val) { + if isError(val) { return nil, false, val.(*types.Err) } if found { @@ -1389,7 +1595,7 @@ func refQualify(adapter types.Adapter, obj any, idx ref.Val, presenceTest, prese case traits.Lister: // If the index argument is not a valid numeric type, then it is possible // for the index operation to produce an error. - i, err := types.IndexOrError(idx) + i, err := types.GetOrError(idx) if err != nil { return nil, false, err } @@ -1406,7 +1612,7 @@ func refQualify(adapter types.Adapter, obj any, idx ref.Val, presenceTest, prese ft, ok := v.(traits.FieldTester) if ok { presence := ft.IsSet(idx) - if types.IsError(presence) { + if isError(presence) { return nil, false, presence.(*types.Err) } // If not found or presence only test, then return. @@ -1417,7 +1623,7 @@ func refQualify(adapter types.Adapter, obj any, idx ref.Val, presenceTest, prese } } val := v.Get(idx) - if types.IsError(val) { + if isError(val) { return nil, false, val.(*types.Err) } return val, true, nil diff --git a/vendor/github.com/google/cel-go/interpreter/decorators.go b/vendor/cel.dev/cel-go/interpreter/decorators.go similarity index 95% rename from vendor/github.com/google/cel-go/interpreter/decorators.go rename to vendor/cel.dev/cel-go/interpreter/decorators.go index 6c48e5c1b9..2b193dbb8a 100644 --- a/vendor/github.com/google/cel-go/interpreter/decorators.go +++ b/vendor/cel.dev/cel-go/interpreter/decorators.go @@ -17,10 +17,10 @@ package interpreter import ( "fmt" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" ) // InterpretableDecorator is a functional interface for decorating or replacing @@ -251,7 +251,9 @@ func maybeOptimizeConstUnary(i InterpretableV2, call InterpretableCall) (Interpr if !isConst { return i, nil } - val := call.Eval(EmptyActivation()) + frame, _ := NewExecutionFrame(EmptyActivation()) + val := call.Exec(frame) + frame.Close() if types.IsError(val) { return nil, val.(*types.Err) } @@ -265,7 +267,10 @@ func maybeBuildListLiteral(i InterpretableV2, l *evalList) (InterpretableV2, err return i, nil } } - return NewConstValue(l.ID(), l.Eval(EmptyActivation())), nil + frame, _ := NewExecutionFrame(EmptyActivation()) + constVal := l.Exec(frame) + frame.Close() + return NewConstValue(l.ID(), constVal), nil } func maybeBuildMapLiteral(i InterpretableV2, mp *evalMap) (InterpretableV2, error) { @@ -279,7 +284,10 @@ func maybeBuildMapLiteral(i InterpretableV2, mp *evalMap) (InterpretableV2, erro return i, nil } } - return NewConstValue(mp.ID(), mp.Eval(EmptyActivation())), nil + frame, _ := NewExecutionFrame(EmptyActivation()) + constVal := mp.Exec(frame) + frame.Close() + return NewConstValue(mp.ID(), constVal), nil } // maybeOptimizeSetMembership may convert an 'in' operation against a list to map key membership diff --git a/vendor/github.com/google/cel-go/interpreter/dispatcher.go b/vendor/cel.dev/cel-go/interpreter/dispatcher.go similarity index 98% rename from vendor/github.com/google/cel-go/interpreter/dispatcher.go rename to vendor/cel.dev/cel-go/interpreter/dispatcher.go index 8f0bdb7b8e..40efe3009b 100644 --- a/vendor/github.com/google/cel-go/interpreter/dispatcher.go +++ b/vendor/cel.dev/cel-go/interpreter/dispatcher.go @@ -17,7 +17,7 @@ package interpreter import ( "fmt" - "github.com/google/cel-go/common/functions" + "cel.dev/cel-go/common/functions" ) // Dispatcher resolves function calls to their appropriate overload. diff --git a/vendor/github.com/google/cel-go/interpreter/evalstate.go b/vendor/cel.dev/cel-go/interpreter/evalstate.go similarity index 97% rename from vendor/github.com/google/cel-go/interpreter/evalstate.go rename to vendor/cel.dev/cel-go/interpreter/evalstate.go index 4bdd1fdc73..c1ee6ea1c5 100644 --- a/vendor/github.com/google/cel-go/interpreter/evalstate.go +++ b/vendor/cel.dev/cel-go/interpreter/evalstate.go @@ -15,7 +15,7 @@ package interpreter import ( - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/ref" ) // EvalState tracks the values associated with expression ids during execution. diff --git a/vendor/github.com/google/cel-go/interpreter/frame.go b/vendor/cel.dev/cel-go/interpreter/frame.go similarity index 64% rename from vendor/github.com/google/cel-go/interpreter/frame.go rename to vendor/cel.dev/cel-go/interpreter/frame.go index 20ab313c8f..a6af17d0ac 100644 --- a/vendor/github.com/google/cel-go/interpreter/frame.go +++ b/vendor/cel.dev/cel-go/interpreter/frame.go @@ -21,9 +21,9 @@ import ( "sync" "sync/atomic" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // evalContext contains the stateful information needed for a single evaluation. @@ -49,6 +49,9 @@ type evalContext struct { // costs provides the context for tracking the evaluation costs. costs *CostTracker + // memory provides the context for tracking peak memory during evaluation. + memory *types.MemoryTracker + // ctx is the context for async call implementations to use. ctx context.Context @@ -70,25 +73,82 @@ type evalContext struct { // The execution frame must not be stored in any fashion as its lifecycle is completely // controlled by the CEL evaluation process. type ExecutionFrame struct { - // Activation provides the context for resolving variables by name. - Activation - - // parent provides the context for parent scopes (used for comprehension iterators). + // parent provides the context for parent scopes (used for comprehension iterators and nested blocks). parent *ExecutionFrame + // scope provides the local activation for this frame (e.g. comprehension folder, block slots, or input Activation). + scope Activation + + // functions supplies the late-bound function implementations for the evaluation, resolved + // once from the input activation. Scopes introduced during evaluation never supply function + // bindings, so a child frame inherits this value from its parent rather than resolving again. + functions FunctionActivation + + // vars holds map-based input variables directly on the frame to eliminate pool allocations. + vars map[string]any + + // lazyVars caches evaluations of lazy variables (func() any / func() ref.Val) in vars. + lazyVars map[string]any + // ctx provides the shared evaluation state across frames. ctx *evalContext + + // costTracker provides direct access to the active CostTracker for this evaluation pass. + costTracker *CostTracker +} + +// Scope returns the local activation scope for this frame, if present. +func (f *ExecutionFrame) Scope() Activation { + return f.scope +} + +// SetScope sets the local activation scope for this frame. +func (f *ExecutionFrame) SetScope(scope Activation) { + f.scope = scope +} + +// SetDefaultVars sets the default variables activation for the frame, composing it +// with any existing scope activation. +func (f *ExecutionFrame) SetDefaultVars(defaultVars Activation) error { + if defaultVars == nil { + return nil + } + fns, err := FindFunctionActivation(defaultVars) + if err != nil { + return err + } + if fns != nil { + if f.functions != nil { + return errNestedFunctionActivation + } + f.functions = fns + } + if f.scope != nil { + f.scope = NewHierarchicalActivation(defaultVars, f.scope) + } else { + f.scope = defaultVars + } + return nil } // NewExecutionFrame creates a new execution frame from the pool. func NewExecutionFrame(input any) (*ExecutionFrame, error) { f := frameStack.Get().(*ExecutionFrame) switch v := input.(type) { + case emptyActivation: + // empty frame, no backing scope needed case Activation: - f.Activation = v + f.scope = v + fns, err := FindFunctionActivation(f.scope) + if err != nil { + frameStack.Put(f) + return nil, err + } + f.functions = fns case map[string]any: - f.Activation = activationInput.create(v) + f.vars = v default: + frameStack.Put(f) return nil, fmt.Errorf("invalid input, wanted Activation or map[string]any, got: (%T)%v", input, input) } return f, nil @@ -128,6 +188,7 @@ func (f *ExecutionFrame) Close() { f.ctx.interrupt = nil f.ctx.state = nil f.ctx.costs = nil + f.ctx.memory = nil f.ctx.interrupted.Store(false) f.ctx.interruptCheckCount.Store(0) f.ctx.interruptCheckFrequency = 0 @@ -135,30 +196,29 @@ func (f *ExecutionFrame) Close() { } f.ctx = nil f.parent = nil - if f.Activation != nil { - switch a := f.Activation.(type) { - case *hierarchicalActivation: - if child, ok := a.child.(*inputActivation); ok { - activationInput.release(child) - } - activationStack.release(a) - case *inputActivation: - activationInput.release(a) - } - f.Activation = nil - frameStack.Put(f) + f.costTracker = nil + f.functions = nil + if f.vars != nil { + f.vars = nil + clear(f.lazyVars) } + f.scope = nil + frameStack.Put(f) } // Push pushes the given activation onto the activation stack and returns the new frame. // // This operation is internal to the interpreter and is used to handle comprehension -// scoping. The child frame inherits the shared evalContext from the parent. +// and block scoping. The child frame inherits the shared evalContext from the parent. func (f *ExecutionFrame) Push(activation Activation) *ExecutionFrame { child := frameStack.Get().(*ExecutionFrame) child.parent = f child.ctx = f.ctx - child.Activation = activationStack.create(f.Activation, activation) + child.costTracker = f.costTracker + child.scope = activation + // Scopes pushed during evaluation never supply late-bound functions, so the child inherits + // the bindings resolved for the evaluation rather than searching its own hierarchy. + child.functions = f.functions return child } @@ -168,37 +228,115 @@ func (f *ExecutionFrame) Pop() *ExecutionFrame { return f } parent := f.parent - activationStack.release(f.Activation) - f.Activation = nil + f.scope = nil f.parent = nil + f.functions = nil f.ctx = nil + f.costTracker = nil + if f.vars != nil { + f.vars = nil + clear(f.lazyVars) + } frameStack.Put(f) return parent } // ResolveName implements the Activation interface by proxying to the internal activation. func (f *ExecutionFrame) ResolveName(name string) (any, bool) { - return f.Activation.ResolveName(name) + if f.vars != nil { + v, found := f.vars[name] + if found { + if f.lazyVars != nil { + if resolved, found := f.lazyVars[name]; found { + return resolved, true + } + } + var lazy any + switch obj := v.(type) { + case func() ref.Val: + lazy = obj() + case func() any: + lazy = obj() + default: + return obj, true + } + if f.lazyVars == nil { + f.lazyVars = make(map[string]any, 4) + } + f.lazyVars[name] = lazy + return lazy, true + } + } + if f.scope != nil { + if val, found := f.scope.ResolveName(name); found { + return val, true + } + } + if f.parent != nil { + return f.parent.ResolveName(name) + } + return nil, false } -// Parent implements the Activation interface by proxying to the internal activation. +// Parent implements the Activation interface by proxying to the parent frame or scope. func (f *ExecutionFrame) Parent() Activation { - return f.Activation.Parent() + if f.parent != nil { + if f.parent.scope != nil { + return f.parent.scope + } + return f.parent + } + if f.scope != nil { + return f.scope.Parent() + } + return nil +} + +// ResolveFunction implements the FunctionActivation interface using the bindings resolved when +// the evaluation began, so the cost of a lookup does not depend on the number of enclosing scopes. +func (f *ExecutionFrame) ResolveFunction(name string) (functions.LateBoundOp, bool) { + if f.functions == nil { + return nil, false + } + return f.functions.ResolveFunction(name) } -// AsPartialActivation implements the PartialActivation interface by proxying to the internal activation. +// AsPartialActivation implements the PartialActivation interface by proxying to the internal scope or parent. func (f *ExecutionFrame) AsPartialActivation() (PartialActivation, bool) { - return AsPartialActivation(f.Activation) + if f.scope != nil { + if pa, ok := AsPartialActivation(f.scope); ok { + return pa, true + } + } + if f.parent != nil { + return f.parent.AsPartialActivation() + } + return nil, false +} + +// UnknownAttributePatterns implements the PartialActivation interface returning the unknown patterns +// if they were provided to the input activation, or an empty set if the frame is not partial. +func (f *ExecutionFrame) UnknownAttributePatterns() []*AttributePattern { + if pa, ok := f.AsPartialActivation(); ok { + return pa.UnknownAttributePatterns() + } + return []*AttributePattern{} } -// Unwrap returns the internal activation. +// Unwrap returns the local activation scope if present, or the parent frame. func (f *ExecutionFrame) Unwrap() Activation { - return f.Activation + if f.scope != nil { + return f.scope + } + if f.parent != nil { + return f.parent + } + return nil } // IsLocalVariable reports whether the variable name is locally bound in the frame. func (f *ExecutionFrame) IsLocalVariable(name string) bool { - if holder, ok := f.Activation.(localVariableHolder); ok { + if holder, ok := f.scope.(localVariableHolder); ok { if holder.IsLocalVariable(name) { return true } @@ -231,6 +369,23 @@ func (f *ExecutionFrame) CheckInterrupt() bool { return false } +// CostTracker returns the active CostTracker for this evaluation pass, or nil. +func (f *ExecutionFrame) CostTracker() *CostTracker { + if f == nil { + return nil + } + return f.costTracker +} + +// SetCostTracker sets the active CostTracker for this evaluation pass. +func (f *ExecutionFrame) SetCostTracker(tracker *CostTracker) { + if f.ctx == nil { + f.ctx = evalContextPool.Get().(*evalContext) + } + f.ctx.costs = tracker + f.costTracker = tracker +} + // ComputeResult tracks and computes the result of the given asynchronous function. // // The first invocation for a given (node id, args) tuple registers the call state and returns an @@ -329,117 +484,3 @@ var evalContextPool = &sync.Pool{ return &evalContext{} }, } - -type activationStackPool struct { - sync.Pool -} - -func (pool *activationStackPool) create(parent, child Activation) Activation { - h := pool.Get().(*hierarchicalActivation) - h.child = child - h.parent = parent - h.poolAllocated = true - return h -} - -func (pool *activationStackPool) release(activation Activation) { - h, ok := activation.(*hierarchicalActivation) - if !ok || !h.poolAllocated { - return - } - h.parent = nil - h.child = nil - pool.Pool.Put(h) -} - -func newActivationStackPool() *activationStackPool { - return &activationStackPool{ - Pool: sync.Pool{ - New: func() any { - return &hierarchicalActivation{} - }, - }, - } -} - -type inputActivation struct { - vars map[string]any - lazyVars map[string]any -} - -// ResolveName looks up the value of the input variable name, if found. -// -// Lazy bindings may be supplied within the map-based input in either of the following forms: -// - func() any -// - func() ref.Val -// -// The lazy binding will only be invoked once per evaluation. -// -// Values which are not represented as ref.Val types on input may be adapted to a ref.Val using -// the types.Adapter configured in the environment. -func (a *inputActivation) ResolveName(name string) (any, bool) { - v, found := a.vars[name] - if !found { - return nil, false - } - switch obj := v.(type) { - case func() ref.Val: - if resolved, found := a.lazyVars[name]; found { - return resolved, true - } - lazy := obj() - a.lazyVars[name] = lazy - return lazy, true - case func() any: - if resolved, found := a.lazyVars[name]; found { - return resolved, true - } - lazy := obj() - a.lazyVars[name] = lazy - return lazy, true - default: - return obj, true - } -} - -// Parent implements the Activation interface -func (a *inputActivation) Parent() Activation { - return nil -} - -func newActivationInputPool() *activationInputPool { - return &activationInputPool{ - Pool: sync.Pool{ - New: func() any { - return &inputActivation{ - lazyVars: make(map[string]any), - } - }, - }, - } -} - -type activationInputPool struct { - sync.Pool -} - -// create initializes a pooled Activation object with the map input. -func (p *activationInputPool) create(vars map[string]any) *inputActivation { - a := p.Pool.Get().(*inputActivation) - a.vars = vars - return a -} - -func (p *activationInputPool) release(value any) { - a := value.(*inputActivation) - for k := range a.lazyVars { - delete(a.lazyVars, k) - } - a.vars = nil - p.Pool.Put(a) -} - -var ( - activationStack = newActivationStackPool() - activationInput = newActivationInputPool() -) diff --git a/vendor/github.com/google/cel-go/interpreter/interpretable.go b/vendor/cel.dev/cel-go/interpreter/interpretable.go similarity index 67% rename from vendor/github.com/google/cel-go/interpreter/interpretable.go rename to vendor/cel.dev/cel-go/interpreter/interpretable.go index 906c4f805f..2759a1f336 100644 --- a/vendor/github.com/google/cel-go/interpreter/interpretable.go +++ b/vendor/cel.dev/cel-go/interpreter/interpretable.go @@ -18,12 +18,12 @@ import ( "fmt" "sync" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" ) // Interpretable evaluates an Activation and produces a value. @@ -161,7 +161,7 @@ func (oi *ObservableInterpretable) Exec(frame *ExecutionFrame) ref.Val { // Eval proxies to the ObserveEval method while invoking a no-op callback to report the observations. func (oi *ObservableInterpretable) Eval(vars Activation) ref.Val { - return oi.ObserveExec(AsFrame(vars), func(any) {}) + return oi.ObserveEval(vars, func(any) {}) } // ObserveEval evaluates an interpretable and performs per-evaluation state-tracking. @@ -169,7 +169,16 @@ func (oi *ObservableInterpretable) Eval(vars Activation) ref.Val { // This method is concurrency safe and the expectation is that the observer function will use // a switch statement to determine the type of the state which has been reported back from the call. func (oi *ObservableInterpretable) ObserveEval(vars Activation, observer func(any)) ref.Val { - return oi.ObserveExec(AsFrame(vars), observer) + frame, ok := vars.(*ExecutionFrame) + if !ok { + var err error + frame, err = NewExecutionFrame(vars) + if err != nil { + return types.NewErr("invalid activation: %v", err) + } + defer frame.Close() + } + return oi.ObserveExec(frame, observer) } // ObserveExec evaluates an interpretable and performs per-evaluation state-tracking. @@ -195,18 +204,19 @@ func (oi *ObservableInterpretable) ObserveExec(frame *ExecutionFrame, observer f return result } -// AsFrame promotes an Activation to an ExecutionFrame. -func AsFrame(a Activation) *ExecutionFrame { - if f, ok := a.(*ExecutionFrame); ok { - return f +// EvalActivation runs an InterpretableV2 Exec method safely with any Activation, +// wrapping it in a pooled ExecutionFrame if needed and releasing it after execution. +func EvalActivation(ctx Activation, exec func(*ExecutionFrame) ref.Val) ref.Val { + if f, ok := ctx.(*ExecutionFrame); ok { + return exec(f) } - frame := &ExecutionFrame{Activation: a} - // Walk the activation hierarchy to find a parent ExecutionFrame and inherit - // its shared context. - if parent := findFrame(a); parent != nil { - frame.ctx = parent.ctx + f, err := NewExecutionFrame(ctx) + if err != nil { + return types.NewErr("invalid activation: %v", err) } - return frame + res := exec(f) + f.Close() + return res } // findFrame walks the activation hierarchy via Unwrap and Parent to locate an @@ -243,19 +253,24 @@ func (test *evalTestOnly) ID() int64 { // Exec implements the InterpretableV2 interface method. func (test *evalTestOnly) Exec(frame *ExecutionFrame) ref.Val { val, err := test.Resolve(frame) + var res ref.Val // Return an error if the resolve step fails if err != nil { - return types.LabelErrNode(test.id, types.WrapErr(err)) + res = types.LabelErrNode(test.id, types.WrapErr(err)) + } else if optVal, isOpt := val.(*types.Optional); isOpt { + res = types.Bool(optVal.HasValue()) + } else { + res = test.Adapter().NativeToValue(val) } - if optVal, isOpt := val.(*types.Optional); isOpt { - return types.Bool(optVal.HasValue()) + if costs := frame.CostTracker(); costs != nil { + costs.EvalAttribute(test.id, true, res) } - return test.Adapter().NativeToValue(val) + return res } // Eval implements the Interpretable interface method. func (test *evalTestOnly) Eval(ctx Activation) ref.Val { - return test.Exec(AsFrame(ctx)) + return EvalActivation(ctx, test.Exec) } // AddQualifier appends a qualifier that will always and only perform a presence test. @@ -350,10 +365,14 @@ func (or *evalOr) Exec(frame *ExecutionFrame) ref.Val { return types.True } if !ok { - isUnk := false - unk, isUnk = types.MaybeMergeUnknowns(val, unk) - if !isUnk && err == nil { - if types.IsError(val) { + if unkVal, isUnk := val.(*types.Unknown); isUnk { + if unk == nil { + unk = unkVal + } else { + unk = types.MergeUnknowns(unk, unkVal) + } + } else if err == nil { + if isError(val) { err = val } else { err = types.MaybeNoSuchOverloadErr(val) @@ -373,7 +392,7 @@ func (or *evalOr) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable interface method. func (or *evalOr) Eval(ctx Activation) ref.Val { - return or.Exec(AsFrame(ctx)) + return EvalActivation(ctx, or.Exec) } type evalAnd struct { @@ -398,10 +417,14 @@ func (and *evalAnd) Exec(frame *ExecutionFrame) ref.Val { return types.False } if !ok { - isUnk := false - unk, isUnk = types.MaybeMergeUnknowns(val, unk) - if !isUnk && err == nil { - if types.IsError(val) { + if unkVal, isUnk := val.(*types.Unknown); isUnk { + if unk == nil { + unk = unkVal + } else { + unk = types.MergeUnknowns(unk, unkVal) + } + } else if err == nil { + if isError(val) { err = val } else { err = types.MaybeNoSuchOverloadErr(val) @@ -421,7 +444,7 @@ func (and *evalAnd) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable interface method. func (and *evalAnd) Eval(ctx Activation) ref.Val { - return and.Exec(AsFrame(ctx)) + return EvalActivation(ctx, and.Exec) } type evalEq struct { @@ -438,25 +461,40 @@ func (eq *evalEq) ID() int64 { // Exec implements the InterpretableV2 interface method. func (eq *evalEq) Exec(frame *ExecutionFrame) ref.Val { lVal := eq.lhs.Exec(frame) - if types.IsError(lVal) { + if isError(lVal) { + // To preserve legacy cost tracking behavior for == + // track this cost, but it will be removed in the future. + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, eq.id, eq, lVal, types.UnknownType, lVal) + } return lVal } rVal := eq.rhs.Exec(frame) - if types.IsError(rVal) { + if isError(rVal) { + // To preserve legacy cost tracking behavior for ==, + // track this cost, but it will be removed in the future. + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, eq.id, eq, lVal, rVal, rVal) + } return rVal } - var unk *types.Unknown - unk, _ = types.MaybeMergeUnknowns(lVal, unk) - unk, _ = types.MaybeMergeUnknowns(rVal, unk) - if unk != nil { + if isUnknown(lVal) || isUnknown(rVal) { + unk := mergeBinaryUnknowns(lVal, rVal) + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, eq.id, eq, lVal, rVal, unk) + } return unk } - return types.Equal(lVal, rVal) + res := types.Equal(lVal, rVal) + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, eq.id, eq, lVal, rVal, res) + } + return res } // Eval implements the Interpretable interface method. func (eq *evalEq) Eval(ctx Activation) ref.Val { - return eq.Exec(AsFrame(ctx)) + return EvalActivation(ctx, eq.Exec) } // Function implements the InterpretableCall interface method. @@ -488,25 +526,40 @@ func (ne *evalNe) ID() int64 { // Exec implements the InterpretableV2 interface method. func (ne *evalNe) Exec(frame *ExecutionFrame) ref.Val { lVal := ne.lhs.Exec(frame) - if types.IsError(lVal) { + if isError(lVal) { + // To preserve legacy cost tracking behavior for !=, + // track this cost, but it will be removed in the future. + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, ne.id, ne, lVal, types.UnknownType, lVal) + } return lVal } rVal := ne.rhs.Exec(frame) - if types.IsError(rVal) { + if isError(rVal) { + // To preserve legacy cost tracking behavior for !=, + // track this cost, but it will be removed in the future. + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, ne.id, ne, lVal, rVal, rVal) + } return rVal } - var unk *types.Unknown - unk, _ = types.MaybeMergeUnknowns(lVal, unk) - unk, _ = types.MaybeMergeUnknowns(rVal, unk) - if unk != nil { + if isUnknown(lVal) || isUnknown(rVal) { + unk := mergeBinaryUnknowns(lVal, rVal) + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, ne.id, ne, lVal, rVal, unk) + } return unk } - return types.Bool(types.Equal(lVal, rVal) != types.True) + res := types.Bool(types.Equal(lVal, rVal) != types.True) + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, ne.id, ne, lVal, rVal, res) + } + return res } // Eval implements the Interpretable interface method. func (ne *evalNe) Eval(ctx Activation) ref.Val { - return ne.Exec(AsFrame(ctx)) + return EvalActivation(ctx, ne.Exec) } // Function implements the InterpretableCall interface method. @@ -538,12 +591,16 @@ func (zero *evalZeroArity) ID() int64 { // Exec implements the InterpretableV2 interface method. func (zero *evalZeroArity) Exec(frame *ExecutionFrame) ref.Val { - return types.LabelErrNode(zero.id, zero.impl()) + res := labelErrNode(zero.id, zero.impl()) + if costs := frame.CostTracker(); costs != nil { + costs.EvalZeroArity(frame, zero.id, zero, res) + } + return res } // Eval implements the Interpretable interface method. func (zero *evalZeroArity) Eval(ctx Activation) ref.Val { - return zero.Exec(AsFrame(ctx)) + return EvalActivation(ctx, zero.Exec) } // Function implements the InterpretableCall interface method. @@ -556,7 +613,7 @@ func (zero *evalZeroArity) OverloadID() string { return zero.overload } -// Args returns the argument to the unary function. +// Args implements the InterpretableCall interface method. func (zero *evalZeroArity) Args() []InterpretableV2 { return []InterpretableV2{} } @@ -579,27 +636,47 @@ func (un *evalUnary) ID() int64 { // Exec implements the InterpretableV2 interface method. func (un *evalUnary) Exec(frame *ExecutionFrame) ref.Val { argVal := un.arg.Exec(frame) - // Early return if the argument to the function is unknown or error. + // Early return if the argument to the function is error or unknown in strict mode. strict := !un.nonStrict - if strict && types.IsUnknownOrError(argVal) { - return argVal + if strict { + switch v := argVal.(type) { + case *types.Err: + // To preserve legacy cost tracking behavior for logical not, + // this cost is tracked, but will be removed in the future. + if un.function == operators.LogicalNot { + if costs := frame.CostTracker(); costs != nil { + costs.EvalUnary(frame, un.id, un, argVal, argVal) + } + } + return v + case *types.Unknown: + if costs := frame.CostTracker(); costs != nil { + costs.EvalUnary(frame, un.id, un, argVal, argVal) + } + return v + } } + var res ref.Val // If the implementation is bound and the argument value has the right traits required to // invoke it, then call the implementation. - if un.impl != nil && (un.trait == 0 || (!strict && types.IsUnknownOrError(argVal)) || argVal.Type().HasTrait(un.trait)) { - return types.LabelErrNode(un.id, un.impl(argVal)) + if un.impl != nil && (un.trait == 0 || matchOperandTrait(un.trait, strict, argVal)) { + res = labelErrNode(un.id, un.impl(argVal)) + } else if argVal.Type().HasTrait(traits.ReceiverType) { + // Otherwise, if the argument is a ReceiverType attempt to invoke the receiver method on the + // operand (arg0). + res = labelErrNode(un.id, argVal.(traits.Receiver).Receive(un.function, un.overload, []ref.Val{})) + } else { + res = types.NewErrWithNodeID(un.id, "no such overload: %s", un.function) } - // Otherwise, if the argument is a ReceiverType attempt to invoke the receiver method on the - // operand (arg0). - if argVal.Type().HasTrait(traits.ReceiverType) { - return types.LabelErrNode(un.id, argVal.(traits.Receiver).Receive(un.function, un.overload, []ref.Val{})) + if costs := frame.CostTracker(); costs != nil { + costs.EvalUnary(frame, un.id, un, argVal, res) } - return types.NewErrWithNodeID(un.id, "no such overload: %s", un.function) + return res } // Eval implements the Interpretable interface method. func (un *evalUnary) Eval(ctx Activation) ref.Val { - return un.Exec(AsFrame(ctx)) + return EvalActivation(ctx, un.Exec) } // Function implements the InterpretableCall interface method. @@ -637,37 +714,58 @@ func (bin *evalBinary) ID() int64 { func (bin *evalBinary) Exec(frame *ExecutionFrame) ref.Val { lVal := bin.lhs.Exec(frame) strict := !bin.nonStrict - if strict && types.IsError(lVal) { - return lVal + if strict { + switch lVal.(type) { + case *types.Err: + return lVal + case *types.Unknown: + rVal := bin.rhs.Exec(frame) + if unk, ok := rVal.(*types.Unknown); ok { + res := types.MergeUnknowns(lVal.(*types.Unknown), unk) + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, bin.id, bin, lVal, rVal, res) + } + return res + } + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, bin.id, bin, lVal, rVal, lVal) + } + return lVal + } } rVal := bin.rhs.Exec(frame) - if strict && types.IsError(rVal) { - return rVal - } if strict { - var unk *types.Unknown - unk, _ = types.MaybeMergeUnknowns(lVal, unk) - unk, _ = types.MaybeMergeUnknowns(rVal, unk) - if unk != nil { - return unk + switch rVal.(type) { + case *types.Err: + return rVal + case *types.Unknown: + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, bin.id, bin, lVal, rVal, rVal) + } + return rVal } } + var res ref.Val // If the implementation is bound and the argument value has the right traits required to // invoke it, then call the implementation. - if bin.impl != nil && (bin.trait == 0 || (!strict && types.IsUnknownOrError(lVal)) || lVal.Type().HasTrait(bin.trait)) { - return types.LabelErrNode(bin.id, bin.impl(lVal, rVal)) + if bin.impl != nil && (bin.trait == 0 || matchOperandTrait(bin.trait, strict, lVal)) { + res = labelErrNode(bin.id, bin.impl(lVal, rVal)) + } else if lVal.Type().HasTrait(traits.ReceiverType) { + // Otherwise, if the argument is a ReceiverType attempt to invoke the receiver method on the + // operand (arg0). + res = labelErrNode(bin.id, lVal.(traits.Receiver).Receive(bin.function, bin.overload, []ref.Val{rVal})) + } else { + res = types.NewErrWithNodeID(bin.id, "no such overload: %s", bin.function) } - // Otherwise, if the argument is a ReceiverType attempt to invoke the receiver method on the - // operand (arg0). - if lVal.Type().HasTrait(traits.ReceiverType) { - return types.LabelErrNode(bin.id, lVal.(traits.Receiver).Receive(bin.function, bin.overload, []ref.Val{rVal})) + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, bin.id, bin, lVal, rVal, res) } - return types.NewErrWithNodeID(bin.id, "no such overload: %s", bin.function) + return res } // Eval implements the Interpretable interface method. func (bin *evalBinary) Eval(ctx Activation) ref.Val { - return bin.Exec(AsFrame(ctx)) + return EvalActivation(ctx, bin.Exec) } // Function implements the InterpretableCall interface method. @@ -717,34 +815,61 @@ func (fn *evalVarArgs) Exec(frame *ExecutionFrame) ref.Val { strict := !fn.nonStrict var unk *types.Unknown for i, arg := range fn.args { - argVals[i] = arg.Exec(frame) + argVal := arg.Exec(frame) if strict { - if types.IsError(argVals[i]) { - return argVals[i] + switch v := argVal.(type) { + case *types.Err: + return v + case *types.Unknown: + if unk == nil { + unk = v + } else { + unk = types.MergeUnknowns(unk, v) + } } - unk, _ = types.MaybeMergeUnknowns(argVals[i], unk) } + argVals[i] = argVal } if strict && unk != nil { + if costs := frame.CostTracker(); costs != nil { + costs.EvalVarArgs(frame, fn.id, fn, argVals, unk) + } return unk } + if len(argVals) == 0 { + var res ref.Val + if fn.impl != nil { + res = labelErrNode(fn.id, fn.impl()) + } else { + res = types.NewErrWithNodeID(fn.id, "no such overload: %s %d", fn.function, fn.id) + } + if costs := frame.CostTracker(); costs != nil { + costs.EvalZeroArity(frame, fn.id, fn, res) + } + return res + } + var res ref.Val // If the implementation is bound and the argument value has the right traits required to // invoke it, then call the implementation. arg0 := argVals[0] - if fn.impl != nil && (fn.trait == 0 || (!strict && types.IsUnknownOrError(arg0)) || arg0.Type().HasTrait(fn.trait)) { - return types.LabelErrNode(fn.id, fn.impl(argVals...)) + if fn.impl != nil && matchOperandTrait(fn.trait, strict, arg0) { + res = labelErrNode(fn.id, fn.impl(argVals...)) + } else if arg0.Type().HasTrait(traits.ReceiverType) { + // Otherwise, if the argument is a ReceiverType attempt to invoke the receiver method on the + // operand (arg0). + res = labelErrNode(fn.id, arg0.(traits.Receiver).Receive(fn.function, fn.overload, argVals[1:])) + } else { + res = types.NewErrWithNodeID(fn.id, "no such overload: %s %d", fn.function, fn.id) } - // Otherwise, if the argument is a ReceiverType attempt to invoke the receiver method on the - // operand (arg0). - if arg0.Type().HasTrait(traits.ReceiverType) { - return types.LabelErrNode(fn.id, arg0.(traits.Receiver).Receive(fn.function, fn.overload, argVals[1:])) + if costs := frame.CostTracker(); costs != nil { + costs.EvalVarArgs(frame, fn.id, fn, argVals, res) } - return types.NewErrWithNodeID(fn.id, "no such overload: %s %d", fn.function, fn.id) + return res } // Eval implements the Interpretable interface method. func (fn *evalVarArgs) Eval(ctx Activation) ref.Val { - return fn.Exec(AsFrame(ctx)) + return EvalActivation(ctx, fn.Exec) } // Function implements the InterpretableCall interface method. @@ -757,11 +882,140 @@ func (fn *evalVarArgs) OverloadID() string { return fn.overload } -// Args returns the argument to the unary function. +// Args returns the normalized arguments to the function overload. func (fn *evalVarArgs) Args() []InterpretableV2 { return fn.args } +// evalLateBoundFunc represents a function call where the function implementation is resolved from +// the Activation at evaluation time. +type evalLateBoundFunc struct { + id int64 + function string + overload string + args []InterpretableV2 + trait int + nonStrict bool + member bool + dispatch functions.LateBoundDispatcher +} + +// ID implements the Interpretable interface method. +func (fn *evalLateBoundFunc) ID() int64 { + return fn.id +} + +// Function implements the InterpretableCall interface method. +func (fn *evalLateBoundFunc) Function() string { + return fn.function +} + +// OverloadID implements the InterpretableCall interface method. +func (fn *evalLateBoundFunc) OverloadID() string { + return fn.overload +} + +// Args returns the argument Interpretables for the function call. +func (fn *evalLateBoundFunc) Args() []InterpretableV2 { + return fn.args +} + +// Eval implements the Interpretable interface method. +func (fn *evalLateBoundFunc) Eval(vars Activation) ref.Val { + return EvalActivation(vars, fn.Exec) +} + +// Exec implements the InterpretableV2 interface method. +func (fn *evalLateBoundFunc) Exec(frame *ExecutionFrame) ref.Val { + argVals := make([]ref.Val, len(fn.args)) + strict := !fn.nonStrict + var unk *types.Unknown + for i, arg := range fn.args { + argVals[i] = arg.Exec(frame) + if strict { + if types.IsError(argVals[i]) { + return argVals[i] + } + unk, _ = types.MaybeMergeUnknowns(argVals[i], unk) + } + } + if strict && unk != nil { + if costs := frame.CostTracker(); costs != nil { + costs.EvalVarArgs(frame, fn.id, fn, argVals, unk) + } + return unk + } + var res ref.Val + // A late-bound function is only invoked when the runtime arguments agree with a declared + // overload and the activation supplies a compatible implementation. Unlike other call + // types, there is no fallback to receiver-style dispatch on the operand: the function + // declaration promised a binding supplied at evaluation time, so a missing or mismatched + // binding is unambiguously an error. + if lateFn, found := fn.resolve(frame, argVals, strict); found { + res = types.LabelErrNode(fn.id, lateFn(argVals...)) + } else { + res = types.NewErrWithNodeID(fn.id, "no such overload: %s", fn.function) + } + switch len(argVals) { + case 0: + if costs := frame.CostTracker(); costs != nil { + costs.EvalZeroArity(frame, fn.id, fn, res) + } + case 1: + if costs := frame.CostTracker(); costs != nil { + costs.EvalUnary(frame, fn.id, fn, argVals[0], res) + } + case 2: + if costs := frame.CostTracker(); costs != nil { + costs.EvalBinary(frame, fn.id, fn, argVals[0], argVals[1], res) + } + default: + if costs := frame.CostTracker(); costs != nil { + costs.EvalVarArgs(frame, fn.id, fn, argVals, res) + } + } + return res +} + +// resolve determines which declared overload the runtime arguments satisfy and resolves its +// implementation from the activation. +func (fn *evalLateBoundFunc) resolve(frame *ExecutionFrame, args []ref.Val, strict bool) (functions.FunctionOp, bool) { + overloadID, matched := fn.matchOverload(args, strict) + if !matched { + return nil, false + } + impl, found := frame.ResolveFunction(fn.function) + if !found { + return nil, false + } + return func(args ...ref.Val) ref.Val { return impl(overloadID, args...) }, true +} + +// matchOverload reports the id of the declared overload which matches the runtime arguments. +// +// Plans which were not created from a function declaration have no signature to check against, +// in which case the call falls back to the operand trait recorded for the call site. +func (fn *evalLateBoundFunc) matchOverload(args []ref.Val, strict bool) (string, bool) { + if fn.dispatch != nil { + return fn.dispatch(fn.member, args...) + } + if len(args) == 0 || matchOperandTrait(fn.trait, strict, args[0]) { + return fn.overload, true + } + return "", false +} + +// matchOperandTrait returns true if the operand satisfies the trait required by the function +// implementation, or if the implementation does not require a trait. +// +// Non-strict functions are given the chance to handle unknown and error operands themselves. +func matchOperandTrait(trait int, strict bool, operand ref.Val) bool { + return trait == 0 || + (!strict && types.IsUnknownOrError(operand)) || + operand.Type().HasTrait(trait) +} + +// evalList evaluates a list construction expression. type evalList struct { id int64 elems []InterpretableV2 @@ -777,39 +1031,74 @@ func (l *evalList) ID() int64 { // Exec implements the InterpretableV2 interface method. func (l *evalList) Exec(frame *ExecutionFrame) ref.Val { - elemVals := make([]ref.Val, 0, len(l.elems)) var unk *types.Unknown + if !l.hasOptionals { + elemVals := make([]ref.Val, len(l.elems)) + for i, elem := range l.elems { + elemVal := elem.Exec(frame) + switch v := elemVal.(type) { + case *types.Err: + return v + case *types.Unknown: + if unk == nil { + unk = v + } else { + unk = types.MergeUnknowns(unk, v) + } + } + elemVals[i] = elemVal + } + if unk != nil { + trackCostCreateList(frame, l.id, unk) + return unk + } + res := types.NewRefValList(l.adapter, elemVals) + trackCostCreateList(frame, l.id, res) + return res + } + + elemVals := make([]ref.Val, 0, len(l.elems)) for i, elem := range l.elems { elemVal := elem.Exec(frame) - if types.IsError(elemVal) { - return elemVal - } - unk, _ = types.MaybeMergeUnknowns(elemVal, unk) - if l.hasOptionals && l.optionals[i] { - if types.IsUnknown(elemVal) { - // skip optional checks for unknown values as they aren't fully resolved yet. + switch v := elemVal.(type) { + case *types.Err: + return v + case *types.Unknown: + if unk == nil { + unk = v } else { - optVal, ok := elemVal.(*types.Optional) - if !ok { - return types.LabelErrNode(l.id, invalidOptionalElementInit(elemVal)) - } - if !optVal.HasValue() { + unk = types.MergeUnknowns(unk, v) + } + case *types.Optional: + if l.optionals[i] { + if !v.HasValue() { continue } - elemVal = optVal.GetValue() + elemVal = v.GetValue() + } + default: + if l.optionals[i] { + return types.LabelErrNode(l.id, invalidOptionalElementInit(elemVal)) } } elemVals = append(elemVals, elemVal) } if unk != nil { + if costs := frame.CostTracker(); costs != nil { + costs.CreateList(l.id, unk) + } return unk } - return types.NewRefValList(l.adapter, elemVals) + res := types.NewRefValList(l.adapter, elemVals) + if costs := frame.CostTracker(); costs != nil { + costs.CreateList(l.id, res) + } + return res } // Eval implements the Interpretable interface method. func (l *evalList) Eval(ctx Activation) ref.Val { - return l.Exec(AsFrame(ctx)) + return EvalActivation(ctx, l.Exec) } func (l *evalList) InitVals() []InterpretableV2 { @@ -838,41 +1127,96 @@ func (m *evalMap) ID() int64 { func (m *evalMap) Exec(frame *ExecutionFrame) ref.Val { entries := make(map[ref.Val]ref.Val, len(m.keys)) var unk *types.Unknown + if !m.hasOptionals { + for i, key := range m.keys { + keyVal := key.Exec(frame) + switch v := keyVal.(type) { + case *types.Err: + return v + case *types.Unknown: + if unk == nil { + unk = v + } else { + unk = types.MergeUnknowns(unk, v) + } + } + + valVal := m.vals[i].Exec(frame) + switch v := valVal.(type) { + case *types.Err: + return v + case *types.Unknown: + if unk == nil { + unk = v + } else { + unk = types.MergeUnknowns(unk, v) + } + } + entries[keyVal] = valVal + } + if unk != nil { + trackCostCreateMap(frame, m.id, unk) + return unk + } + res := types.NewRefValMap(m.adapter, entries) + trackCostCreateMap(frame, m.id, res) + return res + } + for i, key := range m.keys { keyVal := key.Exec(frame) - if types.IsError(keyVal) { - return keyVal + switch v := keyVal.(type) { + case *types.Err: + return v + case *types.Unknown: + if unk == nil { + unk = v + } else { + unk = types.MergeUnknowns(unk, v) + } } - unk, _ = types.MaybeMergeUnknowns(keyVal, unk) valVal := m.vals[i].Exec(frame) - if types.IsError(valVal) { - return valVal - } - unk, _ = types.MaybeMergeUnknowns(valVal, unk) - - if m.hasOptionals && m.optionals[i] && !types.IsUnknown(valVal) { - optVal, ok := valVal.(*types.Optional) - if !ok { - return types.LabelErrNode(m.id, invalidOptionalEntryInit(keyVal, valVal)) + switch v := valVal.(type) { + case *types.Err: + return v + case *types.Unknown: + if unk == nil { + unk = v + } else { + unk = types.MergeUnknowns(unk, v) + } + case *types.Optional: + if m.optionals[i] { + if !v.HasValue() { + delete(entries, keyVal) + continue + } + valVal = v.GetValue() } - if !optVal.HasValue() { - delete(entries, keyVal) - continue + default: + if m.optionals[i] { + return types.LabelErrNode(m.id, invalidOptionalEntryInit(keyVal, valVal)) } - valVal = optVal.GetValue() } entries[keyVal] = valVal } if unk != nil { + if costs := frame.CostTracker(); costs != nil { + costs.CreateMap(m.id, unk) + } return unk } - return types.NewRefValMap(m.adapter, entries) + res := types.NewRefValMap(m.adapter, entries) + if costs := frame.CostTracker(); costs != nil { + costs.CreateMap(m.id, res) + } + return res } // Eval implements the Interpretable interface method. func (m *evalMap) Eval(ctx Activation) ref.Val { - return m.Exec(AsFrame(ctx)) + return EvalActivation(ctx, m.Exec) } func (m *evalMap) InitVals() []InterpretableV2 { @@ -914,34 +1258,72 @@ func (o *evalObj) ID() int64 { func (o *evalObj) Exec(frame *ExecutionFrame) ref.Val { fieldVals := make(map[string]ref.Val, len(o.fields)) var unk *types.Unknown + if !o.hasOptionals { + for i, field := range o.fields { + val := o.vals[i].Exec(frame) + switch v := val.(type) { + case *types.Err: + return v + case *types.Unknown: + if unk == nil { + unk = v + } else { + unk = types.MergeUnknowns(unk, v) + } + } + fieldVals[field] = val + } + if unk != nil { + trackCostCreateStruct(frame, o.id, unk) + return unk + } + res := labelErrNode(o.id, o.provider.NewValue(o.typeName, fieldVals)) + trackCostCreateStruct(frame, o.id, res) + return res + } + for i, field := range o.fields { val := o.vals[i].Exec(frame) - if types.IsError(val) { - return val - } - unk, _ = types.MaybeMergeUnknowns(val, unk) - if o.hasOptionals && o.optionals[i] && !types.IsUnknown(val) { - optVal, ok := val.(*types.Optional) - if !ok { - return types.LabelErrNode(o.id, invalidOptionalEntryInit(field, val)) + switch v := val.(type) { + case *types.Err: + return v + case *types.Unknown: + if unk == nil { + unk = v + } else { + unk = types.MergeUnknowns(unk, v) + } + case *types.Optional: + if o.optionals[i] { + if !v.HasValue() { + delete(fieldVals, field) + continue + } + val = v.GetValue() } - if !optVal.HasValue() { - delete(fieldVals, field) - continue + default: + if o.optionals[i] { + return types.LabelErrNode(o.id, invalidOptionalEntryInit(field, val)) } - val = optVal.GetValue() } fieldVals[field] = val } if unk != nil { + if costs := frame.CostTracker(); costs != nil { + costs.CreateStruct(o.id, unk) + } return unk } - return types.LabelErrNode(o.id, o.provider.NewValue(o.typeName, fieldVals)) + res := labelErrNode(o.id, o.provider.NewValue(o.typeName, fieldVals)) + if costs := frame.CostTracker(); costs != nil { + costs.CreateStruct(o.id, res) + } + return res } // Eval implements the Interpretable interface method. func (o *evalObj) Eval(ctx Activation) ref.Val { - return o.Exec(AsFrame(ctx)) + return EvalActivation(ctx, o.Exec) } // InitVals implements the InterpretableConstructor interface method. @@ -966,6 +1348,11 @@ type evalFold struct { result InterpretableV2 adapter types.Adapter + // mutableAccu indicates that static analysis of the comprehension has determined that the + // accumulator is only ever observed by in-place accumulation steps and the final result, and + // may therefore be backed by a mutable list or map without the mutation being observable. + mutableAccu bool + // note an exhaustive fold will ensure that all branches are evaluated // when using mutable values, these branches will mutate the final result // rather than make a throw-away computation. @@ -980,38 +1367,63 @@ func (fold *evalFold) ID() int64 { // Exec implements the InterpretableV2 interface method. func (fold *evalFold) Exec(frame *ExecutionFrame) ref.Val { - // Initialize the folder interface f := newFolder(fold, frame) - defer releaseFolder(f) - foldRange := fold.iterRange.Exec(frame) + + // Early return if the folder is an error or unknown. if types.IsUnknownOrError(foldRange) { + releaseFolder(f) return foldRange } - if fold.iterVar2 != "" { - var foldable traits.Foldable - switch r := foldRange.(type) { - case traits.Mapper: - foldable = types.ToFoldableMap(r) - case traits.Lister: - foldable = types.ToFoldableList(r) - default: + + // Short-circuit the iteration if the range is empty. + if sizer, ok := foldRange.(traits.Sizer); ok && sizer.Size() == types.IntZero { + res := f.evalResult() + releaseFolder(f) + return res + } + + // Otherwise, attempt a two variable fold. + var foldable traits.Foldable + switch r := foldRange.(type) { + case traits.Foldable: + foldable = r + if fold.iterVar2 == "" { + _, f.listV1Fold = foldRange.(traits.Lister) + } + case traits.Mapper: + foldable = types.ToFoldableMap(r) + case traits.Lister: + if fold.iterVar2 == "" { + f.listV1Fold = true + } + foldable = types.ToFoldableList(r) + default: + if fold.iterVar2 != "" { return types.NewErrWithNodeID(fold.ID(), "unsupported comprehension range type: %T", foldRange) } + } + if foldable != nil { foldable.Fold(f) - return f.evalResult() + res := f.evalResult() + releaseFolder(f) + return res } + // If the value is not foldable or just a single variable, fallback to an iterable fold. if !foldRange.Type().HasTrait(traits.IterableType) { + releaseFolder(f) return types.ValOrErr(foldRange, "got '%T', expected iterable type", foldRange) } iterable := foldRange.(traits.Iterable) - return f.foldIterable(iterable) + res := f.foldIterable(iterable) + releaseFolder(f) + return res } // Eval implements the Interpretable interface method. func (fold *evalFold) Eval(ctx Activation) ref.Val { - return fold.Exec(AsFrame(ctx)) + return EvalActivation(ctx, fold.Exec) } // Optional Interpretable implementations that specialize, subsume, or extend the core evaluation @@ -1044,7 +1456,7 @@ func (e *evalSetMembership) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable interface method. func (e *evalSetMembership) Eval(ctx Activation) ref.Val { - return e.Exec(AsFrame(ctx)) + return EvalActivation(ctx, e.Exec) } // evalWatch is an Interpretable implementation that wraps the execution of a given @@ -1063,7 +1475,7 @@ func (e *evalWatch) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable interface method. func (e *evalWatch) Eval(vars Activation) ref.Val { - return e.Exec(AsFrame(vars)) + return EvalActivation(vars, e.Exec) } // evalWatchAttr describes a watcher of an InterpretableAttribute Interpretable. @@ -1127,7 +1539,7 @@ func (e *evalWatchAttr) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable interface method. func (e *evalWatchAttr) Eval(vars Activation) ref.Val { - return e.Exec(AsFrame(vars)) + return EvalActivation(vars, e.Exec) } // evalWatchConstQual observes the qualification of an object using a constant boolean, int, @@ -1263,7 +1675,7 @@ func (e *evalWatchConst) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable interface method. func (e *evalWatchConst) Eval(vars Activation) ref.Val { - return e.Exec(AsFrame(vars)) + return EvalActivation(vars, e.Exec) } // evalExhaustiveOr is just like evalOr, but does not short-circuit argument evaluation. @@ -1290,10 +1702,14 @@ func (or *evalExhaustiveOr) Exec(frame *ExecutionFrame) ref.Val { isTrue = true } if !ok && !isTrue { - isUnk := false - unk, isUnk = types.MaybeMergeUnknowns(val, unk) - if !isUnk && err == nil { - if types.IsError(val) { + if unkVal, isUnk := val.(*types.Unknown); isUnk { + if unk == nil { + unk = unkVal + } else { + unk = types.MergeUnknowns(unk, unkVal) + } + } else if err == nil { + if isError(val) { err = val } else { err = types.MaybeNoSuchOverloadErr(val) @@ -1315,7 +1731,7 @@ func (or *evalExhaustiveOr) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable interface method. func (or *evalExhaustiveOr) Eval(ctx Activation) ref.Val { - return or.Exec(AsFrame(ctx)) + return EvalActivation(ctx, or.Exec) } // evalExhaustiveAnd is just like evalAnd, but does not short-circuit argument evaluation. @@ -1342,10 +1758,14 @@ func (and *evalExhaustiveAnd) Exec(frame *ExecutionFrame) ref.Val { isFalse = true } if !ok && !isFalse { - isUnk := false - unk, isUnk = types.MaybeMergeUnknowns(val, unk) - if !isUnk && err == nil { - if types.IsError(val) { + if unkVal, isUnk := val.(*types.Unknown); isUnk { + if unk == nil { + unk = unkVal + } else { + unk = types.MergeUnknowns(unk, unkVal) + } + } else if err == nil { + if isError(val) { err = val } else { err = types.MaybeNoSuchOverloadErr(val) @@ -1367,7 +1787,7 @@ func (and *evalExhaustiveAnd) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable interface method. func (and *evalExhaustiveAnd) Eval(ctx Activation) ref.Val { - return and.Exec(AsFrame(ctx)) + return EvalActivation(ctx, and.Exec) } // evalExhaustiveConditional is like evalConditional, but does not short-circuit argument @@ -1406,7 +1826,7 @@ func (cond *evalExhaustiveConditional) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable interface method. func (cond *evalExhaustiveConditional) Eval(ctx Activation) ref.Val { - return cond.Exec(AsFrame(ctx)) + return EvalActivation(ctx, cond.Exec) } // evalAttr evaluates an Attribute value. @@ -1443,15 +1863,23 @@ func (a *evalAttr) Adapter() types.Adapter { // Exec implements the InterpretableV2 interface method. func (a *evalAttr) Exec(frame *ExecutionFrame) ref.Val { v, err := a.attr.Resolve(frame) + var res ref.Val if err != nil { - return types.LabelErrNode(a.ID(), types.WrapErr(err)) + res = types.LabelErrNode(a.ID(), types.WrapErr(err)) + } else { + res = a.adapter.NativeToValue(v) + } + if _, isCond := a.attr.(*conditionalAttribute); !isCond { + if costs := frame.CostTracker(); costs != nil { + costs.EvalAttribute(a.ID(), false, res) + } } - return a.adapter.NativeToValue(v) + return res } // Eval implements the Interpretable interface method. func (a *evalAttr) Eval(ctx Activation) ref.Val { - return a.Exec(AsFrame(ctx)) + return EvalActivation(ctx, a.Exec) } // Qualify proxies to the Attribute's Qualify method. @@ -1502,7 +1930,7 @@ func (c *evalWatchConstructor) Exec(frame *ExecutionFrame) ref.Val { // Eval implements the Interpretable Eval function. func (c *evalWatchConstructor) Eval(vars Activation) ref.Val { - return c.Exec(AsFrame(vars)) + return EvalActivation(vars, c.Exec) } func invalidOptionalEntryInit(field any, value ref.Val) ref.Val { @@ -1550,6 +1978,7 @@ type folder struct { mutableValue bool interrupted bool computeResult bool + listV1Fold bool } func (f *folder) foldIterable(iterable traits.Iterable) ref.Val { @@ -1558,12 +1987,17 @@ func (f *folder) foldIterable(iterable traits.Iterable) ref.Val { f.iterVar1Val = it.Next() cond := f.cond.Exec(f.frame) - condBool, ok := cond.(types.Bool) - if f.interrupted || (!f.exhaustive && ok && condBool != types.True) { + if f.interrupted { + return f.evalResult() + } + if !f.exhaustive && cond != types.True { + if isError(cond) { + f.interrupted = true + } return f.evalResult() } - // Update the accumulation value and check for eval interuption. + // Update the accumulation value and check for eval interruption. f.accuVal = f.step.Exec(f.frame) f.initialized = true if f.interruptable && f.frame.CheckInterrupt() { @@ -1574,22 +2008,36 @@ func (f *folder) foldIterable(iterable traits.Iterable) ref.Val { return f.evalResult() } +// FoldKeyOnly reports whether the folder only consumes the entry key (e.g. 1-variable map +// comprehensions where iterVar2 is empty and listV1Fold is false). +func (f *folder) FoldKeyOnly() bool { + return f.iterVar2 == "" && !f.listV1Fold +} + // FoldEntry will either fold comprehension v1 style macros if iterVar2 is unset, or comprehension v2 style // macros if both the iterVar and iterVar2 are set to non-empty strings. func (f *folder) FoldEntry(key, val any) bool { - // Default to referencing both values. - f.iterVar1Val = key - f.iterVar2Val = val + if f.listV1Fold { + f.iterVar1Val = val + } else { + f.iterVar1Val = key + f.iterVar2Val = val + } // Terminate evaluation if evaluation is interrupted or the condition is not true and exhaustive // eval is not enabled. cond := f.cond.Exec(f.frame) - condBool, ok := cond.(types.Bool) - if f.interrupted || (!f.exhaustive && ok && condBool != types.True) { + if f.interrupted { + return false + } + if !f.exhaustive && cond != types.True { + if isError(cond) { + f.interrupted = true + } return false } - // Update the accumulation value and check for eval interuption. + // Update the accumulation value and check for eval interruption. f.accuVal = f.step.Exec(f.frame) f.initialized = true if f.interruptable && f.frame.CheckInterrupt() { @@ -1607,7 +2055,10 @@ func (f *folder) ResolveName(name string) (any, bool) { if !f.initialized { f.initialized = true initVal := f.accu.Exec(f.frame.parent) - if !f.exhaustive { + // Only substitute a mutable accumulator when the planner has proven that the + // accumulator cannot be aliased, and when evaluation is not exhaustive since + // exhaustive evaluation would apply in-place updates from untaken branches. + if f.mutableAccu && !f.exhaustive { if l, isList := initVal.(traits.Lister); isList && l.Size() == types.IntZero { initVal = types.NewMutableList(f.adapter) f.mutableValue = true @@ -1623,11 +2074,9 @@ func (f *folder) ResolveName(name string) (any, bool) { } if !f.computeResult { if name == f.iterVar { - f.iterVar1Val = f.adapter.NativeToValue(f.iterVar1Val) return f.iterVar1Val, true } if name == f.iterVar2 { - f.iterVar2Val = f.adapter.NativeToValue(f.iterVar2Val) return f.iterVar2Val, true } } @@ -1652,11 +2101,7 @@ func (f *folder) IsLocalVariable(name string) bool { if !f.computeResult && (name == f.iterVar || name == f.iterVar2) { return true } - parent := f.Parent() - if parent == nil { - return false - } - if varHolder, ok := parent.(localVariableHolder); ok { + if varHolder, ok := f.Parent().(localVariableHolder); ok { if varHolder.IsLocalVariable(name) { return true } @@ -1667,8 +2112,8 @@ func (f *folder) IsLocalVariable(name string) bool { // UnknownAttributePatterns implements the PartialActivation interface returning the unknown patterns // if they were provided to the input activation, or an empty set if the proxied activation is not partial. func (f *folder) UnknownAttributePatterns() []*AttributePattern { - if pv, ok := f.frame.parent.Activation.(partialActivationConverter); ok { - if partial, isPartial := pv.AsPartialActivation(); isPartial { + if f.frame.parent != nil { + if partial, isPartial := f.frame.parent.AsPartialActivation(); isPartial { return partial.UnknownAttributePatterns() } } @@ -1676,8 +2121,8 @@ func (f *folder) UnknownAttributePatterns() []*AttributePattern { } func (f *folder) AsPartialActivation() (PartialActivation, bool) { - if pv, ok := f.frame.parent.Activation.(partialActivationConverter); ok { - if _, isPartial := pv.AsPartialActivation(); isPartial { + if f.frame.parent != nil { + if _, isPartial := f.frame.parent.AsPartialActivation(); isPartial { return f, true } } @@ -1717,6 +2162,7 @@ func (f *folder) reset() { f.mutableValue = false f.interrupted = false f.computeResult = false + f.listV1Fold = false } // InterruptError is a specialized error type used to signal that program evaluation should check @@ -1741,3 +2187,68 @@ var ( }, } ) + +func trackCostCreateList(frame *ExecutionFrame, id int64, res ref.Val) { + if costs := frame.CostTracker(); costs != nil { + costs.CreateList(id, res) + } +} + +func trackCostCreateMap(frame *ExecutionFrame, id int64, res ref.Val) { + if costs := frame.CostTracker(); costs != nil { + costs.CreateMap(id, res) + } +} + +func trackCostCreateStruct(frame *ExecutionFrame, id int64, res ref.Val) { + if costs := frame.CostTracker(); costs != nil { + costs.CreateStruct(id, res) + } +} + +func trackCostQualify(frame *ExecutionFrame, id int64) { + if costs := frame.CostTracker(); costs != nil { + costs.Qualify(id) + } +} + +func isError(val ref.Val) bool { + _, ok := val.(*types.Err) + return ok +} + +func isUnknown(val ref.Val) bool { + _, ok := val.(*types.Unknown) + return ok +} + +func mergeBinaryUnknowns(lVal, rVal ref.Val) *types.Unknown { + lUnk, lIsUnk := lVal.(*types.Unknown) + rUnk, rIsUnk := rVal.(*types.Unknown) + if !lIsUnk { + if !rIsUnk { + return nil + } + return rUnk + } + if !rIsUnk { + return lUnk + } + return types.MergeUnknowns(lUnk, rUnk) +} + +func mergeUnknown(dst *types.Unknown, src ref.Val) *types.Unknown { + if unk, ok := src.(*types.Unknown); ok { + if dst == nil { + return unk + } + return types.MergeUnknowns(dst, unk) + } + return dst +} +func labelErrNode(id int64, val ref.Val) ref.Val { + if err, ok := val.(*types.Err); ok && err.NodeID() == 0 { + return types.LabelErrNode(id, err) + } + return val +} diff --git a/vendor/github.com/google/cel-go/interpreter/interpreter.go b/vendor/cel.dev/cel-go/interpreter/interpreter.go similarity index 96% rename from vendor/github.com/google/cel-go/interpreter/interpreter.go rename to vendor/cel.dev/cel-go/interpreter/interpreter.go index 29df9d41ed..da642440d9 100644 --- a/vendor/github.com/google/cel-go/interpreter/interpreter.go +++ b/vendor/cel.dev/cel-go/interpreter/interpreter.go @@ -20,10 +20,10 @@ package interpreter import ( "errors" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/containers" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/containers" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // PlannerOption configures the program plan options during interpretable setup. @@ -50,7 +50,7 @@ type StatefulObserver interface { GetState(*ExecutionFrame) any // Observe passes the activation and relevant evaluation metadata to the observer. - // The observe method is expected to do the equivalent of GetState(AsFrame(activation)) + // The observe method is expected to do the equivalent of GetState(frame) // to find the metadata that needs to be updated upon invocation. Observe(Activation, int64, any, ref.Val) } @@ -76,6 +76,10 @@ const ( // CostLimitExceeded indicates that the operation was cancelled in response to the actual cost limit being // exceeded. CostLimitExceeded + + // MemoryLimitExceeded indicates that the operation was cancelled in response to the peak memory limit + // being exceeded. + MemoryLimitExceeded ) // evalStateOption configures the evalStateFactory behavior. @@ -101,7 +105,6 @@ func EvalStateObserver(opts ...evalStateOption) PlannerOption { return nil, errors.New("eval state factory not configured") } p.observers = append(p.observers, et) - p.decorators = append(p.decorators, decObserveEval(et.Observe)) return p, nil } } @@ -148,7 +151,10 @@ func (et *evalStateFactory) GetState(frame *ExecutionFrame) any { // Observe records the evaluation state for a given expression node and program step. func (et *evalStateFactory) Observe(vars Activation, id int64, programStep any, val ref.Val) { - frame := AsFrame(vars) + frame, ok := vars.(*ExecutionFrame) + if !ok { + return + } if frame.ctx == nil || frame.ctx.state == nil { return } diff --git a/vendor/github.com/google/cel-go/interpreter/optimizations.go b/vendor/cel.dev/cel-go/interpreter/optimizations.go similarity index 94% rename from vendor/github.com/google/cel-go/interpreter/optimizations.go rename to vendor/cel.dev/cel-go/interpreter/optimizations.go index 2fc87e693b..c6478fa72c 100644 --- a/vendor/github.com/google/cel-go/interpreter/optimizations.go +++ b/vendor/cel.dev/cel-go/interpreter/optimizations.go @@ -17,8 +17,8 @@ package interpreter import ( "regexp" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // MatchesRegexOptimization optimizes the 'matches' standard library function by compiling the regex pattern and diff --git a/vendor/github.com/google/cel-go/interpreter/planner.go b/vendor/cel.dev/cel-go/interpreter/planner.go similarity index 79% rename from vendor/github.com/google/cel-go/interpreter/planner.go rename to vendor/cel.dev/cel-go/interpreter/planner.go index 396a9803fc..81e8a54227 100644 --- a/vendor/github.com/google/cel-go/interpreter/planner.go +++ b/vendor/cel.dev/cel-go/interpreter/planner.go @@ -18,13 +18,18 @@ import ( "fmt" "strings" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/containers" - "github.com/google/cel-go/common/functions" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/types" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/containers" + "cel.dev/cel-go/common/functions" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) +// mapInsertFunction is the name of the internal function used by comprehension macros to insert +// key-value pairs into a map accumulator. +const mapInsertFunction = "cel.@mapInsert" + // newPlanner creates an interpretablePlanner which references a Dispatcher, TypeProvider, // TypeAdapter, Container, and CheckedExpr value. These pieces of data are used to resolve // functions, types, and namespaced identifiers at plan time rather than at runtime since @@ -50,15 +55,16 @@ func newPlanner(disp Dispatcher, // planner is an implementation of the interpretablePlanner interface. type planner struct { - disp Dispatcher - provider types.Provider - adapter types.Adapter - attrFactory AttributeFactory - container *containers.Container - refMap map[int64]*ast.ReferenceInfo - typeMap map[int64]*types.Type - decorators []InterpretableDecoratorV2 - observers []StatefulObserver + disp Dispatcher + provider types.Provider + adapter types.Adapter + attrFactory AttributeFactory + container *containers.Container + refMap map[int64]*ast.ReferenceInfo + typeMap map[int64]*types.Type + decorators []InterpretableDecoratorV2 + observers []StatefulObserver + costTrackerFactory func() (*CostTracker, error) } type planBuilder struct { @@ -73,17 +79,38 @@ type planBuilder struct { // such as state-tracking, expression re-write, and possibly efficient thread-safe memoization of // repeated expressions. func (p *planner) Plan(expr ast.Expr) (InterpretableV2, error) { + if len(p.observers) != 0 { + // A single decorator reports to every observer. One decorator per observer would not + // work, since the second decorator would find the node already wrapped by the first and + // leave it alone, silently dropping the second observer's observations. + p.decorators = append(p.decorators, decObserveEval(observeAll(p.observers))) + } pb := &planBuilder{planner: p, localVars: make(map[string]int)} i, err := pb.plan(expr) if err != nil { return nil, err } + if p.costTrackerFactory != nil { + i = &costTrackingInterpretable{InterpretableV2: i, factory: p.costTrackerFactory} + } if len(p.observers) == 0 { return i, nil } return &ObservableInterpretable{InterpretableV2: i, observers: p.observers}, nil } +// observeAll returns an EvalObserver which reports each observation to all of the observers. +func observeAll(observers []StatefulObserver) EvalObserver { + if len(observers) == 1 { + return observers[0].Observe + } + return func(vars Activation, id int64, programStep any, value ref.Val) { + for _, o := range observers { + o.Observe(vars, id, programStep, value) + } + } +} + func (p *planBuilder) plan(expr ast.Expr) (InterpretableV2, error) { switch expr.Kind() { case ast.CallKind: @@ -285,6 +312,10 @@ func (p *planBuilder) planCall(expr ast.Expr) (InterpretableV2, error) { if fnDef != nil && fnDef.Async != nil { return p.planCallAsync(expr, fnName, oName, fnDef, args) } + // Late-bound overloads are planned into an evalLateBoundFunc regardless of arity. + if fnDef != nil && fnDef.LateBound { + return p.planCallLateBound(expr, fnName, oName, fnDef, target != nil, args) + } switch argCount { case 0: return p.planCallZero(expr, fnName, oName, fnDef) @@ -307,6 +338,28 @@ func (p *planBuilder) planCall(expr ast.Expr) (InterpretableV2, error) { } } +// planCallLateBound generates a late-bound callable Interpretable. +func (p *planBuilder) planCallLateBound(expr ast.Expr, + function string, + overload string, + impl *functions.Overload, + memberStyle bool, + args []InterpretableV2) (InterpretableV2, error) { + if impl == nil || !impl.LateBound { + return nil, fmt.Errorf("no such overload: %s()", function) + } + return &evalLateBoundFunc{ + id: expr.ID(), + function: function, + overload: overload, + args: args, + trait: impl.OperandTrait, + nonStrict: impl.NonStrict, + member: memberStyle, + dispatch: impl.LateBoundDispatch, + }, nil +} + // planCallAsync generates an asynchronous callable Interpretable. func (p *planBuilder) planCallAsync(expr ast.Expr, function string, @@ -647,19 +700,117 @@ func (p *planBuilder) planComprehension(expr ast.Expr) (InterpretableV2, error) } p.popLocalVars(fold.AccuVar()) return &evalFold{ - id: expr.ID(), - accuVar: fold.AccuVar(), - accu: accu, - iterVar: fold.IterVar(), - iterVar2: fold.IterVar2(), - iterRange: iterRange, - cond: cond, - step: step, - result: result, - adapter: p.adapter, + id: expr.ID(), + accuVar: fold.AccuVar(), + accu: accu, + iterVar: fold.IterVar(), + iterVar2: fold.IterVar2(), + iterRange: iterRange, + cond: cond, + step: step, + result: result, + adapter: p.adapter, + mutableAccu: isMutableAccuSafe(fold), }, nil } +// isMutableAccuSafe reports whether the comprehension accumulator may be backed by a mutable +// list or map during evaluation. +// +// The checks mirror cel-cpp's IsOptimizableListAppend and IsOptimizableMapInsert in +// eval/compiler/flat_expr_builder.cc: the comprehension must have the shape of a standard +// list-building (map/filter/transformList) or map-building (transformMap/transformMapEntry) +// macro expansion. +// +// In addition to the cel-cpp checks, the accumulator variable must be non-empty, must not be +// shadowed by either of the iteration variables, and must begin with '@'. Since '@' cannot +// appear in an identifier written in CEL source, for ASTs produced by the parser and macros this +// ensures that the accumulator is only referenced where the macro expansion placed it and cannot +// be observed or modified by user expressions within the comprehension, e.g. via a legacy +// accumulator name like `__result__` or a custom macro which uses a user-visible accumulator +// name. Hand-crafted ASTs are assumed to be trusted input. +func isMutableAccuSafe(fold ast.ComprehensionExpr) bool { + accuVar := fold.AccuVar() + if !strings.HasPrefix(accuVar, "@") || accuVar == fold.IterVar() || accuVar == fold.IterVar2() { + return false + } + return isOptimizableListAppend(fold) || isOptimizableMapInsert(fold) +} + +// isOptimizableListAppend mirrors cel-cpp's IsOptimizableListAppend. +// +// Returns whether this comprehension appears to be a standard map/filter macro implementation. +func isOptimizableListAppend(fold ast.ComprehensionExpr) bool { + accuVar := fold.AccuVar() + if accuVar == "" || !isIdentNamed(fold.Result(), accuVar) { + return false + } + accuInit := fold.AccuInit() + if accuInit.Kind() != ast.ListKind || accuInit.AsList().Size() != 0 { + return false + } + step := fold.LoopStep() + if step.Kind() != ast.CallKind { + return false + } + // Macro loop_step for a filter() will contain a ternary: + // filter ? accu_var + [elem] : accu_var + // Macro loop_step for a map() will contain a list concat operation: + // accu_var + [elem] + call := step.AsCall() + if call.FunctionName() == operators.Conditional && len(call.Args()) == 3 { + branch := call.Args()[1] + if branch.Kind() != ast.CallKind { + return false + } + call = branch.AsCall() + } + args := call.Args() + return call.FunctionName() == operators.Add && + len(args) == 2 && + isIdentNamed(args[0], accuVar) && + args[1].Kind() == ast.ListKind && + args[1].AsList().Size() == 1 +} + +// isOptimizableMapInsert mirrors cel-cpp's IsOptimizableMapInsert. +// +// Returns whether this comprehension appears to be a macro implementation for map +// transformations. +func isOptimizableMapInsert(fold ast.ComprehensionExpr) bool { + if fold.IterVar() == "" || fold.IterVar2() == "" { + return false + } + accuVar := fold.AccuVar() + if accuVar == "" || !isIdentNamed(fold.Result(), accuVar) { + return false + } + if fold.AccuInit().Kind() != ast.MapKind || fold.AccuInit().AsMap().Size() != 0 { + return false + } + step := fold.LoopStep() + if step.Kind() != ast.CallKind { + return false + } + call := step.AsCall() + if call.FunctionName() == operators.Conditional && len(call.Args()) == 3 { + branch := call.Args()[1] + if branch.Kind() != ast.CallKind { + return false + } + call = branch.AsCall() + } + args := call.Args() + return call.FunctionName() == mapInsertFunction && + (len(args) == 2 || len(args) == 3) && + isIdentNamed(args[0], accuVar) +} + +// isIdentNamed reports whether the expression is an identifier with the given name. +func isIdentNamed(e ast.Expr, name string) bool { + return e != nil && e.Kind() == ast.IdentKind && e.AsIdent() == name +} + // planConst generates a constant valued Interpretable. func (p *planBuilder) planConst(expr ast.Expr) (InterpretableV2, error) { return NewConstValue(expr.ID(), expr.AsLiteral()), nil diff --git a/vendor/github.com/google/cel-go/interpreter/prune.go b/vendor/cel.dev/cel-go/interpreter/prune.go similarity index 98% rename from vendor/github.com/google/cel-go/interpreter/prune.go rename to vendor/cel.dev/cel-go/interpreter/prune.go index 1662c1c1b3..9f55f1a811 100644 --- a/vendor/github.com/google/cel-go/interpreter/prune.go +++ b/vendor/cel.dev/cel-go/interpreter/prune.go @@ -15,12 +15,12 @@ package interpreter import ( - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/overloads" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" ) type astPruner struct { diff --git a/vendor/cel.dev/cel-go/interpreter/runtimecost.go b/vendor/cel.dev/cel-go/interpreter/runtimecost.go new file mode 100644 index 0000000000..e974f4f14f --- /dev/null +++ b/vendor/cel.dev/cel-go/interpreter/runtimecost.go @@ -0,0 +1,136 @@ +// Copyright 2022 Google LLC +// +// 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 interpreter + +import ( + "errors" + + "cel.dev/cel-go/common/cost" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" +) + +// WARNING: Any changes to cost calculations in this file require a corresponding change in checker/cost.go + +type ( + // ActualCostEstimator provides function call cost estimations at runtime + // + // Deprecated: use cost.ActualCostEstimator + ActualCostEstimator = cost.ActualCostEstimator + + // FunctionTracker computes the actual cost of evaluating the functions with the given arguments and result. + // + // Deprecated: use cost.FunctionTracker + FunctionTracker = cost.FunctionTracker + + // CostTrackerOption configures the behavior of CostTracker objects. + // + // Deprecated: use cost.CostTrackerOption + CostTrackerOption = cost.TrackerOption + + // CostTracker represents the information needed for tracking runtime cost. + // + // Deprecated: use cost.CostTracker + CostTracker = cost.Tracker +) + +// CostTrackerLimit sets the runtime limit on the evaluation cost during execution and will terminate the expression +// evaluation if the limit is exceeded. +// +// Deprecated: use cost.CostTrackerLimit +func CostTrackerLimit(limit uint64) CostTrackerOption { + return cost.TrackerLimit(limit) +} + +// PresenceTestHasCost determines whether presence testing has a cost of one or zero. +// Defaults to presence test has a cost of one. +// +// Deprecated: use cost.CostTrackerPresenceTestHasCost +func PresenceTestHasCost(hasCost bool) CostTrackerOption { + return cost.TrackerPresenceTestHasCost(hasCost) +} + +// OverloadCostTracker binds an overload ID to a runtime FunctionTracker implementation. +// +// Deprecated: use cost.OverloadCostTracker +func OverloadCostTracker(overloadID string, fnTracker FunctionTracker) CostTrackerOption { + return cost.OverloadTracker(overloadID, fnTracker) +} + +// NewCostTracker creates a new CostTracker with a given estimator and a set of functional CostTrackerOption values. +// +// Deprecated: use cost.NewCostTracker +func NewCostTracker(estimator ActualCostEstimator, opts ...CostTrackerOption) (*CostTracker, error) { + evalCancelHandler := cost.TrackerLimitExceededHandler(func() { + panic(EvalCancelledError{Cause: CostLimitExceeded, Message: "operation cancelled: actual cost limit exceeded"}) + }) + allOpts := make([]cost.TrackerOption, 0, len(opts)+1) + allOpts = append(allOpts, evalCancelHandler) + allOpts = append(allOpts, opts...) + return cost.NewTracker(estimator, allOpts...) +} + +// CostTrackPlanOption modifies the cost tracking factory associated with the CostObserver. +type CostTrackPlanOption func(*costTrackerFactory) *costTrackerFactory + +type costTrackPlanOption = CostTrackPlanOption + +// CostTrackerFactory configures the factory method to generate a new cost-tracker per-evaluation. +func CostTrackerFactory(factory func() (*CostTracker, error)) CostTrackPlanOption { + return func(fac *costTrackerFactory) *costTrackerFactory { + fac.factory = factory + return fac + } +} + +// CostObserver provides an observer that tracks runtime cost. +func CostObserver(opts ...CostTrackPlanOption) PlannerOption { + ct := &costTrackerFactory{} + for _, o := range opts { + ct = o(ct) + } + return func(p *planner) (*planner, error) { + if ct.factory == nil { + return nil, errors.New("cost tracker factory not configured") + } + p.costTrackerFactory = ct.factory + return p, nil + } +} + +// costTrackerFactory holds a factory for producing new CostTracker instances on each Eval call. +type costTrackerFactory struct { + factory func() (*CostTracker, error) +} + +type costTrackingInterpretable struct { + InterpretableV2 + factory func() (*CostTracker, error) +} + +func (c *costTrackingInterpretable) Exec(frame *ExecutionFrame) ref.Val { + if frame.CostTracker() == nil { + tracker, err := c.factory() + if err != nil { + return types.NewErr("cost tracker factory: %v", err) + } + frame.SetCostTracker(tracker) + } + return c.InterpretableV2.Exec(frame) +} + +func (c *costTrackingInterpretable) Eval(ctx Activation) ref.Val { + return EvalActivation(ctx, c.Exec) +} diff --git a/vendor/cel.dev/cel-go/interpreter/runtimememory.go b/vendor/cel.dev/cel-go/interpreter/runtimememory.go new file mode 100644 index 0000000000..c4d8a02ac7 --- /dev/null +++ b/vendor/cel.dev/cel-go/interpreter/runtimememory.go @@ -0,0 +1,105 @@ +// Copyright 2026 Google LLC +// +// 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 interpreter + +import ( + "errors" + + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" +) + +// memoryTrackPlanOption modifies the memory tracking factory associated with the MemoryObserver. +type memoryTrackPlanOption func(*memoryTrackerFactory) *memoryTrackerFactory + +// MemoryTrackerFactory configures the factory method to generate a new memory-tracker +// per-evaluation. +func MemoryTrackerFactory(factory func() (*types.MemoryTracker, error)) memoryTrackPlanOption { + return func(fac *memoryTrackerFactory) *memoryTrackerFactory { + fac.factory = factory + return fac + } +} + +// MemoryObserver provides an observer that tracks runtime peak memory. +func MemoryObserver(opts ...memoryTrackPlanOption) PlannerOption { + mt := &memoryTrackerFactory{} + for _, o := range opts { + mt = o(mt) + } + return func(p *planner) (*planner, error) { + if mt.factory == nil { + return nil, errors.New("memory tracker factory not configured") + } + p.observers = append(p.observers, mt) + return p, nil + } +} + +// memoryTrackerFactory holds a factory for producing new MemoryTracker instances on each Eval call. +type memoryTrackerFactory struct { + factory func() (*types.MemoryTracker, error) +} + +// InitState produces a MemoryTracker and bundles it into the ExecutionFrame in a way which is +// not visible to expression evaluation. +func (mt *memoryTrackerFactory) InitState(frame *ExecutionFrame) (any, error) { + if frame.ctx != nil && frame.ctx.memory != nil { + return frame.ctx.memory, nil + } + tracker, err := mt.factory() + if err != nil { + return nil, err + } + if frame.ctx == nil { + frame.ctx = evalContextPool.Get().(*evalContext) + } + frame.ctx.memory = tracker + return tracker, nil +} + +// GetState extracts the MemoryTracker from the ExecutionFrame. +func (mt *memoryTrackerFactory) GetState(frame *ExecutionFrame) any { + if frame == nil || frame.ctx == nil { + return nil + } + return frame.ctx.memory +} + +// Observe records the peak memory watermarks associated with each evaluation step. +// +// Watermarks are observed at the points where values materialize during evaluation: resolved +// attributes, function call results, constructed aggregate literals, and comprehension results. +// Since every intermediate Interpretable is observed, the inputs to a call contribute to the +// peak at the expression nodes which produced them; constants are part of the program image +// rather than runtime-materialized memory and are not observed. +func (mt *memoryTrackerFactory) Observe(vars Activation, id int64, programStep any, val ref.Val) { + frame, ok := vars.(*ExecutionFrame) + if !ok || frame.ctx == nil || frame.ctx.memory == nil { + return + } + tracker := frame.ctx.memory + switch programStep.(type) { + case InterpretableAttribute, InterpretableConst, InterpretableCall, InterpretableConstructor, *evalFold: + if frame.parent != nil { + tracker.Sample(id, val) + } else { + tracker.Track(val) + } + if tracker.ExceedsLimit() { + panic(EvalCancelledError{Cause: MemoryLimitExceeded, Message: "operation cancelled: memory limit exceeded"}) + } + } +} diff --git a/vendor/github.com/google/cel-go/parser/BUILD.bazel b/vendor/cel.dev/cel-go/parser/BUILD.bazel similarity index 86% rename from vendor/github.com/google/cel-go/parser/BUILD.bazel rename to vendor/cel.dev/cel-go/parser/BUILD.bazel index 97bc9bd434..138b9ee529 100644 --- a/vendor/github.com/google/cel-go/parser/BUILD.bazel +++ b/vendor/cel.dev/cel-go/parser/BUILD.bazel @@ -7,16 +7,19 @@ package( go_library( name = "go_default_library", srcs = [ + "antlr_parser.go", "errors.go", "helper.go", "input.go", + "lexer.go", "macro.go", "options.go", "parser.go", + "pratt_parser.go", "unescape.go", "unparser.go", ], - importpath = "github.com/google/cel-go/parser", + importpath = "cel.dev/cel-go/parser", visibility = ["//visibility:public"], deps = [ "//common:go_default_library", @@ -38,6 +41,7 @@ go_test( size = "small", srcs = [ "helper_test.go", + "lexer_test.go", "parser_test.go", "unescape_test.go", "unparser_test.go", @@ -46,8 +50,11 @@ go_test( ":go_default_library", ], deps = [ + "//common:go_default_library", "//common/ast:go_default_library", "//common/debug:go_default_library", + "//common/operators:go_default_library", + "//common/runes:go_default_library", "//common/types:go_default_library", "//parser/gen:go_default_library", "//test:go_default_library", diff --git a/vendor/github.com/google/cel-go/parser/parser.go b/vendor/cel.dev/cel-go/parser/antlr_parser.go similarity index 80% rename from vendor/github.com/google/cel-go/parser/parser.go rename to vendor/cel.dev/cel-go/parser/antlr_parser.go index 338233543d..e755b7ac7b 100644 --- a/vendor/github.com/google/cel-go/parser/parser.go +++ b/vendor/cel.dev/cel-go/parser/antlr_parser.go @@ -1,4 +1,4 @@ -// Copyright 2018 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package parser declares an expression parser with support for macro -// expansion. package parser import ( @@ -25,84 +23,28 @@ import ( antlr "github.com/antlr4-go/antlr/v4" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/runes" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/parser/gen" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/runes" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/parser/gen" ) -// Parser encapsulates the context necessary to perform parsing for different expressions. -type Parser struct { +// antlrParser encapsulates the context necessary to perform ANTLR parsing for different expressions. +type antlrParser struct { options } -// NewParser builds and returns a new Parser using the provided options. -func NewParser(opts ...Option) (*Parser, error) { - p := &Parser{} - p.enableHiddenAccumulatorName = true - p.enableIdentEscapeSyntax = true - for _, opt := range opts { - if err := opt(&p.options); err != nil { - return nil, err - } - } - if p.errorReportingLimit == 0 { - p.errorReportingLimit = 100 - } - if p.maxRecursionDepth == 0 { - p.maxRecursionDepth = 250 - } - if p.maxRecursionDepth == -1 { - p.maxRecursionDepth = int((^uint(0)) >> 1) - } - if p.errorRecoveryTokenLookaheadLimit == 0 { - p.errorRecoveryTokenLookaheadLimit = 256 - } - if p.errorRecoveryLimit == 0 { - p.errorRecoveryLimit = 30 - } - if p.errorRecoveryLimit == -1 { - p.errorRecoveryLimit = int((^uint(0)) >> 1) - } - if p.expressionSizeCodePointLimit == 0 { - p.expressionSizeCodePointLimit = 100_000 - } - if p.expressionSizeCodePointLimit == -1 { - p.expressionSizeCodePointLimit = int((^uint(0)) >> 1) - } - if p.maxExpressionNodeCount == 0 { - p.maxExpressionNodeCount = 100_000 - } - if p.maxExpressionNodeCount == -1 { - p.maxExpressionNodeCount = int((^uint(0)) >> 1) - } - // Bool is false by default, so populateMacroCalls will be false by default - return p, nil -} - -// mustNewParser does the work of NewParser and panics if an error occurs. -// -// This function is only intended for internal use and is for backwards compatibility in Parse and -// ParseWithMacros, where we know the options will result in an error. -func mustNewParser(opts ...Option) *Parser { - p, err := NewParser(opts...) - if err != nil { - panic(err) - } - return p -} - // Parse parses the expression represented by source and returns the result. -func (p *Parser) Parse(source common.Source) (*ast.AST, *common.Errors) { +func (p *antlrParser) Parse(source common.Source) (*ast.AST, *common.Errors) { errs := common.NewErrors(source) accu := AccumulatorName if p.enableHiddenAccumulatorName { accu = HiddenAccumulatorName } fac := ast.NewExprFactoryWithAccumulator(accu) - impl := parser{ + impl := antlrVisitor{ errors: &parseErrors{errs}, exprFactory: fac, helper: newParserHelper(source, fac), @@ -132,32 +74,6 @@ func (p *Parser) Parse(source common.Source) (*ast.AST, *common.Errors) { return ast.NewAST(out, impl.helper.getSourceInfo()), errs } -// reservedIds are not legal to use as variables. We exclude them post-parse, as they *are* valid -// field names for protos, and it would complicate the grammar to distinguish the cases. -var reservedIds = map[string]struct{}{ - "as": {}, - "break": {}, - "const": {}, - "continue": {}, - "else": {}, - "false": {}, - "for": {}, - "function": {}, - "if": {}, - "import": {}, - "in": {}, - "let": {}, - "loop": {}, - "package": {}, - "namespace": {}, - "null": {}, - "return": {}, - "true": {}, - "var": {}, - "void": {}, - "while": {}, -} - func unescapeIdent(in string) (string, error) { if len(in) <= 2 { return "", errors.New("invalid escaped identifier: underflow") @@ -165,28 +81,6 @@ func unescapeIdent(in string) (string, error) { return in[1 : len(in)-1], nil } -// normalizeIdent returns the interpreted identifier. -func (p *parser) normalizeIdent(ctx gen.IEscapeIdentContext) (string, error) { - switch ident := ctx.(type) { - case *gen.SimpleIdentifierContext: - return ident.GetId().GetText(), nil - case *gen.EscapedIdentifierContext: - if !p.enableIdentEscapeSyntax { - return "", errors.New("unsupported syntax: '`'") - } - return unescapeIdent(ident.GetId().GetText()) - } - return "", errors.New("unsupported ident kind") -} - -// Parse converts a source input a parsed expression. -// This function calls ParseWithMacros with AllMacros. -// -// Deprecated: Use NewParser().Parse() instead. -func Parse(source common.Source) (*ast.AST, *common.Errors) { - return mustNewParser(Macros(AllMacros...)).Parse(source) -} - type recursionError struct { message string } @@ -317,7 +211,7 @@ func (rl *recoveryLimitErrorStrategy) checkAttempts(recognizer antlr.Parser) { var _ antlr.ErrorStrategy = &recoveryLimitErrorStrategy{} -type parser struct { +type antlrVisitor struct { gen.BaseCELVisitor errors *parseErrors exprFactory ast.ExprFactory @@ -336,9 +230,23 @@ type parser struct { enableIdentEscapeSyntax bool } -var _ gen.CELVisitor = (*parser)(nil) +var _ gen.CELVisitor = (*antlrVisitor)(nil) + +// normalizeIdent returns the interpreted identifier. +func (p *antlrVisitor) normalizeIdent(ctx gen.IEscapeIdentContext) (string, error) { + switch ident := ctx.(type) { + case *gen.SimpleIdentifierContext: + return ident.GetId().GetText(), nil + case *gen.EscapedIdentifierContext: + if !p.enableIdentEscapeSyntax { + return "", errors.New("unsupported syntax: '`'") + } + return unescapeIdent(ident.GetId().GetText()) + } + return "", errors.New("unsupported ident kind") +} -func (p *parser) parse(expr runes.Buffer, desc string) ast.Expr { +func (p *antlrVisitor) parse(expr runes.Buffer, desc string) ast.Expr { lexer := gen.NewCELLexer(newCharStream(expr, desc)) lexer.RemoveErrorListeners() lexer.AddErrorListener(p) @@ -381,7 +289,7 @@ func (p *parser) parse(expr runes.Buffer, desc string) ast.Expr { } // Visitor implementations. -func (p *parser) Visit(tree antlr.ParseTree) any { +func (p *antlrVisitor) Visit(tree antlr.ParseTree) any { t := unnest(tree) switch tree := t.(type) { case *gen.StartContext: @@ -466,16 +374,15 @@ func (p *parser) Visit(tree antlr.ParseTree) any { return p.reportError(common.NoLocation, "unknown parse element encountered: %s", txt) } return p.helper.newExpr(common.NoLocation) - } // Visit a parse tree produced by CELParser#start. -func (p *parser) VisitStart(ctx *gen.StartContext) any { +func (p *antlrVisitor) VisitStart(ctx *gen.StartContext) any { return p.Visit(ctx.Expr()) } // Visit a parse tree produced by CELParser#expr. -func (p *parser) VisitExpr(ctx *gen.ExprContext) any { +func (p *antlrVisitor) VisitExpr(ctx *gen.ExprContext) any { result := p.Visit(ctx.GetE()).(ast.Expr) if ctx.GetOp() == nil { return result @@ -487,7 +394,7 @@ func (p *parser) VisitExpr(ctx *gen.ExprContext) any { } // Visit a parse tree produced by CELParser#conditionalOr. -func (p *parser) VisitConditionalOr(ctx *gen.ConditionalOrContext) any { +func (p *antlrVisitor) VisitConditionalOr(ctx *gen.ConditionalOrContext) any { result := p.Visit(ctx.GetE()).(ast.Expr) l := p.newLogicManager(operators.LogicalOr, result) rest := ctx.GetE1() @@ -503,7 +410,7 @@ func (p *parser) VisitConditionalOr(ctx *gen.ConditionalOrContext) any { } // Visit a parse tree produced by CELParser#conditionalAnd. -func (p *parser) VisitConditionalAnd(ctx *gen.ConditionalAndContext) any { +func (p *antlrVisitor) VisitConditionalAnd(ctx *gen.ConditionalAndContext) any { result := p.Visit(ctx.GetE()).(ast.Expr) l := p.newLogicManager(operators.LogicalAnd, result) rest := ctx.GetE1() @@ -519,7 +426,7 @@ func (p *parser) VisitConditionalAnd(ctx *gen.ConditionalAndContext) any { } // Visit a parse tree produced by CELParser#relation. -func (p *parser) VisitRelation(ctx *gen.RelationContext) any { +func (p *antlrVisitor) VisitRelation(ctx *gen.RelationContext) any { opText := "" if ctx.GetOp() != nil { opText = ctx.GetOp().GetText() @@ -534,7 +441,7 @@ func (p *parser) VisitRelation(ctx *gen.RelationContext) any { } // Visit a parse tree produced by CELParser#calc. -func (p *parser) VisitCalc(ctx *gen.CalcContext) any { +func (p *antlrVisitor) VisitCalc(ctx *gen.CalcContext) any { opText := "" if ctx.GetOp() != nil { opText = ctx.GetOp().GetText() @@ -548,12 +455,12 @@ func (p *parser) VisitCalc(ctx *gen.CalcContext) any { return p.reportError(ctx, "operator not found") } -func (p *parser) VisitUnary(ctx *gen.UnaryContext) any { +func (p *antlrVisitor) VisitUnary(ctx *gen.UnaryContext) any { return p.helper.newLiteralString(ctx, "<>") } // Visit a parse tree produced by CELParser#LogicalNot. -func (p *parser) VisitLogicalNot(ctx *gen.LogicalNotContext) any { +func (p *antlrVisitor) VisitLogicalNot(ctx *gen.LogicalNotContext) any { if len(ctx.GetOps())%2 == 0 { return p.Visit(ctx.Member()) } @@ -562,7 +469,7 @@ func (p *parser) VisitLogicalNot(ctx *gen.LogicalNotContext) any { return p.globalCallOrMacro(opID, operators.LogicalNot, target) } -func (p *parser) VisitNegate(ctx *gen.NegateContext) any { +func (p *antlrVisitor) VisitNegate(ctx *gen.NegateContext) any { if len(ctx.GetOps())%2 == 0 { return p.Visit(ctx.Member()) } @@ -572,7 +479,7 @@ func (p *parser) VisitNegate(ctx *gen.NegateContext) any { } // VisitSelect visits a parse tree produced by CELParser#Select. -func (p *parser) VisitSelect(ctx *gen.SelectContext) any { +func (p *antlrVisitor) VisitSelect(ctx *gen.SelectContext) any { operand := p.Visit(ctx.Member()).(ast.Expr) // Handle the error case where no valid identifier is specified. if ctx.GetId() == nil || ctx.GetOp() == nil { @@ -596,7 +503,7 @@ func (p *parser) VisitSelect(ctx *gen.SelectContext) any { } // VisitMemberCall visits a parse tree produced by CELParser#MemberCall. -func (p *parser) VisitMemberCall(ctx *gen.MemberCallContext) any { +func (p *antlrVisitor) VisitMemberCall(ctx *gen.MemberCallContext) any { operand := p.Visit(ctx.Member()).(ast.Expr) // Handle the error case where no valid identifier is specified. if ctx.GetId() == nil { @@ -608,7 +515,7 @@ func (p *parser) VisitMemberCall(ctx *gen.MemberCallContext) any { } // Visit a parse tree produced by CELParser#Index. -func (p *parser) VisitIndex(ctx *gen.IndexContext) any { +func (p *antlrVisitor) VisitIndex(ctx *gen.IndexContext) any { target := p.Visit(ctx.Member()).(ast.Expr) // Handle the error case where no valid identifier is specified. if ctx.GetOp() == nil { @@ -627,7 +534,7 @@ func (p *parser) VisitIndex(ctx *gen.IndexContext) any { } // Visit a parse tree produced by CELParser#CreateMessage. -func (p *parser) VisitCreateMessage(ctx *gen.CreateMessageContext) any { +func (p *antlrVisitor) VisitCreateMessage(ctx *gen.CreateMessageContext) any { messageName := "" for _, id := range ctx.GetIds() { if len(messageName) != 0 { @@ -644,7 +551,7 @@ func (p *parser) VisitCreateMessage(ctx *gen.CreateMessageContext) any { } // Visit a parse tree of field initializers. -func (p *parser) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext) any { +func (p *antlrVisitor) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext) any { if ctx == nil || ctx.GetFields() == nil { // This is the result of a syntax error handled elswhere, return empty. return []ast.EntryExpr{} @@ -681,7 +588,7 @@ func (p *parser) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext } // Visit a parse tree produced by CELParser#Ident. -func (p *parser) VisitIdent(ctx *gen.IdentContext) any { +func (p *antlrVisitor) VisitIdent(ctx *gen.IdentContext) any { identName := "" if ctx.GetLeadingDot() != nil { identName = "." @@ -700,7 +607,7 @@ func (p *parser) VisitIdent(ctx *gen.IdentContext) any { } // Visit a parse tree produced by CELParser#GlobalCallContext. -func (p *parser) VisitGlobalCall(ctx *gen.GlobalCallContext) any { +func (p *antlrVisitor) VisitGlobalCall(ctx *gen.GlobalCallContext) any { identName := "" if ctx.GetLeadingDot() != nil { identName = "." @@ -717,18 +624,17 @@ func (p *parser) VisitGlobalCall(ctx *gen.GlobalCallContext) any { identName += id opID := p.helper.id(ctx.GetOp()) return p.globalCallOrMacro(opID, identName, p.visitExprList(ctx.GetArgs())...) - } // Visit a parse tree produced by CELParser#CreateList. -func (p *parser) VisitCreateList(ctx *gen.CreateListContext) any { +func (p *antlrVisitor) VisitCreateList(ctx *gen.CreateListContext) any { listID := p.helper.id(ctx.GetOp()) elems, optionals := p.visitListInit(ctx.GetElems()) return p.helper.newList(listID, elems, optionals...) } // Visit a parse tree produced by CELParser#CreateStruct. -func (p *parser) VisitCreateStruct(ctx *gen.CreateStructContext) any { +func (p *antlrVisitor) VisitCreateStruct(ctx *gen.CreateStructContext) any { structID := p.helper.id(ctx.GetOp()) entries := []ast.EntryExpr{} if ctx.GetEntries() != nil { @@ -738,7 +644,7 @@ func (p *parser) VisitCreateStruct(ctx *gen.CreateStructContext) any { } // Visit a parse tree produced by CELParser#mapInitializerList. -func (p *parser) VisitMapInitializerList(ctx *gen.MapInitializerListContext) any { +func (p *antlrVisitor) VisitMapInitializerList(ctx *gen.MapInitializerListContext) any { if ctx == nil || ctx.GetKeys() == nil { // This is the result of a syntax error handled elswhere, return empty. return []ast.EntryExpr{} @@ -768,7 +674,7 @@ func (p *parser) VisitMapInitializerList(ctx *gen.MapInitializerListContext) any } // Visit a parse tree produced by CELParser#Int. -func (p *parser) VisitInt(ctx *gen.IntContext) any { +func (p *antlrVisitor) VisitInt(ctx *gen.IntContext) any { text := ctx.GetTok().GetText() base := 10 if strings.HasPrefix(text, "0x") { @@ -786,7 +692,7 @@ func (p *parser) VisitInt(ctx *gen.IntContext) any { } // Visit a parse tree produced by CELParser#Uint. -func (p *parser) VisitUint(ctx *gen.UintContext) any { +func (p *antlrVisitor) VisitUint(ctx *gen.UintContext) any { text := ctx.GetTok().GetText() // trim the 'u' designator included in the uint literal. text = text[:len(text)-1] @@ -803,7 +709,7 @@ func (p *parser) VisitUint(ctx *gen.UintContext) any { } // Visit a parse tree produced by CELParser#Double. -func (p *parser) VisitDouble(ctx *gen.DoubleContext) any { +func (p *antlrVisitor) VisitDouble(ctx *gen.DoubleContext) any { txt := ctx.GetTok().GetText() if ctx.GetSign() != nil { txt = ctx.GetSign().GetText() + txt @@ -813,44 +719,43 @@ func (p *parser) VisitDouble(ctx *gen.DoubleContext) any { return p.reportError(ctx, "invalid double literal") } return p.helper.newLiteralDouble(ctx, f) - } // Visit a parse tree produced by CELParser#String. -func (p *parser) VisitString(ctx *gen.StringContext) any { +func (p *antlrVisitor) VisitString(ctx *gen.StringContext) any { s := p.unquote(ctx, ctx.GetTok().GetText(), false) return p.helper.newLiteralString(ctx, s) } // Visit a parse tree produced by CELParser#Bytes. -func (p *parser) VisitBytes(ctx *gen.BytesContext) any { +func (p *antlrVisitor) VisitBytes(ctx *gen.BytesContext) any { b := []byte(p.unquote(ctx, ctx.GetTok().GetText()[1:], true)) return p.helper.newLiteralBytes(ctx, b) } // Visit a parse tree produced by CELParser#BoolTrue. -func (p *parser) VisitBoolTrue(ctx *gen.BoolTrueContext) any { +func (p *antlrVisitor) VisitBoolTrue(ctx *gen.BoolTrueContext) any { return p.helper.newLiteralBool(ctx, true) } // Visit a parse tree produced by CELParser#BoolFalse. -func (p *parser) VisitBoolFalse(ctx *gen.BoolFalseContext) any { +func (p *antlrVisitor) VisitBoolFalse(ctx *gen.BoolFalseContext) any { return p.helper.newLiteralBool(ctx, false) } // Visit a parse tree produced by CELParser#Null. -func (p *parser) VisitNull(ctx *gen.NullContext) any { +func (p *antlrVisitor) VisitNull(ctx *gen.NullContext) any { return p.helper.exprFactory.NewLiteral(p.helper.newID(ctx), types.NullValue) } -func (p *parser) visitExprList(ctx gen.IExprListContext) []ast.Expr { +func (p *antlrVisitor) visitExprList(ctx gen.IExprListContext) []ast.Expr { if ctx == nil { return []ast.Expr{} } return p.visitSlice(ctx.GetE()) } -func (p *parser) visitListInit(ctx gen.IListInitContext) ([]ast.Expr, []int32) { +func (p *antlrVisitor) visitListInit(ctx gen.IListInitContext) ([]ast.Expr, []int32) { if ctx == nil { return []ast.Expr{}, []int32{} } @@ -874,7 +779,7 @@ func (p *parser) visitListInit(ctx gen.IListInitContext) ([]ast.Expr, []int32) { return result, optionals } -func (p *parser) visitSlice(expressions []gen.IExprContext) []ast.Expr { +func (p *antlrVisitor) visitSlice(expressions []gen.IExprContext) []ast.Expr { if expressions == nil { return []ast.Expr{} } @@ -886,7 +791,7 @@ func (p *parser) visitSlice(expressions []gen.IExprContext) []ast.Expr { return result } -func (p *parser) unquote(ctx any, value string, isBytes bool) string { +func (p *antlrVisitor) unquote(ctx any, value string, isBytes bool) string { text, err := unescape(value, isBytes) if err != nil { p.reportError(ctx, "%s", err.Error()) @@ -895,14 +800,14 @@ func (p *parser) unquote(ctx any, value string, isBytes bool) string { return text } -func (p *parser) newLogicManager(function string, term ast.Expr) *logicManager { +func (p *antlrVisitor) newLogicManager(function string, term ast.Expr) *logicManager { if p.enableVariadicOperatorASTs { return newVariadicLogicManager(p.exprFactory, function, term) } return newBalancingLogicManager(p.exprFactory, function, term) } -func (p *parser) reportError(ctx any, format string, args ...any) ast.Expr { +func (p *antlrVisitor) reportError(ctx any, format string, args ...any) ast.Expr { var location common.Location err := p.helper.newExpr(ctx) switch c := ctx.(type) { @@ -917,7 +822,7 @@ func (p *parser) reportError(ctx any, format string, args ...any) ast.Expr { } // ANTLR Parse listener implementations -func (p *parser) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, e antlr.RecognitionException) { +func (p *antlrVisitor) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, e antlr.RecognitionException) { offset := p.helper.sourceInfo.ComputeOffset(int32(line), int32(column)) l := p.helper.getLocationByOffset(offset) // Hack to keep existing error messages consistent with previous versions of CEL when a reserved word @@ -938,33 +843,33 @@ func (p *parser) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, l } } -func (p *parser) ReportAmbiguity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr.BitSet, configs *antlr.ATNConfigSet) { +func (p *antlrVisitor) ReportAmbiguity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr.BitSet, configs *antlr.ATNConfigSet) { // Intentional } -func (p *parser) ReportAttemptingFullContext(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, conflictingAlts *antlr.BitSet, configs *antlr.ATNConfigSet) { +func (p *antlrVisitor) ReportAttemptingFullContext(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, conflictingAlts *antlr.BitSet, configs *antlr.ATNConfigSet) { // Intentional } -func (p *parser) ReportContextSensitivity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex, prediction int, configs *antlr.ATNConfigSet) { +func (p *antlrVisitor) ReportContextSensitivity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex, prediction int, configs *antlr.ATNConfigSet) { // Intentional } -func (p *parser) globalCallOrMacro(exprID int64, function string, args ...ast.Expr) ast.Expr { +func (p *antlrVisitor) globalCallOrMacro(exprID int64, function string, args ...ast.Expr) ast.Expr { if expr, found := p.expandMacro(exprID, function, nil, args...); found { return expr } return p.helper.newGlobalCall(exprID, function, args...) } -func (p *parser) receiverCallOrMacro(exprID int64, function string, target ast.Expr, args ...ast.Expr) ast.Expr { +func (p *antlrVisitor) receiverCallOrMacro(exprID int64, function string, target ast.Expr, args ...ast.Expr) ast.Expr { if expr, found := p.expandMacro(exprID, function, target, args...); found { return expr } return p.helper.newReceiverCall(exprID, function, target, args...) } -func (p *parser) expandMacro(exprID int64, function string, target ast.Expr, args ...ast.Expr) (ast.Expr, bool) { +func (p *antlrVisitor) expandMacro(exprID int64, function string, target ast.Expr, args ...ast.Expr) (ast.Expr, bool) { macro, found := p.macros[makeMacroKey(function, len(args), target != nil)] if !found { macro, found = p.macros[makeVarArgMacroKey(function, target != nil)] @@ -1008,14 +913,14 @@ func (p *parser) expandMacro(exprID int64, function string, target ast.Expr, arg return expr, true } -func (p *parser) checkAndIncrementRecursionDepth() { +func (p *antlrVisitor) checkAndIncrementRecursionDepth() { p.recursionDepth++ if p.recursionDepth > p.maxRecursionDepth { panic(&recursionError{message: "max recursion depth exceeded"}) } } -func (p *parser) decrementRecursionDepth() { +func (p *antlrVisitor) decrementRecursionDepth() { p.recursionDepth-- } diff --git a/vendor/github.com/google/cel-go/parser/errors.go b/vendor/cel.dev/cel-go/parser/errors.go similarity index 97% rename from vendor/github.com/google/cel-go/parser/errors.go rename to vendor/cel.dev/cel-go/parser/errors.go index c3cec01a8d..968dbe82ba 100644 --- a/vendor/github.com/google/cel-go/parser/errors.go +++ b/vendor/cel.dev/cel-go/parser/errors.go @@ -15,7 +15,7 @@ package parser import ( - "github.com/google/cel-go/common" + "cel.dev/cel-go/common" ) // parseErrors is a specialization of Errors. diff --git a/vendor/github.com/google/cel-go/parser/gen/BUILD.bazel b/vendor/cel.dev/cel-go/parser/gen/BUILD.bazel similarity index 90% rename from vendor/github.com/google/cel-go/parser/gen/BUILD.bazel rename to vendor/cel.dev/cel-go/parser/gen/BUILD.bazel index 3efed87b70..6c0187d58c 100644 --- a/vendor/github.com/google/cel-go/parser/gen/BUILD.bazel +++ b/vendor/cel.dev/cel-go/parser/gen/BUILD.bazel @@ -19,7 +19,7 @@ go_library( "CEL.tokens", "CELLexer.tokens", ], - importpath = "github.com/google/cel-go/parser/gen", + importpath = "cel.dev/cel-go/parser/gen", deps = [ "@com_github_antlr4_go_antlr_v4//:go_default_library", ], diff --git a/vendor/github.com/google/cel-go/parser/gen/CEL.g4 b/vendor/cel.dev/cel-go/parser/gen/CEL.g4 similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/CEL.g4 rename to vendor/cel.dev/cel-go/parser/gen/CEL.g4 diff --git a/vendor/github.com/google/cel-go/parser/gen/CEL.interp b/vendor/cel.dev/cel-go/parser/gen/CEL.interp similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/CEL.interp rename to vendor/cel.dev/cel-go/parser/gen/CEL.interp diff --git a/vendor/github.com/google/cel-go/parser/gen/CEL.tokens b/vendor/cel.dev/cel-go/parser/gen/CEL.tokens similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/CEL.tokens rename to vendor/cel.dev/cel-go/parser/gen/CEL.tokens diff --git a/vendor/github.com/google/cel-go/parser/gen/CELLexer.interp b/vendor/cel.dev/cel-go/parser/gen/CELLexer.interp similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/CELLexer.interp rename to vendor/cel.dev/cel-go/parser/gen/CELLexer.interp diff --git a/vendor/github.com/google/cel-go/parser/gen/CELLexer.tokens b/vendor/cel.dev/cel-go/parser/gen/CELLexer.tokens similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/CELLexer.tokens rename to vendor/cel.dev/cel-go/parser/gen/CELLexer.tokens diff --git a/vendor/github.com/google/cel-go/parser/gen/cel_base_listener.go b/vendor/cel.dev/cel-go/parser/gen/cel_base_listener.go similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/cel_base_listener.go rename to vendor/cel.dev/cel-go/parser/gen/cel_base_listener.go diff --git a/vendor/github.com/google/cel-go/parser/gen/cel_base_visitor.go b/vendor/cel.dev/cel-go/parser/gen/cel_base_visitor.go similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/cel_base_visitor.go rename to vendor/cel.dev/cel-go/parser/gen/cel_base_visitor.go diff --git a/vendor/github.com/google/cel-go/parser/gen/cel_lexer.go b/vendor/cel.dev/cel-go/parser/gen/cel_lexer.go similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/cel_lexer.go rename to vendor/cel.dev/cel-go/parser/gen/cel_lexer.go diff --git a/vendor/github.com/google/cel-go/parser/gen/cel_listener.go b/vendor/cel.dev/cel-go/parser/gen/cel_listener.go similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/cel_listener.go rename to vendor/cel.dev/cel-go/parser/gen/cel_listener.go diff --git a/vendor/github.com/google/cel-go/parser/gen/cel_parser.go b/vendor/cel.dev/cel-go/parser/gen/cel_parser.go similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/cel_parser.go rename to vendor/cel.dev/cel-go/parser/gen/cel_parser.go diff --git a/vendor/github.com/google/cel-go/parser/gen/cel_visitor.go b/vendor/cel.dev/cel-go/parser/gen/cel_visitor.go similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/cel_visitor.go rename to vendor/cel.dev/cel-go/parser/gen/cel_visitor.go diff --git a/vendor/github.com/google/cel-go/parser/gen/doc.go b/vendor/cel.dev/cel-go/parser/gen/doc.go similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/doc.go rename to vendor/cel.dev/cel-go/parser/gen/doc.go diff --git a/vendor/github.com/google/cel-go/parser/gen/generate.sh b/vendor/cel.dev/cel-go/parser/gen/generate.sh similarity index 100% rename from vendor/github.com/google/cel-go/parser/gen/generate.sh rename to vendor/cel.dev/cel-go/parser/gen/generate.sh diff --git a/vendor/github.com/google/cel-go/parser/helper.go b/vendor/cel.dev/cel-go/parser/helper.go similarity index 93% rename from vendor/github.com/google/cel-go/parser/helper.go rename to vendor/cel.dev/cel-go/parser/helper.go index 84bef80d5f..8281b2d421 100644 --- a/vendor/github.com/google/cel-go/parser/helper.go +++ b/vendor/cel.dev/cel-go/parser/helper.go @@ -19,10 +19,10 @@ import ( antlr "github.com/antlr4-go/antlr/v4" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) type parserHelper struct { @@ -152,6 +152,18 @@ func (p *parserHelper) newExpr(ctx any) ast.Expr { return p.exprFactory.NewUnspecifiedExpr(p.newID(ctx)) } +// computeOffset converts a 0-based character offset from the local source content to +// the corresponding absolute character offset in the parent SourceInfo (e.g. for RelativeSource). +// If the location cannot be resolved or the source is nil, the original offset is returned. +func (p *parserHelper) computeOffset(offset int32) int32 { + if p.source != nil { + if loc, found := p.source.OffsetLocation(offset); found { + return p.sourceInfo.ComputeOffsetAbsolute(int32(loc.Line()), int32(loc.Column())) + } + } + return offset +} + func (p *parserHelper) id(ctx any) int64 { var offset ast.OffsetRange switch c := ctx.(type) { @@ -162,6 +174,9 @@ func (p *parserHelper) id(ctx any) int64 { case antlr.Token: offset.Start = p.sourceInfo.ComputeOffset(int32(c.GetLine()), int32(c.GetColumn())) offset.Stop = offset.Start + int32(len(c.GetText())) + case token: + offset.Start = p.computeOffset(c.start) + offset.Stop = p.computeOffset(c.end) case common.Location: offset.Start = p.sourceInfo.ComputeOffsetAbsolute(int32(c.Line()), int32(c.Column())) offset.Stop = offset.Start @@ -177,6 +192,28 @@ func (p *parserHelper) id(ctx any) int64 { return id } +func (p *parserHelper) idFromOffsets(start, stop int32) int64 { + id := p.nextID + p.sourceInfo.SetOffsetRange(id, ast.OffsetRange{Start: p.computeOffset(start), Stop: p.computeOffset(stop)}) + p.nextID++ + return id +} + +func (p *parserHelper) allocID() int64 { + id := p.nextID + p.nextID++ + return id +} + +func (p *parserHelper) setTokenLocation(id int64, tok token) { + if tok.start >= 0 { + p.sourceInfo.SetOffsetRange(id, ast.OffsetRange{ + Start: p.computeOffset(tok.start), + Stop: p.computeOffset(tok.end), + }) + } +} + func (p *parserHelper) deleteID(id int64) { p.sourceInfo.ClearOffsetRange(id) if id == p.nextID-1 { diff --git a/vendor/github.com/google/cel-go/parser/input.go b/vendor/cel.dev/cel-go/parser/input.go similarity index 98% rename from vendor/github.com/google/cel-go/parser/input.go rename to vendor/cel.dev/cel-go/parser/input.go index 44792455d8..9ccccd0fc1 100644 --- a/vendor/github.com/google/cel-go/parser/input.go +++ b/vendor/cel.dev/cel-go/parser/input.go @@ -17,7 +17,7 @@ package parser import ( antlr "github.com/antlr4-go/antlr/v4" - "github.com/google/cel-go/common/runes" + "cel.dev/cel-go/common/runes" ) type charStream struct { diff --git a/vendor/cel.dev/cel-go/parser/lexer.go b/vendor/cel.dev/cel-go/parser/lexer.go new file mode 100644 index 0000000000..c696270f97 --- /dev/null +++ b/vendor/cel.dev/cel-go/parser/lexer.go @@ -0,0 +1,664 @@ +// Copyright 2026 Google LLC +// +// 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 parser + +import ( + "cel.dev/cel-go/common/runes" +) + +type tokenKind int + +const ( + tokError tokenKind = iota + tokEnd + tokWhitespace + tokComment + + // Keywords + tokNull + tokFalse + tokTrue + tokIn + tokReservedWord + + // Literals + tokInt + tokUint + tokFloat + tokString + tokBytes + + // Identifiers + tokIdent + + // Delimiters + tokLeftBracket // [ + tokRightBracket // ] + tokLeftBrace // { + tokRightBrace // } + tokLeftParen // ( + tokRightParen // ) + + // Operators + tokDot // . + tokComma // , + tokMinus // - + tokPlus // + + tokAsterisk // * + tokSlash // / + tokPercent // % + tokQuestion // ? + tokColon // : + tokExclamation // ! + tokEqual // = + tokEqualEqual // == + tokExclamationEqual // != + tokLess // < + tokLessEqual // <= + tokGreater // > + tokGreaterEqual // >= + tokLogicalAnd // && + tokLogicalOr // || +) + +func (t tokenKind) String() string { + switch t { + case tokError: + return "error" + case tokEnd: + return "end" + case tokWhitespace: + return "whitespace" + case tokComment: + return "comment" + case tokNull: + return "null" + case tokFalse: + return "false" + case tokTrue: + return "true" + case tokIn: + return "in" + case tokReservedWord: + return "reserved_word" + case tokInt: + return "int" + case tokUint: + return "uint" + case tokFloat: + return "float" + case tokString: + return "string" + case tokBytes: + return "bytes" + case tokIdent: + return "ident" + case tokLeftBracket: + return "[" + case tokRightBracket: + return "]" + case tokLeftBrace: + return "{" + case tokRightBrace: + return "}" + case tokLeftParen: + return "(" + case tokRightParen: + return ")" + case tokDot: + return "." + case tokComma: + return "," + case tokMinus: + return "-" + case tokPlus: + return "+" + case tokAsterisk: + return "*" + case tokSlash: + return "/" + case tokPercent: + return "%" + case tokQuestion: + return "?" + case tokColon: + return ":" + case tokExclamation: + return "!" + case tokEqual: + return "=" + case tokEqualEqual: + return "==" + case tokExclamationEqual: + return "!=" + case tokLess: + return "<" + case tokLessEqual: + return "<=" + case tokGreater: + return ">" + case tokGreaterEqual: + return ">=" + case tokLogicalAnd: + return "&&" + case tokLogicalOr: + return "||" + default: + return "" + } +} + +type token struct { + kind tokenKind + start int32 + end int32 +} + +type lexerError struct { + start int32 + end int32 + message string +} + +var keywords = map[string]tokenKind{ + "false": tokFalse, + "true": tokTrue, + "null": tokNull, + "in": tokIn, + "as": tokReservedWord, + "break": tokReservedWord, + "const": tokReservedWord, + "continue": tokReservedWord, + "else": tokReservedWord, + "for": tokReservedWord, + "function": tokReservedWord, + "if": tokReservedWord, + "import": tokReservedWord, + "let": tokReservedWord, + "loop": tokReservedWord, + "package": tokReservedWord, + "namespace": tokReservedWord, + "return": tokReservedWord, + "var": tokReservedWord, + "void": tokReservedWord, + "while": tokReservedWord, +} + +func isIdentTrailing(r rune) bool { + return r <= 0x7f && ((r >= '0' && r <= '9') || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || r == '_') +} + +func isDigit(r rune) bool { + return r >= '0' && r <= '9' +} + +func isHexDigit(r rune) bool { + return (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F') +} + +func isAlpha(r rune) bool { + return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') +} + +func isPlusOrMinus(r rune) bool { + return r == '+' || r == '-' +} + +// lexer performs fast tokenization of CEL expression source code. +type lexer struct { + content runes.Buffer + length int32 + pos int32 + err lexerError +} + +func newLexer(content runes.Buffer) *lexer { + return &lexer{ + content: content, + length: int32(content.Len()), + pos: 0, + } +} + +func (l *lexer) SavePosition() int32 { + return l.pos +} + +func (l *lexer) RestorePosition(pos int32) { + l.pos = pos + l.err = lexerError{} +} + +func (l *lexer) GetError() lexerError { + return l.err +} + +func (l *lexer) GetPosition() int32 { + return l.pos +} + +func (l *lexer) makeToken(kind tokenKind, start, end int32) token { + return token{kind: kind, start: start, end: end} +} + +func (l *lexer) setError(start, end int32, msg string) token { + l.err = lexerError{start: start, end: end, message: msg} + return token{kind: tokError, start: start, end: end} +} + +func (l *lexer) advance(n int32) { + l.pos += n +} + +func (l *lexer) match(c rune) bool { + return l.pos < l.length && l.content.Get(int(l.pos)) == c +} + +func (l *lexer) matchIgnoreCase(c rune) bool { + if l.pos >= l.length { + return false + } + cp := l.content.Get(int(l.pos)) + if cp <= 0x7f && c <= 0x7f { + cpLower := cp + if cp >= 'A' && cp <= 'Z' { + cpLower += 'a' - 'A' + } + cLower := c + if c >= 'A' && c <= 'Z' { + cLower += 'a' - 'A' + } + return cpLower == cLower + } + return cp == c +} + +func (l *lexer) consume(c rune) bool { + if l.match(c) { + l.advance(1) + return true + } + return false +} + +func (l *lexer) consumeIgnoreCase(c rune) bool { + if l.matchIgnoreCase(c) { + l.advance(1) + return true + } + return false +} + +func (l *lexer) consumeIf(predicate func(rune) bool) bool { + if l.pos < l.length && predicate(l.content.Get(int(l.pos))) { + l.advance(1) + return true + } + return false +} + +func (l *lexer) consumeLine() { + for l.pos < l.length { + if l.content.Get(int(l.pos)) == '\n' { + l.advance(1) + return + } + l.advance(1) + } +} + +func (l *lexer) consumeWhitespace() { + for l.pos < l.length { + c := l.content.Get(int(l.pos)) + switch c { + case '\f', '\n', ' ', '\r', '\t': + l.advance(1) + default: + return + } + } +} + +func (l *lexer) consumeDigits() bool { + advanced := false + for l.pos < l.length { + c := l.content.Get(int(l.pos)) + if !isDigit(c) { + break + } + l.advance(1) + advanced = true + } + return advanced +} + +func (l *lexer) consumeHexDigits() bool { + advanced := false + for l.pos < l.length { + c := l.content.Get(int(l.pos)) + if !isHexDigit(c) { + break + } + l.advance(1) + advanced = true + } + return advanced +} + +func (l *lexer) consumeIntegralSuffix() tokenKind { + if l.consumeIgnoreCase('u') { + return tokUint + } + return tokInt +} + +func (l *lexer) consumeUntilAfter(c rune, isRaw bool) bool { + pos := l.pos + escaped := false + for pos < l.length { + cc := l.content.Get(int(pos)) + if cc == '\n' || cc == '\r' { + l.pos = pos + return false + } + if !isRaw && cc == '\\' { + escaped = !escaped + } else { + if cc == c && !escaped { + l.pos = pos + 1 + return true + } + escaped = false + } + pos++ + } + l.pos = l.length + return false +} + +func (l *lexer) consumeUntilAfterTriple(quote rune, isRaw bool) bool { + pos := l.pos + escaped := false + for pos < l.length { + cc := l.content.Get(int(pos)) + if !isRaw && cc == '\\' { + escaped = !escaped + } else { + if !escaped && pos+3 <= l.length { + if l.content.Get(int(pos)) == quote && + l.content.Get(int(pos+1)) == quote && + l.content.Get(int(pos+2)) == quote { + l.pos = pos + 3 + return true + } + } + escaped = false + } + pos++ + } + l.pos = l.length + return false +} + +func (l *lexer) consumeQuotedIdent() token { + start := l.pos + l.advance(1) + if !l.consumeUntilAfter('`', true) { + return l.setError(start, l.pos, "unterminated quoted identifier") + } + return l.makeToken(tokIdent, start, l.pos) +} + +func (l *lexer) consumeStringLiteral(start int32, quote rune, isBytes, isRaw bool) token { + l.advance(1) + if l.pos+2 <= l.length && l.content.Get(int(l.pos)) == quote && l.content.Get(int(l.pos+1)) == quote { + l.advance(2) + if !l.consumeUntilAfterTriple(quote, isRaw) { + msg := "unterminated string literal" + if isBytes { + msg = "unterminated bytes literal" + } + return l.setError(start, l.pos, msg) + } + kind := tokString + if isBytes { + kind = tokBytes + } + return l.makeToken(kind, start, l.pos) + } + if !l.consumeUntilAfter(quote, isRaw) { + msg := "unterminated string literal" + if isBytes { + msg = "unterminated bytes literal" + } + return l.setError(start, l.pos, msg) + } + kind := tokString + if isBytes { + kind = tokBytes + } + return l.makeToken(kind, start, l.pos) +} + +func (l *lexer) consumePrefixedStringLiteral() (token, bool) { + start := l.pos + if l.pos >= l.length { + return token{}, false + } + c := l.content.Get(int(l.pos)) + isBytes := (c == 'b' || c == 'B') + isRaw := (c == 'r' || c == 'R') + lookahead := int32(1) + if l.pos+1 < l.length { + c2 := l.content.Get(int(l.pos + 1)) + if (isBytes && (c2 == 'r' || c2 == 'R')) || (!isBytes && (c2 == 'b' || c2 == 'B')) { + isBytes = true + isRaw = true + lookahead = 2 + } + } + if l.pos+lookahead < l.length { + quote := l.content.Get(int(l.pos + lookahead)) + if quote == '"' || quote == '\'' { + l.advance(lookahead) + return l.consumeStringLiteral(start, quote, isBytes, isRaw), true + } + } + return token{}, false +} + +func (l *lexer) consumeNumericLiteral() token { + start := l.pos + c := l.content.Get(int(l.pos)) + floatingPoint := false + if c == '.' { + floatingPoint = true + l.advance(1) + if !l.consumeDigits() { + return l.setError(start, l.pos, "floating point literal missing digits after decimal separator") + } + } else { + l.advance(1) + if c == '0' { + if l.consumeIgnoreCase('x') { + if !l.consumeHexDigits() { + return l.setError(start, l.pos, "integral literal missing digits after hexadecimal separator") + } + tokType := l.consumeIntegralSuffix() + return l.makeToken(tokType, start, l.pos) + } + } + _ = l.consumeDigits() + if l.pos < l.length && l.content.Get(int(l.pos)) == '.' && + l.pos+1 < l.length && isDigit(l.content.Get(int(l.pos+1))) { + floatingPoint = true + l.advance(1) + _ = l.consumeDigits() + } + } + if l.consumeIgnoreCase('e') { + floatingPoint = true + _ = l.consumeIf(isPlusOrMinus) + if !l.consumeDigits() { + return l.setError(start, l.pos, "floating point literal missing digits after exponent separator") + } + } + var tokType tokenKind + if floatingPoint { + tokType = tokFloat + } else { + tokType = l.consumeIntegralSuffix() + } + return l.makeToken(tokType, start, l.pos) +} + +func (l *lexer) consumeIdent() token { + start := l.pos + for l.pos < l.length { + c := l.content.Get(int(l.pos)) + if !isIdentTrailing(c) { + break + } + l.advance(1) + } + end := l.pos + word := l.content.Slice(int(start), int(end)) + if kind, ok := keywords[word]; ok { + return l.makeToken(kind, start, end) + } + return l.makeToken(tokIdent, start, end) +} + +// Lex scans and returns the next token from the source. +func (l *lexer) Lex() token { + start := l.pos + if l.pos >= l.length { + return l.makeToken(tokEnd, start, start) + } + c := l.content.Get(int(l.pos)) + switch c { + case '\f', '\t', '\r', '\n', ' ': + l.consumeWhitespace() + return l.makeToken(tokWhitespace, start, l.pos) + case '.': + if l.pos+1 < l.length && isDigit(l.content.Get(int(l.pos+1))) { + return l.consumeNumericLiteral() + } + l.advance(1) + return l.makeToken(tokDot, start, l.pos) + case ',': + l.advance(1) + return l.makeToken(tokComma, start, l.pos) + case '!': + l.advance(1) + if l.consume('=') { + return l.makeToken(tokExclamationEqual, start, l.pos) + } + return l.makeToken(tokExclamation, start, l.pos) + case '?': + l.advance(1) + return l.makeToken(tokQuestion, start, l.pos) + case '(': + l.advance(1) + return l.makeToken(tokLeftParen, start, l.pos) + case ')': + l.advance(1) + return l.makeToken(tokRightParen, start, l.pos) + case '{': + l.advance(1) + return l.makeToken(tokLeftBrace, start, l.pos) + case '}': + l.advance(1) + return l.makeToken(tokRightBrace, start, l.pos) + case '[': + l.advance(1) + return l.makeToken(tokLeftBracket, start, l.pos) + case ']': + l.advance(1) + return l.makeToken(tokRightBracket, start, l.pos) + case '=': + l.advance(1) + if l.consume('=') { + return l.makeToken(tokEqualEqual, start, l.pos) + } + return l.makeToken(tokEqual, start, l.pos) + case '<': + l.advance(1) + if l.consume('=') { + return l.makeToken(tokLessEqual, start, l.pos) + } + return l.makeToken(tokLess, start, l.pos) + case '>': + l.advance(1) + if l.consume('=') { + return l.makeToken(tokGreaterEqual, start, l.pos) + } + return l.makeToken(tokGreater, start, l.pos) + case ':': + l.advance(1) + return l.makeToken(tokColon, start, l.pos) + case '%': + l.advance(1) + return l.makeToken(tokPercent, start, l.pos) + case '+': + l.advance(1) + return l.makeToken(tokPlus, start, l.pos) + case '-': + l.advance(1) + return l.makeToken(tokMinus, start, l.pos) + case '*': + l.advance(1) + return l.makeToken(tokAsterisk, start, l.pos) + case '/': + l.advance(1) + if l.consume('/') { + l.consumeLine() + return l.makeToken(tokComment, start, l.pos) + } + return l.makeToken(tokSlash, start, l.pos) + case '&': + l.advance(1) + if l.consume('&') { + return l.makeToken(tokLogicalAnd, start, l.pos) + } + return l.setError(start, l.pos, "unexpected single '&', expected '&&'") + case '|': + l.advance(1) + if l.consume('|') { + return l.makeToken(tokLogicalOr, start, l.pos) + } + return l.setError(start, l.pos, "unexpected single '|', expected '||'") + case '_': + return l.consumeIdent() + case '`': + return l.consumeQuotedIdent() + case '\'': + return l.consumeStringLiteral(start, '\'', false, false) + case '"': + return l.consumeStringLiteral(start, '"', false, false) + case 'r', 'R', 'b', 'B': + if tok, ok := l.consumePrefixedStringLiteral(); ok { + return tok + } + } + if isDigit(c) { + return l.consumeNumericLiteral() + } + if isAlpha(c) { + return l.consumeIdent() + } + l.advance(1) + return l.setError(start, l.pos, "unexpected character") +} diff --git a/vendor/github.com/google/cel-go/parser/macro.go b/vendor/cel.dev/cel-go/parser/macro.go similarity index 99% rename from vendor/github.com/google/cel-go/parser/macro.go rename to vendor/cel.dev/cel-go/parser/macro.go index 1ef43c4b5e..b9f53d7baa 100644 --- a/vendor/github.com/google/cel-go/parser/macro.go +++ b/vendor/cel.dev/cel-go/parser/macro.go @@ -17,11 +17,11 @@ package parser import ( "fmt" - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // MacroOpt defines a functional option for configuring macro behavior. diff --git a/vendor/github.com/google/cel-go/parser/options.go b/vendor/cel.dev/cel-go/parser/options.go similarity index 90% rename from vendor/github.com/google/cel-go/parser/options.go rename to vendor/cel.dev/cel-go/parser/options.go index 281021f122..6fbeb0bd66 100644 --- a/vendor/github.com/google/cel-go/parser/options.go +++ b/vendor/cel.dev/cel-go/parser/options.go @@ -28,7 +28,9 @@ type options struct { enableOptionalSyntax bool enableVariadicOperatorASTs bool enableIdentEscapeSyntax bool + enableCallEscapeSyntax bool enableHiddenAccumulatorName bool + enablePrattParser bool } // Option configures the behavior of the parser. @@ -174,3 +176,20 @@ func EnableVariadicOperatorASTs(varArgASTs bool) Option { return nil } } + +// EnablePrattParser enables the Pratt parser implementation instead of the ANTLR parser. +func EnablePrattParser(enablePrattParser bool) Option { + return func(opts *options) error { + opts.enablePrattParser = enablePrattParser + return nil + } +} + +// EnableCallEscapeSyntax enables backtick (`) escaped function and method call identifiers, +// as well as internal identifiers with '@' characters. +func EnableCallEscapeSyntax(enableCallEscapeSyntax bool) Option { + return func(opts *options) error { + opts.enableCallEscapeSyntax = enableCallEscapeSyntax + return nil + } +} diff --git a/vendor/cel.dev/cel-go/parser/parser.go b/vendor/cel.dev/cel-go/parser/parser.go new file mode 100644 index 0000000000..8fe906a0b2 --- /dev/null +++ b/vendor/cel.dev/cel-go/parser/parser.go @@ -0,0 +1,127 @@ +// Copyright 2018 Google LLC +// +// 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 parser declares an expression parser with support for macro +// expansion. +package parser + +import ( + "math" + + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" +) + +// Parser encapsulates the context necessary to perform parsing for different expressions. +type Parser struct { + options +} + +// NewParser builds and returns a new Parser using the provided options. +func NewParser(opts ...Option) (*Parser, error) { + p := &Parser{} + p.enableHiddenAccumulatorName = true + p.enableIdentEscapeSyntax = true + for _, opt := range opts { + if err := opt(&p.options); err != nil { + return nil, err + } + } + if p.errorReportingLimit == 0 { + p.errorReportingLimit = 100 + } + if p.maxRecursionDepth == 0 { + p.maxRecursionDepth = 250 + } + if p.maxRecursionDepth == -1 { + p.maxRecursionDepth = math.MaxInt + } + if p.errorRecoveryTokenLookaheadLimit == 0 { + p.errorRecoveryTokenLookaheadLimit = 256 + } + if p.errorRecoveryLimit == 0 { + p.errorRecoveryLimit = 30 + } + if p.errorRecoveryLimit == -1 { + p.errorRecoveryLimit = math.MaxInt + } + if p.expressionSizeCodePointLimit == 0 { + p.expressionSizeCodePointLimit = 100_000 + } + if p.expressionSizeCodePointLimit == -1 { + p.expressionSizeCodePointLimit = math.MaxInt + } + if p.maxExpressionNodeCount == 0 { + p.maxExpressionNodeCount = 100_000 + } + if p.maxExpressionNodeCount == -1 { + p.maxExpressionNodeCount = math.MaxInt + } + // Bool is false by default, so populateMacroCalls will be false by default + return p, nil +} + +// mustNewParser does the work of NewParser and panics if an error occurs. +// +// This function is only intended for internal use and is for backwards compatibility in Parse and +// ParseWithMacros, where we know the options will result in an error. +func mustNewParser(opts ...Option) *Parser { + p, err := NewParser(opts...) + if err != nil { + panic(err) + } + return p +} + +// Parse parses the expression represented by source and returns the result. +func (p *Parser) Parse(source common.Source) (*ast.AST, *common.Errors) { + if p.enablePrattParser { + return (&prattParser{options: p.options}).Parse(source) + } + return (&antlrParser{options: p.options}).Parse(source) +} + +// reservedIds are not legal to use as variables. We exclude them post-parse, as they *are* valid +// field names for protos, and it would complicate the grammar to distinguish the cases. +var reservedIds = map[string]struct{}{ + "as": {}, + "break": {}, + "const": {}, + "continue": {}, + "else": {}, + "false": {}, + "for": {}, + "function": {}, + "if": {}, + "import": {}, + "in": {}, + "let": {}, + "loop": {}, + "package": {}, + "namespace": {}, + "null": {}, + "return": {}, + "true": {}, + "var": {}, + "void": {}, + "while": {}, +} + +// Parse converts a source input a parsed expression. +// This function calls ParseWithMacros with AllMacros. +// +// Deprecated: Use NewParser().Parse() instead. +func Parse(source common.Source) (*ast.AST, *common.Errors) { + return mustNewParser(Macros(AllMacros...)).Parse(source) +} diff --git a/vendor/cel.dev/cel-go/parser/pratt_parser.go b/vendor/cel.dev/cel-go/parser/pratt_parser.go new file mode 100644 index 0000000000..72a4e1deac --- /dev/null +++ b/vendor/cel.dev/cel-go/parser/pratt_parser.go @@ -0,0 +1,1133 @@ +// Copyright 2026 Google LLC +// +// 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 parser + +import ( + "fmt" + "strconv" + "strings" + + "cel.dev/cel-go/common" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/runes" + "cel.dev/cel-go/common/types" +) + +type binaryOpInfo struct { + precedence int + name string + kind tokenKind +} + +var ( + opLogicalOr = binaryOpInfo{precedence: 1, name: operators.LogicalOr, kind: tokLogicalOr} + opLogicalAnd = binaryOpInfo{precedence: 2, name: operators.LogicalAnd, kind: tokLogicalAnd} + opLess = binaryOpInfo{precedence: 3, name: operators.Less, kind: tokLess} + opLessEqual = binaryOpInfo{precedence: 3, name: operators.LessEquals, kind: tokLessEqual} + opGreater = binaryOpInfo{precedence: 3, name: operators.Greater, kind: tokGreater} + opGreaterEqual = binaryOpInfo{precedence: 3, name: operators.GreaterEquals, kind: tokGreaterEqual} + opEqualEqual = binaryOpInfo{precedence: 3, name: operators.Equals, kind: tokEqualEqual} + opExclamationEqual = binaryOpInfo{precedence: 3, name: operators.NotEquals, kind: tokExclamationEqual} + opIn = binaryOpInfo{precedence: 3, name: operators.In, kind: tokIn} + opPlus = binaryOpInfo{precedence: 4, name: operators.Add, kind: tokPlus} + opMinus = binaryOpInfo{precedence: 4, name: operators.Subtract, kind: tokMinus} + opAsterisk = binaryOpInfo{precedence: 5, name: operators.Multiply, kind: tokAsterisk} + opSlash = binaryOpInfo{precedence: 5, name: operators.Divide, kind: tokSlash} + opPercent = binaryOpInfo{precedence: 5, name: operators.Modulo, kind: tokPercent} + opDefault = binaryOpInfo{precedence: 0, name: "", kind: tokError} + + binaryOpInfoTable = [tokLogicalOr + 1]binaryOpInfo{ + tokLogicalOr: opLogicalOr, + tokLogicalAnd: opLogicalAnd, + tokLess: opLess, + tokLessEqual: opLessEqual, + tokGreater: opGreater, + tokGreaterEqual: opGreaterEqual, + tokEqualEqual: opEqualEqual, + tokExclamationEqual: opExclamationEqual, + tokIn: opIn, + tokPlus: opPlus, + tokMinus: opMinus, + tokAsterisk: opAsterisk, + tokSlash: opSlash, + tokPercent: opPercent, + } +) + +func getBinaryOpInfo(kind tokenKind) binaryOpInfo { + if int(kind) < len(binaryOpInfoTable) { + return binaryOpInfoTable[kind] + } + return opDefault +} + +type prattParserWorker struct { + content runes.Buffer + length int32 + helper *parserHelper + errors *parseErrors + exprFactory ast.ExprFactory + lexer *lexer + currTok token + peekTok token + macros map[string]Macro + recursionDepth int + lastParsedDepth int + recursionLimitExceeded bool + errorCount int + maxRecursionDepth int + maxExpressionNodeCount int + errorReportingLimit int + errorRecoveryLimit int + populateMacroCalls bool + enableOptionalSyntax bool + enableVariadicOperatorASTs bool + enableIdentEscapeSyntax bool + enableCallEscapeSyntax bool +} + +// prattParser encapsulates the context necessary to perform Pratt parsing for different expressions. +type prattParser struct { + options +} + +// Parse parses the expression represented by source using the Pratt parser and returns the result. +func (p *prattParser) Parse(source common.Source) (*ast.AST, *common.Errors) { + errs := common.NewErrors(source) + buf, ok := source.(runes.Buffer) + if !ok { + buf = runes.NewBuffer(source.Content()) + } + if buf.Len() > p.expressionSizeCodePointLimit { + errs.ReportError(common.NoLocation, + "expression code point size exceeds limit: size: %d, limit %d", + buf.Len(), p.expressionSizeCodePointLimit) + return nil, errs + } + accu := AccumulatorName + if p.enableHiddenAccumulatorName { + accu = HiddenAccumulatorName + } + fac := ast.NewExprFactoryWithAccumulator(accu) + pratt := &prattParserWorker{ + content: buf, + length: int32(buf.Len()), + helper: newParserHelper(source, fac), + errors: &parseErrors{errs}, + exprFactory: fac, + lexer: newLexer(buf), + macros: p.macros, + maxRecursionDepth: p.maxRecursionDepth, + maxExpressionNodeCount: p.maxExpressionNodeCount, + errorReportingLimit: p.errorReportingLimit, + errorRecoveryLimit: p.errorRecoveryLimit, + populateMacroCalls: p.populateMacroCalls, + enableOptionalSyntax: p.enableOptionalSyntax, + enableVariadicOperatorASTs: p.enableVariadicOperatorASTs, + enableIdentEscapeSyntax: p.enableIdentEscapeSyntax, + enableCallEscapeSyntax: p.enableCallEscapeSyntax, + } + pratt.initTokenStream() + out := pratt.parse() + if len(errs.GetErrors()) > 0 { + return nil, errs + } + return ast.NewAST(out, pratt.helper.getSourceInfo()), errs +} + +func (p *prattParserWorker) initTokenStream() { + p.currTok = token{kind: tokError, start: 0, end: 0} + p.peekTok = p.nextSignificantToken() +} + +func (p *prattParserWorker) isRecoveryLimitExceeded() bool { + return p.errorCount > p.errorRecoveryLimit +} + +// checkRecursion returns true and trips the recursion limit if depth exceeds the configured +// limit. +// +// The parser bounds two depths separately against maxRecursionDepth: +// +// - recursionDepth tracks syntactic expression nesting: each parenthesized expression, list, +// map or struct element, call argument, index and conditional false branch opens a new +// level. This bounds the parser's Go call-stack recursion (along with iterative runs of +// grouping parentheses). +// - lastParsedDepth tracks the depth of the AST parsed so far, counting binary, conditional, +// field selection, member call and index nodes. Grouping parentheses, unary operators +// (which are folded), logical operators (which are balanced or variadic), and composite or +// call containers (lists, maps, structs and global calls, whose nesting is already bounded +// by recursionDepth) do not add to it. Because operator and selector chains are parsed +// iteratively, this depth is computed bottom-up and checked as each node is built. +func (p *prattParserWorker) checkRecursion(depth int) bool { + if depth > p.maxRecursionDepth { + if !p.recursionLimitExceeded { + p.recursionLimitExceeded = true + p.errors.internalError(fmt.Sprintf("expression recursion limit exceeded: %d", p.maxRecursionDepth)) + p.peekTok = token{kind: tokEnd, start: p.length, end: p.length} + } + return true + } + return false +} + +func (p *prattParserWorker) nextSignificantToken() token { + if p.isRecoveryLimitExceeded() { + return token{kind: tokEnd, start: p.length, end: p.length} + } + for { + tok := p.lexer.Lex() + if tok.kind == tokWhitespace || tok.kind == tokComment { + continue + } + if tok.kind == tokError { + p.reportSyntaxError(tok, "%s", p.lexer.GetError().message) + if p.isRecoveryLimitExceeded() { + return token{kind: tokEnd, start: p.length, end: p.length} + } + } + return tok + } +} + +func (p *prattParserWorker) scanNextSignificantToken() token { + for { + tok := p.lexer.Lex() + if tok.kind == tokWhitespace || tok.kind == tokComment { + continue + } + return tok + } +} + +// isStructCreationAhead checks whether the current identifier is the root of a struct/message +// creation expression (`CreateMessage` in grammar: `'.'? IDENTIFIER ('.' IDENTIFIER)* '{' ... '}'`). +// Unlike standalone identifiers or selector chains, reserved identifiers (e.g. `import{}` or `import.Foo{}`) +// are permitted in message type names. +func (p *prattParserWorker) isStructCreationAhead() bool { + if p.peekTok.kind == tokLeftBrace { + return true + } + if p.peekTok.kind != tokDot { + return false + } + savedPos := p.lexer.SavePosition() + defer p.lexer.RestorePosition(savedPos) + + tok := p.peekTok + for tok.kind == tokDot { + tok = p.scanNextSignificantToken() + if tok.kind != tokIdent && tok.kind != tokReservedWord { + return false + } + // Quoted identifiers are not allowed in struct creation expressions. + text := p.tokenText(tok) + if len(text) > 0 && text[0] == '`' { + return false + } + tok = p.scanNextSignificantToken() + } + return tok.kind == tokLeftBrace +} + +func (p *prattParserWorker) nextToken() token { + p.currTok = p.peekTok + if p.isRecoveryLimitExceeded() { + p.peekTok = token{kind: tokEnd, start: p.length, end: p.length} + return p.currTok + } + if p.peekTok.kind != tokEnd { + p.peekTok = p.nextSignificantToken() + } + return p.currTok +} + +func (p *prattParserWorker) tokenText(tok token) string { + if tok.start >= 0 && tok.end >= tok.start && tok.end <= p.length { + return p.content.Slice(int(tok.start), int(tok.end)) + } + return "" +} + +func (p *prattParserWorker) nextID(tok token) int64 { + return p.helper.idFromOffsets(tok.start, tok.end) +} + +func (p *prattParserWorker) expect(kind tokenKind, msg string) bool { + if p.peekTok.kind == kind { + p.nextToken() + return true + } + if p.recursionLimitExceeded || p.isRecoveryLimitExceeded() { + return false + } + if p.peekTok.kind != tokError { + if msg == "" { + tokText := p.tokenText(p.peekTok) + formattedTok := fmt.Sprintf("'%s'", tokText) + if p.peekTok.kind == tokEnd { + formattedTok = "" + } + msg = fmt.Sprintf("mismatched input %s expecting '%s'", formattedTok, kind.String()) + } + p.reportSyntaxError(p.peekTok, "%s", msg) + } + p.synchronizeOnDelimiter() + return false +} + +func (p *prattParserWorker) synchronizeOnDelimiter() { + if p.recursionLimitExceeded || p.isRecoveryLimitExceeded() { + p.peekTok = token{kind: tokEnd, start: p.length, end: p.length} + return + } + for p.peekTok.kind != tokEnd { + if p.peekTok.kind == tokComma || + p.peekTok.kind == tokRightParen || + p.peekTok.kind == tokRightBracket || + p.peekTok.kind == tokRightBrace { + break + } + p.nextToken() + } +} + +func (p *prattParserWorker) reportError(ctx any, format string, args ...any) ast.Expr { + if p.isRecoveryLimitExceeded() { + return p.helper.newExpr(common.NoLocation) + } + p.errorCount++ + var location common.Location + err := p.helper.newExpr(ctx) + switch c := ctx.(type) { + case common.Location: + location = c + case token: + location = p.helper.getLocation(err.ID()) + default: + location = p.helper.getLocation(err.ID()) + } + if p.errorCount <= p.errorReportingLimit { + p.errors.reportErrorAtID(err.ID(), location, format, args...) + } + if p.isRecoveryLimitExceeded() { + p.peekTok = token{kind: tokEnd, start: p.length, end: p.length} + } + return err +} + +func (p *prattParserWorker) reportSyntaxError(ctx any, format string, args ...any) ast.Expr { + return p.reportError(ctx, "Syntax error: "+format, args...) +} + +func (p *prattParserWorker) newLogicManager(function string, term ast.Expr) *logicManager { + if p.enableVariadicOperatorASTs { + return newVariadicLogicManager(p.exprFactory, function, term) + } + return newBalancingLogicManager(p.exprFactory, function, term) +} + +func (p *prattParserWorker) globalCallOrMacro(exprID int64, function string, args ...ast.Expr) ast.Expr { + if expr, found := p.expandMacro(exprID, function, nil, args...); found { + return expr + } + return p.helper.newGlobalCall(exprID, function, args...) +} + +func (p *prattParserWorker) receiverCallOrMacro(exprID int64, function string, target ast.Expr, args ...ast.Expr) ast.Expr { + if expr, found := p.expandMacro(exprID, function, target, args...); found { + return expr + } + return p.helper.newReceiverCall(exprID, function, target, args...) +} + +func (p *prattParserWorker) expandMacro(exprID int64, function string, target ast.Expr, args ...ast.Expr) (ast.Expr, bool) { + if len(p.macros) == 0 { + return nil, false + } + macro, found := p.macros[makeMacroKey(function, len(args), target != nil)] + if !found { + macro, found = p.macros[makeVarArgMacroKey(function, target != nil)] + if !found { + return nil, false + } + } + if int(p.helper.expressionCount()) > p.maxExpressionNodeCount { + loc := p.helper.getLocation(exprID) + p.helper.deleteID(exprID) + return p.reportError(loc, "expression count exceeds limit of %d while expanding macro '%s'", p.maxExpressionNodeCount, function), true + } + eh := exprHelperPool.Get().(*exprHelper) + eh.parserHelper = p.helper + eh.id = exprID + expr, err := macro.Expander()(eh, target, args) + exprHelperPool.Put(eh) + if int(p.helper.expressionCount()) > p.maxExpressionNodeCount { + loc := p.helper.getLocation(exprID) + p.helper.deleteID(exprID) + return p.reportError(loc, "expression count exceeds limit of %d while expanding macro '%s'", p.maxExpressionNodeCount, function), true + } + if err != nil { + loc := err.Location + if loc == nil { + loc = p.helper.getLocation(exprID) + } + p.helper.deleteID(exprID) + return p.reportError(loc, "%s", err.Message), true + } + if expr == nil { + return nil, false + } + if p.populateMacroCalls { + p.helper.addMacroCall(expr.ID(), function, target, args...) + } + p.helper.deleteID(exprID) + return expr, true +} + +func (p *prattParserWorker) normalizeIdent(tok token, allowQuoted bool, isQuoted *bool) string { + if isQuoted != nil { + *isQuoted = false + } + text := p.tokenText(tok) + if len(text) == 0 { + return "" + } + if text[0] == '`' { + if isQuoted != nil { + *isQuoted = true + } + if !allowQuoted { + p.reportError(tok, "unexpected quoted identifier") + return "" + } + if !p.enableIdentEscapeSyntax { + p.reportError(tok, "unsupported syntax: '`'") + } + if len(text) < 2 || text[len(text)-1] != '`' { + p.reportError(tok, "unterminated quoted identifier") + return "" + } + // Validate the quoted identifier syntax: + // ESC_IDENTIFIER : '`' (LETTER | DIGIT | '_' | '.' | '-' | '/' | ' ')+ '`'; + inner := text[1 : len(text)-1] + if len(inner) == 0 { + p.reportError(tok, "unexpected quoted identifier") + return "" + } + for _, c := range inner { + if !isAlpha(c) && !isDigit(c) && c != '_' && c != '.' && c != '-' && c != '/' && c != ' ' { + if c == '@' && p.enableCallEscapeSyntax { + continue + } + p.reportError(tok, "unexpected quoted identifier") + return "" + } + } + return inner + } + return text +} + +func (p *prattParserWorker) parse() ast.Expr { + expr := p.parseExpr() + if p.recursionLimitExceeded || p.isRecoveryLimitExceeded() { + return expr + } + if p.peekTok.kind != tokEnd && p.peekTok.kind != tokError { + p.reportSyntaxError(p.peekTok, "unexpected token after expression") + } + return expr +} + +func (p *prattParserWorker) parseExpr() ast.Expr { + if p.recursionLimitExceeded || p.isRecoveryLimitExceeded() { + return p.helper.newExpr(common.NoLocation) + } + if p.checkRecursion(p.recursionDepth + 1) { + return p.helper.newExpr(common.NoLocation) + } + p.recursionDepth++ + expr := p.parseBinaryAndTernary(0) + p.recursionDepth-- + return expr +} + +// parseElementExpr parses one element of a delimited construct (list, map, struct or argument +// list), accumulating lastParsedDepth to the deepest element seen so far. A construct is as +// deep as its deepest element, not its last one, so callers must reset lastParsedDepth to 0 +// before the first element. +func (p *prattParserWorker) parseElementExpr() ast.Expr { + maxDepth := p.lastParsedDepth + expr := p.parseExpr() + if maxDepth > p.lastParsedDepth { + p.lastParsedDepth = maxDepth + } + return expr +} + +func (p *prattParserWorker) parseBinaryAndTernary(minPrec int) ast.Expr { + lhs := p.parseSelectorChain() + return p.parseBinaryAndTernaryFromLhs(lhs, minPrec, p.lastParsedDepth) +} + +// parseBinaryAndTernaryFromLhs parses the operators following lhs, which is lhsDepth deep, and +// leaves the depth of the resulting expression in lastParsedDepth. +func (p *prattParserWorker) parseBinaryAndTernaryFromLhs(lhs ast.Expr, minPrec int, lhsDepth int) ast.Expr { + depth := lhsDepth + for !p.recursionLimitExceeded && !p.isRecoveryLimitExceeded() { + tok := p.peekTok.kind + if tok == tokQuestion && minPrec <= 0 { + lhs = p.parseTernary(lhs, depth) + depth = p.lastParsedDepth + continue + } + + opInfo := getBinaryOpInfo(tok) + if opInfo.kind == tokError || opInfo.precedence < minPrec { + break + } + + if opInfo.name == operators.LogicalOr || opInfo.name == operators.LogicalAnd { + lhs = p.parseLogicalChain(lhs, opInfo, depth) + depth = p.lastParsedDepth + continue + } + + opTok := p.nextToken() + opID := p.nextID(opTok) + rhs := p.parseBinaryAndTernary(opInfo.precedence + 1) + lhs = p.helper.newGlobalCall(opID, opInfo.name, lhs, rhs) + // lastParsedDepth is the depth of the rhs just parsed. The operator node + // sits one level above whichever operand is deeper: "x + a.b.c.d" reaches + // 4 through its rhs and "a.b.c.d + x" reaches 4 through its lhs. + depth = max(depth, p.lastParsedDepth) + 1 + p.checkRecursion(depth) + } + p.lastParsedDepth = depth + return lhs +} + +// parseTernary parses the branches of a conditional whose condition, lhs, is condDepth deep, +// and leaves the depth of the conditional in lastParsedDepth. +func (p *prattParserWorker) parseTernary(lhs ast.Expr, condDepth int) ast.Expr { + qTok := p.nextToken() + opID := p.nextID(qTok) + trueExpr := p.parseBinaryAndTernary(1) + depth := max(condDepth, p.lastParsedDepth) + if !p.expect(tokColon, "expected ':' in conditional expression") { + p.lastParsedDepth = condDepth + return lhs + } + falseExpr := p.parseExpr() + // The conditional node sits one level above the deepest of its operands. + depth = max(depth, p.lastParsedDepth) + 1 + p.lastParsedDepth = depth + p.checkRecursion(depth) + return p.helper.newGlobalCall(opID, operators.Conditional, lhs, trueExpr, falseExpr) +} + +// parseLogicalChain parses a run of '&&' or '||' operators following lhs, which is lhsDepth +// deep, and leaves the depth of the resulting expression in lastParsedDepth. Logical operators +// do not add to the depth: the chain is as deep as its deepest term. +func (p *prattParserWorker) parseLogicalChain(lhs ast.Expr, opInfo binaryOpInfo, lhsDepth int) ast.Expr { + depth := lhsDepth + l := p.newLogicManager(opInfo.name, lhs) + for !p.recursionLimitExceeded && !p.isRecoveryLimitExceeded() && p.peekTok.kind == opInfo.kind { + opTok := p.nextToken() + rhs := p.parseBinaryAndTernary(opInfo.precedence + 1) + depth = max(depth, p.lastParsedDepth) + opID := p.nextID(opTok) + l.addTerm(opID, rhs) + } + p.lastParsedDepth = depth + return l.toExpr() +} + +func (p *prattParserWorker) parseSelectorChain() ast.Expr { + p.lastParsedDepth = 0 + tok := p.peekTok.kind + if tok == tokExclamation || tok == tokMinus { + return p.parseUnaryOps() + } + return p.parseMember() +} + +func (p *prattParserWorker) parseMember() ast.Expr { + p.lastParsedDepth = 0 + canBeStructName := false + lhs := p.parsePrimary(&canBeStructName) + return p.parseSelectorChainTail(lhs, canBeStructName, p.lastParsedDepth) +} + +// parseSelectorChainTail parses the field selections, member calls, indexes and struct +// creations following lhs, which is lhsDepth deep, and leaves the depth of the resulting +// expression in lastParsedDepth. +func (p *prattParserWorker) parseSelectorChainTail(lhs ast.Expr, canBeStructName bool, lhsDepth int) ast.Expr { + depth := lhsDepth +loop: + for !p.recursionLimitExceeded { + switch p.peekTok.kind { + case tokDot: + dotTok := p.nextToken() + optional := false + if p.peekTok.kind == tokQuestion { + p.nextToken() + optional = true + if !p.enableOptionalSyntax { + p.reportError(dotTok, "unsupported syntax '.?'") + } + } + fieldTok := p.nextToken() + if fieldTok.kind != tokIdent && fieldTok.kind != tokReservedWord { + if fieldTok.kind != tokError { + p.reportSyntaxError(fieldTok, "expected identifier after '.'") + } + p.synchronizeOnDelimiter() + break loop + } + isMemberCall := p.peekTok.kind == tokLeftParen + var isQuoted bool + field := p.normalizeIdent(fieldTok, p.enableCallEscapeSyntax || !isMemberCall, &isQuoted) + depth++ + if optional { + fieldID := p.nextID(fieldTok) + opID := p.nextID(dotTok) + lhs = p.helper.newGlobalCall(opID, operators.OptSelect, lhs, p.helper.newLiteralString(fieldID, field)) + canBeStructName = false + } else if isMemberCall { + lparen := p.nextToken() + callID := p.nextID(lparen) + args := p.parseArguments(tokRightParen) + lhs = p.receiverCallOrMacro(callID, field, lhs, args...) + // parseArguments leaves lastParsedDepth at the deepest argument. + // Arguments hang one level below the call node, so "a.f(b.c.d.e)" is 4 + // deep. The max preserves the selectors already walked when the + // arguments are shallower, as in "a.b.c.f(1)". + depth = max(depth, p.lastParsedDepth+1) + canBeStructName = false + } else { + dotID := p.nextID(dotTok) + lhs = p.helper.newSelect(dotID, lhs, field) + canBeStructName = canBeStructName && !isQuoted + } + // A plain qualified name such as "a.b.Msg" may still turn out to be the + // type name of a struct creation, which adds no depth, so its field + // selections are only checked once the chain is known to be something else. + if !canBeStructName { + p.checkRecursion(depth) + } + case tokLeftBracket: + bracketTok := p.nextToken() + opID := p.nextID(bracketTok) + optional := false + if p.peekTok.kind == tokQuestion { + p.nextToken() + optional = true + if !p.enableOptionalSyntax { + p.reportError(bracketTok, "unsupported syntax '[?'") + } + } + index := p.parseExpr() + p.expect(tokRightBracket, "expected ']'") + opName := operators.Index + if optional { + opName = operators.OptIndex + } + lhs = p.helper.newGlobalCall(opID, opName, lhs, index) + // lastParsedDepth is the depth of the index expression just parsed. The + // index node sits one level above the deeper of its operand and its index, + // so "a[b.c.d.e]" is 4 deep and "a.b.c[0]" is 3 deep. + depth = max(depth, p.lastParsedDepth) + 1 + canBeStructName = false + p.checkRecursion(depth) + case tokLeftBrace: + if !canBeStructName { + break loop + } + structName, ok := p.extractStructName(lhs) + if !ok { + break loop + } + objID := p.nextID(p.peekTok) + lhs = p.parseStruct(objID, structName) + // parseStruct leaves lastParsedDepth at the deepest field value. Struct + // creation is a primary rather than a chain link and its qualified type + // name is part of it, so neither adds a level: "a.b.Msg{f: 1}" is 0 deep + // and "Msg{f: a.b.c.d}" is 3 deep. + depth = p.lastParsedDepth + canBeStructName = false + default: + break loop + } + } + // A chain that ended as a plain qualified name, such as "a.b.c", still needs + // to be checked. + if canBeStructName { + p.checkRecursion(depth) + } + p.lastParsedDepth = depth + return lhs +} + +// extractStructName converts a chain of pre-parsed AST nodes representing field selections, +// such as "a.b.Msg", into a qualified struct type name. +func (p *prattParserWorker) extractStructName(expr ast.Expr) (string, bool) { + var name string + for expr != nil && expr.Kind() == ast.SelectKind { + sel := expr.AsSelect() + if sel.IsTestOnly() { + return "", false + } + p.helper.deleteID(expr.ID()) + name = "." + sel.FieldName() + name + expr = sel.Operand() + } + if expr == nil || expr.Kind() != ast.IdentKind { + return "", false + } + p.helper.deleteID(expr.ID()) + return expr.AsIdent() + name, true +} + +func (p *prattParserWorker) parseStruct(objID int64, structName string) ast.Expr { + p.nextToken() // consumes { + var fields []ast.EntryExpr + p.lastParsedDepth = 0 + for p.peekTok.kind != tokRightBrace && p.peekTok.kind != tokEnd { + optional := false + if p.peekTok.kind == tokQuestion { + q := p.nextToken() + optional = true + if !p.enableOptionalSyntax { + p.reportError(q, "unsupported syntax '?'") + } + } + fieldTok := p.nextToken() + if fieldTok.kind != tokIdent && fieldTok.kind != tokReservedWord { + p.reportSyntaxError(fieldTok, "expected struct field name") + p.synchronizeOnDelimiter() + break + } + fieldName := p.normalizeIdent(fieldTok, true, nil) + colonTok := p.peekTok + if !p.expect(tokColon, "expected ':' in struct field") { + break + } + fieldID := p.nextID(colonTok) + val := p.parseElementExpr() + fields = append(fields, p.helper.newObjectField(fieldID, fieldName, val, optional)) + if p.peekTok.kind == tokComma { + p.nextToken() + } else { + break + } + } + p.expect(tokRightBrace, "expected '}'") + return p.helper.newObject(objID, structName, fields...) +} + +func (p *prattParserWorker) parseUnaryOps() ast.Expr { + firstOp := p.nextToken() + opType := firstOp.kind + ops := []token{firstOp} + for p.peekTok.kind == opType { + ops = append(ops, p.nextToken()) + } + + if opType == tokMinus && len(ops) == 1 && (p.peekTok.kind == tokInt || p.peekTok.kind == tokFloat) { + opID := p.nextID(firstOp) + var lhs ast.Expr + if p.peekTok.kind == tokInt { + lhs = p.parseNegativeIntLiteral(opID) + } else { + lhs = p.parseNegativeDoubleLiteral(opID) + } + tok := p.peekTok.kind + if tok == tokDot || tok == tokLeftBracket || tok == tokLeftBrace { + lhs = p.parseSelectorChainTail(lhs, false, 0) + } + return lhs + } + + if len(ops)%2 == 0 { + ops = ops[:0] + } else { + ops = ops[:1] + } + + type unaryOpWithID struct { + token token + id int64 + } + retainedOps := make([]unaryOpWithID, len(ops)) + for i, op := range ops { + retainedOps[i] = unaryOpWithID{token: op, id: p.nextID(op)} + } + + var operand ast.Expr + if opType == tokExclamation && p.peekTok.kind == tokMinus { + minusTok := p.nextToken() + minusID := p.nextID(minusTok) + if p.peekTok.kind == tokInt { + operand = p.parseNegativeIntLiteral(minusID) + operand = p.parseSelectorChainTail(operand, false, 0) + } else if p.peekTok.kind == tokFloat { + operand = p.parseNegativeDoubleLiteral(minusID) + operand = p.parseSelectorChainTail(operand, false, 0) + } else { + p.reportSyntaxError(minusTok, "unexpected '-'") + operand = p.parseMember() + } + } else { + operand = p.parseMember() + } + if p.recursionLimitExceeded { + return p.helper.newExpr(common.NoLocation) + } + + for i := len(retainedOps) - 1; i >= 0; i-- { + opName := operators.LogicalNot + if retainedOps[i].token.kind == tokMinus { + opName = operators.Negate + } + operand = p.globalCallOrMacro(retainedOps[i].id, opName, operand) + } + return operand +} + +func (p *prattParserWorker) parsePrimary(canBeStructName *bool) ast.Expr { + if canBeStructName != nil { + *canBeStructName = false + } + switch p.peekTok.kind { + case tokLeftParen: + if p.recursionLimitExceeded || p.isRecoveryLimitExceeded() { + return p.helper.newExpr(common.NoLocation) + } + // To avoid deep call-stack recursion on heavily nested parentheses (e.g. + // "((((a))))" or "((((a + 1) + 1) + 1))"), consume all consecutive + // leading '(' tokens upfront, parse the innermost expression once, and + // then iteratively unwind each enclosing '(' from innermost to outermost. + // After consuming each matching ')', if more enclosing '(' remain open + // and the next token is not another ')', continue parsing any trailing + // selectors or binary/ternary operators belonging to that enclosing + // parenthesized level using the already-parsed inner expression as the + // LHS. + openParens := 0 + for p.peekTok.kind == tokLeftParen { + openParens++ + p.nextToken() + } + // Every '(' nested inside the enclosing expression is a nesting level and + // costs one unit of recursion budget, so charge all of them here: the + // innermost of openParens parentheses sits at recursionDepth + openParens - 1. + // recursionDepth itself only advances by 1 because the parens are unwound + // iteratively and entering parseBinaryAndTernary(0) below adds just one + // stack frame. Parentheses do not add to the depth of the AST. + if p.checkRecursion(p.recursionDepth + openParens - 1) { + return p.helper.newExpr(common.NoLocation) + } + p.recursionDepth++ + expr := p.parseBinaryAndTernary(0) + depth := p.lastParsedDepth + for i := 0; i < openParens; i++ { + p.expect(tokRightParen, "expected ')'") + if i < openParens-1 && p.peekTok.kind != tokRightParen { + tok := p.peekTok.kind + if tok == tokDot || tok == tokLeftBracket || tok == tokLeftBrace { + expr = p.parseSelectorChainTail(expr, false, depth) + depth = p.lastParsedDepth + } + expr = p.parseBinaryAndTernaryFromLhs(expr, 0, depth) + depth = p.lastParsedDepth + } + } + p.recursionDepth-- + p.lastParsedDepth = depth + return expr + case tokNull: + return p.helper.exprFactory.NewLiteral(p.nextID(p.nextToken()), types.NullValue) + case tokTrue: + tok := p.nextToken() + return p.helper.newLiteralBool(p.nextID(tok), true) + case tokFalse: + tok := p.nextToken() + return p.helper.newLiteralBool(p.nextID(tok), false) + case tokInt: + return p.parseIntLiteral() + case tokUint: + return p.parseUintLiteral() + case tokFloat: + return p.parseDoubleLiteral() + case tokString: + return p.parseStringLiteral() + case tokBytes: + return p.parseBytesLiteral() + case tokLeftBracket: + return p.parseList() + case tokLeftBrace: + return p.parseMap() + case tokDot, tokIdent, tokReservedWord: + return p.parseIdentOrCall(canBeStructName) + default: + badTok := p.nextToken() + if badTok.kind != tokError { + if badTok.kind == tokEnd { + p.reportSyntaxError(badTok, "mismatched input '' expecting expression") + } else { + p.reportSyntaxError(badTok, "unexpected token") + } + } + return p.helper.newExpr(badTok) + } +} + +func (p *prattParserWorker) parseList() ast.Expr { + openTok := p.nextToken() + listID := p.nextID(openTok) + var elems []ast.Expr + var optionals []int32 + p.lastParsedDepth = 0 + for p.peekTok.kind != tokRightBracket && p.peekTok.kind != tokEnd { + optional := false + if p.peekTok.kind == tokQuestion { + q := p.nextToken() + optional = true + if !p.enableOptionalSyntax { + p.reportError(q, "unsupported syntax '?'") + } + } + if optional { + optionals = append(optionals, int32(len(elems))) + } + elem := p.parseElementExpr() + elems = append(elems, elem) + if p.peekTok.kind == tokComma { + p.nextToken() + if p.peekTok.kind == tokRightBracket { + break + } + continue + } + break + } + p.expect(tokRightBracket, "expected ']'") + return p.helper.newList(listID, elems, optionals...) +} + +func (p *prattParserWorker) parseMap() ast.Expr { + openTok := p.nextToken() + mapID := p.nextID(openTok) + var entries []ast.EntryExpr + p.lastParsedDepth = 0 + for p.peekTok.kind != tokRightBrace && p.peekTok.kind != tokEnd { + optional := false + if p.peekTok.kind == tokQuestion { + q := p.nextToken() + optional = true + if !p.enableOptionalSyntax { + p.reportError(q, "unsupported syntax '?'") + } + } + entryID := p.helper.allocID() + key := p.parseElementExpr() + colonTok := p.peekTok + if !p.expect(tokColon, "expected ':' in map entry") { + break + } + p.helper.setTokenLocation(entryID, colonTok) + val := p.parseElementExpr() + entries = append(entries, p.helper.newMapEntry(entryID, key, val, optional)) + if p.peekTok.kind == tokComma { + p.nextToken() + if p.peekTok.kind == tokRightBrace { + break + } + continue + } + break + } + p.expect(tokRightBrace, "expected '}'") + return p.helper.newMap(mapID, entries...) +} + +func (p *prattParserWorker) parseIdentOrCall(canBeStructName *bool) ast.Expr { + leadingDot := false + firstTok := p.peekTok + if p.peekTok.kind == tokDot { + p.nextToken() + leadingDot = true + } + idTok := p.nextToken() + if idTok.kind != tokIdent && idTok.kind != tokReservedWord { + if idTok.kind != tokError { + p.reportSyntaxError(idTok, "expected identifier") + } + if canBeStructName != nil { + *canBeStructName = false + } + return p.helper.newExpr(idTok) + } + var isQuoted bool + idText := p.normalizeIdent(idTok, p.enableCallEscapeSyntax, &isQuoted) + if idTok.kind == tokReservedWord { + if _, ok := reservedIds[idText]; ok && !p.isStructCreationAhead() { + p.reportError(idTok, "reserved identifier: %s", idText) + } + } + name := idText + if leadingDot { + name = "." + idText + } + if p.peekTok.kind == tokLeftParen { + lparen := p.nextToken() + callID := p.nextID(lparen) + args := p.parseArguments(tokRightParen) + if canBeStructName != nil { + *canBeStructName = false + } + return p.globalCallOrMacro(callID, name, args...) + } + if canBeStructName != nil { + *canBeStructName = !isQuoted + } + targetTok := idTok + if leadingDot { + targetTok = firstTok + } + id := p.nextID(targetTok) + return p.helper.newIdent(id, name) +} + +func (p *prattParserWorker) parseArguments(closeTok tokenKind) []ast.Expr { + var args []ast.Expr + p.lastParsedDepth = 0 + if p.peekTok.kind != closeTok && p.peekTok.kind != tokEnd { + for { + args = append(args, p.parseElementExpr()) + if p.peekTok.kind == tokComma { + p.nextToken() + if p.peekTok.kind == closeTok { + p.reportSyntaxError(p.peekTok, "unexpected token") + break + } + continue + } + break + } + } + p.expect(closeTok, "") + return args +} + +func (p *prattParserWorker) parseIntLiteral() ast.Expr { + tok := p.nextToken() + id := p.nextID(tok) + text := p.tokenText(tok) + base := 10 + if strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X") { + base = 16 + text = text[2:] + } + val, err := strconv.ParseInt(text, base, 64) + if err != nil { + return p.reportSyntaxError(tok, "invalid int literal") + } + return p.helper.newLiteralInt(id, val) +} + +func (p *prattParserWorker) parseNegativeIntLiteral(opID int64) ast.Expr { + tok := p.nextToken() + text := p.tokenText(tok) + base := 10 + if strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X") { + base = 16 + text = text[2:] + } + val, err := strconv.ParseInt("-"+text, base, 64) + if err != nil { + return p.reportSyntaxError(tok, "invalid int literal") + } + return p.helper.newLiteralInt(opID, val) +} + +func (p *prattParserWorker) parseUintLiteral() ast.Expr { + tok := p.nextToken() + id := p.nextID(tok) + text := p.tokenText(tok) + text = text[:len(text)-1] + base := 10 + if strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X") { + base = 16 + text = text[2:] + } + val, err := strconv.ParseUint(text, base, 64) + if err != nil { + return p.reportSyntaxError(tok, "invalid uint literal") + } + return p.helper.newLiteralUint(id, val) +} + +func (p *prattParserWorker) parseDoubleLiteral() ast.Expr { + tok := p.nextToken() + id := p.nextID(tok) + text := p.tokenText(tok) + val, err := strconv.ParseFloat(text, 64) + if err != nil { + return p.reportSyntaxError(tok, "invalid double literal") + } + return p.helper.newLiteralDouble(id, val) +} + +func (p *prattParserWorker) parseNegativeDoubleLiteral(opID int64) ast.Expr { + tok := p.nextToken() + text := p.tokenText(tok) + val, err := strconv.ParseFloat(text, 64) + if err != nil { + return p.reportSyntaxError(tok, "invalid double literal") + } + return p.helper.newLiteralDouble(opID, -val) +} + +func (p *prattParserWorker) parseStringLiteral() ast.Expr { + tok := p.nextToken() + id := p.nextID(tok) + text := p.tokenText(tok) + unescaped, err := unescape(text, false) + if err != nil { + return p.reportError(tok, "%s", err.Error()) + } + return p.helper.newLiteralString(id, unescaped) +} + +func (p *prattParserWorker) parseBytesLiteral() ast.Expr { + tok := p.nextToken() + id := p.nextID(tok) + text := p.tokenText(tok) + if strings.HasPrefix(text, "b") || strings.HasPrefix(text, "B") { + text = text[1:] + } else if strings.HasPrefix(text, "rb") || strings.HasPrefix(text, "RB") || strings.HasPrefix(text, "rB") || strings.HasPrefix(text, "Rb") { + text = "r" + text[2:] + } else if strings.HasPrefix(text, "br") || strings.HasPrefix(text, "BR") || strings.HasPrefix(text, "bR") || strings.HasPrefix(text, "Br") { + text = text[1:] + } + unescaped, err := unescape(text, true) + if err != nil { + return p.reportError(tok, "%s", err.Error()) + } + return p.helper.newLiteralBytes(id, []byte(unescaped)) +} diff --git a/vendor/github.com/google/cel-go/parser/unescape.go b/vendor/cel.dev/cel-go/parser/unescape.go similarity index 100% rename from vendor/github.com/google/cel-go/parser/unescape.go rename to vendor/cel.dev/cel-go/parser/unescape.go diff --git a/vendor/github.com/google/cel-go/parser/unparser.go b/vendor/cel.dev/cel-go/parser/unparser.go similarity index 87% rename from vendor/github.com/google/cel-go/parser/unparser.go rename to vendor/cel.dev/cel-go/parser/unparser.go index d503a450e9..db96504bda 100644 --- a/vendor/github.com/google/cel-go/parser/unparser.go +++ b/vendor/cel.dev/cel-go/parser/unparser.go @@ -17,14 +17,15 @@ package parser import ( "errors" "fmt" + "math" "regexp" "strconv" "strings" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" + "cel.dev/cel-go/common/ast" + "cel.dev/cel-go/common/operators" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" ) // Unparse takes an input expression and source position information and generates a human-readable @@ -69,7 +70,42 @@ func Unparse(expr ast.Expr, info *ast.SourceInfo, opts ...UnparserOption) (strin var identifierPartPattern *regexp.Regexp = regexp.MustCompile(`^[A-Za-z_][0-9A-Za-z_]*$`) -func maybeQuoteField(field string) string { +func (un *unparser) maybeQuoteIdent(name string) string { + if !un.options.escapeIdentifiers { + return name + } + if name == "" { + return "" + } + if strings.HasPrefix(name, ".") { + return "." + un.maybeQuoteIdent(name[1:]) + } + if strings.Contains(name, ".") { + parts := strings.Split(name, ".") + for i, part := range parts { + parts[i] = un.maybeQuoteIdent(part) + } + return strings.Join(parts, ".") + } + if !identifierPartPattern.MatchString(name) || isReservedIdent(name) { + return "`" + name + "`" + } + return name +} + +func (un *unparser) maybeQuoteFunction(fun string) string { + return un.maybeQuoteIdent(fun) +} + +func isReservedIdent(name string) bool { + _, ok := reservedIds[name] + return ok +} + +func (un *unparser) maybeQuoteField(field string) string { + if !un.options.escapeIdentifiers { + return field + } if !identifierPartPattern.MatchString(field) || field == "in" { return "`" + field + "`" } @@ -220,8 +256,10 @@ func (un *unparser) visitCallFunc(expr ast.Expr) error { return err } un.str.WriteString(".") + un.str.WriteString(un.maybeQuoteIdent(fun)) + } else { + un.str.WriteString(un.maybeQuoteFunction(fun)) } - un.str.WriteString(fun) un.str.WriteString("(") for i, arg := range args { err := un.visit(arg) @@ -270,7 +308,7 @@ func (un *unparser) visitCallUnary(expr ast.Expr) error { return fmt.Errorf("cannot unmangle operator: %s", fun) } un.str.WriteString(unmangled) - nested := isComplexOperator(args[0]) + nested := isComplexOperator(args[0]) || isAmbiguousUnaryOperand(args[0]) return un.visitMaybeNested(args[0], nested) } @@ -334,7 +372,7 @@ func (un *unparser) visitConst(expr ast.Expr) error { } func (un *unparser) visitIdent(expr ast.Expr) error { - un.str.WriteString(expr.AsIdent()) + un.str.WriteString(un.maybeQuoteIdent(expr.AsIdent())) return nil } @@ -386,7 +424,7 @@ func (un *unparser) visitSelectInternal(operand ast.Expr, testOnly bool, op stri return err } un.str.WriteString(op) - un.str.WriteString(maybeQuoteField(field)) + un.str.WriteString(un.maybeQuoteField(field)) if testOnly { un.str.WriteString(")") } @@ -396,7 +434,7 @@ func (un *unparser) visitSelectInternal(operand ast.Expr, testOnly bool, op stri func (un *unparser) visitStructMsg(expr ast.Expr) error { m := expr.AsStruct() fields := m.Fields() - un.str.WriteString(m.TypeName()) + un.str.WriteString(un.maybeQuoteFunction(m.TypeName())) un.str.WriteString("{") for i, f := range fields { field := f.AsStructField() @@ -404,7 +442,7 @@ func (un *unparser) visitStructMsg(expr ast.Expr) error { if field.IsOptional() { un.str.WriteString("?") } - un.str.WriteString(maybeQuoteField(f)) + un.str.WriteString(un.maybeQuoteField(f)) un.str.WriteString(": ") v := field.Value() err := un.visit(v) @@ -507,6 +545,30 @@ func isComplexOperator(expr ast.Expr) bool { return false } +// Indicates whether the operand of a unary operator must be wrapped in parentheses in order for +// the unparsed expression to parse back to an equivalent AST. +// +// The CEL grammar parses a run of leading '!' or '-' tokens as a single unary expression and drops +// the operators when their count is even, and it also treats a leading '-' as part of an int or +// double literal. Emitting such an operand without parentheses either changes the expression, e.g. +// `!(!a)` would unparse to `!!a` which parses back to `a`, or produces output which does not parse +// at all, e.g. `-(!a)` would unparse to `-!a`. +func isAmbiguousUnaryOperand(expr ast.Expr) bool { + switch expr.Kind() { + case ast.CallKind: + fun := expr.AsCall().FunctionName() + return fun == operators.LogicalNot || fun == operators.Negate + case ast.LiteralKind: + switch lit := expr.AsLiteral().(type) { + case types.Int: + return lit < 0 + case types.Double: + return math.Signbit(float64(lit)) + } + } + return false +} + // Indicates whether it is a complex operation compared to another. // expr is *not* considered complex if it is not a call expression or has // less than two arguments, or if it has a higher precedence than op. @@ -586,6 +648,16 @@ type unparserOption struct { wrapOnColumn int operatorsToWrapOn map[string]bool wrapAfterColumnLimit bool + escapeIdentifiers bool +} + +// EscapeIdentifiers enables backtick (`) escaping for non-standard and reserved identifiers, +// function names, and field names when unparsing. +func EscapeIdentifiers(escape bool) UnparserOption { + return func(opt *unparserOption) (*unparserOption, error) { + opt.escapeIdentifiers = escape + return opt, nil + } } // WrapOnColumn wraps the output expression when its string length exceeds a specified limit diff --git a/vendor/cloud.google.com/go/auth/CHANGES.md b/vendor/cloud.google.com/go/auth/CHANGES.md index 38014c4fb2..2c1f6ff8fa 100644 --- a/vendor/cloud.google.com/go/auth/CHANGES.md +++ b/vendor/cloud.google.com/go/auth/CHANGES.md @@ -1,5 +1,7 @@ # Changes +## [0.20.0](https://github.com/googleapis/google-cloud-go/releases/tag/auth%2Fv0.20.0) (2026-04-06) + ## [0.19.0](https://github.com/googleapis/google-cloud-go/releases/tag/auth%2Fv0.19.0) (2026-03-23) ### Features diff --git a/vendor/cloud.google.com/go/auth/grpctransport/grpctransport.go b/vendor/cloud.google.com/go/auth/grpctransport/grpctransport.go index 1792c47286..f77f6423c4 100644 --- a/vendor/cloud.google.com/go/auth/grpctransport/grpctransport.go +++ b/vendor/cloud.google.com/go/auth/grpctransport/grpctransport.go @@ -22,9 +22,11 @@ import ( "errors" "fmt" "log/slog" + "net" "net/http" "os" "strconv" + "strings" "cloud.google.com/go/auth" "cloud.google.com/go/auth/credentials" @@ -38,11 +40,9 @@ import ( "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" "google.golang.org/grpc" - "google.golang.org/grpc/codes" grpccreds "google.golang.org/grpc/credentials" grpcinsecure "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" ) const ( @@ -370,7 +370,7 @@ func dial(ctx context.Context, secure bool, opts *Options) (*grpc.ClientConn, er // Add tracing, but before the other options, so that clients can override the // gRPC stats handler. // This assumes that gRPC options are processed in order, left to right. - grpcOpts = addOpenTelemetryStatsHandler(grpcOpts, opts) + grpcOpts = addOpenTelemetryStatsHandler(grpcOpts, opts, transportCreds.Endpoint) grpcOpts = append(grpcOpts, opts.GRPCDialOpts...) return grpc.DialContext(ctx, transportCreds.Endpoint, grpcOpts...) @@ -458,29 +458,89 @@ func (c *grpcCredentialsProvider) RequireTransportSecurity() bool { return c.secure } -func addOpenTelemetryStatsHandler(dialOpts []grpc.DialOption, opts *Options) []grpc.DialOption { +func addOpenTelemetryStatsHandler(dialOpts []grpc.DialOption, opts *Options, endpoint string) []grpc.DialOption { if opts.DisableTelemetry { return dialOpts } - if !gax.IsFeatureEnabled("TRACING") { + if gax.IsFeatureEnabled("METRICS") { + host, port := extractHostPort(endpoint) + dialOpts = append(dialOpts, grpc.WithChainUnaryInterceptor(openTelemetryUnaryClientInterceptor(host, port))) + } + if !gax.IsFeatureEnabled("TRACING") && !gax.IsFeatureEnabled("LOGGING") { return append(dialOpts, grpc.WithStatsHandler(otelgrpc.NewClientHandler())) } var staticAttrs []attribute.KeyValue + var scopedLogger *slog.Logger + + if gax.IsFeatureEnabled("LOGGING") && opts.Logger != nil { + scopedLogger = opts.Logger + } + if opts.InternalOptions != nil { staticAttrs = transport.StaticTelemetryAttributes(opts.InternalOptions.TelemetryAttributes) + if scopedLogger != nil { + var staticLogAttrs []any + for _, attr := range staticAttrs { + staticLogAttrs = append(staticLogAttrs, slog.String(string(attr.Key), attr.Value.AsString())) + } + scopedLogger = scopedLogger.With(staticLogAttrs...) + } } - otelOpts := []otelgrpc.Option{ - otelgrpc.WithSpanAttributes(staticAttrs...), + var otelOpts []otelgrpc.Option + if gax.IsFeatureEnabled("TRACING") { + otelOpts = append(otelOpts, otelgrpc.WithSpanAttributes(staticAttrs...)) } return append(dialOpts, grpc.WithStatsHandler(&otelHandler{ Handler: otelgrpc.NewClientHandler(otelOpts...), + logger: scopedLogger, })) } +// Extract the host and port from a target address +func extractHostPort(target string) (string, int) { + if idx := strings.Index(target, "://"); idx != -1 { + target = target[idx+3:] + // Ensure any leading authorities (like 8.8.8.8 in dns://8.8.8.8/foo) are stripped + if slashIdx := strings.Index(target, "/"); slashIdx != -1 { + target = target[slashIdx+1:] + } + } + host, portStr, err := net.SplitHostPort(target) + if err != nil { + return target, 0 + } + port, err := strconv.Atoi(portStr) + if err != nil { + return host, 0 + } + return host, port +} + +// openTelemetryUnaryClientInterceptor returns an interceptor that populates +// TransportTelemetryData with the server peer address. +func openTelemetryUnaryClientInterceptor(host string, port int) grpc.UnaryClientInterceptor { + return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + transportData := gax.ExtractTransportTelemetry(ctx) + if transportData != nil { + if host != "" { + transportData.SetServerAddress(host) + } + if port != 0 { + transportData.SetServerPort(port) + } + } + + err := invoker(ctx, method, req, reply, cc, opts...) + + return err + } +} + // otelHandler is a wrapper around the OpenTelemetry gRPC client handler that // adds custom Google Cloud-specific attributes to spans and metrics. type otelHandler struct { stats.Handler + logger *slog.Logger } // TagRPC intercepts the RPC start to extract dynamic attributes like resource @@ -488,8 +548,15 @@ type otelHandler struct { // the current span. func (h *otelHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { ctx = h.Handler.TagRPC(ctx, info) - span := trace.SpanFromContext(ctx) - if !span.IsRecording() { + + var span trace.Span + if gax.IsFeatureEnabled("TRACING") { + if s := trace.SpanFromContext(ctx); s != nil && s.IsRecording() { + span = s + } + } + + if span == nil { return ctx } var attrs []attribute.KeyValue @@ -515,62 +582,94 @@ func (h *otelHandler) HandleRPC(ctx context.Context, s stats.RPCStats) { h.Handler.HandleRPC(ctx, s) return } - span := trace.SpanFromContext(ctx) - if !span.IsRecording() { + + var span trace.Span + if gax.IsFeatureEnabled("TRACING") { + if s := trace.SpanFromContext(ctx); s != nil && s.IsRecording() { + span = s + } + } + + var logger *slog.Logger + if gax.IsFeatureEnabled("LOGGING") { + if l := h.logger; l != nil && l.Enabled(ctx, slog.LevelDebug) { + logger = l + } + } + + if span == nil && logger == nil { h.Handler.HandleRPC(ctx, s) return } - var attrs []attribute.KeyValue if end.Error != nil { - st, ok := status.FromError(end.Error) - rpcStatusCode := codeToCanonicalStr(st.Code()) - - var errorType string - // 1. Check if the local context expired or was cancelled. This is the only - // reliable way to distinguish a local client timeout from a server timeout - // because gRPC does not wrap context errors in its status.Error types. - if errors.Is(ctx.Err(), context.DeadlineExceeded) { - errorType = "CLIENT_TIMEOUT" - } else if errors.Is(ctx.Err(), context.Canceled) { - errorType = "CLIENT_CANCELLED" - } else if !ok || st.Code() == codes.Unknown || st.Code() == codes.Internal { - // 2. If the error isn't a context breakdown and the gRPC framework - // doesn't "understand" it (returning ok=false or a generic catch-all - // bucket like Unknown/Internal), we "pack" the actual Go error type - // name into error.type (e.g., "*net.OpError"). This is per the error.type - // [spec](https://opentelemetry.io/docs/specs/semconv/registry/attributes/error/#error-type). - // "When error.type is set to a type (e.g., an exception type), its canonical - // class name identifying the type within the artifact SHOULD be used." - errorType = fmt.Sprintf("%T", end.Error) - } else { - // 3. Otherwise, it is a well-understood gRPC protocol error (e.g., - // PERMISSION_DENIED) likely returned by the server. - errorType = rpcStatusCode - } + h.handleRPCError(ctx, span, logger, end) + } else { + h.handleRPCSuccess(span) + } + h.Handler.HandleRPC(ctx, s) +} - attrs = []attribute.KeyValue{ - attribute.String("error.type", errorType), - attribute.String("status.message", st.Message()), - attribute.String("rpc.response.status_code", rpcStatusCode), +func (h *otelHandler) handleRPCError(ctx context.Context, span trace.Span, logger *slog.Logger, end *stats.End) { + info := gax.ExtractTelemetryErrorInfo(ctx, end.Error) + + if logger != nil { + logActionableError(ctx, logger, info) + } + + if span != nil { + attrs := []attribute.KeyValue{ + attribute.String("error.type", info.ErrorType), + attribute.String("status.message", info.StatusMessage), + attribute.String("rpc.response.status_code", info.StatusCode), attribute.String("exception.type", fmt.Sprintf("%T", end.Error)), } - } else { - attrs = []attribute.KeyValue{ + span.SetAttributes(attrs...) + } +} + +func (h *otelHandler) handleRPCSuccess(span trace.Span) { + if span != nil { + attrs := []attribute.KeyValue{ attribute.String("rpc.response.status_code", "OK"), } + span.SetAttributes(attrs...) } - span.SetAttributes(attrs...) - h.Handler.HandleRPC(ctx, s) } -// codeToCanonicalStr returns the canonical name for each of the 17 gRPC -// status codes defined in https://github.com/grpc/grpc-go/blob/master/codes/codes.go. -// For any codes.Code that converts to an out-of-bounds int, -// it returns "UNKNOWN". -func codeToCanonicalStr(code codes.Code) string { - if int(code) >= 0 && int(code) < len(codeToStr) { - return codeToStr[code] +func logActionableError(ctx context.Context, logger *slog.Logger, info gax.TelemetryErrorInfo) { + baseLogAttrs := []slog.Attr{ + slog.String("rpc.system.name", "grpc"), + slog.String("rpc.response.status_code", info.StatusCode), } - return "UNKNOWN" + + if resendCountStr, ok := callctx.TelemetryFromContext(ctx, "resend_count"); ok { + if count, e := strconv.Atoi(resendCountStr); e == nil { + baseLogAttrs = append(baseLogAttrs, slog.Int64("gcp.grpc.resend_count", int64(count))) + } + } + + msg := info.StatusMessage + if msg == "" { + msg = "API call failed" + } + + if rpcMethod, ok := callctx.TelemetryFromContext(ctx, "rpc_method"); ok { + baseLogAttrs = append(baseLogAttrs, slog.String("rpc.method", rpcMethod)) + } + + if resName, ok := callctx.TelemetryFromContext(ctx, "resource_name"); ok { + baseLogAttrs = append(baseLogAttrs, slog.String("gcp.resource.destination.id", resName)) + } + + if info.Domain != "" { + baseLogAttrs = append(baseLogAttrs, slog.String("gcp.errors.domain", info.Domain)) + } + for k, v := range info.Metadata { + baseLogAttrs = append(baseLogAttrs, slog.String("gcp.errors.metadata."+k, v)) + } + + baseLogAttrs = append(baseLogAttrs, slog.String("error.type", info.ErrorType)) + + logger.LogAttrs(ctx, slog.LevelDebug, msg, baseLogAttrs...) } diff --git a/vendor/cloud.google.com/go/auth/httptransport/transport.go b/vendor/cloud.google.com/go/auth/httptransport/transport.go index 2ece1ea360..87b3fef218 100644 --- a/vendor/cloud.google.com/go/auth/httptransport/transport.go +++ b/vendor/cloud.google.com/go/auth/httptransport/transport.go @@ -15,14 +15,17 @@ package httptransport import ( + "bytes" "context" "crypto/tls" - "errors" "fmt" + "io" + "log/slog" "net" "net/http" "os" "strconv" + "sync" "time" "cloud.google.com/go/auth" @@ -37,10 +40,12 @@ import ( "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" "golang.org/x/net/http2" + "google.golang.org/api/googleapi" ) const ( quotaProjectHeaderKey = "X-goog-user-project" + maxErrorReadBytes = int64(8192) // 8KB ) func newTransport(base http.RoundTripper, opts *Options) (http.RoundTripper, error) { @@ -180,33 +185,65 @@ func addOpenTelemetryTransport(trans http.RoundTripper, opts *Options) http.Roun if opts.DisableTelemetry { return trans } - if !gax.IsFeatureEnabled("TRACING") { - return otelhttp.NewTransport(trans) + + var traceAttrs []attribute.KeyValue + var scopedLogger *slog.Logger + + if gax.IsFeatureEnabled("LOGGING") && opts.Logger != nil { + scopedLogger = opts.Logger } - var staticAttrs []attribute.KeyValue + if opts.InternalOptions != nil { - staticAttrs = transport.StaticTelemetryAttributes(opts.InternalOptions.TelemetryAttributes) + attrs := transport.StaticTelemetryAttributes(opts.InternalOptions.TelemetryAttributes) + if gax.IsFeatureEnabled("TRACING") { + traceAttrs = attrs + } + if scopedLogger != nil { + var logAttrs []any + for _, attr := range attrs { + logAttrs = append(logAttrs, slog.String(string(attr.Key), attr.Value.AsString())) + } + scopedLogger = scopedLogger.With(logAttrs...) + } + } + + if gax.IsFeatureEnabled("METRICS") || gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") { + trans = &otelAttributeTransport{ + base: trans, + logger: scopedLogger, + } + } + + if !gax.IsFeatureEnabled("TRACING") && !gax.IsFeatureEnabled("LOGGING") { + return otelhttp.NewTransport(trans) } - otelOpts := []otelhttp.Option{ - otelhttp.WithSpanOptions(trace.WithAttributes(staticAttrs...)), + + var otelOpts []otelhttp.Option + if len(traceAttrs) > 0 { + otelOpts = append(otelOpts, otelhttp.WithSpanOptions(trace.WithAttributes(traceAttrs...))) } - return otelhttp.NewTransport(&otelAttributeTransport{ - base: trans, - }, otelOpts...) + return otelhttp.NewTransport(trans, otelOpts...) } // otelAttributeTransport is a wrapper around an http.RoundTripper that adds // custom Google Cloud-specific attributes to OpenTelemetry spans. type otelAttributeTransport struct { - base http.RoundTripper + base http.RoundTripper + logger *slog.Logger } // RoundTrip intercepts the HTTP request and response to enrich the active // OpenTelemetry span with static and dynamic attributes, as well as detailed // error information. func (t *otelAttributeTransport) RoundTrip(req *http.Request) (*http.Response, error) { - span := trace.SpanFromContext(req.Context()) - if span.IsRecording() { + var span trace.Span + if gax.IsFeatureEnabled("TRACING") { + if s := trace.SpanFromContext(req.Context()); s != nil && s.IsRecording() { + span = s + } + } + + if span != nil { var attrs []attribute.KeyValue attrs = append(attrs, attribute.String("rpc.system.name", "http")) if resName, ok := callctx.TelemetryFromContext(req.Context(), "resource_name"); ok { @@ -224,37 +261,232 @@ func (t *otelAttributeTransport) RoundTrip(req *http.Request) (*http.Response, e span.SetAttributes(attrs...) } + var data *gax.TransportTelemetryData + if gax.IsFeatureEnabled("METRICS") { + data = gax.ExtractTransportTelemetry(req.Context()) + if data != nil && req.URL != nil { + host := req.URL.Hostname() + if host != "" { + data.SetServerAddress(host) + } + portStr := req.URL.Port() + if portStr == "" { + if req.URL.Scheme == "https" { + portStr = "443" + } else if req.URL.Scheme == "http" { + portStr = "80" + } + } + if port, pErr := strconv.Atoi(portStr); pErr == nil { + data.SetServerPort(port) + } + } + } + resp, err := t.base.RoundTrip(req) - if span.IsRecording() { - if err != nil { - var errorType string - switch { - case errors.Is(err, context.DeadlineExceeded): - errorType = "CLIENT_TIMEOUT" - case errors.Is(err, context.Canceled): - errorType = "CLIENT_CANCELLED" - default: - errorType = "CLIENT_CONNECTION_ERROR" + var logger *slog.Logger + if gax.IsFeatureEnabled("LOGGING") { + if l := t.logger; l != nil && l.Enabled(req.Context(), slog.LevelDebug) { + logger = l + } + } + + if span == nil && logger == nil { + return resp, err + } + + if err != nil { + t.logAndSpanError(req, resp, err, err, span, logger) + } else if resp.StatusCode >= 400 { + if resp.Body != nil && resp.Body != http.NoBody && (resp.ContentLength < 0 || resp.ContentLength <= maxErrorReadBytes) { + resp.Body = &errorTrackingBody{ + ReadCloser: resp.Body, + req: req, + resp: resp, + span: span, + logger: logger, + t: t, } + } else { + t.logAndSpanError(req, resp, &googleapi.Error{ + Code: resp.StatusCode, + Message: resp.Status, + }, nil, span, logger) + } + } else { + if span != nil { + span.SetAttributes(attribute.Int("http.response.status_code", resp.StatusCode)) + } + } + + return resp, err +} + +func (t *otelAttributeTransport) logAndSpanError(req *http.Request, resp *http.Response, errToParse error, netErr error, span trace.Span, logger *slog.Logger) { + var httpStatusCode int + if resp != nil { + httpStatusCode = resp.StatusCode + } + + info := gax.ExtractTelemetryErrorInfo(req.Context(), errToParse) + + if netErr == nil && resp != nil && resp.StatusCode >= 400 { + if info.ErrorType == "*googleapi.Error" { + info.ErrorType = strconv.Itoa(resp.StatusCode) + } + } + + if logger != nil { + logAttrs := []slog.Attr{ + slog.String("rpc.system.name", "http"), + } + if httpStatusCode > 0 { + logAttrs = append(logAttrs, slog.Int64("http.response.status_code", int64(httpStatusCode))) + } + + ctx := req.Context() + if resendCountStr, ok := callctx.TelemetryFromContext(ctx, "resend_count"); ok { + if count, e := strconv.Atoi(resendCountStr); e == nil { + logAttrs = append(logAttrs, slog.Int64("http.request.resend_count", int64(count))) + } + } + if urlTemplate, ok := callctx.TelemetryFromContext(ctx, "url_template"); ok { + logAttrs = append(logAttrs, slog.String("url.template", urlTemplate)) + } + logAttrs = append(logAttrs, slog.String("http.request.method", req.Method)) + + msg := info.StatusMessage + if msg == "" { + msg = "API call failed" + } + + if rpcMethod, ok := callctx.TelemetryFromContext(ctx, "rpc_method"); ok { + logAttrs = append(logAttrs, slog.String("rpc.method", rpcMethod)) + } + + if resName, ok := callctx.TelemetryFromContext(ctx, "resource_name"); ok { + logAttrs = append(logAttrs, slog.String("gcp.resource.destination.id", resName)) + } + + if info.Domain != "" { + logAttrs = append(logAttrs, slog.String("gcp.errors.domain", info.Domain)) + } + for k, v := range info.Metadata { + logAttrs = append(logAttrs, slog.String("gcp.errors.metadata."+k, v)) + } + + logAttrs = append(logAttrs, slog.String("error.type", info.ErrorType)) + if info.StatusCode != "" { + logAttrs = append(logAttrs, slog.String("rpc.response.status_code", info.StatusCode)) + } + + logger.LogAttrs(ctx, slog.LevelDebug, msg, logAttrs...) + } + + if span != nil { + if netErr != nil { span.SetAttributes( - attribute.String("error.type", errorType), - attribute.String("status.message", err.Error()), - attribute.String("exception.type", fmt.Sprintf("%T", err)), + attribute.String("error.type", info.ErrorType), + attribute.String("status.message", info.StatusMessage), + attribute.String("exception.type", fmt.Sprintf("%T", netErr)), ) } else { - span.SetAttributes(attribute.Int("http.response.status_code", resp.StatusCode)) - if resp.StatusCode >= 400 { - errorType := strconv.Itoa(resp.StatusCode) - span.SetAttributes( - attribute.String("error.type", errorType), - attribute.String("status.message", resp.Status), - ) + span.SetAttributes( + attribute.Int("http.response.status_code", httpStatusCode), + attribute.String("error.type", info.ErrorType), + attribute.String("status.message", info.StatusMessage), + ) + } + } +} + +type errorTrackingBody struct { + io.ReadCloser + req *http.Request + resp *http.Response + span trace.Span + logger *slog.Logger + t *otelAttributeTransport + + mu sync.Mutex + buf bytes.Buffer + recorded bool +} + +func (b *errorTrackingBody) Read(p []byte) (n int, err error) { + n, err = b.ReadCloser.Read(p) + + b.mu.Lock() + shouldRecord := false + if !b.recorded { + if n > 0 { + remaining := maxErrorReadBytes - int64(b.buf.Len()) + if remaining > 0 { + if int64(n) > remaining { + b.buf.Write(p[:remaining]) + } else { + b.buf.Write(p[:n]) + } } } + + if err == io.EOF || int64(b.buf.Len()) >= maxErrorReadBytes { + shouldRecord = true + b.recorded = true + } } + b.mu.Unlock() - return resp, err + if shouldRecord { + b.recordError() + } + + return n, err +} + +func (b *errorTrackingBody) Close() error { + b.mu.Lock() + shouldRecord := !b.recorded + b.recorded = true + b.mu.Unlock() + + // We can close the network stream immediately. + err := b.ReadCloser.Close() + + // Do heavy in-memory telemetry parsing without holding the lock + if shouldRecord { + b.recordError() // If this panics here, the socket is already released + } + + return err +} + +func (b *errorTrackingBody) recordError() { + errToParse := &googleapi.Error{ + Code: b.resp.StatusCode, + Message: b.resp.Status, + } + + if b.buf.Len() > 0 { + clone := *b.resp + clone.Body = io.NopCloser(bytes.NewReader(b.buf.Bytes())) + if errResp := googleapi.CheckResponse(&clone); errResp != nil { + if gErr, ok := errResp.(*googleapi.Error); ok { + if gErr.Message == "" { + gErr.Message = b.resp.Status + } + errToParse = gErr + } else { + errToParse = &googleapi.Error{ + Code: b.resp.StatusCode, + Message: errResp.Error(), + } + } + } + } + + b.t.logAndSpanError(b.req, b.resp, errToParse, nil, b.span, b.logger) } type authTransport struct { diff --git a/vendor/cloud.google.com/go/auth/internal/version.go b/vendor/cloud.google.com/go/auth/internal/version.go index fb1c45739c..d627069b57 100644 --- a/vendor/cloud.google.com/go/auth/internal/version.go +++ b/vendor/cloud.google.com/go/auth/internal/version.go @@ -4,7 +4,7 @@ // 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 +// https://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, @@ -17,4 +17,4 @@ package internal // Version is the current tagged release of the library. -const Version = "0.19.0" +const Version = "0.20.0" diff --git a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go index bcbe00d0c5..01c9519c3d 100644 --- a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go +++ b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go @@ -26,7 +26,7 @@ func (csiState csiEntryState) Handle(b byte) (s state, e error) { func (csiState csiEntryState) Transition(s state) error { csiState.parser.logf("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name()) - csiState.baseState.Transition(s) + _ = csiState.baseState.Transition(s) switch s { case csiState.parser.ground: @@ -34,9 +34,9 @@ func (csiState csiEntryState) Transition(s state) error { case csiState.parser.csiParam: switch { case sliceContains(csiParams, csiState.parser.context.currentChar): - csiState.parser.collectParam() + _ = csiState.parser.collectParam() case sliceContains(intermeds, csiState.parser.context.currentChar): - csiState.parser.collectInter() + _ = csiState.parser.collectInter() } } diff --git a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go index 7ed5e01c34..88146e6fe5 100644 --- a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go +++ b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go @@ -16,8 +16,7 @@ func (csiState csiParamState) Handle(b byte) (s state, e error) { case sliceContains(alphabetics, b): return csiState.parser.ground, nil case sliceContains(csiCollectables, b): - csiState.parser.collectParam() - return csiState, nil + return csiState, csiState.parser.collectParam() case sliceContains(executors, b): return csiState, csiState.parser.execute() } @@ -27,7 +26,7 @@ func (csiState csiParamState) Handle(b byte) (s state, e error) { func (csiState csiParamState) Transition(s state) error { csiState.parser.logf("CsiParam::Transition %s --> %s", csiState.Name(), s.Name()) - csiState.baseState.Transition(s) + _ = csiState.baseState.Transition(s) switch s { case csiState.parser.ground: diff --git a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go index 1c719db9e4..88429690f9 100644 --- a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go +++ b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go @@ -25,7 +25,7 @@ func (escState escapeIntermediateState) Handle(b byte) (s state, e error) { func (escState escapeIntermediateState) Transition(s state) error { escState.parser.logf("escapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name()) - escState.baseState.Transition(s) + _ = escState.baseState.Transition(s) switch s { case escState.parser.ground: diff --git a/vendor/github.com/Azure/go-ansiterm/escape_state.go b/vendor/github.com/Azure/go-ansiterm/escape_state.go index 6390abd231..854e3812a9 100644 --- a/vendor/github.com/Azure/go-ansiterm/escape_state.go +++ b/vendor/github.com/Azure/go-ansiterm/escape_state.go @@ -29,7 +29,7 @@ func (escState escapeState) Handle(b byte) (s state, e error) { func (escState escapeState) Transition(s state) error { escState.parser.logf("Escape::Transition %s --> %s", escState.Name(), s.Name()) - escState.baseState.Transition(s) + _ = escState.baseState.Transition(s) switch s { case escState.parser.ground: diff --git a/vendor/github.com/Azure/go-ansiterm/parser.go b/vendor/github.com/Azure/go-ansiterm/parser.go index 03cec7ada6..2e8ef80fb7 100644 --- a/vendor/github.com/Azure/go-ansiterm/parser.go +++ b/vendor/github.com/Azure/go-ansiterm/parser.go @@ -113,16 +113,13 @@ func (ap *AnsiParser) handle(b byte) error { if newState == nil { ap.logf("WARNING: newState is nil") - return errors.New("New state of 'nil' is invalid.") + return errors.New("new state of 'nil' is invalid") } - if newState != ap.currState { - if err := ap.changeState(newState); err != nil { - return err - } + if newState == ap.currState { + return nil } - - return nil + return ap.changeState(newState) } func (ap *AnsiParser) changeState(newState state) error { @@ -136,7 +133,7 @@ func (ap *AnsiParser) changeState(newState state) error { // Perform transition action if err := ap.currState.Transition(newState); err != nil { - ap.logf("Transition from '%s' to '%s' failed with: '%v'", ap.currState.Name(), newState.Name, err) + ap.logf("Transition from '%s' to '%s' failed with: '%v'", ap.currState.Name(), newState.Name(), err) return err } diff --git a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go index de0a1f9cde..dc001532a6 100644 --- a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go @@ -4,9 +4,9 @@ import ( "strconv" ) -func parseParams(bytes []byte) ([]string, error) { - paramBuff := make([]byte, 0, 0) - params := []string{} +func parseParams(bytes []byte) []string { + var paramBuff []byte + var params []string for _, v := range bytes { if v == ';' { @@ -14,7 +14,7 @@ func parseParams(bytes []byte) ([]string, error) { // Completed parameter, append it to the list s := string(paramBuff) params = append(params, s) - paramBuff = make([]byte, 0, 0) + paramBuff = paramBuff[:0] } } else { paramBuff = append(paramBuff, v) @@ -27,11 +27,7 @@ func parseParams(bytes []byte) ([]string, error) { params = append(params, s) } - return params, nil -} - -func parseCmd(context ansiContext) (string, error) { - return string(context.currentChar), nil + return params } func getInt(params []string, dflt int) int { diff --git a/vendor/github.com/Azure/go-ansiterm/parser_actions.go b/vendor/github.com/Azure/go-ansiterm/parser_actions.go index 0bb5e51e9a..2aee10159a 100644 --- a/vendor/github.com/Azure/go-ansiterm/parser_actions.go +++ b/vendor/github.com/Azure/go-ansiterm/parser_actions.go @@ -15,10 +15,9 @@ func (ap *AnsiParser) collectInter() error { } func (ap *AnsiParser) escDispatch() error { - cmd, _ := parseCmd(*ap.context) - intermeds := ap.context.interBuffer + cmd := string(ap.context.currentChar) ap.logf("escDispatch currentChar: %#x", ap.context.currentChar) - ap.logf("escDispatch: %v(%v)", cmd, intermeds) + ap.logf("escDispatch: %s(%q)", cmd, string(ap.context.interBuffer)) switch cmd { case "D": // IND @@ -31,14 +30,14 @@ func (ap *AnsiParser) escDispatch() error { return err case "M": // RI return ap.eventHandler.RI() + default: + return nil } - - return nil } func (ap *AnsiParser) csiDispatch() error { - cmd, _ := parseCmd(*ap.context) - params, _ := parseParams(ap.context.paramBuffer) + cmd := string(ap.context.currentChar) + params := parseParams(ap.context.paramBuffer) ap.logf("Parsed params: %v with length: %d", params, len(params)) ap.logf("csiDispatch: %v(%v)", cmd, params) @@ -109,9 +108,8 @@ func (ap *AnsiParser) print() error { return ap.eventHandler.Print(ap.context.currentChar) } -func (ap *AnsiParser) clear() error { +func (ap *AnsiParser) clear() { ap.context = &ansiContext{} - return nil } func (ap *AnsiParser) execute() error { diff --git a/vendor/github.com/Azure/go-ansiterm/states.go b/vendor/github.com/Azure/go-ansiterm/states.go index f2ea1fcd12..cf72692261 100644 --- a/vendor/github.com/Azure/go-ansiterm/states.go +++ b/vendor/github.com/Azure/go-ansiterm/states.go @@ -1,7 +1,5 @@ package ansiterm -type stateID int - type state interface { Enter() error Exit() error diff --git a/vendor/github.com/Azure/go-ansiterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/utilities.go index 392114493a..d94dd3a347 100644 --- a/vendor/github.com/Azure/go-ansiterm/utilities.go +++ b/vendor/github.com/Azure/go-ansiterm/utilities.go @@ -1,9 +1,5 @@ package ansiterm -import ( - "strconv" -) - func sliceContains(bytes []byte, b byte) bool { for _, v := range bytes { if v == b { @@ -13,9 +9,3 @@ func sliceContains(bytes []byte, b byte) bool { return false } - -func convertBytesToInteger(bytes []byte) int { - s := string(bytes) - i, _ := strconv.Atoi(s) - return i -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go index 5599082ae9..c6cc027a78 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go @@ -5,12 +5,9 @@ package winterm import ( "fmt" "os" - "strconv" - "strings" "syscall" - "github.com/Azure/go-ansiterm" - windows "golang.org/x/sys/windows" + "golang.org/x/sys/windows" ) // Windows keyboard constants @@ -55,100 +52,6 @@ const ( ENHANCED_KEY = 0x0100 ) -type ansiCommand struct { - CommandBytes []byte - Command string - Parameters []string - IsSpecial bool -} - -func newAnsiCommand(command []byte) *ansiCommand { - - if isCharacterSelectionCmdChar(command[1]) { - // Is Character Set Selection commands - return &ansiCommand{ - CommandBytes: command, - Command: string(command), - IsSpecial: true, - } - } - - // last char is command character - lastCharIndex := len(command) - 1 - - ac := &ansiCommand{ - CommandBytes: command, - Command: string(command[lastCharIndex]), - IsSpecial: false, - } - - // more than a single escape - if lastCharIndex != 0 { - start := 1 - // skip if double char escape sequence - if command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_ESCAPE_SECONDARY { - start++ - } - // convert this to GetNextParam method - ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ansiterm.ANSI_PARAMETER_SEP) - } - - return ac -} - -func (ac *ansiCommand) paramAsSHORT(index int, defaultValue int16) int16 { - if index < 0 || index >= len(ac.Parameters) { - return defaultValue - } - - param, err := strconv.ParseInt(ac.Parameters[index], 10, 16) - if err != nil { - return defaultValue - } - - return int16(param) -} - -func (ac *ansiCommand) String() string { - return fmt.Sprintf("0x%v \"%v\" (\"%v\")", - bytesToHex(ac.CommandBytes), - ac.Command, - strings.Join(ac.Parameters, "\",\"")) -} - -// isAnsiCommandChar returns true if the passed byte falls within the range of ANSI commands. -// See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html. -func isAnsiCommandChar(b byte) bool { - switch { - case ansiterm.ANSI_COMMAND_FIRST <= b && b <= ansiterm.ANSI_COMMAND_LAST && b != ansiterm.ANSI_ESCAPE_SECONDARY: - return true - case b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_OSC || b == ansiterm.ANSI_CMD_DECPAM || b == ansiterm.ANSI_CMD_DECPNM: - // non-CSI escape sequence terminator - return true - case b == ansiterm.ANSI_CMD_STR_TERM || b == ansiterm.ANSI_BEL: - // String escape sequence terminator - return true - } - return false -} - -func isXtermOscSequence(command []byte, current byte) bool { - return (len(command) >= 2 && command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_CMD_OSC && current != ansiterm.ANSI_BEL) -} - -func isCharacterSelectionCmdChar(b byte) bool { - return (b == ansiterm.ANSI_CMD_G0 || b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_G2 || b == ansiterm.ANSI_CMD_G3) -} - -// bytesToHex converts a slice of bytes to a human-readable string. -func bytesToHex(b []byte) string { - hex := make([]string, len(b)) - for i, ch := range b { - hex[i] = fmt.Sprintf("%X", ch) - } - return strings.Join(hex, "") -} - // ensureInRange adjusts the passed value, if necessary, to ensure it is within // the passed min / max range. func ensureInRange(n int16, min int16, max int16) int16 { diff --git a/vendor/github.com/Microsoft/go-winio/.golangci.yml b/vendor/github.com/Microsoft/go-winio/.golangci.yml index faedfe937a..07a22649a0 100644 --- a/vendor/github.com/Microsoft/go-winio/.golangci.yml +++ b/vendor/github.com/Microsoft/go-winio/.golangci.yml @@ -1,9 +1,15 @@ +version: "2" +formatters: + enable: + - gofmt # files are gofmt'ed linters: enable: # style - containedctx # struct contains a context - dupl # duplicate code - - errname # erorrs are named correctly + - dupword # duplicate words in comments + - errname # errors are named correctly + - intrange # integer ranges in for loop - nolintlint # "//nolint" directives are properly explained - revive # golint replacement - unconvert # unnecessary conversions @@ -13,135 +19,155 @@ linters: - contextcheck # function uses a non-inherited context - errorlint # errors not wrapped for 1.13 - exhaustive # check exhaustiveness of enum switch statements - - gofmt # files are gofmt'ed + - gocritic # various code quality checks - gosec # security + - mirror # avoid allocations - nilerr # returns nil even with non-nil error - thelper # test helpers without t.Helper() - unparam # unused function params -issues: - exclude-dirs: - - pkg/etw/sample - - exclude-rules: - # err is very often shadowed in nested scopes - - linters: - - govet - text: '^shadow: declaration of "err" shadows declaration' + exclusions: + paths: + - pkg/etw/sample + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + # err is very often shadowed in nested scopes + - linters: + - govet + text: '^shadow: declaration of "err" shadows declaration' - # ignore long lines for skip autogen directives - - linters: - - revive - text: "^line-length-limit: " - source: "^//(go:generate|sys) " + # ignore long lines for skip autogen directives + - linters: + - revive + text: "^line-length-limit: " + source: "^//(go:generate|sys) " - #TODO: remove after upgrading to go1.18 - # ignore comment spacing for nolint and sys directives - - linters: - - revive - text: "^comment-spacings: no space between comment delimiter and comment text" - source: "//(cspell:|nolint:|sys |todo)" + # ignore comment spacing for sys directives + - linters: + - revive + text: "^comment-spacings: no space between comment delimiter and comment text" + source: "//(cspell:|sys )" - # not on go 1.18 yet, so no any - - linters: - - revive - text: "^use-any: since GO 1.18 'interface{}' can be replaced by 'any'" + # allow unjustified ignores of error checks in defer statements + - linters: + - nolintlint + text: "^directive `//nolint:errcheck` should provide explanation" + source: '^\s*defer ' - # allow unjustified ignores of error checks in defer statements - - linters: - - nolintlint - text: "^directive `//nolint:errcheck` should provide explanation" - source: '^\s*defer ' + # allow unjustified ignores of error lints for io.EOF + - linters: + - nolintlint + text: "^directive `//nolint:errorlint` should provide explanation" + source: '[=|!]= io.EOF' - # allow unjustified ignores of error lints for io.EOF - - linters: - - nolintlint - text: "^directive `//nolint:errorlint` should provide explanation" - source: '[=|!]= io.EOF' + - linters: + - gosec + text: "^G115: integer overflow conversion" -linters-settings: - exhaustive: - default-signifies-exhaustive: true - govet: - enable-all: true - disable: - # struct order is often for Win32 compat - # also, ignore pointer bytes/GC issues for now until performance becomes an issue - - fieldalignment - nolintlint: - require-explanation: true - require-specific: true - revive: - # revive is more configurable than static check, so likely the preferred alternative to static-check - # (once the perf issue is solved: https://github.com/golangci/golangci-lint/issues/2997) - enable-all-rules: - true + settings: + exhaustive: + default-signifies-exhaustive: true + gocritic: + disable-all: true + enabled-checks: + - nilValReturn + - sprintfQuotedString + govet: + enable-all: true + disable: + # struct order is often for Win32 compat + # also, ignore pointer bytes/GC issues for now until performance becomes an issue + - fieldalignment + nolintlint: + require-explanation: true + require-specific: true + revive: + # revive is more configurable than static check, so likely the preferred alternative to static-check + # (once the perf issue is solved: https://github.com/golangci/golangci-lint/issues/2997) + enable-all-rules: + true # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md - rules: - # rules with required arguments - - name: argument-limit - disabled: true - - name: banned-characters - disabled: true - - name: cognitive-complexity - disabled: true - - name: cyclomatic - disabled: true - - name: file-header - disabled: true - - name: function-length - disabled: true - - name: function-result-limit - disabled: true - - name: max-public-structs - disabled: true - # geneally annoying rules - - name: add-constant # complains about any and all strings and integers - disabled: true - - name: confusing-naming # we frequently use "Foo()" and "foo()" together - disabled: true - - name: flag-parameter # excessive, and a common idiom we use - disabled: true - - name: unhandled-error # warns over common fmt.Print* and io.Close; rely on errcheck instead - disabled: true - # general config - - name: line-length-limit - arguments: - - 140 - - name: var-naming - arguments: - - [] - - - CID - - CRI - - CTRD - - DACL - - DLL - - DOS - - ETW - - FSCTL - - GCS - - GMSA - - HCS - - HV - - IO - - LCOW - - LDAP - - LPAC - - LTSC - - MMIO - - NT - - OCI - - PMEM - - PWSH - - RX - - SACl - - SID - - SMB - - TX - - VHD - - VHDX - - VMID - - VPCI - - WCOW - - WIM + rules: + # rules with required arguments + - name: argument-limit + disabled: true + - name: banned-characters + disabled: true + - name: cognitive-complexity + disabled: true + - name: cyclomatic + disabled: true + # covered by "exhaustive" linter + - name: enforce-switch-style + disabled: true + - name: file-header + disabled: true + - name: function-length + disabled: true + - name: function-result-limit + disabled: true + - name: max-public-structs + disabled: true + # generally annoying rules + - name: add-constant # complains about any and all strings and integers + disabled: true + - name: confusing-naming # we frequently use "Foo()" and "foo()" together + disabled: true + - name: flag-parameter # excessive, and a common idiom we use + disabled: true + - name: multiline-if-init # too opinionated; see https://github.com/microsoft/go-winio/pull/325#issuecomment-5822487436 + disabled: true + - name: unhandled-error # warns over common fmt.Print* and io.Close; rely on errcheck instead + disabled: true + # general config + - name: line-length-limit + arguments: + - 140 + - name: var-naming + arguments: + - [] + - - CID + - CRI + - CTRD + - DACL + - DLL + - DOS + - ETW + - FSCTL + - GCS + - GMSA + - HCS + - HV + - IO + - LCOW + - LDAP + - LPAC + - LTSC + - MMIO + - NT + - OCI + - PMEM + - PWSH + - RX + - SACl + - SID + - SMB + - TX + - VHD + - VHDX + - VMID + - VPCI + - WCOW + - WIM + staticcheck: + # Enable all options, with some exceptions. + # For defaults, see https://golangci-lint.run/usage/linters/#staticcheck + checks: + - all + - -QF1008 # Omit embedded fields from selector expression; https://staticcheck.dev/docs/checks/#QF1008 + - -ST1003 # Poorly chosen identifier; https://staticcheck.dev/docs/checks/#ST1003 diff --git a/vendor/github.com/Microsoft/go-winio/backup.go b/vendor/github.com/Microsoft/go-winio/backup.go index b54341daac..37055fa6a9 100644 --- a/vendor/github.com/Microsoft/go-winio/backup.go +++ b/vendor/github.com/Microsoft/go-winio/backup.go @@ -1,5 +1,4 @@ //go:build windows -// +build windows package winio @@ -36,7 +35,7 @@ const ( StreamSparseAttributes = uint32(8) ) -//nolint:revive // var-naming: ALL_CAPS +//nolint:revive,nolintlint // var-naming: ALL_CAPS const ( WRITE_DAC = windows.WRITE_DAC WRITE_OWNER = windows.WRITE_OWNER diff --git a/vendor/github.com/Microsoft/go-winio/ea.go b/vendor/github.com/Microsoft/go-winio/ea.go index e104dbdfdf..00a4bd96c8 100644 --- a/vendor/github.com/Microsoft/go-winio/ea.go +++ b/vendor/github.com/Microsoft/go-winio/ea.go @@ -95,7 +95,7 @@ func writeEa(buf *bytes.Buffer, ea *ExtendedAttribute, last bool) error { return err } - _, err = buf.Write([]byte(ea.Name)) + _, err = buf.WriteString(ea.Name) if err != nil { return err } diff --git a/vendor/github.com/Microsoft/go-winio/file.go b/vendor/github.com/Microsoft/go-winio/file.go index fe82a180db..449bb3bd1b 100644 --- a/vendor/github.com/Microsoft/go-winio/file.go +++ b/vendor/github.com/Microsoft/go-winio/file.go @@ -1,11 +1,11 @@ //go:build windows -// +build windows package winio import ( - "errors" + "context" "io" + "os" "runtime" "sync" "sync/atomic" @@ -21,16 +21,33 @@ import ( //sys setFileCompletionNotificationModes(h windows.Handle, flags uint8) (err error) = SetFileCompletionNotificationModes //sys wsaGetOverlappedResult(h windows.Handle, o *windows.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult -var ( - ErrFileClosed = errors.New("file has already been closed") - ErrTimeout = &timeoutError{} -) - +// ErrFileClosed is returned when an operation is performed on a closed file. +// +// Deprecated: use [os.ErrClosed] instead. +var ErrFileClosed = os.ErrClosed + +// ErrTimeout is returned when an I/O operation exceeds its deadline. +// +// It matches both [context.DeadlineExceeded] and [os.ErrDeadlineExceeded] +// with [errors.Is]. +var ErrTimeout error = &timeoutError{} + +// timeoutError preserves the historical "i/o timeout" error while matching +// both context.DeadlineExceeded and os.ErrDeadlineExceeded through errors.Is. +// This mirrors the behavior of net.errTimeout: +// https://github.com/golang/go/blob/go1.27.1/src/net/net.go +// +// TODO: consider replacing ErrTimeout with os.ErrDeadlineExceeded if os.ErrDeadlineExceeded is changed to match context.DeadlineExceeded. type timeoutError struct{} func (*timeoutError) Error() string { return "i/o timeout" } func (*timeoutError) Timeout() bool { return true } func (*timeoutError) Temporary() bool { return true } +func (*timeoutError) Unwrap() error { return os.ErrDeadlineExceeded } + +func (*timeoutError) Is(err error) bool { + return err == context.DeadlineExceeded +} type timeoutChan chan struct{} @@ -144,7 +161,7 @@ func (f *win32File) prepareIO() (*ioOperation, error) { f.wgLock.RLock() if f.closing.Load() { f.wgLock.RUnlock() - return nil, ErrFileClosed + return nil, os.ErrClosed } f.wg.Add(1) f.wgLock.RUnlock() @@ -193,7 +210,7 @@ func (f *win32File) asyncIO(c *ioOperation, d *deadlineHandler, bytes uint32, er err = r.err if err == windows.ERROR_OPERATION_ABORTED { //nolint:errorlint // err is Errno if f.closing.Load() { - err = ErrFileClosed + err = os.ErrClosed } } else if err != nil && f.socket { // err is from Win32. Query the overlapped structure to get the winsock error. @@ -235,12 +252,17 @@ func (f *win32File) Read(b []byte) (int, error) { runtime.KeepAlive(b) // Handle EOF conditions. - if err == nil && n == 0 && len(b) != 0 { - return 0, io.EOF - } else if err == windows.ERROR_BROKEN_PIPE { //nolint:errorlint // err is Errno + switch err { + case windows.ERROR_BROKEN_PIPE: //nolint:errorlint // err is Errno return 0, io.EOF + case nil: + if n == 0 && len(b) != 0 { + return 0, io.EOF + } + return n, nil + default: + return n, err } - return n, err } // Write writes to a file handle. diff --git a/vendor/github.com/Microsoft/go-winio/fileinfo.go b/vendor/github.com/Microsoft/go-winio/fileinfo.go index c860eb9917..01cd891e84 100644 --- a/vendor/github.com/Microsoft/go-winio/fileinfo.go +++ b/vendor/github.com/Microsoft/go-winio/fileinfo.go @@ -1,5 +1,4 @@ //go:build windows -// +build windows package winio diff --git a/vendor/github.com/Microsoft/go-winio/hvsock.go b/vendor/github.com/Microsoft/go-winio/hvsock.go index c4fdd9d4ae..df2008f6f6 100644 --- a/vendor/github.com/Microsoft/go-winio/hvsock.go +++ b/vendor/github.com/Microsoft/go-winio/hvsock.go @@ -1,5 +1,4 @@ //go:build windows -// +build windows package winio @@ -442,7 +441,7 @@ func canRedial(err error) bool { func (conn *HvsockConn) opErr(op string, err error) error { // translate from "file closed" to "socket closed" - if errors.Is(err, ErrFileClosed) { + if errors.Is(err, os.ErrClosed) { err = socket.ErrSocketClosed } return &net.OpError{Op: op, Net: "hvsock", Source: &conn.local, Addr: &conn.remote, Err: err} diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go b/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go index 0cd9621df7..f3bc2aeb8a 100644 --- a/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go +++ b/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go @@ -243,7 +243,7 @@ const ( // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlew func GetFinalPathNameByHandle(h windows.Handle, flags GetFinalPathFlag) (string, error) { b := stringbuffer.NewWString() - //TODO: can loop infinitely if Win32 keeps returning the same (or a larger) n? + // TODO: can loop infinitely if Win32 keeps returning the same (or a larger) n? for { n, err := windows.GetFinalPathNameByHandle(h, b.Pointer(), b.Cap(), uint32(flags)) if err != nil { diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go index a94e234c70..f7b27abfcc 100644 --- a/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go +++ b/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go @@ -15,12 +15,8 @@ var _ unsafe.Pointer // Do the interface allocations only once for common // Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) + errERROR_IO_PENDING error = windows.ERROR_IO_PENDING errERROR_EINVAL error = syscall.EINVAL ) @@ -30,7 +26,7 @@ func errnoErr(e syscall.Errno) error { switch e { case 0: return errERROR_EINVAL - case errnoERROR_IO_PENDING: + case windows.ERROR_IO_PENDING: return errERROR_IO_PENDING } return e diff --git a/vendor/github.com/Microsoft/go-winio/internal/socket/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/internal/socket/zsyscall_windows.go index e1504126aa..06e84da653 100644 --- a/vendor/github.com/Microsoft/go-winio/internal/socket/zsyscall_windows.go +++ b/vendor/github.com/Microsoft/go-winio/internal/socket/zsyscall_windows.go @@ -15,12 +15,8 @@ var _ unsafe.Pointer // Do the interface allocations only once for common // Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) + errERROR_IO_PENDING error = windows.ERROR_IO_PENDING errERROR_EINVAL error = syscall.EINVAL ) @@ -30,7 +26,7 @@ func errnoErr(e syscall.Errno) error { switch e { case 0: return errERROR_EINVAL - case errnoERROR_IO_PENDING: + case windows.ERROR_IO_PENDING: return errERROR_IO_PENDING } return e diff --git a/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go b/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go index 42ebc019fc..2295408733 100644 --- a/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go +++ b/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go @@ -7,7 +7,7 @@ import ( // TODO: worth exporting and using in mkwinsyscall? -// Uint16BufferSize is the buffer size in the pool, chosen somewhat arbitrarily to accommodate +// MinWStringCap is the buffer size in the pool, chosen somewhat arbitrarily to accommodate // large path strings: // MAX_PATH (260) + size of volume GUID prefix (49) + null terminator = 310. const MinWStringCap = 310 @@ -16,7 +16,7 @@ const MinWStringCap = 310 // is copied to heap and then referenced via pointer in the interface header that sync.Pool // stores. var pathPool = sync.Pool{ // if go1.18+ adds Pool[T], use that to store []uint16 directly - New: func() interface{} { + New: func() any { b := make([]uint16, MinWStringCap) return &b }, diff --git a/vendor/github.com/Microsoft/go-winio/pipe.go b/vendor/github.com/Microsoft/go-winio/pipe.go index a2da6639d0..850fe3e53a 100644 --- a/vendor/github.com/Microsoft/go-winio/pipe.go +++ b/vendor/github.com/Microsoft/go-winio/pipe.go @@ -1,5 +1,4 @@ //go:build windows -// +build windows package winio @@ -11,6 +10,7 @@ import ( "net" "os" "runtime" + "sync" "time" "unsafe" @@ -102,12 +102,10 @@ func (status ntStatus) Err() error { return rtlNtStatusToDosError(status) } -var ( - // ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed. - ErrPipeListenerClosed = net.ErrClosed - - errPipeWriteClosed = errors.New("pipe has been closed for write") -) +// ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed. +// +// Deprecated: use [net.ErrClosed] instead. +var ErrPipeListenerClosed = net.ErrClosed type win32Pipe struct { *win32File @@ -144,9 +142,10 @@ func (f *win32Pipe) Disconnect() error { } // CloseWrite closes the write side of a message pipe in byte mode. +// It returns [io.ErrClosedPipe] if the write side is already closed. func (f *win32MessageBytePipe) CloseWrite() error { if f.writeClosed { - return errPipeWriteClosed + return io.ErrClosedPipe } err := f.win32File.Flush() if err != nil { @@ -161,10 +160,10 @@ func (f *win32MessageBytePipe) CloseWrite() error { } // Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since -// they are used to implement CloseWrite(). +// they are used to implement CloseWrite. It returns [io.ErrClosedPipe] if the write side is closed. func (f *win32MessageBytePipe) Write(b []byte) (int, error) { if f.writeClosed { - return 0, errPipeWriteClosed + return 0, io.ErrClosedPipe } if len(b) == 0 { return 0, nil @@ -179,14 +178,15 @@ func (f *win32MessageBytePipe) Read(b []byte) (int, error) { return 0, io.EOF } n, err := f.win32File.Read(b) - if err == io.EOF { //nolint:errorlint + switch err { + case io.EOF: //nolint:errorlint // error is not wrapped. // If this was the result of a zero-byte read, then // it is possible that the read was due to a zero-size // message. Since we are simulating CloseWrite with a // zero-byte message, ensure that all future Read() calls // also return EOF. f.readEOF = true - } else if err == windows.ERROR_MORE_DATA { //nolint:errorlint // err is Errno + case windows.ERROR_MORE_DATA: // ERROR_MORE_DATA indicates that the pipe's read mode is message mode // and the message still has more bytes. Treat this as a success, since // this package presents all named pipes as byte streams. @@ -316,8 +316,9 @@ type win32PipeListener struct { path string config PipeConfig acceptCh chan (chan acceptResponse) - closeCh chan int - doneCh chan int + closeOnce sync.Once + closeCh chan struct{} // closed (never sent on) to broadcast listener shutdown + doneCh chan struct{} } func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (windows.Handle, error) { @@ -344,7 +345,7 @@ func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (wi // The security descriptor is only needed for the first pipe. if first { if sd != nil { - //todo: does `sdb` need to be allocated on the heap, or can go allocate it? + // todo: does `sdb` need to be allocated on the heap, or can go allocate it? l := uint32(len(sd)) sdb, err := windows.LocalAlloc(0, l) if err != nil { @@ -445,13 +446,14 @@ func (l *win32PipeListener) makeConnectedServerPipe() (*win32File, error) { p = nil } case <-l.closeCh: - // Abort the connect request by closing the handle. - p.Close() + // Abort the connect request by closing the handle. Listener closure is + // authoritative: ConnectNamedPipe may race the handle close and report a + // connection or error (e.g. ERROR_NO_DATA) instead of ErrFileClosed, and + // that result must not be surfaced or cause listenerRoutine to retry. + _ = p.Close() p = nil - err = <-ch - if err == nil || err == ErrFileClosed { //nolint:errorlint // err is Errno - err = ErrPipeListenerClosed - } + <-ch + err = net.ErrClosed } return p, err } @@ -476,7 +478,7 @@ func (l *win32PipeListener) listenerRoutine() { } } responseCh <- acceptResponse{p, err} - closed = err == ErrPipeListenerClosed //nolint:errorlint // err is Errno + closed = err == net.ErrClosed //nolint:errorlint // err is Errno } } windows.Close(l.firstHandle) @@ -530,8 +532,8 @@ func ListenPipe(path string, c *PipeConfig) (net.Listener, error) { path: path, config: *c, acceptCh: make(chan (chan acceptResponse)), - closeCh: make(chan int), - doneCh: make(chan int), + closeCh: make(chan struct{}), + doneCh: make(chan struct{}), } go l.listenerRoutine() return l, nil @@ -568,16 +570,15 @@ func (l *win32PipeListener) Accept() (net.Conn, error) { } return &win32Pipe{win32File: response.f, path: l.path}, nil case <-l.doneCh: - return nil, ErrPipeListenerClosed + return nil, net.ErrClosed } } func (l *win32PipeListener) Close() error { - select { - case l.closeCh <- 1: - <-l.doneCh - case <-l.doneCh: - } + l.closeOnce.Do(func() { + close(l.closeCh) + }) + <-l.doneCh return nil } diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go index 48ce4e9243..fa1bde3a90 100644 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go +++ b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go @@ -14,7 +14,7 @@ import ( "strconv" ) -//go:generate go run golang.org/x/tools/cmd/stringer -type=Variant -trimprefix=Variant -linecomment +//go:generate go tool stringer -type=Variant -trimprefix=Variant -linecomment // Variant specifies which GUID variant (or "type") of the GUID. It determines // how the entirety of the rest of the GUID is interpreted. diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_nonwindows.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_nonwindows.go index 805bd35484..b933821a54 100644 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_nonwindows.go +++ b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_nonwindows.go @@ -1,5 +1,4 @@ //go:build !windows -// +build !windows package guid diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_windows.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_windows.go index 27e45ee5cc..4aa95a7068 100644 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_windows.go +++ b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_windows.go @@ -1,5 +1,4 @@ //go:build windows -// +build windows package guid diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/variant_string.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/variant_string.go index 4076d3132f..76e387d111 100644 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/variant_string.go +++ b/vendor/github.com/Microsoft/go-winio/pkg/guid/variant_string.go @@ -20,8 +20,9 @@ const _Variant_name = "UnknownNCSRFC 4122MicrosoftFuture" var _Variant_index = [...]uint8{0, 7, 10, 18, 27, 33} func (i Variant) String() string { - if i >= Variant(len(_Variant_index)-1) { + idx := int(i) - 0 + if i < 0 || idx >= len(_Variant_index)-1 { return "Variant(" + strconv.FormatInt(int64(i), 10) + ")" } - return _Variant_name[_Variant_index[i]:_Variant_index[i+1]] + return _Variant_name[_Variant_index[idx]:_Variant_index[idx+1]] } diff --git a/vendor/github.com/Microsoft/go-winio/privilege.go b/vendor/github.com/Microsoft/go-winio/privilege.go index d9b90b6e86..747eefd326 100644 --- a/vendor/github.com/Microsoft/go-winio/privilege.go +++ b/vendor/github.com/Microsoft/go-winio/privilege.go @@ -1,5 +1,4 @@ //go:build windows -// +build windows package winio diff --git a/vendor/github.com/Microsoft/go-winio/reparse.go b/vendor/github.com/Microsoft/go-winio/reparse.go index 67d1a104a6..9847fbd6c5 100644 --- a/vendor/github.com/Microsoft/go-winio/reparse.go +++ b/vendor/github.com/Microsoft/go-winio/reparse.go @@ -1,11 +1,11 @@ //go:build windows -// +build windows package winio import ( "bytes" "encoding/binary" + "errors" "fmt" "strings" "unicode/utf16" @@ -15,6 +15,9 @@ import ( const ( reparseTagMountPoint = 0xA0000003 reparseTagSymlink = 0xA000000C + reparseTagLxSymlink = 0xA000001D // WSL/MSYS2 native symlinks + + lxSymlinkVersion = 2 // LX symlink format version ) type reparseDataBuffer struct { @@ -31,6 +34,7 @@ type reparseDataBuffer struct { type ReparsePoint struct { Target string IsMountPoint bool + IsLxSymlink bool // True if this is an LX symlink (WSL/MSYS2 native) } // UnsupportedReparsePointError is returned when trying to decode a non-symlink or @@ -51,14 +55,19 @@ func DecodeReparsePoint(b []byte) (*ReparsePoint, error) { } func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) { - isMountPoint := false switch tag { case reparseTagMountPoint: - isMountPoint = true + return decodeWindowsReparsePointData(b, true) case reparseTagSymlink: + return decodeWindowsReparsePointData(b, false) + case reparseTagLxSymlink: + return decodeLxReparsePointData(b) default: return nil, &UnsupportedReparsePointError{tag} } +} + +func decodeWindowsReparsePointData(b []byte, isMountPoint bool) (*ReparsePoint, error) { nameOffset := 8 + binary.LittleEndian.Uint16(b[4:6]) if !isMountPoint { nameOffset += 4 @@ -69,16 +78,56 @@ func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) { if err != nil { return nil, err } - return &ReparsePoint{string(utf16.Decode(name)), isMountPoint}, nil + return &ReparsePoint{Target: string(utf16.Decode(name)), IsMountPoint: isMountPoint, IsLxSymlink: false}, nil +} + +func decodeLxReparsePointData(b []byte) (*ReparsePoint, error) { + // LX symlinks store the target as UTF-8 after a 4-byte version field + if len(b) < 4 { + return nil, errors.New("LX symlink buffer too short") + } + targetBytes := b[4:] + for i, c := range targetBytes { + if c == 0 { + targetBytes = targetBytes[:i] + break + } + } + target := string(targetBytes) + return &ReparsePoint{Target: target, IsMountPoint: false, IsLxSymlink: true}, nil } func isDriveLetter(c byte) bool { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') } -// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink or -// mount point. +// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink, +// mount point, or LX symlink. func EncodeReparsePoint(rp *ReparsePoint) []byte { + if rp == nil { + return nil + } + if rp.IsLxSymlink { + return encodeLxReparsePoint(rp) + } + return encodeWindowsReparsePoint(rp) +} + +func encodeLxReparsePoint(rp *ReparsePoint) []byte { + // LX symlink: 4-byte version + UTF-8 target + targetBytes := []byte(rp.Target) + dataLength := 4 + len(targetBytes) + + var b bytes.Buffer + _ = binary.Write(&b, binary.LittleEndian, uint32(reparseTagLxSymlink)) + _ = binary.Write(&b, binary.LittleEndian, uint16(dataLength)) + _ = binary.Write(&b, binary.LittleEndian, uint16(0)) + _ = binary.Write(&b, binary.LittleEndian, uint32(lxSymlinkVersion)) + _, _ = b.Write(targetBytes) + return b.Bytes() +} + +func encodeWindowsReparsePoint(rp *ReparsePoint) []byte { // Generate an NT path and determine if this is a relative path. var ntTarget string relative := false diff --git a/vendor/github.com/Microsoft/go-winio/sd.go b/vendor/github.com/Microsoft/go-winio/sd.go index c3685e98e1..7834c6adcb 100644 --- a/vendor/github.com/Microsoft/go-winio/sd.go +++ b/vendor/github.com/Microsoft/go-winio/sd.go @@ -1,5 +1,4 @@ //go:build windows -// +build windows package winio diff --git a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go index 89b66eda8c..f4329bbfd6 100644 --- a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go +++ b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go @@ -15,12 +15,8 @@ var _ unsafe.Pointer // Do the interface allocations only once for common // Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) + errERROR_IO_PENDING error = windows.ERROR_IO_PENDING errERROR_EINVAL error = syscall.EINVAL ) @@ -30,7 +26,7 @@ func errnoErr(e syscall.Errno) error { switch e { case 0: return errERROR_EINVAL - case errnoERROR_IO_PENDING: + case windows.ERROR_IO_PENDING: return errERROR_IO_PENDING } return e diff --git a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go b/vendor/github.com/docker/go-connections/sockets/inmem_socket.go index 06fcf747ac..d35b105f37 100644 --- a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go +++ b/vendor/github.com/docker/go-connections/sockets/inmem_socket.go @@ -1,21 +1,19 @@ package sockets import ( + "context" "net" "sync" ) -// dummyAddr is used to satisfy net.Addr for the in-mem socket -// it is just stored as a string and returns the string for all calls -type dummyAddr string +// inmemAddr is used to satisfy net.Addr for the in-memory socket. +type inmemAddr string // Network returns the addr string, satisfies net.Addr -func (a dummyAddr) Network() string { - return string(a) -} +func (a inmemAddr) Network() string { return "inmem" } // String returns the string form -func (a dummyAddr) String() string { +func (a inmemAddr) String() string { return string(a) } @@ -23,7 +21,7 @@ func (a dummyAddr) String() string { type InmemSocket struct { chConn chan net.Conn chClose chan struct{} - addr dummyAddr + addr inmemAddr mu sync.Mutex } @@ -34,7 +32,7 @@ func NewInmemSocket(addr string, bufSize int) *InmemSocket { return &InmemSocket{ chConn: make(chan net.Conn, bufSize), chClose: make(chan struct{}), - addr: dummyAddr(addr), + addr: inmemAddr(addr), } } @@ -67,15 +65,41 @@ func (s *InmemSocket) Close() error { return nil } -// Dial is used to establish a connection with the in-mem server. -// It returns a [net.ErrClosed] if the connection is already closed. +// Dial establishes a connection with the in-memory listener. +// +// The network and addr parameters are accepted for compatibility with +// conventional dialer APIs but are currently ignored. +// +// It is equivalent to calling DialContext with context.Background(). +// It returns [net.ErrClosed] if the listener has already been closed. func (s *InmemSocket) Dial(network, addr string) (net.Conn, error) { + return s.DialContext(context.Background(), network, addr) +} + +// DialContext establishes a connection with the in-memory listener. +// +// The network and addr parameters are accepted for compatibility with +// conventional dialer APIs but are currently ignored. +// +// If ctx is canceled before the connection is established, DialContext +// returns the context error. It returns [net.ErrClosed] if the listener +// has already been closed. +func (s *InmemSocket) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + srvConn, clientConn := net.Pipe() select { case s.chConn <- srvConn: + return clientConn, nil + case <-ctx.Done(): + _ = srvConn.Close() + _ = clientConn.Close() + return nil, ctx.Err() case <-s.chClose: + _ = srvConn.Close() + _ = clientConn.Close() return nil, net.ErrClosed } - - return clientConn, nil } diff --git a/vendor/github.com/docker/go-connections/sockets/tcp_socket.go b/vendor/github.com/docker/go-connections/sockets/tcp_socket.go index 53cbb6c79e..3224ed97dc 100644 --- a/vendor/github.com/docker/go-connections/sockets/tcp_socket.go +++ b/vendor/github.com/docker/go-connections/sockets/tcp_socket.go @@ -9,13 +9,17 @@ import ( // NewTCPSocket creates a TCP socket listener with the specified address and // the specified tls configuration. If TLSConfig is set, will encapsulate the // TCP listener inside a TLS one. +// If no ALPN protocols are configured, it defaults to HTTP/1.1. func NewTCPSocket(addr string, tlsConfig *tls.Config) (net.Listener, error) { l, err := net.Listen("tcp", addr) if err != nil { return nil, err } if tlsConfig != nil { - tlsConfig.NextProtos = []string{"http/1.1"} + if len(tlsConfig.NextProtos) == 0 { + tlsConfig = tlsConfig.Clone() + tlsConfig.NextProtos = []string{"http/1.1"} + } l = tls.NewListener(l, tlsConfig) } return l, nil diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket.go b/vendor/github.com/docker/go-connections/sockets/unix_socket.go index e736f71d38..1f7b7cd95e 100644 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket.go +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket.go @@ -47,38 +47,69 @@ For example: package sockets import ( + "errors" + "fmt" "net" "os" + "runtime" "syscall" ) +const supportsAbstractSockets = runtime.GOOS == "linux" + // SockOption sets up socket file's creating option type SockOption func(string) error -// NewUnixSocketWithOpts creates a unix socket with the specified options. -// By default, socket permissions are 0000 (i.e.: no access for anyone); pass -// WithChmod() and WithChown() to set the desired ownership and permissions. +// NewUnixSocketWithOpts creates a Unix socket with the specified options. +// +// On Unix platforms, socket permissions are 0000 by default, i.e. no access +// for anyone. Pass WithChmod() and WithChown() to set the desired permissions +// and ownership. +// +// On Windows, the socket uses Windows ACLs. Pass WithBasePermissions() to allow +// Administrators and LocalSystem full access, or WithAdditionalUsersAndGroups() +// to also grant generic read and write access to additional users or groups. // -// This function temporarily changes the system's "umask" to 0777 to work around -// a race condition between creating the socket and setting its permissions. While -// this should only be for a short duration, it may affect other processes that -// create files/directories during that period. +// Abstract Unix sockets (Go's Linux-specific "@" shorthand and the native +// leading-NUL representation) are supported only on Linux. On other platforms, +// attempts to use abstract socket addresses return an error. Because abstract +// sockets have no filesystem representation, filesystem-specific socket +// options are not supported. +// +// On platforms without abstract Unix socket support, attempts to use abstract +// socket addresses return an error wrapping [errors.ErrUnsupported]. func NewUnixSocketWithOpts(path string, opts ...SockOption) (net.Listener, error) { - if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { - return nil, err + if isAbstractSocket(path) { + if !supportsAbstractSockets { + return nil, fmt.Errorf("abstract Unix socket %q is not supported on %s: %w", path, runtime.GOOS, errors.ErrUnsupported) + } + for _, opt := range opts { + if err := opt(path); err != nil { + return nil, err + } + } + return net.Listen("unix", path) } - - l, err := listenUnix(path) - if err != nil { + if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { return nil, err } - for _, op := range opts { - if err := op(path); err != nil { - _ = l.Close() - return nil, err - } - } + return listenUnix(path, opts...) +} - return l, nil +// isAbstractSocket reports whether path is an abstract Unix socket address. +// +// Go recognizes two representations of abstract socket addresses: +// +// - On Linux, a path beginning with '@' is translated by the standard library +// to the kernel's native leading-NUL representation. +// See https://pkg.go.dev/net@go1.27rc2#UnixAddr. +// +// - A path beginning with a NUL byte uses the kernel's native representation +// directly. See https://github.com/golang/go/issues/78615. +// +// The interpretation of these addresses is platform-dependent; this helper only +// recognizes the syntax. +func isAbstractSocket(path string) bool { + return len(path) > 0 && (path[0] == '@' || path[0] == 0) } diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket_bsd.go b/vendor/github.com/docker/go-connections/sockets/unix_socket_bsd.go new file mode 100644 index 0000000000..22774d20e4 --- /dev/null +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket_bsd.go @@ -0,0 +1,39 @@ +//go:build darwin || dragonfly || freebsd || netbsd || openbsd + +package sockets + +import ( + "runtime" + "syscall" +) + +// maxListenerBacklog is similar to the equivalent in stdlib; +// https://github.com/golang/go/blob/go1.26.3/src/net/sock_bsd.go#L14-L39 +func maxListenerBacklog() int { + var ( + n uint32 + err error + ) + switch runtime.GOOS { + case "darwin", "ios": + n, err = syscall.SysctlUint32("kern.ipc.somaxconn") + case "freebsd": + n, err = syscall.SysctlUint32("kern.ipc.soacceptqueue") + case "netbsd": + // NOTE: NetBSD has no somaxconn-like kernel state so far + case "openbsd": + n, err = syscall.SysctlUint32("kern.somaxconn") + default: + return syscall.SOMAXCONN + } + if n == 0 || err != nil { + return syscall.SOMAXCONN + } + // FreeBSD stores the backlog in a uint16, as does Linux. + // Assume the other BSDs do too. Truncate number to avoid wrapping. + // See issue 5030. + if n > 1<<16-1 { + n = 1<<16 - 1 + } + return int(n) +} diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket_linux.go b/vendor/github.com/docker/go-connections/sockets/unix_socket_linux.go new file mode 100644 index 0000000000..59860610c3 --- /dev/null +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket_linux.go @@ -0,0 +1,25 @@ +package sockets + +import ( + "os" + "strconv" + "strings" + "syscall" +) + +// maxListenerBacklog returns the maximum length of the queue of pending +// connections for a listening socket. +// +// It is similar to in stdlib, but without the fallbacks for Kernel < 4.1.0; +// https://github.com/golang/go/blob/go1.26.3/src/net/sock_linux.go#L33-L53 +func maxListenerBacklog() int { + b, err := os.ReadFile("/proc/sys/net/core/somaxconn") + if err != nil { + return syscall.SOMAXCONN + } + n, err := strconv.Atoi(strings.TrimSpace(string(b))) + if err != nil || n <= 0 { + return syscall.SOMAXCONN + } + return n +} diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket_other.go b/vendor/github.com/docker/go-connections/sockets/unix_socket_other.go new file mode 100644 index 0000000000..2608e56e46 --- /dev/null +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket_other.go @@ -0,0 +1,9 @@ +//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd && !windows + +package sockets + +import "syscall" + +func maxListenerBacklog() int { + return syscall.SOMAXCONN +} diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket_unix.go b/vendor/github.com/docker/go-connections/sockets/unix_socket_unix.go index a41a716547..2bc1c1b44b 100644 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket_unix.go +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket_unix.go @@ -3,14 +3,35 @@ package sockets import ( + "errors" + "fmt" "net" "os" + "sync" "syscall" ) -// WithChown modifies the socket file's uid and gid +// defaultSocketPerms is the default permission mode applied to newly created +// Unix sockets. Sockets are created inaccessible by default; callers can +// override this by passing [WithChmod]. +// +// TODO(thaJeztah): Consider changing the default to 0o600, making the socket usable by its owner by default. +const defaultSocketPerms os.FileMode = 0o000 + +// WithChown modifies the socket file's uid and gid. +// +// Abstract Unix sockets have no filesystem representation, so this option +// returns an error wrapping [errors.ErrUnsupported] when used with an abstract +// socket. func WithChown(uid, gid int) SockOption { return func(path string) error { + if isAbstractSocket(path) { + return &os.PathError{ + Op: "chown", + Path: path, + Err: fmt.Errorf("abstract Unix sockets do not support filesystem permissions: %w", errors.ErrUnsupported), + } + } if err := os.Chown(path, uid, gid); err != nil { return err } @@ -19,8 +40,19 @@ func WithChown(uid, gid int) SockOption { } // WithChmod modifies socket file's access mode. +// +// Abstract Unix sockets have no filesystem representation, so this option +// returns an error wrapping [errors.ErrUnsupported] when used with an abstract +// socket. func WithChmod(mask os.FileMode) SockOption { return func(path string) error { + if isAbstractSocket(path) { + return &os.PathError{ + Op: "chmod", + Path: path, + Err: fmt.Errorf("abstract Unix sockets do not support filesystem permissions: %w", errors.ErrUnsupported), + } + } if err := os.Chmod(path, mask); err != nil { return err } @@ -28,27 +60,90 @@ func WithChmod(mask os.FileMode) SockOption { } } -// NewUnixSocket creates a unix socket with the specified path and group. +// NewUnixSocket creates a Unix socket with the specified path and group. +// +// On Unix platforms, the socket is owned by root:gid and has permissions 0660. +// +// Abstract Unix sockets are not supported by this helper. Use [NewUnixSocketWithOpts] +// without filesystem permission options instead. func NewUnixSocket(path string, gid int) (net.Listener, error) { return NewUnixSocketWithOpts(path, WithChown(0, gid), WithChmod(0o660)) } -func listenUnix(path string) (net.Listener, error) { - // net.Listen does not allow for permissions to be set. As a result, when - // specifying custom permissions ("WithChmod()"), there is a short time - // between creating the socket and applying the permissions, during which - // the socket permissions are Less restrictive than desired. +func listenUnix(path string, opts ...SockOption) (_ net.Listener, retErr error) { + // net.Listen does not allow permissions or ownership to be set between + // bind(2), which creates the socket path, and listen(2), which makes it + // possible for clients to connect. // - // To work around this limitation of net.Listen(), we temporarily set the - // umask to 0777, which forces the socket to be created with 000 permissions - // (i.e.: no access for anyone). After that, WithChmod() must be used to set - // the desired permissions. + // Creating the socket manually lets us apply options after bind(2), but + // before listen(2). This avoids temporarily relaxing the process umask while + // still preventing a socket from becoming connectable before the requested + // permissions are applied. // - // We don't use "defer" here, to reset the umask to its original value as soon - // as possible. Ideally we'd be able to detect if WithChmod() was passed as - // an option, and skip changing umask if default permissions are used. - origUmask := syscall.Umask(0o777) - l, err := net.Listen("unix", path) - syscall.Umask(origUmask) - return l, err + // See https://github.com/golang/go/issues/11822 + + // Similar to sysSocket in stdlib, but without the fast path for Linux. + // https://github.com/golang/go/blob/go1.26.3/src/net/sys_cloexec.go#L18-L36 + syscall.ForkLock.RLock() + fd, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM, 0) + if err == nil { + syscall.CloseOnExec(fd) // No syscall.SOCK_CLOEXEC on macOS. + } + syscall.ForkLock.RUnlock() + if err != nil { + return nil, os.NewSyscallError("socket", err) + } + + defer func() { + if fd >= 0 { + _ = syscall.Close(fd) + } + }() + + if err := syscall.Bind(fd, &syscall.SockaddrUnix{Name: path}); err != nil { + return nil, os.NewSyscallError("bind", err) + } + + defer func() { + if retErr != nil { + _ = syscall.Unlink(path) + } + }() + + // Secure by default: the socket is not accessible at all + // unless permission options are set through WithChmod. + if err := os.Chmod(path, defaultSocketPerms); err != nil { + return nil, err + } + + for _, op := range opts { + if err := op(path); err != nil { + return nil, err + } + } + + if err := syscall.Listen(fd, listenerBacklog()); err != nil { + return nil, os.NewSyscallError("listen", err) + } + + f := os.NewFile(uintptr(fd), "unix:"+path) + fd = -1 // f now owns the original fd; prevent the defer from closing it. + + // FileListener duplicates f, sets the duplicate close-on-exec and nonblocking, + // and returns a net.Listener backed by that duplicate. The temporary *os.File + // is no longer needed after this point. + l, err := net.FileListener(f) + _ = f.Close() + if err != nil { + return nil, err + } + + if ul, ok := l.(*net.UnixListener); ok { + ul.SetUnlinkOnClose(true) + } + + return l, nil } + +// listenerBacklog is a caching wrapper around maxListenerBacklog. +var listenerBacklog = sync.OnceValue(maxListenerBacklog) diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket_windows.go b/vendor/github.com/docker/go-connections/sockets/unix_socket_windows.go index 01aee5f11a..a9a9e80d50 100644 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket_windows.go +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket_windows.go @@ -48,7 +48,7 @@ func WithAdditionalUsersAndGroups(additionalUsersAndGroups []string) SockOption } sd, err := getSecurityDescriptor(additionalUsersAndGroups...) if err != nil { - return fmt.Errorf("looking up SID: %w", err) + return err } return withSDDL(sd)(path) } @@ -85,12 +85,15 @@ func withSDDL(sddl string) SockOption { } } -// NewUnixSocket creates a new unix socket. +// NewUnixSocket creates a new Unix socket. // // It sets [BasePermissions] on the socket path and grants the given additional // users and groups to generic read (GR) and write (GW) access. It returns // an error when failing to resolve any of the additional users and groups, // or when failing to apply the ACL. +// +// Abstract Unix sockets are not supported by this helper. Attempts to use +// abstract socket addresses return an error wrapping [errors.ErrUnsupported]. func NewUnixSocket(path string, additionalUsersAndGroups []string) (net.Listener, error) { var opts []SockOption if len(additionalUsersAndGroups) > 0 { @@ -103,27 +106,38 @@ func NewUnixSocket(path string, additionalUsersAndGroups []string) (net.Listener // getSecurityDescriptor returns the DACL for the Unix socket. // -// By default, it grants [BasePermissions], but allows for additional -// users and groups to get generic read (GR) and write (GW) access. It -// returns an error when failing to resolve any of the additional users -// and groups. +// By default, it grants [BasePermissions]. Additional users and groups +// are granted generic read (GR) and write (GW) access. It returns an +// error if any name cannot be resolved to a SID. func getSecurityDescriptor(additionalUsersAndGroups ...string) (string, error) { sddl := BasePermissions // Grant generic read (GR) and write (GW) access to whatever // additional users or groups were specified. // - // TODO(thaJeztah): should we fail on, or remove duplicates? + // We keep duplicates; two identical allow ACEs are redundant, + // but they do not create conflicting permissions, so should not error. + // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/20233ed8-a6c6-4097-aafa-dd545ed24428 for _, g := range additionalUsersAndGroups { sid, err := winio.LookupSidByName(strings.TrimSpace(g)) if err != nil { return "", fmt.Errorf("looking up SID: %w", err) } - sddl += fmt.Sprintf("(A;;GRGW;;;%s)", sid) + sddl += "(A;;GRGW;;;" + sid + ")" } return sddl, nil } -func listenUnix(path string) (net.Listener, error) { - return net.Listen("unix", path) +func listenUnix(path string, opts ...SockOption) (net.Listener, error) { + l, err := net.Listen("unix", path) + if err != nil { + return nil, err + } + for _, op := range opts { + if err := op(path); err != nil { + _ = l.Close() + return nil, err + } + } + return l, nil } diff --git a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml b/vendor/github.com/go-openapi/jsonpointer/.golangci.yml index 9d2733176e..e09106a30d 100644 --- a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml +++ b/vendor/github.com/go-openapi/jsonpointer/.golangci.yml @@ -9,6 +9,7 @@ linters: - gomodguard - gomodguard_v2 - exhaustruct + - exhaustruct_v5 - nlreturn - nonamedreturns - noinlineerr @@ -28,10 +29,12 @@ linters: goconst: min-len: 2 min-occurrences: 3 + gocognit: + min-complexity: 35 cyclop: - max-complexity: 20 + max-complexity: 25 gocyclo: - min-complexity: 20 + min-complexity: 35 exhaustive: default-signifies-exhaustive: true default-case-required: true diff --git a/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md b/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md index de0bf5c04b..6941823e6c 100644 --- a/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md +++ b/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md @@ -4,11 +4,11 @@ | Total Contributors | Total Contributions | | --- | --- | -| 13 | 132 | +| 13 | 136 | | Username | All Time Contribution Count | All Commits | | --- | --- | --- | -| @fredbi | 83 | | +| @fredbi | 87 | | | @casualjim | 33 | | | @magodo | 3 | | | @youyuanwu | 3 | | diff --git a/vendor/github.com/go-openapi/jsonpointer/README.md b/vendor/github.com/go-openapi/jsonpointer/README.md index 6e7929c64b..e563fac772 100644 --- a/vendor/github.com/go-openapi/jsonpointer/README.md +++ b/vendor/github.com/go-openapi/jsonpointer/README.md @@ -5,7 +5,7 @@ -[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] +[![Release][release-badge]][release-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] [![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] @@ -152,8 +152,6 @@ Maintainers can cut a new release by either: [release-badge]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer.svg [release-url]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer -[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/jsonpointer -[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/jsonpointer [codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/jsonpointer [codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/jsonpointer diff --git a/vendor/github.com/go-openapi/jsonpointer/errors.go b/vendor/github.com/go-openapi/jsonpointer/errors.go index 2ae6e3cfb3..9b54008baa 100644 --- a/vendor/github.com/go-openapi/jsonpointer/errors.go +++ b/vendor/github.com/go-openapi/jsonpointer/errors.go @@ -3,7 +3,10 @@ package jsonpointer -import "fmt" +import ( + "fmt" + "reflect" +) type pointerError string @@ -47,6 +50,24 @@ func errInvalidReference(token string) error { return fmt.Errorf("invalid token reference %q: %w", token, ErrPointer) } +func errNoField(token string) error { + return fmt.Errorf("object has no field %q: %w", token, ErrPointer) +} + +// errUnreachableField reports a field that exists on the type but cannot be reached on this value, +// because it is promoted through a nil embedded pointer. +func errUnreachableField(name string, cause error) error { + return fmt.Errorf("cannot reach field %q: %w: %w", name, cause, ErrPointer) +} + +// errMapKey reports a reference token that cannot serve as a key of the target map type. +// +// JSON object member names are strings, so only maps keyed by a string type (or by an interface +// type a string satisfies) can be addressed by a JSON pointer. +func errMapKey(token string, mapType reflect.Type) error { + return fmt.Errorf("can't use token %q as a key of map type %v: %w", token, mapType, ErrPointer) +} + func errDashOnGet() error { return fmt.Errorf("cannot resolve %q token on get: %w: %w", dashToken, ErrDashToken, ErrPointer) } diff --git a/vendor/github.com/go-openapi/jsonpointer/jsonname/go_name_provider.go b/vendor/github.com/go-openapi/jsonpointer/jsonname/go_name_provider.go index 5eec18fbfd..6c93621e5e 100644 --- a/vendor/github.com/go-openapi/jsonpointer/jsonname/go_name_provider.go +++ b/vendor/github.com/go-openapi/jsonpointer/jsonname/go_name_provider.go @@ -46,7 +46,7 @@ func (n *GoNameProvider) GetJSONNames(subject any) []string { n.lock.Lock() defer n.lock.Unlock() - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + tpe := typeOfSubject(subject) names := n.nameIndexFor(tpe) res := make([]string, 0, len(names.jsonNames)) @@ -59,7 +59,7 @@ func (n *GoNameProvider) GetJSONNames(subject any) []string { // GetJSONName gets the json name for a go property name. func (n *GoNameProvider) GetJSONName(subject any, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + tpe := typeOfSubject(subject) return n.GetJSONNameForType(tpe, name) } @@ -77,7 +77,7 @@ func (n *GoNameProvider) GetJSONNameForType(tpe reflect.Type, name string) (stri // GetGoName gets the go name for a json property name. func (n *GoNameProvider) GetGoName(subject any, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + tpe := typeOfSubject(subject) return n.GetGoNameForType(tpe, name) } @@ -132,7 +132,7 @@ func buildGoNameIndex(tpe reflect.Type) nameIndex { // //nolint:gocognit // everything is inlined to help the compiler determine what escapes and what doesn't func collectGoFields(tpe reflect.Type) []fieldEntry { - if tpe.Kind() != reflect.Struct { + if tpe == nil || tpe.Kind() != reflect.Struct { return nil } diff --git a/vendor/github.com/go-openapi/jsonpointer/jsonname/name_provider.go b/vendor/github.com/go-openapi/jsonpointer/jsonname/name_provider.go index 1bec2406b5..377c18e2c0 100644 --- a/vendor/github.com/go-openapi/jsonpointer/jsonname/name_provider.go +++ b/vendor/github.com/go-openapi/jsonpointer/jsonname/name_provider.go @@ -39,15 +39,20 @@ func NewNameProvider() *NameProvider { } func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { - for i := range tpe.NumField() { - targetDes := tpe.Field(i) + for targetDes := range tpe.Fields() { if targetDes.PkgPath != "" { // unexported continue } if targetDes.Anonymous { // walk embedded structures tree down first - buildnameIndex(targetDes.Type, idx, reverseIdx) + // An embedded field is not necessarily a struct: it may be a pointer to a struct, or a named + // non-struct type (e.g. an embedded named slice or map). Only struct shapes carry promoted + // fields worth indexing; anything else contributes no json name and must not be walked. + if embedded := structTypeOf(targetDes.Type); embedded != nil { + buildnameIndex(embedded, idx, reverseIdx) + } + continue } @@ -73,6 +78,12 @@ func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { } func newNameIndex(tpe reflect.Type) nameIndex { + tpe = structTypeOf(tpe) + if tpe == nil { + // only struct shapes carry json names: anything else indexes to nothing. + return nameIndex{jsonNames: map[string]string{}, goNames: map[string]string{}} + } + idx := make(map[string]string, tpe.NumField()) reverseIdx := make(map[string]string, tpe.NumField()) @@ -80,11 +91,44 @@ func newNameIndex(tpe reflect.Type) nameIndex { return nameIndex{jsonNames: idx, goNames: reverseIdx} } +// structTypeOf reduces tpe to the struct type it designates, dereferencing a pointer type. +// +// It returns nil when tpe is nil or does not designate a struct, so that callers may treat +// "nothing to index here" uniformly instead of panicking in [reflect.Type.NumField]. +func structTypeOf(tpe reflect.Type) reflect.Type { + if tpe == nil { + return nil + } + + if tpe.Kind() == reflect.Pointer { + tpe = tpe.Elem() + } + + if tpe.Kind() != reflect.Struct { + return nil + } + + return tpe +} + +// typeOfSubject returns the type of a document subject, dereferencing pointers. +// +// It returns nil for an untyped nil subject, which resolves to an empty name index rather than +// panicking in [reflect.Value.Type]. +func typeOfSubject(subject any) reflect.Type { + rValue := reflect.Indirect(reflect.ValueOf(subject)) + if !rValue.IsValid() { + return nil + } + + return rValue.Type() +} + // GetJSONNames gets all the json property names for a type. func (n *NameProvider) GetJSONNames(subject any) []string { n.lock.Lock() defer n.lock.Unlock() - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + tpe := typeOfSubject(subject) names, ok := n.index[tpe] if !ok { names = n.makeNameIndex(tpe) @@ -99,7 +143,7 @@ func (n *NameProvider) GetJSONNames(subject any) []string { // GetJSONName gets the json name for a go property name. func (n *NameProvider) GetJSONName(subject any, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + tpe := typeOfSubject(subject) return n.GetJSONNameForType(tpe, name) } @@ -117,7 +161,7 @@ func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string // GetGoName gets the go name for a json property name. func (n *NameProvider) GetGoName(subject any, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + tpe := typeOfSubject(subject) return n.GetGoNameForType(tpe, name) } diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer.go b/vendor/github.com/go-openapi/jsonpointer/pointer.go index 05fc863ee6..d17fa19ac4 100644 --- a/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ b/vendor/github.com/go-openapi/jsonpointer/pointer.go @@ -26,10 +26,12 @@ const ( // // - if a type implements [JSONPointable], its [JSONPointable.JSONLookup] method is used to resolve [Pointer.Get] // - if a type implements [JSONSetable], its [JSONSetable.JSONSet] method is used to resolve [Pointer.Set] -// - a go map[K]V is interpreted as an object, with type K assignable to a string +// - a go map[K]V is interpreted as an object, with K a string type. A named string type is +// converted; a map keyed by anything else (e.g. map[int]V) cannot be addressed by a pointer // - a go slice []T is interpreted as an array // - a go struct is interpreted as an object, with exported fields interpreted as keys -// - promoted fields from an embedded struct are traversed +// - promoted fields from an embedded struct are traversed, including through an embedded pointer +// to a struct. Resolving one on a value whose embedded pointer is nil reports an error // - scalars (e.g. int, float64 ...), channels, functions and go arrays cannot be traversed // // For struct s resolved by reflection, key mappings honor the conventional struct tag `json`. @@ -40,7 +42,9 @@ const ( // # Limitations // // - Unlike go standard marshaling, untagged fields do not default to the go field name and are ignored. -// - anonymous fields are not traversed if untagged +// - an anonymous field is walked for the fields it promotes, and its own `json` tag is ignored. +// An anonymous field that is not a struct (e.g. an embedded named slice) promotes nothing and +// is unreachable. type Pointer struct { referenceTokens []string } @@ -82,6 +86,17 @@ func (p *Pointer) Get(document any, opts ...Option) (any, reflect.Kind, error) { // Pass *[]T if you want in-place rebind for that case as well. // // See [ErrDashToken] for the semantics of the "-" token. +// +// # Setting a null value +// +// A nil value (what [encoding/json] decodes a JSON null into) is set as the zero value of the +// target, provided the target can hold nil: an interface, pointer, map, slice, channel or func. +// +// Setting nil on a target that cannot represent it — a string or an int field, an element of a +// []int — reports an error wrapping [ErrPointer] rather than substituting a zero value, which +// would erase the difference between a null and a 0. +// +// Setting a map member to nil keeps the member with a nil value. It does not delete it. func (p *Pointer) Set(document any, value any, opts ...Option) (any, error) { o := optionsWithDefaults(opts) @@ -284,7 +299,7 @@ func (p *Pointer) set(node, data any, nameProvider NameProvider) (any, error) { // new child reference (e.g. a slice header returned by an "-" append) into its parent on the way // back up. // -// Returning the (possibly new) node at each level is what makes append work at any depth without +// Returning the (possibly new) node at each level makes append work at any depth without // requiring the caller to pass a pointer to the containing slice: the new slice header propagates // up and each parent rebinds it via the appropriate kind-specific setter. func (p *Pointer) setAt(node any, tokens []string, data any, nameProvider NameProvider) (any, error) { @@ -330,7 +345,10 @@ func rebindChild(node any, decodedToken string, newChild any, nameProvider NameP if !ok { return node, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } - fld := rValue.FieldByName(nm) + fld, err := fieldByName(rValue, nm) + if err != nil { + return node, err + } if !fld.CanSet() { return node, nil } @@ -338,7 +356,16 @@ func rebindChild(node any, decodedToken string, newChild any, nameProvider NameP return node, nil case reflect.Map: - rValue.SetMapIndex(reflect.ValueOf(decodedToken), reflect.ValueOf(newChild)) + kv, err := mapKeyValue(rValue.Type(), decodedToken) + if err != nil { + return node, err + } + nv := reflect.ValueOf(newChild) + if !nv.IsValid() || !nv.Type().AssignableTo(rValue.Type().Elem()) { + // the child was mutated in place: there is nothing to rebind. + return node, nil + } + rValue.SetMapIndex(kv, nv) return node, nil case reflect.Slice: @@ -409,10 +436,18 @@ func (p *Pointer) resolveNodeForToken(node any, decodedToken string, nameProvide return nil, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } - return typeFromValue(rValue.FieldByName(nm)), nil + fld, err := fieldByName(rValue, nm) + if err != nil { + return nil, err + } + + return typeFromValue(fld), nil case reflect.Map: - kv := reflect.ValueOf(decodedToken) + kv, err := mapKeyValue(rValue.Type(), decodedToken) + if err != nil { + return nil, err + } mv := rValue.MapIndex(kv) if !mv.IsValid() { @@ -456,6 +491,80 @@ func isNil(input any) bool { } } +func isNilableKind(kind reflect.Kind) bool { + switch kind { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice, reflect.UnsafePointer: + return true + default: + return false + } +} + +// fieldByName resolves a (possibly promoted) struct field by its go name. +// +// Unlike [reflect.Value.FieldByName], it reports an error instead of panicking when the field is +// promoted through a nil embedded pointer: the field exists on the type, but there is no value to +// reach it through. +func fieldByName(rValue reflect.Value, nm string) (reflect.Value, error) { + sf, ok := rValue.Type().FieldByName(nm) + if !ok { + return reflect.Value{}, errNoField(nm) + } + + fld, err := rValue.FieldByIndexErr(sf.Index) + if err != nil { + return reflect.Value{}, errUnreachableField(nm, err) + } + + return fld, nil +} + +// mapKeyValue converts a reference token into a value usable as a key of mapType. +// +// JSON object member names are strings, so the map key type must accept one: named string types are +// converted, and anything else (e.g. a map keyed by an integer) is an error rather than a panic in +// [reflect.Value.MapIndex] or [reflect.Value.SetMapIndex]. +func mapKeyValue(mapType reflect.Type, decodedToken string) (reflect.Value, error) { + kv := reflect.ValueOf(decodedToken) + keyType := mapType.Key() + + switch { + case kv.Type().AssignableTo(keyType): + return kv, nil + case keyType.Kind() == reflect.String && kv.Type().ConvertibleTo(keyType): + return kv.Convert(keyType), nil + default: + return reflect.Value{}, errMapKey(decodedToken, mapType) + } +} + +// resolveSetValue converts data into a [reflect.Value] assignable to target. +// +// A nil data value (typically a JSON null) resolves to the zero value of target whenever target can +// hold nil. Targets that cannot represent null (e.g. a string or an int field) yield an error: they +// have no faithful representation of the value being set, and silently substituting a zero value +// would lose that distinction. +// +// verb and what describe the destination for error reporting, e.g. "set" and `field Name with type +// int`. +func resolveSetValue(data any, target reflect.Type, verb, what string) (reflect.Value, error) { + value := reflect.ValueOf(data) + + if !value.IsValid() { + if !isNilableKind(target.Kind()) { + return reflect.Value{}, fmt.Errorf("can't %s null value to %s: %w", verb, what, ErrPointer) + } + + return reflect.Zero(target), nil + } + + if !value.Type().AssignableTo(target) { + return reflect.Value{}, fmt.Errorf("can't %s value with type %T to %s: %w", verb, data, what, ErrPointer) + } + + return value, nil +} + func typeFromValue(v reflect.Value) any { if v.CanAddr() && v.Kind() != reflect.Interface && v.Kind() != reflect.Map && v.Kind() != reflect.Slice && v.Kind() != reflect.Pointer { return v.Addr().Interface() @@ -506,12 +615,18 @@ func getSingleImpl(node any, decodedToken string, nameProvider NameProvider) (an return nil, kind, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } - fld := rValue.FieldByName(nm) + fld, err := fieldByName(rValue, nm) + if err != nil { + return nil, kind, err + } return fld.Interface(), kind, nil case reflect.Map: - kv := reflect.ValueOf(decodedToken) + kv, err := mapKeyValue(rValue.Type(), decodedToken) + if err != nil { + return nil, kind, err + } mv := rValue.MapIndex(kv) if mv.IsValid() { @@ -557,20 +672,21 @@ func setSingleImpl(node, data any, decodedToken string, nameProvider NameProvide case reflect.Struct: nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) if !ok { - return node, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) + return node, errNoField(decodedToken) } - fld := rValue.FieldByName(nm) + fld, err := fieldByName(rValue, nm) + if err != nil { + return node, err + } if !fld.CanSet() { return node, fmt.Errorf("can't set struct field %s to %v: %w", nm, data, ErrPointer) } - value := reflect.ValueOf(data) - valueType := value.Type() assignedType := fld.Type() - - if !valueType.AssignableTo(assignedType) { - return node, fmt.Errorf("can't set value with type %T to field %s with type %v: %w", data, nm, assignedType, ErrPointer) + value, err := resolveSetValue(data, assignedType, "set", fmt.Sprintf("field %s with type %v", nm, assignedType)) + if err != nil { + return node, err } fld.Set(value) @@ -578,8 +694,20 @@ func setSingleImpl(node, data any, decodedToken string, nameProvider NameProvide return node, nil case reflect.Map: - kv := reflect.ValueOf(decodedToken) - rValue.SetMapIndex(kv, reflect.ValueOf(data)) + kv, err := mapKeyValue(rValue.Type(), decodedToken) + if err != nil { + return node, err + } + + // reflect.Value.SetMapIndex deletes the key when handed the zero Value, so a nil data value + // must be resolved to a typed zero first: setting a member to JSON null keeps the member. + elemType := rValue.Type().Elem() + value, err := resolveSetValue(data, elemType, "set", fmt.Sprintf("map value %q with type %v", decodedToken, elemType)) + if err != nil { + return node, err + } + + rValue.SetMapIndex(kv, value) return node, nil @@ -589,11 +717,12 @@ func setSingleImpl(node, data any, decodedToken string, nameProvider NameProvide // // We rebind in place when the slice is reachable via an addressable ancestor; otherwise we // return the new slice header for the parent (or the public Set) to rebind. - value := reflect.ValueOf(data) elemType := rValue.Type().Elem() - if !value.Type().AssignableTo(elemType) { - return node, fmt.Errorf("can't append value of type %T to slice of %v: %w", data, elemType, ErrPointer) + value, err := resolveSetValue(data, elemType, "append", fmt.Sprintf("slice of %v", elemType)) + if err != nil { + return node, err } + newSlice := reflect.Append(rValue, value) if rValue.CanSet() { rValue.Set(newSlice) @@ -617,12 +746,10 @@ func setSingleImpl(node, data any, decodedToken string, nameProvider NameProvide return node, fmt.Errorf("can't set slice index %s to %v: %w", decodedToken, data, ErrPointer) } - value := reflect.ValueOf(data) - valueType := value.Type() assignedType := elem.Type() - - if !valueType.AssignableTo(assignedType) { - return node, fmt.Errorf("can't set value with type %T to slice element %d with type %v: %w", data, tokenIndex, assignedType, ErrPointer) + value, err := resolveSetValue(data, assignedType, "set", fmt.Sprintf("slice element %d with type %v", tokenIndex, assignedType)) + if err != nil { + return node, err } elem.Set(value) diff --git a/vendor/github.com/go-openapi/jsonpointer/revive.toml b/vendor/github.com/go-openapi/jsonpointer/revive.toml new file mode 100644 index 0000000000..40fda4fc6d --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/revive.toml @@ -0,0 +1,18 @@ +# revive configuration used by codefactor.io. +# +# This is redundant with .golangci.yml, since revive is part of golangci-lint, +# but we need to configure it to remain consistent across reporting tools. + +ignore-generated-header = false +severity = "warning" +confidence = 0.8 +error-code = 0 +warning-code = 0 +enable-default-rules = true + +[rule.exported] +disabled = true +[rule.cyclomatic] +arguments = [20] +[rule.cognitive-complexity] +arguments = [20] diff --git a/vendor/github.com/go-openapi/jsonreference/.golangci.yml b/vendor/github.com/go-openapi/jsonreference/.golangci.yml index dc7c96053d..3f3b5af8db 100644 --- a/vendor/github.com/go-openapi/jsonreference/.golangci.yml +++ b/vendor/github.com/go-openapi/jsonreference/.golangci.yml @@ -4,8 +4,12 @@ linters: disable: - depguard - funlen + - goconst - godox + - gomodguard + - gomodguard_v2 - exhaustruct + - exhaustruct_v5 - nlreturn - nonamedreturns - noinlineerr diff --git a/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md b/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md index d20737c946..ce4326eef2 100644 --- a/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md +++ b/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md @@ -4,11 +4,11 @@ | Total Contributors | Total Contributions | | --- | --- | -| 9 | 83 | +| 9 | 90 | | Username | All Time Contribution Count | All Commits | | --- | --- | --- | -| @fredbi | 46 | | +| @fredbi | 53 | | | @casualjim | 25 | | | @youyuanwu | 5 | | | @olivierlemasle | 2 | | diff --git a/vendor/github.com/go-openapi/jsonreference/README.md b/vendor/github.com/go-openapi/jsonreference/README.md index fbd16cf892..000a1feb56 100644 --- a/vendor/github.com/go-openapi/jsonreference/README.md +++ b/vendor/github.com/go-openapi/jsonreference/README.md @@ -5,7 +5,7 @@ -[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] +[![Release][release-badge]][release-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] [![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] @@ -97,8 +97,6 @@ Maintainers can cut a new release by either: [gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonreference.svg [gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonreference -[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/jsonreference -[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/jsonreference [codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/jsonreference [codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/jsonreference diff --git a/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go b/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go index a08b47320e..f8ac54735c 100644 --- a/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go +++ b/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go @@ -5,19 +5,12 @@ package internal import ( "net/url" - "regexp" "strings" ) const ( - defaultHTTPPort = ":80" - defaultHTTPSPort = ":443" -) - -// Regular expressions used by the normalizations. -var ( - rxPort = regexp.MustCompile(`(:\d+)/?$`) - rxDupSlashes = regexp.MustCompile(`/{2,}`) + defaultHTTPPort = "80" + defaultHTTPSPort = "443" ) // NormalizeURL will normalize the specified URL @@ -55,20 +48,88 @@ func lowercaseHost(u *url.URL) { } } +// removeDefaultPort drops :80 from an http URL and :443 from an https one. +// +// The port stays when dropping it would leave an authority url.Parse no longer accepts, so the +// shortened host is parsed before being kept. url.Parse reads "https://:a:443" as the host ":a" +// on port 443, and ":a" on its own is an invalid port, so "https://:a" no longer parses. +// +// A degenerate authority can spell a default port more than once - with GODEBUG urlstrictcolons=0, +// url.Parse reads "http://:80:80" as the host ":80" on port 80 - so every trailing repetition comes +// off, and normalizing the result again changes nothing. +// +// The repetitions are counted in one scan and the shortened host is parsed at most twice, so the +// cost stays linear in the length of the host: stripping and re-parsing one repetition at a time +// was quadratic, and a $ref spelling ":80" a few ten thousand times took seconds to normalize. +// +// Every shortened host but the last still ends with the default port, which url.Parse accepted +// on the original host already, so only the last one may fail to parse. When it does, a single +// repetition stays: that is where removing them one by one would have stopped. func removeDefaultPort(u *url.URL) { - if len(u.Host) > 0 { - scheme := strings.ToLower(u.Scheme) - u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string { - if (scheme == "http" && val == defaultHTTPPort) || (scheme == "https" && val == defaultHTTPSPort) { - return "" - } - return val - }) + port := u.Port() + if port == "" || port != defaultPortForScheme(strings.ToLower(u.Scheme)) { + return + } + + suffix := ":" + port + host := u.Host + repeats := 0 + for strings.HasSuffix(host, suffix) { + host = host[:len(host)-len(suffix)] + repeats++ + } + + if _, err := url.Parse("//" + host); err == nil { + u.Host = host + + return + } + + if repeats == 1 { // the host as it came is the only one to keep + return + } + + host += suffix + if _, err := url.Parse("//" + host); err == nil { + u.Host = host + } +} + +func defaultPortForScheme(scheme string) string { + switch scheme { + case "http": + return defaultHTTPPort + case "https": + return defaultHTTPSPort + default: + return "" } } +// removeDuplicateSlashes collapses every run of slashes in the path to a single one, however +// long the run is: "/a//b///c" becomes "/a/b/c". +// +// A path holding no "//" is left as it is, which is the common case and costs one scan and no +// allocation. func removeDuplicateSlashes(u *url.URL) { - if len(u.Path) > 0 { - u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/") + const doubleSlash = "//" + + start := strings.Index(u.Path, doubleSlash) + if start < 0 { + return + } + + var collapsed strings.Builder + collapsed.Grow(len(u.Path)) + collapsed.WriteString(u.Path[:start+1]) // everything up to and including the first slash of the run + + for i := start + 1; i < len(u.Path); i++ { + c := u.Path[i] + if c == '/' && u.Path[i-1] == '/' { + continue + } + collapsed.WriteByte(c) } + + u.Path = collapsed.String() } diff --git a/vendor/github.com/go-openapi/swag/.golangci.yml b/vendor/github.com/go-openapi/swag/.golangci.yml index 099c0a78c6..e0932d0a65 100644 --- a/vendor/github.com/go-openapi/swag/.golangci.yml +++ b/vendor/github.com/go-openapi/swag/.golangci.yml @@ -7,6 +7,7 @@ linters: - errchkjson - errorlint - exhaustruct + - exhaustruct_v5 - forcetypeassert - funlen - gochecknoglobals @@ -48,7 +49,7 @@ linters: min-len: 2 min-occurrences: 3 gocyclo: - min-complexity: 45 + min-complexity: 25 exclusions: generated: lax presets: diff --git a/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md b/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md index 0f0711cd5f..1ff92bc1c0 100644 --- a/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md +++ b/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md @@ -4,11 +4,11 @@ | Total Contributors | Total Contributions | | --- | --- | -| 24 | 251 | +| 24 | 272 | | Username | All Time Contribution Count | All Commits | | --- | --- | --- | -| @fredbi | 121 | | +| @fredbi | 142 | | | @casualjim | 98 | | | @alexandear | 4 | | | @orisano | 3 | | diff --git a/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md index c6c2d21e94..f56801e430 100644 --- a/vendor/github.com/go-openapi/swag/README.md +++ b/vendor/github.com/go-openapi/swag/README.md @@ -5,7 +5,7 @@ -[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] +[![Release][release-badge]][release-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] [![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] @@ -197,8 +197,6 @@ Maintainers can cut a new release by either: [gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fswag.svg [gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fswag -[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/swag -[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/swag [codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/swag [codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/swag diff --git a/vendor/github.com/go-openapi/swag/fileutils/doc.go b/vendor/github.com/go-openapi/swag/fileutils/doc.go index 859a200d84..d5ca57b962 100644 --- a/vendor/github.com/go-openapi/swag/fileutils/doc.go +++ b/vendor/github.com/go-openapi/swag/fileutils/doc.go @@ -3,8 +3,14 @@ // Package fileutils exposes utilities to deal with files and paths. // -// Currently, there is: -// - [File] to represent an abstraction of an uploaded file. -// For instance, this is used by [github.com/go-openapi/runtime.File]. -// - path search utilities (e.g. finding packages in the GO search path) +// It provides: +// +// - [File], an abstraction of an uploaded file. +// It is used by [github.com/go-openapi/runtime.File]. +// - Implementations of [fs.FS]: [OsFS] and [GlobOsFS] wrap the os package, +// [MapFS] serves files held in memory, [OverlayFS] stacks file systems on top of one another, +// [OpaqueFS] lets a layer claim a directory for itself, and [FileReaderFS] adds a ReadFile +// method to any [fs.FS]. +// - [MustSub], to re-root a file system inline when the directory is a constant of the program. +// - path search utilities, to locate a package in the go search path. package fileutils diff --git a/vendor/github.com/go-openapi/swag/fileutils/file.go b/vendor/github.com/go-openapi/swag/fileutils/file.go index 5ad4cfaeaf..a5ff03c75f 100644 --- a/vendor/github.com/go-openapi/swag/fileutils/file.go +++ b/vendor/github.com/go-openapi/swag/fileutils/file.go @@ -6,17 +6,22 @@ package fileutils import "mime/multipart" // File represents an uploaded file. +// +// Data holds the payload, and Header the multipart metadata. +// File implements [io.ReadCloser] by delegating both methods to Data. +// +// The zero File is not usable: [File.Read] and [File.Close] both panic when Data is nil. type File struct { Data multipart.File Header *multipart.FileHeader } -// Read bytes from the file +// Read reads bytes from the payload. func (f *File) Read(p []byte) (n int, err error) { return f.Data.Read(p) } -// Close the file +// Close closes the payload. func (f *File) Close() error { return f.Data.Close() } diff --git a/vendor/github.com/go-openapi/swag/fileutils/fs.go b/vendor/github.com/go-openapi/swag/fileutils/fs.go new file mode 100644 index 0000000000..56b0a1f53a --- /dev/null +++ b/vendor/github.com/go-openapi/swag/fileutils/fs.go @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package fileutils + +import ( + "fmt" + "io/fs" + "os" +) + +// OsFS exposes package os features as an [fs.FS], without having to use [os.Root]. +// +// Existing alternatives from the standard library are [os.DirFS], which requires a base directory, +// and [os.Root.FS], which requires a root. +// [OsFS] is intended to be used when none of these alternatives are workable, +// that is when the caller does not know which root it should run in. +// +// Names are passed to the os package unchanged, +// so [OsFS] accepts absolute and relative paths, which a conforming [fs.FS] rejects. +// It offers no containment: every file that the process may read is reachable. +// +// [OsFS] implements [fs.FS], [fs.ReadFileFS] and [fs.ReadDirFS]. +type OsFS struct { +} + +// NewReadOnlyOsFS builds an [OsFS], a read-only view of the os file system. +func NewReadOnlyOsFS() *OsFS { + return &OsFS{} +} + +// Open opens the named file for reading. +func (f *OsFS) Open(name string) (fs.File, error) { + return os.Open(name) +} + +// ReadFile reads the named file and returns its content. +func (f *OsFS) ReadFile(name string) ([]byte, error) { + return os.ReadFile(name) +} + +// ReadDir reads the named directory and returns its entries sorted by file name. +func (f *OsFS) ReadDir(name string) ([]fs.DirEntry, error) { + return os.ReadDir(name) +} + +// FileReaderFS makes a [fs.FS] into a [fs.ReadFileFS], with a [FileReaderFS.ReadFile] method. +type FileReaderFS struct { + fs.FS +} + +// NewFileReaderFS transforms a [fs.FS] into a [fs.ReadFileFS]. +func NewFileReaderFS(base fs.FS) *FileReaderFS { + return &FileReaderFS{ + FS: base, + } +} + +// ReadFile reads the named file from the base file system and returns its content. +func (f *FileReaderFS) ReadFile(name string) ([]byte, error) { + return fs.ReadFile(f.FS, name) +} + +// GlobOsFS is an [OsFS] that also implements [fs.GlobFS], with a [GlobOsFS.Glob] method. +type GlobOsFS struct { + *OsFS +} + +// NewGlobOsFS is like [NewReadOnlyOsFS], augmented to match the [fs.GlobFS] interface. +func NewGlobOsFS() *GlobOsFS { + return &GlobOsFS{ + OsFS: NewReadOnlyOsFS(), + } +} + +// Glob returns the names matching pattern, sorted in lexical order. +// +// It returns a nil slice and no error when nothing matches, +// and [path.ErrBadPattern] when the pattern is malformed. +func (f *GlobOsFS) Glob(pattern string) ([]string, error) { + return fs.Glob(f.OsFS, pattern) +} + +// MustSub re-roots a file system at one of its directories, and panics when it cannot. +// +// It is [fs.Sub] for the cases where the directory is a constant of the program, such as a folder +// of an [embed.FS] assembled at initialization time: there, a failure means the program is wrong, +// not that its input is. +// +// Use [fs.Sub] itself whenever the directory comes from the outside, such as a flag, +// a configuration file or a request, so that an invalid one is reported rather than fatal. +// +// It is meant to be composed inline: +// +// assets := NewOverlayFS( +// MustSub(embedded, "templates"), +// MustSub(embedded, "templates/contrib/mine"), +// ) +func MustSub(fsys fs.FS, dir string) fs.FS { + subFS, err := fs.Sub(fsys, dir) + if err != nil { + panic(fmt.Errorf("fileutils.MustSub: cannot re-root at %q: %w", dir, err)) + } + + return subFS +} diff --git a/vendor/github.com/go-openapi/swag/fileutils/mapfs.go b/vendor/github.com/go-openapi/swag/fileutils/mapfs.go new file mode 100644 index 0000000000..5a81879f63 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/fileutils/mapfs.go @@ -0,0 +1,366 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package fileutils + +import ( + "bytes" + "errors" + "io" + "io/fs" + "path" + "slices" + "strings" + "time" +) + +// Default modes of the entries of a [MapFS]. +// +// A [MapFS] is read-only, so its files and directories are readable and never writable. +const ( + // DefaultFileMode is the mode reported by a file with no [MapFile.Mode] of its own. + DefaultFileMode fs.FileMode = 0o444 + + // DefaultDirMode is the mode reported by the directories of a [MapFS]. + DefaultDirMode fs.FileMode = fs.ModeDir | 0o555 +) + +var ( + // errNameIsFileAndDir is reported when the same name is held as a file and as a parent directory. + errNameIsFileAndDir = errors.New("name is held both as a file and as a directory") + + // errNotDir is reported when a regular file is listed as a directory. + errNotDir = errors.New("not a directory") +) + +// MapFile is a file held by a [MapFS]. +// +// Only [MapFile.Data] is required. [NewMapFS] fills the remaining fields with presets when they +// are left to their zero value. +type MapFile struct { + // Data is the content of the file. + Data []byte + + // Mode is the file mode reported by [fs.FileInfo.Mode]. Zero means [DefaultFileMode]. + Mode fs.FileMode + + // ModTime is the modification time reported by [fs.FileInfo.ModTime]. + // + // The zero value is left as is, so that a [MapFS] built from the same input twice + // reports the same metadata. + ModTime time.Time + + // Sys is the opaque value reported by [fs.FileInfo.Sys]. + Sys any +} + +// MapFS is a read-only in-memory [fs.FS], built from a map of file names to content. +// +// It is intended for the cases where the files to serve are held in memory rather than on disk: +// an overlay assembled from raw bytes, assets that a configuration provides, or a fixture in a test. +// +// Names are slash-separated paths, as accepted by [fs.ValidPath]. [NewMapFS] cleans them, +// so a name may be given with a leading "./" or "/", or with redundant elements. +// A name that remains invalid once cleaned, such as one climbing above the root, is reported +// as an error rather than dropped. +// +// Separators are never translated, so that the same input yields the same file system on every +// platform: a caller holding os paths converts them with [path/filepath.ToSlash] beforehand. +// +// Directories are implied by the names of the files, and are indexed once, when the file system +// is built: a name holds a file, and every one of its parents holds a directory. +// The root "." always exists, even when the file system holds no file at all. +// +// [MapFS] implements [fs.FS], [fs.ReadFileFS], [fs.StatFS] and [fs.ReadDirFS], but not [fs.GlobFS]: +// [fs.Glob] resolves against it all the same, through [MapFS.ReadDir]. +type MapFS struct { + files map[string]MapFile + dirs map[string][]fs.DirEntry +} + +// NewMapFS builds an in-memory file system from a map of file names to content. +// +// Names are normalized, and reported as an error when they remain invalid, or when the same name +// is held both as a file and as the parent directory of another one. +// A [MapFile] left with a zero [MapFile.Mode] reports [DefaultFileMode]. +// +// The map is copied, so adding or removing an entry afterwards leaves the file system alone. +// The contents are not: a caller that writes to a [MapFile.Data] slice it still holds changes +// what the file system serves. Hand over a slice nothing else keeps, or copy it first. +func NewMapFS(files map[string]MapFile) (*MapFS, error) { + normalized := make(map[string]MapFile, len(files)) + + for name, file := range files { + clean, err := normalizeMapName(name) + if err != nil { + return nil, err + } + + if _, isDuplicate := normalized[clean]; isDuplicate { + return nil, &fs.PathError{Op: "newmapfs", Path: clean, Err: fs.ErrExist} + } + + if file.Mode == 0 { + file.Mode = DefaultFileMode + } + + normalized[clean] = file + } + + dirs, err := indexMapDirs(normalized) + if err != nil { + return nil, err + } + + return &MapFS{ + files: normalized, + dirs: dirs, + }, nil +} + +// FromRawMap builds the files of a [MapFS] from raw contents, leaving every metadata field to its preset. +// +// It is the shortest way to a [MapFS] when all the caller holds is bytes: +// +// mapFS, err := NewMapFS(FromRawMap(map[string][]byte{ +// "folder/file1": raw1, +// "folder/file2": raw2, +// })) +func FromRawMap(raw map[string][]byte) map[string]MapFile { + files := make(map[string]MapFile, len(raw)) + for name, data := range raw { + files[name] = MapFile{Data: data} + } + + return files +} + +// Open opens the named file or directory. +// +// Opening a directory yields a [fs.ReadDirFile] reporting the same entries as [MapFS.ReadDir]. +func (f *MapFS) Open(name string) (fs.File, error) { + if !fs.ValidPath(name) { + return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrInvalid} + } + + if file, isFile := f.files[name]; isFile { + return &openMapFile{ + info: mapFileInfo{name: path.Base(name), file: file}, + reader: bytes.NewReader(file.Data), + }, nil + } + + entries, isDir := f.dirs[name] + if !isDir { + return nil, notFound("open", name) + } + + return &openMapDir{info: mapDirInfo{name: path.Base(name)}, entries: entries}, nil +} + +// ReadFile reads the named file and returns a copy of its content. +func (f *MapFS) ReadFile(name string) ([]byte, error) { + if !fs.ValidPath(name) { + return nil, &fs.PathError{Op: "read", Path: name, Err: fs.ErrInvalid} + } + + file, isFile := f.files[name] + if !isFile { + if _, isDir := f.dirs[name]; isDir { + return nil, &fs.PathError{Op: "read", Path: name, Err: errIsDir} + } + + return nil, notFound("read", name) + } + + // a caller mutating the result would otherwise mutate what the file system serves + return slices.Clone(file.Data), nil +} + +// Stat returns the [fs.FileInfo] of the named file or directory. +func (f *MapFS) Stat(name string) (fs.FileInfo, error) { + if !fs.ValidPath(name) { + return nil, &fs.PathError{Op: "stat", Path: name, Err: fs.ErrInvalid} + } + + if file, isFile := f.files[name]; isFile { + return mapFileInfo{name: path.Base(name), file: file}, nil + } + + if _, isDir := f.dirs[name]; isDir { + return mapDirInfo{name: path.Base(name)}, nil + } + + return nil, notFound("stat", name) +} + +// ReadDir lists the named directory, with its entries sorted by file name. +func (f *MapFS) ReadDir(name string) ([]fs.DirEntry, error) { + if !fs.ValidPath(name) { + return nil, &fs.PathError{Op: "readdir", Path: name, Err: fs.ErrInvalid} + } + + entries, isDir := f.dirs[name] + if !isDir { + if _, isFile := f.files[name]; isFile { + return nil, &fs.PathError{Op: "readdir", Path: name, Err: errNotDir} + } + + return nil, notFound("readdir", name) + } + + // the index is shared by every caller, so it must not escape + return slices.Clone(entries), nil +} + +// normalizeMapName turns the name of a file into the cleaned form that [fs.ValidPath] accepts. +// +// Separators are left alone: an [fs.FS] name is slash-separated by definition, and translating +// them here would resolve the same input differently depending on the platform. +func normalizeMapName(name string) (string, error) { + clean := path.Clean(strings.TrimPrefix(name, "/")) + + if !fs.ValidPath(clean) || clean == "." { + return "", &fs.PathError{Op: "newmapfs", Path: name, Err: fs.ErrInvalid} + } + + return clean, nil +} + +// indexMapDirs builds the directory index of a [MapFS], once, from the names of its files. +// +// Every parent of a file name holds a directory, up to the root, which always exists. +func indexMapDirs(files map[string]MapFile) (map[string][]fs.DirEntry, error) { + children := map[string]map[string]bool{".": {}} // directory -> child base name -> is a directory + + for name := range files { + dir := path.Dir(name) + addMapChild(children, dir, path.Base(name), false) + + // every ancestor of the file holds a directory + for dir != "." { + parent := path.Dir(dir) + addMapChild(children, parent, path.Base(dir), true) + dir = parent + } + } + + dirs := make(map[string][]fs.DirEntry, len(children)) + for dir, names := range children { + if _, isFile := files[dir]; isFile { + return nil, &fs.PathError{Op: "newmapfs", Path: dir, Err: errNameIsFileAndDir} + } + + entries := make([]fs.DirEntry, 0, len(names)) + for base, isDir := range names { + if isDir { + entries = append(entries, mapDirInfo{name: base}) + + continue + } + + entries = append(entries, mapFileInfo{name: base, file: files[path.Join(dir, base)]}) + } + + slices.SortFunc(entries, func(a, b fs.DirEntry) int { + return strings.Compare(a.Name(), b.Name()) + }) + dirs[dir] = entries + } + + return dirs, nil +} + +// addMapChild records that a directory holds an entry. +func addMapChild(children map[string]map[string]bool, dir, base string, isDir bool) { + entries, exists := children[dir] + if !exists { + entries = make(map[string]bool) + children[dir] = entries + } + + entries[base] = isDir +} + +// mapFileInfo reports the metadata of a file of a [MapFS]. It is both a [fs.FileInfo] and a [fs.DirEntry]. +type mapFileInfo struct { + name string + file MapFile +} + +func (i mapFileInfo) Name() string { return i.name } +func (i mapFileInfo) Size() int64 { return int64(len(i.file.Data)) } +func (i mapFileInfo) Mode() fs.FileMode { return i.file.Mode } +func (i mapFileInfo) Type() fs.FileMode { return i.file.Mode.Type() } +func (i mapFileInfo) ModTime() time.Time { return i.file.ModTime } +func (i mapFileInfo) IsDir() bool { return false } +func (i mapFileInfo) Sys() any { return i.file.Sys } +func (i mapFileInfo) Info() (fs.FileInfo, error) { return i, nil } + +// mapDirInfo reports the metadata of a directory of a [MapFS]. It is both a [fs.FileInfo] and a [fs.DirEntry]. +// +// Directories are implied by the names of the files, so they carry no metadata of their own. +type mapDirInfo struct { + name string +} + +func (i mapDirInfo) Name() string { return i.name } +func (i mapDirInfo) Size() int64 { return 0 } +func (i mapDirInfo) Mode() fs.FileMode { return DefaultDirMode } +func (i mapDirInfo) Type() fs.FileMode { return fs.ModeDir } +func (i mapDirInfo) ModTime() time.Time { return time.Time{} } +func (i mapDirInfo) IsDir() bool { return true } +func (i mapDirInfo) Sys() any { return nil } +func (i mapDirInfo) Info() (fs.FileInfo, error) { return i, nil } + +// openMapFile is the [fs.File] returned when opening a file of a [MapFS]. +type openMapFile struct { + info mapFileInfo + reader *bytes.Reader +} + +func (f *openMapFile) Stat() (fs.FileInfo, error) { return f.info, nil } + +func (f *openMapFile) Close() error { return nil } + +func (f *openMapFile) Read(p []byte) (int, error) { return f.reader.Read(p) } + +func (f *openMapFile) Seek(offset int64, whence int) (int64, error) { + return f.reader.Seek(offset, whence) +} + +// openMapDir is the [fs.ReadDirFile] returned when opening a directory of a [MapFS]. +type openMapDir struct { + info mapDirInfo + entries []fs.DirEntry + offset int +} + +func (d *openMapDir) Stat() (fs.FileInfo, error) { return d.info, nil } + +func (d *openMapDir) Close() error { return nil } + +func (d *openMapDir) Read([]byte) (int, error) { + return 0, &fs.PathError{Op: "read", Path: d.info.name, Err: errIsDir} +} + +// ReadDir returns the next n entries, or all the remaining ones when n is not positive. +func (d *openMapDir) ReadDir(n int) ([]fs.DirEntry, error) { + remaining := len(d.entries) - d.offset + if n <= 0 { + entries := slices.Clone(d.entries[d.offset:]) + d.offset = len(d.entries) + + return entries, nil + } + + if remaining == 0 { + return nil, io.EOF + } + + n = min(n, remaining) + entries := slices.Clone(d.entries[d.offset : d.offset+n]) + d.offset += n + + return entries, nil +} diff --git a/vendor/github.com/go-openapi/swag/fileutils/opaque.go b/vendor/github.com/go-openapi/swag/fileutils/opaque.go new file mode 100644 index 0000000000..526e867362 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/fileutils/opaque.go @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package fileutils + +import ( + "io/fs" + "path" +) + +// OpaqueDirFS is a file system that entirely owns some of its directories. +// +// [OverlayFS] neither merges an opaque directory with the layers below it, +// nor resolves any name under it against them: +// what the owning layer holds replaces what they hold under the same name. +// +// [OpaqueFS] is the implementation provided by this package. +type OpaqueDirFS interface { + fs.FS + + // IsOpaqueDir reports whether a directory was declared as entirely owned by this file system. + // + // It answers from the declarations given to [NewOpaqueFS], and does not check that the file + // system holds the directory: a name declared opaque reports true either way. + // [OverlayFS] consults it only for a layer that holds the directory. + IsOpaqueDir(name string) bool +} + +// OpaqueDirsAll declares that a file system owns every directory it holds, except its root. +// +// It is the only pattern recognized by [NewOpaqueFS]: directories are otherwise matched +// by their exact name. +const OpaqueDirsAll = "*" + +// OpaqueFS makes a [fs.FS] into an [OpaqueDirFS], by declaring the directories that it owns. +type OpaqueFS struct { + fs.FS + + opaqueDirs map[string]struct{} +} + +// NewOpaqueFS declares the directories that a file system entirely owns, +// so that they shadow the layers below when it is stacked in an [OverlayFS]. +// +// Directories are slash-separated paths, as accepted by [fs.ValidPath], and are cleaned. +// Declaring "." makes the whole file system opaque, down from its root. +// Declaring [OpaqueDirsAll] makes every directory opaque but the root, +// so that the root still merges and the layers below keep contributing what they hold beside it. +// +// Declaring a directory that this file system does not hold changes nothing once it is stacked. +// [OverlayFS] skips a layer that does not hold the directory before it consults opacity, +// so the layers below keep resolving that directory and everything under it. +func NewOpaqueFS(base fs.FS, dirs ...string) *OpaqueFS { + opaqueDirs := make(map[string]struct{}, len(dirs)) + for _, dir := range dirs { + opaqueDirs[path.Clean(dir)] = struct{}{} + } + + return &OpaqueFS{ + FS: base, + opaqueDirs: opaqueDirs, + } +} + +// IsOpaqueDir reports whether a directory was declared as entirely owned by this file system. +// +// It answers from the declarations given to [NewOpaqueFS], and does not check that the file +// system holds the directory: a name declared opaque reports true either way. +// [OverlayFS] consults it only for a layer that holds the directory. +func (f *OpaqueFS) IsOpaqueDir(name string) bool { + if _, isOpaque := f.opaqueDirs[name]; isOpaque { + return true + } + + if name == "." { + // the root is owned only when it is declared explicitly + return false + } + + _, ownsAll := f.opaqueDirs[OpaqueDirsAll] + + return ownsAll +} + +// ReadFile reads a file from the wrapped file system. +func (f *OpaqueFS) ReadFile(name string) ([]byte, error) { + return fs.ReadFile(f.FS, name) +} + +// Stat returns the [fs.FileInfo] of a name in the wrapped file system. +func (f *OpaqueFS) Stat(name string) (fs.FileInfo, error) { + return fs.Stat(f.FS, name) +} + +// ReadDir lists a directory of the wrapped file system. +func (f *OpaqueFS) ReadDir(name string) ([]fs.DirEntry, error) { + return fs.ReadDir(f.FS, name) +} diff --git a/vendor/github.com/go-openapi/swag/fileutils/overlay.go b/vendor/github.com/go-openapi/swag/fileutils/overlay.go new file mode 100644 index 0000000000..d67ab6a5fa --- /dev/null +++ b/vendor/github.com/go-openapi/swag/fileutils/overlay.go @@ -0,0 +1,345 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package fileutils + +import ( + "errors" + "io" + "io/fs" + "path" + "slices" + "strings" + "syscall" +) + +// OverlayFS is a read-only [fs.FS] that stacks overlays on top of a base file system. +// +// A name is resolved in the topmost layer that holds it, then down to the base. +// See [NewOverlayFS] for the order in which layers are stacked. +// When the name is absent from all layers, every method returns a [fs.PathError] that reports +// the name and matches [fs.ErrNotExist]. +// +// [OverlayFS] implements [fs.FS], [fs.ReadFileFS], [fs.StatFS] and [fs.ReadDirFS], but not [fs.GlobFS]. +// A directory returns an error when the resolved layer does not support reading directories. +// +// Directories are merged: a directory reports the union of the entries held by every layer, +// and the topmost layer wins whenever the same name is held by several of them. +// A layer may claim a directory for itself with [NewOpaqueFS], which stops the merge +// and hides everything the lower layers hold under that directory. +type OverlayFS struct { + layers []fs.FS +} + +// NewOverlayFS builds an overlay file system from a base file system and a list of overlays. +// +// Overlays are stacked in the order in which they are provided: +// the last one sits on top and is resolved first, then the preceding ones in reverse order. +// The base is always resolved last. +// +// An empty list of overlays yields a file system that resolves against the base alone. +func NewOverlayFS(base fs.FS, overlays ...fs.FS) *OverlayFS { + layers := make([]fs.FS, 0, len(overlays)+1) + for _, overlay := range slices.Backward(overlays) { + layers = append(layers, overlay) + } + layers = append(layers, base) + + return &OverlayFS{ + layers: layers, + } +} + +// Open opens a file, resolving layers from the topmost overlay down to the base. +// +// Opening a directory yields a [fs.ReadDirFile] that reports the same entries as +// [OverlayFS.ReadDir], so that a merged directory reads alike either way. +func (f *OverlayFS) Open(name string) (fs.File, error) { + file, err := f.openInLayers(name) + if err != nil { + return nil, err + } + + info, err := file.Stat() + if err != nil { + _ = file.Close() + + return nil, err + } + + if !info.IsDir() { + return file, nil + } + + // the entries of a directory come from every layer, not from the one that resolved it + _ = file.Close() + + entries, err := f.readMergedDir(name) + if err != nil { + return nil, err + } + + return &mergedDir{name: name, info: info, entries: entries}, nil +} + +// ReadFile reads a file, resolving layers from the topmost overlay down to the base. +func (f *OverlayFS) ReadFile(name string) ([]byte, error) { + layer, err := f.findInLayers("open", name) + if err != nil { + return nil, err + } + + return fs.ReadFile(layer, name) +} + +// Stat returns the [fs.FileInfo] of a file, resolving layers from the topmost overlay down to the base. +func (f *OverlayFS) Stat(name string) (fs.FileInfo, error) { + layer, err := f.findInLayers("stat", name) + if err != nil { + return nil, err + } + + return fs.Stat(layer, name) +} + +// ReadDir lists a directory, resolving layers from the topmost overlay down to the base. +// +// The entries of every layer holding the directory are merged, sorted by file name, +// and a name held by several layers is reported by the topmost of them. +// The merge stops at the topmost layer that owns the directory, as declared by [NewOpaqueFS]. +func (f *OverlayFS) ReadDir(name string) ([]fs.DirEntry, error) { + return f.readMergedDir(name) +} + +// readMergedDir collects the entries of every layer that holds a directory. +// +// A name that is not a directory in some layer shadows the layers below it, +// just like a regular file does. +func (f *OverlayFS) readMergedDir(name string) ([]fs.DirEntry, error) { + var ( + merged []fs.DirEntry + found bool + ) + seen := make(map[string]struct{}) + + for _, layer := range f.layers { + info, err := fs.Stat(layer, name) + if err != nil { + if !isNotFound(err) { + return nil, err + } + + if ownsSubtreeOf(layer, name) { + break + } + + continue + } + + if !info.IsDir() { + if found { + // a directory held by an upper layer shadows this entry + break + } + + // let the layer report why the name cannot be listed + return fs.ReadDir(layer, name) + } + + entries, err := fs.ReadDir(layer, name) + if err != nil { + return nil, err + } + + found = true + for _, entry := range entries { + if _, isShadowed := seen[entry.Name()]; isShadowed { + continue + } + + seen[entry.Name()] = struct{}{} + merged = append(merged, entry) + } + + if declaresOpaqueDir(layer, name) || ownsSubtreeOf(layer, name) { + // this layer owns the directory, or one of its parents: + // the layers below it contribute nothing + break + } + } + + if !found { + return nil, notFound("readdir", name) + } + + slices.SortFunc(merged, func(a, b fs.DirEntry) int { + return strings.Compare(a.Name(), b.Name()) + }) + + return merged, nil +} + +// openInLayers opens a name in the topmost layer that holds it. +func (f *OverlayFS) openInLayers(name string) (fs.File, error) { + for _, layer := range f.layers { + file, err := layer.Open(name) + if err == nil { + return file, nil + } + + if !isNotFound(err) { + return nil, err + } + + if ownsSubtreeOf(layer, name) { + break + } + } + + return nil, notFound("open", name) +} + +// findInLayers returns the topmost layer that holds a name. +// +// op names the operation reported by the [fs.PathError] raised when no layer holds the name. +func (f *OverlayFS) findInLayers(op, name string) (fs.FS, error) { + for _, layer := range f.layers { + err := probeInLayer(layer, name) + if err == nil { + return layer, nil + } + + if !isNotFound(err) { + return nil, err + } + + if ownsSubtreeOf(layer, name) { + break + } + } + + return nil, notFound(op, name) +} + +// probeInLayer reports the error raised by a layer when looking a name up. +// +// A layer implementing [fs.StatFS] is probed with Stat. +// Otherwise the name is opened, then closed again. +func probeInLayer(layer fs.FS, name string) error { + if statFS, supportsStat := layer.(fs.StatFS); supportsStat { + _, err := statFS.Stat(name) + + return err + } + + file, err := layer.Open(name) + if err == nil { + _ = file.Close() + } + + return err +} + +// declaresOpaqueDir tells whether a layer marks a directory as entirely owned. +func declaresOpaqueDir(layer fs.FS, name string) bool { + opaque, isOpaqueFS := layer.(OpaqueDirFS) + + return isOpaqueFS && opaque.IsOpaqueDir(name) +} + +// ownsDir tells whether a layer marks a directory as entirely owned, and holds it. +func ownsDir(layer fs.FS, name string) bool { + if !declaresOpaqueDir(layer, name) { + return false + } + + info, err := fs.Stat(layer, name) + + return err == nil && info.IsDir() +} + +// ownsSubtreeOf tells whether a layer owns one of the parent directories of a name. +// +// The layers below such a layer hold nothing that is reachable under that name. +func ownsSubtreeOf(layer fs.FS, name string) bool { + if _, isOpaqueFS := layer.(OpaqueDirFS); !isOpaqueFS { + return false + } + + for dir := path.Dir(name); ; { + if ownsDir(layer, dir) { + return true + } + + // "." and "/" are their own parent, so this is where the walk up ends + parent := path.Dir(dir) + if parent == dir { + return false + } + + dir = parent + } +} + +// errIsDir is reported when a merged directory is read as a regular file. +var errIsDir = errors.New("is a directory") + +// mergedDir is the [fs.ReadDirFile] returned when opening a directory with merged layers. +// +// Its [fs.FileInfo] is the one of the topmost layer holding the directory, +// while its entries come from all the layers holding it. +type mergedDir struct { + name string + info fs.FileInfo + entries []fs.DirEntry + offset int +} + +func (d *mergedDir) Stat() (fs.FileInfo, error) { return d.info, nil } + +func (d *mergedDir) Close() error { return nil } + +func (d *mergedDir) Read([]byte) (int, error) { + return 0, &fs.PathError{Op: "read", Path: d.name, Err: errIsDir} +} + +// ReadDir returns the next n entries, or all the remaining ones when n is not positive. +func (d *mergedDir) ReadDir(n int) ([]fs.DirEntry, error) { + remaining := len(d.entries) - d.offset + if n <= 0 { + entries := d.entries[d.offset:] + d.offset = len(d.entries) + + return entries, nil + } + + if remaining == 0 { + return nil, io.EOF + } + + n = min(n, remaining) + entries := d.entries[d.offset : d.offset+n] + d.offset += n + + return entries, nil +} + +// notFound builds the error reported when a name is absent from all layers. +// +// It mirrors what the os package raises for a missing file, +// so that a caller may retrieve the name from the error alone. +func notFound(op, name string) error { + return &fs.PathError{Op: op, Path: name, Err: fs.ErrNotExist} +} + +// isNotFound tells whether an error raised by a layer means that the name is absent from that layer. +// +// The whole error chain is inspected, so a layer that wraps its errors resolves like any other, +// and so does a layer that is itself an [OverlayFS]. +// +// [syscall.ENOTDIR] is matched explicitly, because a path traversing a regular file +// does not report [fs.ErrNotExist] on all platforms. +// Any other error stops the resolution and is reported to the caller. +func isNotFound(err error) bool { + return errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) +} diff --git a/vendor/github.com/go-openapi/swag/fileutils/path.go b/vendor/github.com/go-openapi/swag/fileutils/path.go index dd09f690bf..647df76091 100644 --- a/vendor/github.com/go-openapi/swag/fileutils/path.go +++ b/vendor/github.com/go-openapi/swag/fileutils/path.go @@ -10,10 +10,17 @@ import ( "strings" ) -// GOPATHKey represents the env key for gopath +// GOPATHKey is the name of the environment variable that holds the go search path. const GOPATHKey = "GOPATH" -// FindInSearchPath finds a package in a provided lists of paths +// FindInSearchPath finds a package in a list of search paths. +// +// searchPath lists directories separated by the OS path separator, +// in the form accepted by [filepath.SplitList]. +// Each directory is probed for a src/pkg subdirectory. +// +// It returns the first match, with symlinks resolved, +// or an empty string when the package is not found in any of the directories. func FindInSearchPath(searchPath, pkg string) string { pathsList := filepath.SplitList(searchPath) for _, path := range pathsList { @@ -26,7 +33,9 @@ func FindInSearchPath(searchPath, pkg string) string { return "" } -// FindInGoSearchPath finds a package in the $GOPATH:$GOROOT +// FindInGoSearchPath finds a package in $GOPATH and $GOROOT. +// +// It returns an empty string when the package is not found. // // Deprecated: this function is no longer relevant with modern go. // It uses [runtime.GOROOT] under the hood, which is deprecated as of go1.24. @@ -34,7 +43,10 @@ func FindInGoSearchPath(pkg string) string { return FindInSearchPath(FullGoSearchPath(), pkg) } -// FullGoSearchPath gets the search paths for finding packages +// FullGoSearchPath returns the search paths in which a package may be found. +// +// It joins $GOPATH, which defaults to $HOME/go when unset, with [runtime.GOROOT]. +// The two are separated by a colon, so the result is not usable on windows. // // Deprecated: this function is no longer relevant with modern go. // It uses [runtime.GOROOT] under the hood, which is deprecated as of go1.24. diff --git a/vendor/github.com/go-openapi/swag/go.work b/vendor/github.com/go-openapi/swag/go.work index f1dddc436e..bb58106509 100644 --- a/vendor/github.com/go-openapi/swag/go.work +++ b/vendor/github.com/go-openapi/swag/go.work @@ -18,4 +18,4 @@ use ( ./yamlutils ) -go 1.25.0 +go 1.26.0 diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/options.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/options.go index f114f1f1a1..cfcd426852 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/options.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/options.go @@ -10,6 +10,11 @@ package json // It mirrors the limit enforced by the standard library's [encoding/json] decoder // (see encoding/json's internal maxNestingDepth), which this adapter would otherwise // not benefit from since it drives [encoding/json.Decoder.Token] directly. +// +// With encoding/json v2 (GOEXPERIMENT=jsonv2, the default from go1.27), Token applies +// that same limit itself and reports "exceeded max depth" before this counter fires. +// Set a lower limit with [WithMaxNestingDepth] to be rejected earlier than the stdlib; +// a higher one does not lift the stdlib's own 10,000-level ceiling on the decode path. const defaultMaxNestingDepth = 10000 // Option selects options for the stdlib adapter. diff --git a/vendor/github.com/go-openapi/swag/revive.toml b/vendor/github.com/go-openapi/swag/revive.toml new file mode 100644 index 0000000000..eef9c17126 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/revive.toml @@ -0,0 +1,18 @@ +# revive configuration used by codefactor.io. +# +# This is redundant with .golangci.yml, since revive is part of golangci-lint, +# but we need to configure it to remain consistent across reporting tools. + +ignore-generated-header = false +severity = "warning" +confidence = 0.8 +error-code = 0 +warning-code = 0 +enable-default-rules = true + +[rule.exported] +disabled = true +[rule.cyclomatic] +arguments = [25] +[rule.cognitive-complexity] +arguments = [25] diff --git a/vendor/github.com/go-openapi/swag/yamlutils/yaml.go b/vendor/github.com/go-openapi/swag/yamlutils/yaml.go index d4b5335f6f..01ce324aec 100644 --- a/vendor/github.com/go-openapi/swag/yamlutils/yaml.go +++ b/vendor/github.com/go-openapi/swag/yamlutils/yaml.go @@ -248,7 +248,7 @@ func yamlScalar(node *yaml.Node) (any, error) { func yamlStringScalarC(node *yaml.Node) (string, error) { if node.Kind != yaml.ScalarNode { - return "", fmt.Errorf("expecting a string scalar but got %q: %w", node.Kind, ErrYAML) + return "", fmt.Errorf("expecting a string scalar but got node.Kind(%d): %w", node.Kind, ErrYAML) } switch node.LongTag() { case yamlStringScalar, yamlIntScalar, yamlFloatScalar: diff --git a/vendor/github.com/google/cel-go/checker/cost.go b/vendor/github.com/google/cel-go/checker/cost.go deleted file mode 100644 index 3d7dd7ec4a..0000000000 --- a/vendor/github.com/google/cel-go/checker/cost.go +++ /dev/null @@ -1,1055 +0,0 @@ -// Copyright 2022 Google LLC -// -// 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 checker - -import ( - "math" - - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/ast" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/parser" -) - -// WARNING: Any changes to cost calculations in this file require a corresponding change in interpreter/runtimecost.go - -// CostEstimator estimates the sizes of variable length input data and the costs of functions. -type CostEstimator interface { - // EstimateSize returns a SizeEstimate for the given AstNode, or nil if the estimator has no - // estimate to provide. - // - // The size is equivalent to the result of the CEL `size()` function: - // * Number of unicode characters in a string - // * Number of bytes in a sequence - // * Number of map entries or number of list items. - // - // EstimateSize is only called for AstNodes where CEL does not know the size; EstimateSize is not - // called for values defined inline in CEL where the size is already obvious to CEL. - EstimateSize(element AstNode) *SizeEstimate - - // EstimateCallCost returns the estimated cost of an invocation, or nil if the estimator has no - // estimate to provide. - EstimateCallCost(function, overloadID string, target *AstNode, args []AstNode) *CallEstimate -} - -// CallEstimate includes a CostEstimate for the call, and an optional estimate of the result object size. -// The ResultSize should only be provided if the call results in a map, list, string or bytes. -type CallEstimate struct { - CostEstimate - - ResultSize *SizeEstimate -} - -// AstNode represents an AST node for the purpose of cost estimations. -type AstNode interface { - // Path returns a field path through the provided type declarations to the type of the AstNode, or nil if the AstNode does not - // represent type directly reachable from the provided type declarations. - // The first path element is a variable. All subsequent path elements are one of: field name, '@items', '@keys', '@values'. - Path() []string - - // Type returns the deduced type of the AstNode. - Type() *types.Type - - // Expr returns the expression of the AstNode. - Expr() ast.Expr - - // ComputedSize returns a size estimate of the AstNode derived from information available in the CEL expression. - // For constants and inline list and map declarations, the exact size is returned. For concatenated list, strings - // and bytes, the size is derived from the size estimates of the operands. nil is returned if there is no - // computed size available. - ComputedSize() *SizeEstimate -} - -type astNode struct { - path []string - t *types.Type - expr ast.Expr - derivedSize *SizeEstimate -} - -func (e astNode) Path() []string { - return e.path -} - -func (e astNode) Type() *types.Type { - return e.t -} - -func (e astNode) Expr() ast.Expr { - return e.expr -} - -func (e astNode) ComputedSize() *SizeEstimate { - return e.derivedSize -} - -// SizeEstimate represents an estimated size of a variable length string, bytes, map or list. -type SizeEstimate struct { - Min, Max uint64 -} - -// UnknownSizeEstimate returns a size between 0 and max uint -func UnknownSizeEstimate() SizeEstimate { - return unknownSizeEstimate -} - -// FixedSizeEstimate returns a size estimate with a fixed min and max range. -func FixedSizeEstimate(size uint64) SizeEstimate { - return SizeEstimate{Min: size, Max: size} -} - -// Add adds to another SizeEstimate and returns the sum. -// If add would result in an uint64 overflow, the result is math.MaxUint64. -func (se SizeEstimate) Add(sizeEstimate SizeEstimate) SizeEstimate { - return SizeEstimate{ - addUint64NoOverflow(se.Min, sizeEstimate.Min), - addUint64NoOverflow(se.Max, sizeEstimate.Max), - } -} - -// Multiply multiplies by another SizeEstimate and returns the product. -// If multiply would result in an uint64 overflow, the result is math.MaxUint64. -func (se SizeEstimate) Multiply(sizeEstimate SizeEstimate) SizeEstimate { - return SizeEstimate{ - multiplyUint64NoOverflow(se.Min, sizeEstimate.Min), - multiplyUint64NoOverflow(se.Max, sizeEstimate.Max), - } -} - -// MultiplyByCostFactor multiplies a SizeEstimate by a cost factor and returns the CostEstimate with the -// nearest integer of the result, rounded up. -func (se SizeEstimate) MultiplyByCostFactor(costPerUnit float64) CostEstimate { - return CostEstimate{ - multiplyByCostFactor(se.Min, costPerUnit), - multiplyByCostFactor(se.Max, costPerUnit), - } -} - -// MultiplyByCost multiplies by the cost and returns the product. -// If multiply would result in an uint64 overflow, the result is math.MaxUint64. -func (se SizeEstimate) MultiplyByCost(cost CostEstimate) CostEstimate { - return CostEstimate{ - multiplyUint64NoOverflow(se.Min, cost.Min), - multiplyUint64NoOverflow(se.Max, cost.Max), - } -} - -// Union returns a SizeEstimate that encompasses both input the SizeEstimate. -func (se SizeEstimate) Union(size SizeEstimate) SizeEstimate { - result := se - if size.Min < result.Min { - result.Min = size.Min - } - if size.Max > result.Max { - result.Max = size.Max - } - return result -} - -// AsCost converts a size estimates to an equivalent cost estimate. -func (se SizeEstimate) AsCost() CostEstimate { - return se.MultiplyByCostFactor(1) -} - -// CostEstimate represents an estimated cost range and provides add and multiply operations -// that do not overflow. -type CostEstimate struct { - Min, Max uint64 -} - -// UnknownCostEstimate returns a cost with an unknown impact. -func UnknownCostEstimate() CostEstimate { - return unknownCostEstimate -} - -// FixedCostEstimate returns a cost with a fixed min and max range. -func FixedCostEstimate(cost uint64) CostEstimate { - return CostEstimate{Min: cost, Max: cost} -} - -// Add adds the costs and returns the sum. -// If add would result in an uint64 overflow for the min or max, the value is set to math.MaxUint64. -func (ce CostEstimate) Add(cost CostEstimate) CostEstimate { - return CostEstimate{ - Min: addUint64NoOverflow(ce.Min, cost.Min), - Max: addUint64NoOverflow(ce.Max, cost.Max), - } -} - -// Multiply multiplies by the cost and returns the product. -// If multiply would result in an uint64 overflow, the result is math.MaxUint64. -func (ce CostEstimate) Multiply(cost CostEstimate) CostEstimate { - return CostEstimate{ - Min: multiplyUint64NoOverflow(ce.Min, cost.Min), - Max: multiplyUint64NoOverflow(ce.Max, cost.Max), - } -} - -// MultiplyByCostFactor multiplies a CostEstimate by a cost factor and returns the CostEstimate with the -// nearest integer of the result, rounded up. -func (ce CostEstimate) MultiplyByCostFactor(costPerUnit float64) CostEstimate { - return CostEstimate{ - Min: multiplyByCostFactor(ce.Min, costPerUnit), - Max: multiplyByCostFactor(ce.Max, costPerUnit), - } -} - -// Union returns a CostEstimate that encompasses both input the CostEstimates. -func (ce CostEstimate) Union(size CostEstimate) CostEstimate { - result := ce - if size.Min < result.Min { - result.Min = size.Min - } - if size.Max > result.Max { - result.Max = size.Max - } - return result -} - -// addUint64NoOverflow adds non-negative ints. If the result is exceeds math.MaxUint64, math.MaxUint64 -// is returned. -func addUint64NoOverflow(x, y uint64) uint64 { - if y > 0 && x > math.MaxUint64-y { - return math.MaxUint64 - } - return x + y -} - -// multiplyUint64NoOverflow multiplies non-negative ints. If the result is exceeds math.MaxUint64, math.MaxUint64 -// is returned. -func multiplyUint64NoOverflow(x, y uint64) uint64 { - if y != 0 && x > math.MaxUint64/y { - return math.MaxUint64 - } - return x * y -} - -// multiplyByFactor multiplies an integer by a cost factor float and returns the nearest integer value, rounded up. -func multiplyByCostFactor(x uint64, y float64) uint64 { - xFloat := float64(x) - if xFloat > 0 && y > 0 && xFloat > math.MaxUint64/y { - return math.MaxUint64 - } - ceil := math.Ceil(xFloat * y) - if ceil >= doubleTwoTo64 { - return math.MaxUint64 - } - return uint64(ceil) -} - -// CostOption configures flags which affect cost computations. -type CostOption func(*coster) error - -// PresenceTestHasCost determines whether presence testing has a cost of one or zero. -// -// Defaults to presence test has a cost of one. -func PresenceTestHasCost(hasCost bool) CostOption { - return func(c *coster) error { - if hasCost { - c.presenceTestCost = selectAndIdentCost - return nil - } - c.presenceTestCost = FixedCostEstimate(0) - return nil - } -} - -// FunctionEstimator provides a CallEstimate given the target and arguments for a specific function, overload pair. -type FunctionEstimator func(estimator CostEstimator, target *AstNode, args []AstNode) *CallEstimate - -// OverloadCostEstimate binds a FunctionCoster to a specific function overload ID. -// -// When a OverloadCostEstimate is provided, it will override the cost calculation of the CostEstimator provided to -// the Cost() call. -func OverloadCostEstimate(overloadID string, functionCoster FunctionEstimator) CostOption { - return func(c *coster) error { - c.overloadEstimators[overloadID] = functionCoster - return nil - } -} - -// Cost estimates the cost of the parsed and type checked CEL expression. -func Cost(checked *ast.AST, estimator CostEstimator, opts ...CostOption) (CostEstimate, error) { - c := &coster{ - checkedAST: checked, - estimator: estimator, - overloadEstimators: map[string]FunctionEstimator{}, - exprPaths: map[int64][]string{}, - localVars: make(scopes), - computedSizes: map[int64]SizeEstimate{}, - computedEntrySizes: map[int64]entrySizeEstimate{}, - presenceTestCost: FixedCostEstimate(1), - } - for _, opt := range opts { - err := opt(c) - if err != nil { - return CostEstimate{}, err - } - } - return c.cost(checked.Expr()), nil -} - -type coster struct { - // exprPaths maps from Expr Id to field path. - exprPaths map[int64][]string - // localVars tracks the local and iteration variables assigned during evaluation. - localVars scopes - // computedSizes tracks the computed sizes of call results. - computedSizes map[int64]SizeEstimate - // computedEntrySizes tracks the size of list and map entries - computedEntrySizes map[int64]entrySizeEstimate - - checkedAST *ast.AST - estimator CostEstimator - overloadEstimators map[string]FunctionEstimator - // presenceTestCost will either be a zero or one based on whether has() macros count against cost computations. - presenceTestCost CostEstimate -} - -// entrySizeEstimate captures the container kind and associated key/index and value SizeEstimate values. -// -// An entrySizeEstimate only exists if both the key/index and the value have SizeEstimate values, otherwise -// a nil entrySizeEstimate should be used. -type entrySizeEstimate struct { - containerKind types.Kind - key SizeEstimate - val SizeEstimate -} - -// container returns the container kind (list or map) of the entry. -func (s *entrySizeEstimate) container() types.Kind { - if s == nil { - return types.UnknownKind - } - return s.containerKind -} - -// keySize returns the SizeEstimate for the key if one exists. -func (s *entrySizeEstimate) keySize() *SizeEstimate { - if s == nil { - return nil - } - return &s.key -} - -// valSize returns the SizeEstimate for the value if one exists. -func (s *entrySizeEstimate) valSize() *SizeEstimate { - if s == nil { - return nil - } - return &s.val -} - -func (s *entrySizeEstimate) union(other *entrySizeEstimate) *entrySizeEstimate { - if s == nil || other == nil { - return nil - } - sk := s.key.Union(other.key) - sv := s.val.Union(other.val) - return &entrySizeEstimate{ - containerKind: s.containerKind, - key: sk, - val: sv, - } -} - -// localVar captures the local variable size and entrySize estimates if they exist for variables -type localVar struct { - exprID int64 - path []string - size *SizeEstimate - entrySize *entrySizeEstimate -} - -// scopes is a stack of variable name to integer id stack to handle scopes created by cel.bind() like macros -type scopes map[string][]*localVar - -func (s scopes) push(varName string, expr ast.Expr, path []string, size *SizeEstimate, entrySize *entrySizeEstimate) { - s[varName] = append(s[varName], &localVar{ - exprID: expr.ID(), - path: path, - size: size, - entrySize: entrySize, - }) -} - -func (s scopes) pop(varName string) { - varStack := s[varName] - s[varName] = varStack[:len(varStack)-1] -} - -func (s scopes) peek(varName string) (*localVar, bool) { - varStack := s[varName] - if len(varStack) > 0 { - return varStack[len(varStack)-1], true - } - return nil, false -} - -func (c *coster) pushIterKey(varName string, rangeExpr ast.Expr) { - entrySize := c.computeEntrySize(rangeExpr) - size := entrySize.keySize() - path := c.getPath(rangeExpr) - container := entrySize.container() - if container == types.UnknownKind { - container = c.getType(rangeExpr).Kind() - } - subpath := "@keys" - if container == types.ListKind { - subpath = "@indices" - } - c.localVars.push(varName, rangeExpr, append(path, subpath), size, nil) -} - -func (c *coster) pushIterValue(varName string, rangeExpr ast.Expr) { - entrySize := c.computeEntrySize(rangeExpr) - size := entrySize.valSize() - path := c.getPath(rangeExpr) - container := entrySize.container() - if container == types.UnknownKind { - container = c.getType(rangeExpr).Kind() - } - subpath := "@values" - if container == types.ListKind { - subpath = "@items" - } - c.localVars.push(varName, rangeExpr, append(path, subpath), size, nil) -} - -func (c *coster) pushIterSingle(varName string, rangeExpr ast.Expr) { - entrySize := c.computeEntrySize(rangeExpr) - size := entrySize.keySize() - subpath := "@keys" - container := entrySize.container() - if container == types.UnknownKind { - container = c.getType(rangeExpr).Kind() - } - if container == types.ListKind { - size = entrySize.valSize() - subpath = "@items" - } - path := c.getPath(rangeExpr) - c.localVars.push(varName, rangeExpr, append(path, subpath), size, nil) -} - -func (c *coster) pushLocalVar(varName string, e ast.Expr) { - path := c.getPath(e) - // note: retrieve the entry size for the local variable based on the size of the binding expression - // since the binding expression could be a list or map, the entry size should also be propagated - entrySize := c.computeEntrySize(e) - c.localVars.push(varName, e, path, c.computeSize(e), entrySize) -} - -func (c *coster) peekLocalVar(varName string) (*localVar, bool) { - return c.localVars.peek(varName) -} - -func (c *coster) popLocalVar(varName string) { - c.localVars.pop(varName) -} - -func (c *coster) cost(e ast.Expr) CostEstimate { - if e == nil { - return CostEstimate{} - } - var cost CostEstimate - switch e.Kind() { - case ast.LiteralKind: - cost = constCost - case ast.IdentKind: - cost = c.costIdent(e) - case ast.SelectKind: - cost = c.costSelect(e) - case ast.CallKind: - cost = c.costCall(e) - case ast.ListKind: - cost = c.costCreateList(e) - case ast.MapKind: - cost = c.costCreateMap(e) - case ast.StructKind: - cost = c.costCreateStruct(e) - case ast.ComprehensionKind: - if c.isBind(e) { - cost = c.costBind(e) - } else { - cost = c.costComprehension(e) - } - default: - return CostEstimate{} - } - return cost -} - -func (c *coster) costIdent(e ast.Expr) CostEstimate { - identName := e.AsIdent() - // build and track the field path - if v, ok := c.peekLocalVar(identName); ok { - c.addPath(e, v.path) - } else { - c.addPath(e, []string{identName}) - } - return selectAndIdentCost -} - -func (c *coster) costSelect(e ast.Expr) CostEstimate { - sel := e.AsSelect() - var sum CostEstimate - if sel.IsTestOnly() { - // recurse, but do not add any cost - // this is equivalent to how evalTestOnly increments the runtime cost counter - // but does not add any additional cost for the qualifier, except here we do - // the reverse (ident adds cost) - sum = sum.Add(c.presenceTestCost) - sum = sum.Add(c.cost(sel.Operand())) - return sum - } - sum = sum.Add(c.cost(sel.Operand())) - targetType := c.getType(sel.Operand()) - switch targetType.Kind() { - case types.MapKind, types.StructKind, types.TypeParamKind: - sum = sum.Add(selectAndIdentCost) - } - - // build and track the field path - c.addPath(e, append(c.getPath(sel.Operand()), sel.FieldName())) - return sum -} - -func (c *coster) costCall(e ast.Expr) CostEstimate { - // Dyn is just a way to disable type-checking, so return the cost of 1 with the cost of the argument - if dynEstimate := c.maybeUnwrapDynCall(e); dynEstimate != nil { - return *dynEstimate - } - - // Continue estimating the cost of all other calls. - call := e.AsCall() - args := call.Args() - var sum CostEstimate - - argTypes := make([]AstNode, len(args)) - argCosts := make([]CostEstimate, len(args)) - for i, arg := range args { - argCosts[i] = c.cost(arg) - argTypes[i] = c.newAstNode(arg) - } - - overloadIDs := c.checkedAST.GetOverloadIDs(e.ID()) - if len(overloadIDs) == 0 { - return CostEstimate{} - } - var targetType *AstNode - if call.IsMemberFunction() { - sum = sum.Add(c.cost(call.Target())) - var t AstNode = c.newAstNode(call.Target()) - targetType = &t - } - // Pick a cost estimate range that covers all the overload cost estimation ranges - fnCost := CostEstimate{Min: uint64(math.MaxUint64), Max: 0} - var resultSize *SizeEstimate - for _, overload := range overloadIDs { - overloadCost := c.functionCost(e, call.FunctionName(), overload, targetType, argTypes, argCosts) - fnCost = fnCost.Union(overloadCost.CostEstimate) - if overloadCost.ResultSize != nil { - if resultSize == nil { - resultSize = overloadCost.ResultSize - } else { - size := resultSize.Union(*overloadCost.ResultSize) - resultSize = &size - } - } - // build and track the field path for index operations - switch overload { - case overloads.IndexList: - if len(args) > 0 { - // note: assigning resultSize here could be redundant with the path-based lookup later - resultSize = c.computeEntrySize(args[0]).valSize() - c.addPath(e, append(c.getPath(args[0]), "@items")) - } - case overloads.IndexMap: - if len(args) > 0 { - resultSize = c.computeEntrySize(args[0]).valSize() - c.addPath(e, append(c.getPath(args[0]), "@values")) - } - } - if resultSize == nil { - resultSize = c.computeSize(e) - } - } - c.setSize(e, resultSize) - return sum.Add(fnCost) -} - -func (c *coster) maybeUnwrapDynCall(e ast.Expr) *CostEstimate { - call := e.AsCall() - if call.FunctionName() != "dyn" { - return nil - } - arg := call.Args()[0] - argCost := c.cost(arg) - c.copySizeEstimates(e, arg) - callCost := FixedCostEstimate(1).Add(argCost) - return &callCost -} - -func (c *coster) costCreateList(e ast.Expr) CostEstimate { - create := e.AsList() - var sum CostEstimate - itemSize := SizeEstimate{Min: math.MaxUint64, Max: 0} - if create.Size() == 0 { - itemSize.Min = 0 - } - for _, e := range create.Elements() { - sum = sum.Add(c.cost(e)) - is := c.sizeOrUnknown(e) - itemSize = itemSize.Union(is) - } - c.setEntrySize(e, &entrySizeEstimate{containerKind: types.ListKind, key: FixedSizeEstimate(1), val: itemSize}) - return sum.Add(createListBaseCost) -} - -func (c *coster) costCreateMap(e ast.Expr) CostEstimate { - mapVal := e.AsMap() - var sum CostEstimate - keySize := SizeEstimate{Min: math.MaxUint64, Max: 0} - valSize := SizeEstimate{Min: math.MaxUint64, Max: 0} - if mapVal.Size() == 0 { - valSize.Min = 0 - keySize.Min = 0 - } - for _, ent := range mapVal.Entries() { - entry := ent.AsMapEntry() - sum = sum.Add(c.cost(entry.Key())) - sum = sum.Add(c.cost(entry.Value())) - // Compute the key size range - ks := c.sizeOrUnknown(entry.Key()) - keySize = keySize.Union(ks) - // Compute the value size range - vs := c.sizeOrUnknown(entry.Value()) - valSize = valSize.Union(vs) - } - c.setEntrySize(e, &entrySizeEstimate{containerKind: types.MapKind, key: keySize, val: valSize}) - return sum.Add(createMapBaseCost) -} - -func (c *coster) costCreateStruct(e ast.Expr) CostEstimate { - msgVal := e.AsStruct() - var sum CostEstimate - for _, ent := range msgVal.Fields() { - field := ent.AsStructField() - sum = sum.Add(c.cost(field.Value())) - } - return sum.Add(createMessageBaseCost) -} - -func (c *coster) costComprehension(e ast.Expr) CostEstimate { - comp := e.AsComprehension() - var sum CostEstimate - sum = sum.Add(c.cost(comp.IterRange())) - sum = sum.Add(c.cost(comp.AccuInit())) - c.pushLocalVar(comp.AccuVar(), comp.AccuInit()) - - // Track the iterRange of each IterVar and AccuVar for field path construction - if comp.HasIterVar2() { - c.pushIterKey(comp.IterVar(), comp.IterRange()) - c.pushIterValue(comp.IterVar2(), comp.IterRange()) - } else { - c.pushIterSingle(comp.IterVar(), comp.IterRange()) - } - - // Determine the cost for each element in the loop - loopCost := c.cost(comp.LoopCondition()) - stepCost := c.cost(comp.LoopStep()) - - // Clear the intermediate variable tracking. - c.popLocalVar(comp.IterVar()) - if comp.HasIterVar2() { - c.popLocalVar(comp.IterVar2()) - } - - // Determine the result cost. - sum = sum.Add(c.cost(comp.Result())) - c.localVars.pop(comp.AccuVar()) - - // Estimate the cost of the loop. - rangeCnt := c.sizeOrUnknown(comp.IterRange()) - rangeCost := rangeCnt.MultiplyByCost(stepCost.Add(loopCost)) - sum = sum.Add(rangeCost) - - switch k := comp.AccuInit().Kind(); k { - case ast.LiteralKind: - c.setSize(e, c.computeSize(comp.AccuInit())) - case ast.ListKind, ast.MapKind: - c.setSize(e, &rangeCnt) - // For a step which produces a container value, it will have an entry size associated - // with its expression id. - if stepEntrySize := c.computeEntrySize(comp.LoopStep()); stepEntrySize != nil { - c.setEntrySize(e, stepEntrySize) - break - } - } - return sum -} - -func (c *coster) isBind(e ast.Expr) bool { - comp := e.AsComprehension() - iterRange := comp.IterRange() - loopCond := comp.LoopCondition() - return iterRange.Kind() == ast.ListKind && iterRange.AsList().Size() == 0 && - loopCond.Kind() == ast.LiteralKind && loopCond.AsLiteral() == types.False && - comp.AccuVar() != parser.AccumulatorName -} - -func (c *coster) costBind(e ast.Expr) CostEstimate { - comp := e.AsComprehension() - var sum CostEstimate - // Binds are lazily initialized, so we retain the cost of an empty iteration range. - sum = sum.Add(c.cost(comp.IterRange())) - sum = sum.Add(c.cost(comp.AccuInit())) - - c.pushLocalVar(comp.AccuVar(), comp.AccuInit()) - sum = sum.Add(c.cost(comp.Result())) - c.popLocalVar(comp.AccuVar()) - - // Associate the bind output size with the result size. - c.copySizeEstimates(e, comp.Result()) - return sum -} - -func (c *coster) functionCost(e ast.Expr, function, overloadID string, target *AstNode, args []AstNode, argCosts []CostEstimate) CallEstimate { - argCostSum := func() CostEstimate { - var sum CostEstimate - for _, a := range argCosts { - sum = sum.Add(a) - } - return sum - } - if len(c.overloadEstimators) != 0 { - if estimator, found := c.overloadEstimators[overloadID]; found { - if est := estimator(c.estimator, target, args); est != nil { - callEst := *est - return CallEstimate{CostEstimate: callEst.Add(argCostSum()), ResultSize: est.ResultSize} - } - } - } - if est := c.estimator.EstimateCallCost(function, overloadID, target, args); est != nil { - callEst := *est - return CallEstimate{CostEstimate: callEst.Add(argCostSum()), ResultSize: est.ResultSize} - } - switch overloadID { - // O(n) functions - case overloads.ExtFormatString: - if target != nil { - // ResultSize not calculated because we can't bound the max size. - return CallEstimate{ - CostEstimate: c.sizeOrUnknown(*target).MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum())} - } - case overloads.StringToBytes: - if len(args) == 1 { - sz := c.sizeOrUnknown(args[0]) - // ResultSize max is when each char converts to 4 bytes. - return CallEstimate{ - CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), - ResultSize: &SizeEstimate{Min: sz.Min, Max: sz.Max * 4}} - } - case overloads.BytesToString: - if len(args) == 1 { - sz := c.sizeOrUnknown(args[0]) - // ResultSize min is when 4 bytes convert to 1 char. - return CallEstimate{ - CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), - ResultSize: &SizeEstimate{Min: sz.Min / 4, Max: sz.Max}} - } - case overloads.ExtQuoteString: - if len(args) == 1 { - sz := c.sizeOrUnknown(args[0]) - // ResultSize max is when each char is escaped. 2 quote chars always added. - return CallEstimate{ - CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), - ResultSize: &SizeEstimate{Min: sz.Min + 2, Max: sz.Max*2 + 2}} - } - case overloads.StartsWithString, overloads.EndsWithString: - if len(args) == 1 { - return CallEstimate{CostEstimate: c.sizeOrUnknown(args[0]).MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum())} - } - case overloads.InList: - // If a list is composed entirely of constant values this is O(1), but we don't account for that here. - // We just assume all list containment checks are O(n). - if len(args) == 2 { - return CallEstimate{CostEstimate: c.sizeOrUnknown(args[1]).MultiplyByCostFactor(1).Add(argCostSum())} - } - // O(nm) functions - case overloads.Matches, overloads.MatchesString: - // https://swtch.com/~rsc/regexp/regexp1.html applies to RE2 implementation supported by CEL - var strNode, regexNode AstNode - if overloadID == overloads.MatchesString && target != nil && len(args) == 1 { - strNode = *target - regexNode = args[0] - } else if overloadID == overloads.Matches && target == nil && len(args) == 2 { - strNode = args[0] - regexNode = args[1] - } - if strNode != nil && regexNode != nil { - // Add one to string length for purposes of cost calculation to prevent product of string and regex to be 0 - // in case where string is empty but regex is still expensive. - strCost := c.sizeOrUnknown(strNode).Add(SizeEstimate{Min: 1, Max: 1}).MultiplyByCostFactor(common.StringTraversalCostFactor) - // We don't know how many expressions are in the regex, just the string length (a huge - // improvement here would be to somehow get a count the number of expressions in the regex or - // how many states are in the regex state machine and use that to measure regex cost). - // For now, we're making a guess that each expression in a regex is typically at least 4 chars - // in length. - regexCost := c.sizeOrUnknown(regexNode).MultiplyByCostFactor(common.RegexStringLengthCostFactor) - return CallEstimate{CostEstimate: strCost.Multiply(regexCost).Add(argCostSum())} - } - case overloads.ContainsString: - if target != nil && len(args) == 1 { - strCost := c.sizeOrUnknown(*target).MultiplyByCostFactor(common.StringTraversalCostFactor) - substrCost := c.sizeOrUnknown(args[0]).MultiplyByCostFactor(common.StringTraversalCostFactor) - return CallEstimate{CostEstimate: strCost.Multiply(substrCost).Add(argCostSum())} - } - case overloads.LogicalOr, overloads.LogicalAnd: - lhs := argCosts[0] - rhs := argCosts[1] - // min cost is min of LHS for short circuited && or || - argCost := CostEstimate{Min: lhs.Min, Max: lhs.Add(rhs).Max} - return CallEstimate{CostEstimate: argCost} - case overloads.Conditional: - size := c.sizeOrUnknown(args[1]).Union(c.sizeOrUnknown(args[2])) - resultEntrySize := c.computeEntrySize(args[1].Expr()).union(c.computeEntrySize(args[2].Expr())) - c.setEntrySize(e, resultEntrySize) - conditionalCost := argCosts[0] - ifTrueCost := argCosts[1] - ifFalseCost := argCosts[2] - argCost := conditionalCost.Add(ifTrueCost.Union(ifFalseCost)) - return CallEstimate{CostEstimate: argCost, ResultSize: &size} - case overloads.AddString, overloads.AddBytes, overloads.AddList: - if len(args) == 2 { - lhsSize := c.sizeOrUnknown(args[0]) - rhsSize := c.sizeOrUnknown(args[1]) - resultSize := lhsSize.Add(rhsSize) - rhsEntrySize := c.computeEntrySize(args[0].Expr()) - lhsEntrySize := c.computeEntrySize(args[1].Expr()) - resultEntrySize := rhsEntrySize.union(lhsEntrySize) - if resultEntrySize != nil { - c.setEntrySize(e, resultEntrySize) - } - switch overloadID { - case overloads.AddList: - // list concatenation is O(1), but we handle it here to track size - return CallEstimate{CostEstimate: FixedCostEstimate(1).Add(argCostSum()), ResultSize: &resultSize} - default: - return CallEstimate{CostEstimate: resultSize.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), ResultSize: &resultSize} - } - } - case overloads.LessString, overloads.GreaterString, overloads.LessEqualsString, overloads.GreaterEqualsString, - overloads.LessBytes, overloads.GreaterBytes, overloads.LessEqualsBytes, overloads.GreaterEqualsBytes, - overloads.Equals, overloads.NotEquals: - lhsCost := c.sizeOrUnknown(args[0]) - rhsCost := c.sizeOrUnknown(args[1]) - min := uint64(0) - smallestMax := lhsCost.Max - if rhsCost.Max < smallestMax { - smallestMax = rhsCost.Max - } - if smallestMax > 0 { - min = 1 - } - // equality of 2 scalar values results in a cost of 1 - return CallEstimate{ - CostEstimate: CostEstimate{Min: min, Max: smallestMax}.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), - } - } - // O(1) functions - // See CostTracker.costCall for more details about O(1) cost calculations - - // Benchmarks suggest that most of the other operations take +/- 50% of a base cost unit - // which on an Intel xeon 2.20GHz CPU is 50ns. - return CallEstimate{CostEstimate: FixedCostEstimate(1).Add(argCostSum())} -} - -func (c *coster) getType(e ast.Expr) *types.Type { - return c.checkedAST.GetType(e.ID()) -} - -func (c *coster) getPath(e ast.Expr) []string { - if e.Kind() == ast.IdentKind { - if v, found := c.peekLocalVar(e.AsIdent()); found { - return v.path[:] - } - } - return c.exprPaths[e.ID()][:] -} - -func (c *coster) addPath(e ast.Expr, path []string) { - c.exprPaths[e.ID()] = path -} - -func isAccumulatorVar(name string) bool { - return name == parser.AccumulatorName || name == parser.HiddenAccumulatorName -} - -func (c *coster) newAstNode(e ast.Expr) *astNode { - path := c.getPath(e) - if len(path) > 0 && isAccumulatorVar(path[0]) { - // only provide paths to root vars; omit accumulator vars - path = nil - } - return &astNode{ - path: path, - t: c.getType(e), - expr: e, - derivedSize: c.computeSize(e)} -} - -func (c *coster) setSize(e ast.Expr, size *SizeEstimate) { - if size == nil { - return - } - // Store the computed size with the expression - c.computedSizes[e.ID()] = *size -} - -func (c *coster) sizeOrUnknown(node any) SizeEstimate { - switch v := node.(type) { - case ast.Expr: - if sz := c.computeSize(v); sz != nil { - return *sz - } - case AstNode: - if sz := v.ComputedSize(); sz != nil { - return *sz - } - } - return UnknownSizeEstimate() -} - -func (c *coster) copySizeEstimates(dst, src ast.Expr) { - c.setSize(dst, c.computeSize(src)) - c.setEntrySize(dst, c.computeEntrySize(src)) -} - -func (c *coster) computeSize(e ast.Expr) *SizeEstimate { - if size, ok := c.computedSizes[e.ID()]; ok { - return &size - } - if size := computeExprSize(e); size != nil { - return size - } - // Ensure size estimates are computed first as users may choose to override the costs that - // CEL would otherwise ascribe to the type. - node := astNode{expr: e, path: c.getPath(e), t: c.getType(e)} - if size := c.estimator.EstimateSize(node); size != nil { - // storing the computed size should reduce calls to EstimateSize() - c.computedSizes[e.ID()] = *size - return size - } - if size := computeTypeSize(c.getType(e)); size != nil { - return size - } - if e.Kind() == ast.IdentKind { - varName := e.AsIdent() - if v, ok := c.peekLocalVar(varName); ok && v.size != nil { - return v.size - } - } - return nil -} - -func (c *coster) setEntrySize(e ast.Expr, size *entrySizeEstimate) { - if size == nil { - return - } - c.computedEntrySizes[e.ID()] = *size -} - -func (c *coster) computeEntrySize(e ast.Expr) *entrySizeEstimate { - if sz, found := c.computedEntrySizes[e.ID()]; found { - return &sz - } - if e.Kind() == ast.IdentKind { - varName := e.AsIdent() - if v, ok := c.peekLocalVar(varName); ok && v.entrySize != nil { - return v.entrySize - } - } - return nil -} - -func computeExprSize(expr ast.Expr) *SizeEstimate { - var v uint64 - switch expr.Kind() { - case ast.LiteralKind: - switch ck := expr.AsLiteral().(type) { - case types.String: - // converting to runes here is an O(n) operation, but - // this is consistent with how size is computed at runtime, - // and how the language definition defines string size - v = uint64(len([]rune(ck))) - case types.Bytes: - v = uint64(len(ck)) - case types.Bool, types.Double, types.Duration, - types.Int, types.Timestamp, types.Uint, - types.Null: - v = uint64(1) - default: - return nil - } - case ast.ListKind: - v = uint64(expr.AsList().Size()) - case ast.MapKind: - v = uint64(expr.AsMap().Size()) - default: - return nil - } - cost := FixedSizeEstimate(v) - return &cost -} - -func computeTypeSize(t *types.Type) *SizeEstimate { - if isScalar(t) { - cost := FixedSizeEstimate(1) - return &cost - } - return nil -} - -// isScalar returns true if the given type is known to be of a constant size at -// compile time. isScalar will return false for strings (they are variable-width) -// in addition to protobuf.Any and protobuf.Value (their size is not knowable at compile time). -func isScalar(t *types.Type) bool { - switch t.Kind() { - case types.BoolKind, types.DoubleKind, types.DurationKind, types.IntKind, types.TimestampKind, types.UintKind: - return true - case types.OpaqueKind: - if t.TypeName() == "optional_type" { - return isScalar(t.Parameters()[0]) - } - } - return false -} - -var ( - doubleTwoTo64 = math.Ldexp(1.0, 64) - - unknownSizeEstimate = SizeEstimate{Min: 0, Max: math.MaxUint64} - unknownCostEstimate = unknownSizeEstimate.MultiplyByCostFactor(1) - - selectAndIdentCost = FixedCostEstimate(common.SelectAndIdentCost) - constCost = FixedCostEstimate(common.ConstCost) - - createListBaseCost = FixedCostEstimate(common.ListCreateBaseCost) - createMapBaseCost = FixedCostEstimate(common.MapCreateBaseCost) - createMessageBaseCost = FixedCostEstimate(common.StructCreateBaseCost) -) diff --git a/vendor/github.com/google/cel-go/common/env/io.go b/vendor/github.com/google/cel-go/common/env/io.go deleted file mode 100644 index ec126f9ce6..0000000000 --- a/vendor/github.com/google/cel-go/common/env/io.go +++ /dev/null @@ -1,271 +0,0 @@ -// Copyright 2026 Google LLC -// -// 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 env - -import ( - "errors" - "fmt" - - "go.yaml.in/yaml/v3" -) - -type internalTypeDesc struct { - TypeName string `yaml:"type_name"` - Params []*TypeDesc `yaml:"params,omitempty"` - IsTypeParam bool `yaml:"is_type_param,omitempty"` -} - -// Embedding TypeDesc in variable causes issues with customizing -// unmarshalling / marshalling. Work around with a parallel type. -type internalVariable struct { - Name string `yaml:"name"` - Description string `yaml:"description,omitempty"` - - // Type represents the type declaration for the variable. - Type *TypeDesc `yaml:"type,omitempty"` - - TypeName string `yaml:"type_name"` - Params []*TypeDesc `yaml:"params,omitempty"` - IsTypeParam bool `yaml:"is_type_param,omitempty"` -} - -// UnmarshalYAML implements yaml.Unmarshal -func (v *Variable) UnmarshalYAML(n *yaml.Node) error { - buf := internalVariable{} - err := n.Decode(&buf) - if err != nil { - return err - } - v.Name = buf.Name - v.Description = buf.Description - if buf.TypeName != "" { - v.TypeDesc = &TypeDesc{ - TypeName: buf.TypeName, - Params: buf.Params, - IsTypeParam: buf.IsTypeParam, - } - } else if buf.Type != nil { - v.TypeDesc = buf.Type - } - return nil -} - -// MarshalYAML implements yaml.Marshaler -func (v *Variable) MarshalYAML() (any, error) { - // The presence of an unmarshaller alters the default marshaller behavior so - // provide a simple marshal implementation. - buf := internalVariable{ - Name: v.Name, - Description: v.Description, - } - if t := v.GetType(); t != nil { - buf.TypeName = t.TypeName - buf.Params = t.Params - buf.IsTypeParam = t.IsTypeParam - } - return &buf, nil -} - -// UnmarshalYAML implements yaml.Unmarshaler -func (td *TypeDesc) UnmarshalYAML(n *yaml.Node) error { - if td == nil { - return fmt.Errorf("unexpected Unmarshal for TypeDesc at: %d", n.Line) - } - if n.Kind == yaml.ScalarNode { - o, err := ParseTypeDesc(n.Value) - if err != nil { - return err - } - *td = *o - return nil - } - - if n.Kind != yaml.MappingNode { - return errors.New("unsupported yaml for TypeDesc") - } - - buf := internalTypeDesc{} - err := n.Decode(&buf) - if err != nil { - return err - } - td.TypeName = buf.TypeName - td.Params = buf.Params - td.IsTypeParam = buf.IsTypeParam - return nil -} - -type typeDescParser struct { - text string - pos int - length int -} - -// ParseTypeDesc parses a TypeDesc from the type specifier format: "map" -func ParseTypeDesc(text string) (*TypeDesc, error) { - p := &typeDescParser{text: text, length: len(text)} - res, err := p.parseTypeElem() - if err != nil { - return nil, fmt.Errorf("failed to parse type %q: %v", text, err) - } - p.skipWhitespace() - if p.pos < p.length { - return nil, fmt.Errorf("unexpected character %q at position %d in %q", p.text[p.pos], p.pos, text) - } - return res, nil -} - -func (p *typeDescParser) parseConcreteType() (*TypeDesc, error) { - id, err := p.parseNamespaceIdentifier() - if err != nil { - return nil, err - } - if p.pos < p.length && p.text[p.pos] == '<' { - p.pos++ // consume '<' - var params []*TypeDesc - for { - p.skipWhitespace() - param, err := p.parseTypeElem() - if err != nil { - return nil, err - } - params = append(params, param) - p.skipWhitespace() - if p.pos < p.length && p.text[p.pos] == ',' { - p.pos++ // consume ',' - continue - } - if p.pos < p.length && p.text[p.pos] == '>' { - p.pos++ // consume '>' - break - } - return nil, fmt.Errorf("expected ',' or '>' at position %d", p.pos) - } - return NewTypeDesc(id, params...), nil - } - return NewTypeDesc(id), nil -} - -func (p *typeDescParser) parseTypeElem() (*TypeDesc, error) { - p.skipWhitespace() - if p.pos < p.length && p.text[p.pos] == '~' { - p.pos++ // consume '~' - id, err := p.parseTypeParamIdent() - if err != nil { - return nil, err - } - return NewTypeParam(id), nil - } - return p.parseConcreteType() -} - -func (p *typeDescParser) parseNamespaceIdentifier() (string, error) { - p.skipWhitespace() - var id string - for p.pos < p.length && p.text[p.pos] != '<' { - c := p.text[p.pos] - if c == '.' { - id += "." - p.pos++ // consume '.' - } - ident, err := p.parseIdentifier() - if err != nil { - return "", err - } - id += ident - p.skipWhitespace() - if p.pos < p.length && p.text[p.pos] != '.' { - break - } - } - if id == "" { - return "", fmt.Errorf("missing identifier at position %d", p.pos) - } - return id, nil -} - -func (p *typeDescParser) parseIdentifier() (string, error) { - p.skipWhitespace() - if p.pos >= p.length { - return "", fmt.Errorf("unexpected end of input") - } - start := p.pos - c := p.text[p.pos] - if !isAlpha(c) && c != '_' { - return "", fmt.Errorf("identifier is expected, but %q was found at position %d", c, p.pos) - } - p.pos++ - for p.pos < p.length { - c := p.text[p.pos] - if !isAlphaNumeric(c) && c != '_' { - break - } - p.pos++ - } - return p.text[start:p.pos], nil -} - -func (p *typeDescParser) parseTypeParamIdent() (string, error) { - p.skipWhitespace() - if p.pos >= p.length { - return "", fmt.Errorf("unexpected end of input") - } - c := p.text[p.pos] - if !isAlpha(c) { - return "", fmt.Errorf("invalid type parameter identifier %q at position %d, must be a single character from A-Z", c, p.pos) - } - p.pos++ - if p.pos < p.length && isAlpha(p.text[p.pos]) { - return "", fmt.Errorf("invalid type param, must have a single alphabetic character at position %d", p.pos) - } - return string(c), nil -} - -func (p *typeDescParser) skipWhitespace() { - for p.pos < p.length && p.text[p.pos] == ' ' { - p.pos++ - } -} - -func isAlpha(c byte) bool { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') -} - -func isAlphaNumeric(c byte) bool { - return isAlpha(c) || (c >= '0' && c <= '9') -} - -// ConfigFromYAML returns a config from YAML source. -// -// Adds custom parsing logic for normalizing shorthand for specifiying some fields -// in a YAML document (mainly the type-specifier shorthand). -// -// Using yaml.Unmarshal with any implementation should be sufficient for most -// cases. -func ConfigFromYAML(data []byte) (*Config, error) { - c := &Config{} - e := yaml.Unmarshal(data, c) - if e != nil { - return nil, e - } - return c, nil -} - -// ConfigToYAML returns the config serialized to YAML -// -// Provided as a convenience wrapper around a tested YAML Marshaler. -func ConfigToYAML(c *Config) ([]byte, error) { - return yaml.Marshal(c) -} diff --git a/vendor/github.com/google/cel-go/common/types/list.go b/vendor/github.com/google/cel-go/common/types/list.go deleted file mode 100644 index 028770ed68..0000000000 --- a/vendor/github.com/google/cel-go/common/types/list.go +++ /dev/null @@ -1,593 +0,0 @@ -// Copyright 2018 Google LLC -// -// 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 types - -import ( - "fmt" - "reflect" - "strings" - - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" - - anypb "google.golang.org/protobuf/types/known/anypb" - structpb "google.golang.org/protobuf/types/known/structpb" -) - -// NewDynamicList returns a traits.Lister with heterogenous elements. -// value should be an array of "native" types, i.e. any type that -// NativeToValue() can convert to a ref.Val. -func NewDynamicList(adapter Adapter, value any) traits.Lister { - refValue := reflect.ValueOf(value) - return &baseList{ - Adapter: adapter, - value: value, - size: refValue.Len(), - get: func(i int) any { - return refValue.Index(i).Interface() - }, - } -} - -// NewStringList returns a traits.Lister containing only strings. -func NewStringList(adapter Adapter, elems []string) traits.Lister { - return &baseList{ - Adapter: adapter, - value: elems, - size: len(elems), - get: func(i int) any { return elems[i] }, - } -} - -// NewRefValList returns a traits.Lister with ref.Val elements. -// -// This type specialization is used with list literals within CEL expressions. -func NewRefValList(adapter Adapter, elems []ref.Val) traits.Lister { - return &baseList{ - Adapter: adapter, - value: elems, - size: len(elems), - get: func(i int) any { return elems[i] }, - } -} - -// NewProtoList returns a traits.Lister based on a pb.List instance. -func NewProtoList(adapter Adapter, list protoreflect.List) traits.Lister { - return &baseList{ - Adapter: adapter, - value: list, - size: list.Len(), - get: func(i int) any { return list.Get(i).Interface() }, - } -} - -// NewJSONList returns a traits.Lister based on structpb.ListValue instance. -func NewJSONList(adapter Adapter, l *structpb.ListValue) traits.Lister { - vals := l.GetValues() - return &baseList{ - Adapter: adapter, - value: l, - size: len(vals), - get: func(i int) any { return vals[i] }, - } -} - -// NewMutableList creates a new mutable list whose internal state can be modified. -func NewMutableList(adapter Adapter) traits.MutableLister { - var mutableValues []ref.Val - l := &mutableList{ - baseList: &baseList{ - Adapter: adapter, - value: mutableValues, - size: 0, - }, - mutableValues: mutableValues, - } - l.get = func(i int) any { - return l.mutableValues[i] - } - return l -} - -// baseList points to a list containing elements of any type. -// The `value` is an array of native values, and refValue is its reflection object. -// The `Adapter` enables native type to CEL type conversions. -type baseList struct { - Adapter - value any - - // size indicates the number of elements within the list. - // Since objects are immutable the size of a list is static. - size int - - // get returns a value at the specified integer index. - // The index is guaranteed to be checked against the list index range. - get func(int) any -} - -// Add implements the traits.Adder interface method. -func (l *baseList) Add(other ref.Val) ref.Val { - otherList, ok := other.(traits.Lister) - if !ok { - return MaybeNoSuchOverloadErr(other) - } - return newConcatList(l.Adapter, l, otherList) -} - -// Contains implements the traits.Container interface method. -func (l *baseList) Contains(elem ref.Val) ref.Val { - for i := 0; i < l.size; i++ { - val := l.NativeToValue(l.get(i)) - cmp := elem.Equal(val) - b, ok := cmp.(Bool) - if ok && b == True { - return True - } - } - return False -} - -// ConvertToNative implements the ref.Val interface method. -func (l *baseList) ConvertToNative(typeDesc reflect.Type) (any, error) { - if typeDesc == reflect.TypeFor[any]() { - typeDesc = reflect.TypeFor[[]any]() - } - // If the underlying list value is assignable to the reflected type return it. - if reflect.TypeOf(l.value).AssignableTo(typeDesc) { - return l.value, nil - } - // If the list wrapper is assignable to the desired type return it. - if reflect.TypeOf(l).AssignableTo(typeDesc) { - return l, nil - } - // Attempt to convert the list to a set of well known protobuf types. - switch typeDesc { - case anyValueType: - json, err := l.ConvertToNative(JSONListType) - if err != nil { - return nil, err - } - return anypb.New(json.(proto.Message)) - case JSONValueType, JSONListType: - jsonValues, err := - l.ConvertToNative(reflect.TypeOf([]*structpb.Value{})) - if err != nil { - return nil, err - } - jsonList := &structpb.ListValue{Values: jsonValues.([]*structpb.Value)} - if typeDesc == JSONListType { - return jsonList, nil - } - return structpb.NewListValue(jsonList), nil - } - // Non-list conversion. - if typeDesc.Kind() != reflect.Slice && typeDesc.Kind() != reflect.Array { - return nil, fmt.Errorf("type conversion error from list to '%v'", typeDesc) - } - - // List conversion. - // Allow the element ConvertToNative() function to determine whether conversion is possible. - otherElemType := typeDesc.Elem() - elemCount := l.size - var nativeList reflect.Value - if typeDesc.Kind() == reflect.Array { - nativeList = reflect.New(reflect.ArrayOf(elemCount, typeDesc)).Elem().Index(0) - } else { - nativeList = reflect.MakeSlice(typeDesc, elemCount, elemCount) - - } - for i := 0; i < elemCount; i++ { - elem := l.NativeToValue(l.get(i)) - nativeElemVal, err := elem.ConvertToNative(otherElemType) - if err != nil { - return nil, err - } - nativeList.Index(i).Set(reflect.ValueOf(nativeElemVal)) - } - return nativeList.Interface(), nil -} - -// ConvertToType implements the ref.Val interface method. -func (l *baseList) ConvertToType(typeVal ref.Type) ref.Val { - switch typeVal { - case ListType: - return l - case TypeType: - return ListType - } - return NewErr("type conversion error from '%s' to '%s'", ListType, typeVal) -} - -// Equal implements the ref.Val interface method. -func (l *baseList) Equal(other ref.Val) ref.Val { - otherList, ok := other.(traits.Lister) - if !ok { - return False - } - if l.Size() != otherList.Size() { - return False - } - for i := IntZero; i < l.Size().(Int); i++ { - thisElem := l.Get(i) - otherElem := otherList.Get(i) - elemEq := Equal(thisElem, otherElem) - if elemEq == False { - return False - } - } - return True -} - -// Get implements the traits.Indexer interface method. -func (l *baseList) Get(index ref.Val) ref.Val { - ind, err := IndexOrError(index) - if err != nil { - return ValOrErr(index, "%v", err) - } - if ind < 0 || ind >= l.size { - return NewErr("index '%d' out of range in list size '%d'", ind, l.Size()) - } - return l.NativeToValue(l.get(ind)) -} - -// IsZeroValue returns true if the list is empty. -func (l *baseList) IsZeroValue() bool { - return l.size == 0 -} - -// Fold calls the FoldEntry method for each (index, value) pair in the list. -func (l *baseList) Fold(f traits.Folder) { - for i := 0; i < l.size; i++ { - if !f.FoldEntry(i, l.get(i)) { - break - } - } -} - -// Iterator implements the traits.Iterable interface method. -func (l *baseList) Iterator() traits.Iterator { - return newListIterator(l) -} - -// Size implements the traits.Sizer interface method. -func (l *baseList) Size() ref.Val { - return Int(l.size) -} - -// Type implements the ref.Val interface method. -func (l *baseList) Type() ref.Type { - return ListType -} - -// Value implements the ref.Val interface method. -func (l *baseList) Value() any { - return l.value -} - -// String converts the list to a human readable string form. -func (l *baseList) String() string { - var sb strings.Builder - sb.WriteString("[") - for i := 0; i < l.size; i++ { - sb.WriteString(fmt.Sprintf("%v", l.get(i))) - if i != l.size-1 { - sb.WriteString(", ") - } - } - sb.WriteString("]") - return sb.String() -} - -func formatList(l traits.Lister, sb *strings.Builder) { - sb.WriteString("[") - n, _ := l.Size().(Int) - for i := 0; i < int(n); i++ { - formatTo(sb, l.Get(Int(i))) - if i != int(n)-1 { - sb.WriteString(", ") - } - } - sb.WriteString("]") -} - -func (l *baseList) format(sb *strings.Builder) { - formatList(l, sb) -} - -// mutableList aggregates values into its internal storage. For use with internal CEL variables only. -type mutableList struct { - *baseList - mutableValues []ref.Val -} - -// Add copies elements from the other list into the internal storage of the mutable list. -// The ref.Val returned by Add is the receiver. -func (l *mutableList) Add(other ref.Val) ref.Val { - switch otherList := other.(type) { - case *mutableList: - l.mutableValues = append(l.mutableValues, otherList.mutableValues...) - l.size += len(otherList.mutableValues) - case traits.Lister: - for i := IntZero; i < otherList.Size().(Int); i++ { - l.size++ - l.mutableValues = append(l.mutableValues, otherList.Get(i)) - } - default: - return MaybeNoSuchOverloadErr(otherList) - } - return l -} - -// ToImmutableList returns an immutable list based on the internal storage of the mutable list. -func (l *mutableList) ToImmutableList() traits.Lister { - // The reference to internal state is guaranteed to be safe as this call is only performed - // when mutations have been completed. - return NewRefValList(l.Adapter, l.mutableValues) -} - -// concatList combines two list implementations together into a view. -// The `Adapter` enables native type to CEL type conversions. -type concatList struct { - Adapter - value any - prevList traits.Lister - nextList traits.Lister - cachedSize ref.Val -} - -func newConcatList(adapter Adapter, prevList, nextList traits.Lister) ref.Val { - prevSize := prevList.Size().(Int) - nextSize := nextList.Size().(Int) - if prevSize == IntZero { - return nextList.(ref.Val) - } - if nextSize == IntZero { - return prevList.(ref.Val) - } - return &concatList{ - Adapter: adapter, - prevList: prevList, - nextList: nextList, - cachedSize: prevSize.Add(nextSize), - } -} - -// Add implements the traits.Adder interface method. -func (l *concatList) Add(other ref.Val) ref.Val { - otherList, ok := other.(traits.Lister) - if !ok { - return MaybeNoSuchOverloadErr(other) - } - return newConcatList(l.Adapter, l, otherList) -} - -// Contains implements the traits.Container interface method. -func (l *concatList) Contains(elem ref.Val) ref.Val { - // The concat list relies on the IsErrorOrUnknown checks against the input element to be - // performed by the `prevList` and/or `nextList`. - prev := l.prevList.Contains(elem) - // Short-circuit the return if the elem was found in the prev list. - if prev == True { - return prev - } - // Return if the elem was found in the next list. - next := l.nextList.Contains(elem) - if next == True { - return next - } - // Handle the case where an error or unknown was encountered before checking next. - if IsUnknownOrError(prev) { - return prev - } - // Otherwise, rely on the next value as the representative result. - return next -} - -// ConvertToNative implements the ref.Val interface method. -func (l *concatList) ConvertToNative(typeDesc reflect.Type) (any, error) { - combined := NewDynamicList(l.Adapter, l.Value().([]any)) - return combined.ConvertToNative(typeDesc) -} - -// ConvertToType implements the ref.Val interface method. -func (l *concatList) ConvertToType(typeVal ref.Type) ref.Val { - switch typeVal { - case ListType: - return l - case TypeType: - return ListType - } - return NewErr("type conversion error from '%s' to '%s'", ListType, typeVal) -} - -// Equal implements the ref.Val interface method. -func (l *concatList) Equal(other ref.Val) ref.Val { - otherList, ok := other.(traits.Lister) - if !ok { - return False - } - if l.Size() != otherList.Size() { - return False - } - var maybeErr ref.Val - for i := IntZero; i < l.Size().(Int); i++ { - thisElem := l.Get(i) - otherElem := otherList.Get(i) - elemEq := Equal(thisElem, otherElem) - if elemEq == False { - return False - } - if maybeErr == nil && IsUnknownOrError(elemEq) { - maybeErr = elemEq - } - } - if maybeErr != nil { - return maybeErr - } - return True -} - -// Get implements the traits.Indexer interface method. -func (l *concatList) Get(index ref.Val) ref.Val { - ind, err := IndexOrError(index) - if err != nil { - return ValOrErr(index, "%v", err) - } - i := Int(ind) - if i < l.prevList.Size().(Int) { - return l.prevList.Get(i) - } - offset := i - l.prevList.Size().(Int) - return l.nextList.Get(offset) -} - -// IsZeroValue returns true if the list is empty. -func (l *concatList) IsZeroValue() bool { - return l.Size().(Int) == 0 -} - -// Fold calls the FoldEntry method for each (index, value) pair in the list. -func (l *concatList) Fold(f traits.Folder) { - for i := Int(0); i < l.Size().(Int); i++ { - if !f.FoldEntry(i, l.Get(i)) { - break - } - } -} - -// Iterator implements the traits.Iterable interface method. -func (l *concatList) Iterator() traits.Iterator { - return newListIterator(l) -} - -// Size implements the traits.Sizer interface method. -func (l *concatList) Size() ref.Val { - return l.cachedSize -} - -// String converts the concatenated list to a human-readable string. -func (l *concatList) String() string { - var sb strings.Builder - sb.WriteString("[") - for i := Int(0); i < l.Size().(Int); i++ { - sb.WriteString(fmt.Sprintf("%v", l.Get(i))) - if i != l.Size().(Int)-1 { - sb.WriteString(", ") - } - } - sb.WriteString("]") - return sb.String() -} - -// Type implements the ref.Val interface method. -func (l *concatList) Type() ref.Type { - return ListType -} - -// Value implements the ref.Val interface method. -func (l *concatList) Value() any { - if l.value == nil { - merged := make([]any, l.Size().(Int)) - prevLen := l.prevList.Size().(Int) - for i := Int(0); i < prevLen; i++ { - merged[i] = l.prevList.Get(i).Value() - } - nextLen := l.nextList.Size().(Int) - for j := Int(0); j < nextLen; j++ { - merged[prevLen+j] = l.nextList.Get(j).Value() - } - l.value = merged - } - return l.value -} - -func newListIterator(listValue traits.Lister) traits.Iterator { - return &listIterator{ - listValue: listValue, - len: listValue.Size().(Int), - } -} - -type listIterator struct { - *baseIterator - listValue traits.Lister - cursor Int - len Int -} - -// HasNext implements the traits.Iterator interface method. -func (it *listIterator) HasNext() ref.Val { - return Bool(it.cursor < it.len) -} - -// Next implements the traits.Iterator interface method. -func (it *listIterator) Next() ref.Val { - if it.HasNext() == True { - index := it.cursor - it.cursor++ - return it.listValue.Get(index) - } - return nil -} - -// IndexOrError converts an input index value into either a lossless integer index or an error. -func IndexOrError(index ref.Val) (int, error) { - switch iv := index.(type) { - case Int: - return int(iv), nil - case Double: - if ik, ok := doubleToInt64Lossless(float64(iv)); ok { - return int(ik), nil - } - return -1, fmt.Errorf("unsupported index value %v in list", index) - case Uint: - if ik, ok := uint64ToInt64Lossless(uint64(iv)); ok { - return int(ik), nil - } - return -1, fmt.Errorf("unsupported index value %v in list", index) - default: - return -1, fmt.Errorf("unsupported index type '%s' in list", index.Type()) - } -} - -// ToFoldableList will create a Foldable version of a list suitable for key-value pair iteration. -// -// For values which are already Foldable, this call is a no-op. For all other values, the fold is -// driven via the Size() and Get() calls which means that the folding will function, but take a -// performance hit. -func ToFoldableList(l traits.Lister) traits.Foldable { - if f, ok := l.(traits.Foldable); ok { - return f - } - return interopFoldableList{Lister: l} -} - -type interopFoldableList struct { - traits.Lister -} - -// Fold implements the traits.Foldable interface method and performs an iteration over the -// range of elements of the list. -func (l interopFoldableList) Fold(f traits.Folder) { - sz := l.Size().(Int) - for i := Int(0); i < sz; i++ { - if !f.FoldEntry(i, l.Get(i)) { - break - } - } -} diff --git a/vendor/github.com/google/cel-go/common/types/native.go b/vendor/github.com/google/cel-go/common/types/native.go deleted file mode 100644 index 33c897b430..0000000000 --- a/vendor/github.com/google/cel-go/common/types/native.go +++ /dev/null @@ -1,583 +0,0 @@ -// Copyright 2022 Google LLC -// -// 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 me. -// limitations under the License. - -package types - -import ( - "errors" - "fmt" - "reflect" - "strings" - "time" - - "google.golang.org/protobuf/reflect/protoreflect" - - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" - - structpb "google.golang.org/protobuf/types/known/structpb" -) - -var ( - nativeObjTraitMask = traits.FieldTesterType | traits.IndexerType - jsonValueType = reflect.TypeFor[*structpb.Value]() - jsonStructType = reflect.TypeFor[*structpb.Struct]() - - pbMsgInterfaceType = reflect.TypeFor[protoreflect.ProtoMessage]() - refValType = reflect.TypeFor[ref.Val]() - timestampType = reflect.TypeFor[time.Time]() - durationType = reflect.TypeFor[time.Duration]() - - errDuplicatedFieldName = errors.New("field name already exists in struct") -) - -// NewNativeType constructs a NativeType instance for a Go struct reflect.Type. -func NewNativeType(rawType reflect.Type, opts ...NativeTypeOption) (*NativeType, error) { - tpOptions := NativeTypeOptions{} - for _, opt := range opts { - if err := opt(&tpOptions); err != nil { - return nil, err - } - } - return newNativeType(rawType, tpOptions.fieldNameHandler) -} - -// NativeTypesFieldNameHandler is a handler for mapping a reflect.StructField to a CEL field name. -// This can be used to override the default Go struct field to CEL field name mapping. -type NativeTypesFieldNameHandler = func(field reflect.StructField) string - -// NativeTypeOptions holds options for native types. -type NativeTypeOptions struct { - fieldNameHandler NativeTypesFieldNameHandler -} - -// NativeTypeOption is a functional option for configuring handling of native types. -type NativeTypeOption func(*NativeTypeOptions) error - -// ParseStructTags configures if native types field names should be overridable by CEL struct tags. -// This is equivalent to ParseStructTag("cel"). -func ParseStructTags(enabled bool) NativeTypeOption { - if enabled { - return ParseStructTag("cel") - } - return ParseStructField(nil) -} - -// ParseStructTag configures the struct tag to parse. The 0th item in the tag is used as the name of the CEL field. -func ParseStructTag(tag string) NativeTypeOption { - return ParseStructField(fieldNameByTag(tag)) -} - -// ParseStructField configures how to parse Go struct fields. It can be used to customize struct field parsing. -func ParseStructField(handler NativeTypesFieldNameHandler) NativeTypeOption { - return func(opts *NativeTypeOptions) error { - opts.fieldNameHandler = handler - return nil - } -} - -func fieldNameByTag(structTagToParse string) func(field reflect.StructField) string { - return func(field reflect.StructField) string { - tag, found := field.Tag.Lookup(structTagToParse) - if found { - splits := strings.Split(tag, ",") - if len(splits) > 0 { - name := splits[0] - return name - } - } - return field.Name - } -} - -func isSkippedFieldName(name string) bool { - return name == "" || name == "-" -} - -// NativeType represents a CEL struct type descriptor generated from a native Go struct. -type NativeType struct { - typeName string - refType reflect.Type - fieldsByName map[string]reflect.StructField -} - -// ReflectType implements StructTypeDescriptor. -func (t *NativeType) ReflectType() reflect.Type { - return t.refType -} - -// Adapt implements StructTypeDescriptor. -func (t *NativeType) Adapt(adapter Adapter, value any) ref.Val { - if value == nil { - return NullValue - } - refVal := reflect.ValueOf(value) - if refVal.Kind() == reflect.Ptr { - if refVal.IsNil() { - return NullValue - } - refVal = refVal.Elem() - } - return &nativeObj{ - Adapter: adapter, - val: value, - valType: t, - refValue: refVal, - } -} - -// ConvertToNative implements ref.Val.ConvertToNative. -func (t *NativeType) ConvertToNative(typeDesc reflect.Type) (any, error) { - return nil, fmt.Errorf("type conversion error for type to '%v'", typeDesc) -} - -// ConvertToType implements ref.Val.ConvertToType. -func (t *NativeType) ConvertToType(typeVal ref.Type) ref.Val { - switch typeVal { - case TypeType: - return TypeType - } - return NewErr("type conversion error from '%s' to '%s'", TypeType, typeVal) -} - -// Equal returns true if both type names are equal to each other. -func (t *NativeType) Equal(other ref.Val) ref.Val { - otherType, ok := other.(ref.Type) - return Bool(ok && t.TypeName() == otherType.TypeName()) -} - -// HasTrait implements the ref.Type interface method. -func (t *NativeType) HasTrait(trait int) bool { - return nativeObjTraitMask&trait == trait -} - -// String implements the fmt.Stringer interface method. -func (t *NativeType) String() string { - return t.typeName -} - -// Type implements the ref.Val interface method. -func (t *NativeType) Type() ref.Type { - return TypeType -} - -// TypeName implements the ref.Type interface method. -func (t *NativeType) TypeName() string { - return t.typeName -} - -// Value implements the ref.Val interface method. -func (t *NativeType) Value() any { - return t.typeName -} - -func (t *NativeType) hasField(fieldName string) (reflect.StructField, bool) { - f, found := t.fieldsByName[fieldName] - if !found { - return reflect.StructField{}, false - } - return f, true -} - -// FieldNames provides the list of field names for this type. -func (t *NativeType) FieldNames() []string { - fields := make([]string, 0, len(t.fieldsByName)) - for fieldName := range t.fieldsByName { - fields = append(fields, fieldName) - } - return fields -} - -// FindFieldType looks up a field by name and provides the type and accessors. -func (t *NativeType) FindFieldType(fieldName string) (*FieldType, bool) { - refField, found := t.hasField(fieldName) - if !found { - return nil, false - } - celType, ok := convertToCelType(refField.Type) - if !ok { - return nil, false - } - return &FieldType{ - Type: celType, - IsSet: func(obj any) bool { - refVal := reflect.Indirect(reflect.ValueOf(obj)) - refFieldVal := safeGetFieldByIndex(refVal, refField.Index) - return refFieldVal.IsValid() && !refFieldVal.IsZero() - }, - GetFrom: func(obj any) (any, error) { - refVal := reflect.Indirect(reflect.ValueOf(obj)) - refFieldVal := safeGetFieldByIndex(refVal, refField.Index) - return getFieldValue(refFieldVal), nil - }, - }, true -} - -// NewValue constructs a new native Go struct instance populated with given field values. -func (t *NativeType) NewValue(adapter Adapter, fields map[string]ref.Val) ref.Val { - refPtr := reflect.New(t.refType) - refVal := refPtr.Elem() - for fieldName, val := range fields { - refFieldDef, isDefined := t.hasField(fieldName) - if !isDefined { - return NewErr("no such field: %s", fieldName) - } - fieldVal, err := val.ConvertToNative(refFieldDef.Type) - if err != nil { - return NewErrFromString(err.Error()) - } - refField := safeSetFieldByIndex(refVal, refFieldDef.Index) - if !refField.IsValid() { - return NewErr("cannot set field: %s", fieldName) - } - refField.Set(reflect.ValueOf(fieldVal)) - } - return adapter.NativeToValue(refPtr.Interface()) -} - -type nativeObj struct { - Adapter - val any - valType *NativeType - refValue reflect.Value -} - -func (o *nativeObj) ConvertToNative(typeDesc reflect.Type) (any, error) { - if o.refValue.Type() == typeDesc { - if reflect.TypeOf(o.val) == typeDesc { - return o.val, nil - } - return o.refValue.Interface(), nil - } - if typeDesc.Kind() == reflect.Pointer && o.refValue.Type() == typeDesc.Elem() { - if reflect.TypeOf(o.val) == typeDesc { - return o.val, nil - } - ptr := reflect.New(o.refValue.Type()) - ptr.Elem().Set(o.refValue) - return ptr.Interface(), nil - } - switch typeDesc { - case jsonValueType: - jsonStruct, err := o.ConvertToNative(jsonStructType) - if err != nil { - return nil, err - } - return structpb.NewStructValue(jsonStruct.(*structpb.Struct)), nil - case jsonStructType: - refVal := reflect.Indirect(o.refValue) - fields := make(map[string]*structpb.Value, refVal.NumField()) - for fieldName, fieldType := range o.valType.fieldsByName { - fieldValue := safeGetFieldByIndex(refVal, fieldType.Index) - if !fieldValue.IsValid() || fieldValue.IsZero() { - continue - } - fieldCELVal := o.NativeToValue(fieldValue.Interface()) - fieldJSONVal, err := fieldCELVal.ConvertToNative(jsonValueType) - if err != nil { - return nil, err - } - fields[fieldName] = fieldJSONVal.(*structpb.Value) - } - return &structpb.Struct{Fields: fields}, nil - } - return nil, fmt.Errorf("type conversion error from '%v' to '%v'", o.Type(), typeDesc) -} - -func (o *nativeObj) ConvertToType(typeVal ref.Type) ref.Val { - switch typeVal { - case TypeType: - return o.valType - default: - if typeVal.TypeName() == o.valType.typeName { - return o - } - } - return NewErr("type conversion error from '%s' to '%s'", o.Type(), typeVal) -} - -func (o *nativeObj) Equal(other ref.Val) ref.Val { - otherNtv, ok := other.(*nativeObj) - if !ok { - return False - } - val := o.val - otherVal := otherNtv.val - if reflect.TypeOf(val).Kind() != reflect.TypeOf(otherVal).Kind() { - val = o.refValue.Interface() - otherVal = otherNtv.refValue.Interface() - } - return Bool(reflect.DeepEqual(val, otherVal)) -} - -func (o *nativeObj) IsZeroValue() bool { - return o.refValue.IsZero() -} - -func (o *nativeObj) IsSet(field ref.Val) ref.Val { - refField, refErr := o.getReflectedField(field) - if refErr != nil { - return refErr - } - return Bool(!refField.IsZero()) -} - -func (o *nativeObj) Get(field ref.Val) ref.Val { - refField, refErr := o.getReflectedField(field) - if refErr != nil { - return refErr - } - return adaptFieldValue(o, refField) -} - -func (o *nativeObj) getReflectedField(field ref.Val) (reflect.Value, ref.Val) { - fieldName, ok := field.(String) - if !ok { - return reflect.Value{}, MaybeNoSuchOverloadErr(field) - } - fieldNameStr := string(fieldName) - refField, isDefined := o.valType.hasField(fieldNameStr) - if !isDefined { - return reflect.Value{}, NewErr("no such field: %s", fieldName) - } - refVal := reflect.Indirect(o.refValue) - return safeGetFieldByIndex(refVal, refField.Index), nil -} - -func (o *nativeObj) Type() ref.Type { - return o.valType -} - -func (o *nativeObj) Value() any { - return o.val -} - -func newNativeTypes(rawType reflect.Type, fieldNameHandler NativeTypesFieldNameHandler) ([]*NativeType, error) { - nt, err := newNativeType(rawType, fieldNameHandler) - if err != nil { - return nil, err - } - result := []*NativeType{nt} - - alreadySeen := make(map[string]struct{}) - var iterateStructMembers func(reflect.Type) - iterateStructMembers = func(t reflect.Type) { - if t.Implements(reflect.TypeFor[ref.Val]()) { - return - } - if k := t.Kind(); k == reflect.Pointer || k == reflect.Slice || k == reflect.Array || k == reflect.Map { - iterateStructMembers(t.Elem()) - return - } - if t.Kind() != reflect.Struct { - return - } - if _, seen := alreadySeen[t.String()]; seen { - return - } - alreadySeen[t.String()] = struct{}{} - nt, ntErr := newNativeType(t, fieldNameHandler) - if ntErr != nil { - err = ntErr - return - } - result = append(result, nt) - - for _, field := range reflect.VisibleFields(t) { - if !field.IsExported() || !isSupportedType(field.Type) { - continue - } - iterateStructMembers(field.Type) - } - } - iterateStructMembers(rawType) - - return result, err -} - -func toFieldName(f reflect.StructField, fieldNameHandler NativeTypesFieldNameHandler) string { - if fieldNameHandler == nil { - return f.Name - } - return fieldNameHandler(f) -} - -func newNativeType(rawType reflect.Type, fieldNameHandler NativeTypesFieldNameHandler) (*NativeType, error) { - refType := rawType - if refType.Kind() == reflect.Pointer { - refType = refType.Elem() - } - if !isValidObjectType(refType) { - return nil, fmt.Errorf("unsupported reflect.Type %v, must be reflect.Struct", rawType) - } - - fieldsByName := make(map[string]reflect.StructField) - for _, field := range reflect.VisibleFields(refType) { - if !field.IsExported() || !isSupportedType(field.Type) { - continue - } - fieldName := toFieldName(field, fieldNameHandler) - if isSkippedFieldName(fieldName) { - continue - } - if _, found := fieldsByName[fieldName]; found { - return nil, fmt.Errorf("invalid field name `%s` in struct `%s`: %w", fieldName, refType.Name(), errDuplicatedFieldName) - } - fieldsByName[fieldName] = field - } - - return &NativeType{ - typeName: fmt.Sprintf("%s.%s", simplePkgAlias(refType.PkgPath()), refType.Name()), - refType: refType, - fieldsByName: fieldsByName, - }, nil -} - -func adaptFieldValue(adapter Adapter, refField reflect.Value) ref.Val { - return adapter.NativeToValue(getFieldValue(refField)) -} - -func safeSetFieldByIndex(v reflect.Value, index []int) reflect.Value { - for _, i := range index { - if v.Kind() == reflect.Pointer { - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - if v.Kind() != reflect.Struct || i >= v.NumField() { - return reflect.Value{} - } - v = v.Field(i) - } - return v -} - -func safeGetFieldByIndex(v reflect.Value, index []int) reflect.Value { - for _, i := range index { - if v.Kind() == reflect.Pointer { - if v.IsNil() { - v = reflect.New(v.Type().Elem()).Elem() - } else { - v = v.Elem() - } - } - if v.Kind() != reflect.Struct || i >= v.NumField() { - return reflect.Value{} - } - v = v.Field(i) - } - return v -} - -func getFieldValue(refField reflect.Value) any { - if !refField.IsValid() { - return nil - } - if refField.IsZero() { - switch refField.Kind() { - case reflect.Struct: - if refField.Type() == timestampType { - return time.Unix(0, 0) - } - case reflect.Pointer: - return reflect.New(refField.Type().Elem()).Interface() - } - } - return refField.Interface() -} - -func simplePkgAlias(pkgPath string) string { - paths := strings.Split(pkgPath, "/") - if len(paths) == 0 { - return "" - } - return paths[len(paths)-1] -} - -func isValidObjectType(refType reflect.Type) bool { - return refType.Kind() == reflect.Struct -} - -func isSupportedType(refType reflect.Type) bool { - switch refType.Kind() { - case reflect.Chan, reflect.Complex64, reflect.Complex128, reflect.Func, reflect.UnsafePointer, reflect.Uintptr: - return false - case reflect.Array, reflect.Slice: - return isSupportedType(refType.Elem()) - case reflect.Map: - return isSupportedType(refType.Key()) && isSupportedType(refType.Elem()) - } - return true -} - -func convertToCelType(refType reflect.Type) (*Type, bool) { - switch refType.Kind() { - case reflect.Bool: - return BoolType, true - case reflect.Float32, reflect.Float64: - return DoubleType, true - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if refType == durationType { - return DurationType, true - } - return IntType, true - case reflect.String: - return StringType, true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return UintType, true - case reflect.Array, reflect.Slice: - refElem := refType.Elem() - if refElem == reflect.TypeOf(byte(0)) { - return BytesType, true - } - elemType, ok := convertToCelType(refElem) - if !ok { - return nil, false - } - return NewListType(elemType), true - case reflect.Map: - keyType, ok := convertToCelType(refType.Key()) - if !ok { - return nil, false - } - elemType, ok := convertToCelType(refType.Elem()) - if !ok { - return nil, false - } - return NewMapType(keyType, elemType), true - case reflect.Struct: - if refType == timestampType { - return TimestampType, true - } - if refType.Implements(refValType) { - emptyCelVal := reflect.New(refType).Elem().Interface().(ref.Val) - return emptyCelVal.Type().(*Type), true - } - return NewObjectType( - fmt.Sprintf("%s.%s", simplePkgAlias(refType.PkgPath()), refType.Name()), - ), true - case reflect.Pointer: - if refType.Implements(refValType) { - emptyCelVal := reflect.New(refType.Elem()).Interface().(ref.Val) - return emptyCelVal.Type().(*Type), true - } - if refType.Implements(pbMsgInterfaceType) { - pbMsg := reflect.New(refType.Elem()).Interface().(protoreflect.ProtoMessage) - return NewObjectType(string(pbMsg.ProtoReflect().Descriptor().FullName())), true - } - return convertToCelType(refType.Elem()) - } - return nil, false -} diff --git a/vendor/github.com/google/cel-go/interpreter/runtimecost.go b/vendor/github.com/google/cel-go/interpreter/runtimecost.go deleted file mode 100644 index 81e4ef63c4..0000000000 --- a/vendor/github.com/google/cel-go/interpreter/runtimecost.go +++ /dev/null @@ -1,416 +0,0 @@ -// Copyright 2022 Google LLC -// -// 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 interpreter - -import ( - "errors" - "math" - - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" -) - -// WARNING: Any changes to cost calculations in this file require a corresponding change in checker/cost.go - -// ActualCostEstimator provides function call cost estimations at runtime -// CallCost returns an estimated cost for the function overload invocation with the given args, or nil if it has no -// estimate to provide. CEL attempts to provide reasonable estimates for its standard function library, so CallCost -// should typically not need to provide an estimate for CELs standard function. -type ActualCostEstimator interface { - CallCost(function, overloadID string, args []ref.Val, result ref.Val) *uint64 -} - -// costTrackPlanOption modifies the cost tracking factory associatied with the CostObserver -type costTrackPlanOption func(*costTrackerFactory) *costTrackerFactory - -// CostTrackerFactory configures the factory method to generate a new cost-tracker per-evaluation. -func CostTrackerFactory(factory func() (*CostTracker, error)) costTrackPlanOption { - return func(fac *costTrackerFactory) *costTrackerFactory { - fac.factory = factory - return fac - } -} - -// CostObserver provides an observer that tracks runtime cost. -func CostObserver(opts ...costTrackPlanOption) PlannerOption { - ct := &costTrackerFactory{} - for _, o := range opts { - ct = o(ct) - } - return func(p *planner) (*planner, error) { - if ct.factory == nil { - return nil, errors.New("cost tracker factory not configured") - } - p.observers = append(p.observers, ct) - p.decorators = append(p.decorators, decObserveEval(ct.Observe)) - return p, nil - } -} - -// costTrackerFactory holds a factory for producing new CostTracker instances on each Eval call. -type costTrackerFactory struct { - factory func() (*CostTracker, error) -} - -// InitState produces a CostTracker and bundles it into an Activation in a way which is not visible -// to expression evaluation. -func (ct *costTrackerFactory) InitState(frame *ExecutionFrame) (any, error) { - if frame.ctx != nil && frame.ctx.costs != nil { - return frame.ctx.costs, nil - } - tracker, err := ct.factory() - if err != nil { - return nil, err - } - if frame.ctx == nil { - frame.ctx = evalContextPool.Get().(*evalContext) - } - frame.ctx.costs = tracker - return tracker, nil -} - -// GetState extracts the CostTracker from the Activation. -func (ct *costTrackerFactory) GetState(frame *ExecutionFrame) any { - if frame == nil || frame.ctx == nil { - return nil - } - return frame.ctx.costs -} - -// Observe computes the incremental cost of each step and records it into the CostTracker associated -// with the evaluation. -func (ct *costTrackerFactory) Observe(vars Activation, id int64, programStep any, val ref.Val) { - frame := AsFrame(vars) - state := ct.GetState(frame) - if state == nil { - return - } - tracker, ok := state.(*CostTracker) - if !ok { - // The state is configured with CostTrackFactory so this shouldn't happen. - return - } - switch t := programStep.(type) { - case ConstantQualifier: - // TODO: Push identifiers on to the stack before observing constant qualifiers that apply to them - // and enable the below pop. Once enabled this can case can be collapsed into the Qualifier case. - tracker.cost++ - case InterpretableConst: - // zero cost - case InterpretableAttribute: - switch a := t.Attr().(type) { - case *conditionalAttribute: - // Ternary has no direct cost. All cost is from the conditional and the true/false branch expressions. - tracker.stack.drop(a.falsy.ID(), a.truthy.ID(), a.expr.ID()) - default: - tracker.stack.drop(t.Attr().ID()) - tracker.cost += common.SelectAndIdentCost - } - if !tracker.presenceTestHasCost { - if _, isTestOnly := programStep.(*evalTestOnly); isTestOnly { - tracker.cost -= common.SelectAndIdentCost - } - } - case *evalExhaustiveConditional: - // Ternary has no direct cost. All cost is from the conditional and the true/false branch expressions. - tracker.stack.drop(t.attr.falsy.ID(), t.attr.truthy.ID(), t.attr.expr.ID()) - - // While the field names are identical, the boolean operation eval structs do not share an interface and so - // must be handled individually. - case *evalOr: - for _, term := range t.terms { - tracker.stack.drop(term.ID()) - } - case *evalAnd: - for _, term := range t.terms { - tracker.stack.drop(term.ID()) - } - case *evalExhaustiveOr: - for _, term := range t.terms { - tracker.stack.drop(term.ID()) - } - case *evalExhaustiveAnd: - for _, term := range t.terms { - tracker.stack.drop(term.ID()) - } - case *evalFold: - tracker.stack.drop(t.iterRange.ID()) - case Qualifier: - tracker.cost++ - case InterpretableCall: - if argVals, ok := tracker.stack.dropArgs(t.Args()); ok { - tracker.cost += tracker.costCall(t, argVals, val) - } - case InterpretableConstructor: - tracker.stack.dropArgs(t.InitVals()) - switch t.Type() { - case types.ListType: - tracker.cost += common.ListCreateBaseCost - case types.MapType: - tracker.cost += common.MapCreateBaseCost - default: - tracker.cost += common.StructCreateBaseCost - } - } - tracker.stack.push(val, id) - - if tracker.Limit != nil && tracker.cost > *tracker.Limit { - panic(EvalCancelledError{Cause: CostLimitExceeded, Message: "operation cancelled: actual cost limit exceeded"}) - } -} - -// CostTrackerOption configures the behavior of CostTracker objects. -type CostTrackerOption func(*CostTracker) error - -// CostTrackerLimit sets the runtime limit on the evaluation cost during execution and will terminate the expression -// evaluation if the limit is exceeded. -func CostTrackerLimit(limit uint64) CostTrackerOption { - return func(tracker *CostTracker) error { - tracker.Limit = &limit - return nil - } -} - -// PresenceTestHasCost determines whether presence testing has a cost of one or zero. -// Defaults to presence test has a cost of one. -func PresenceTestHasCost(hasCost bool) CostTrackerOption { - return func(tracker *CostTracker) error { - tracker.presenceTestHasCost = hasCost - return nil - } -} - -// NewCostTracker creates a new CostTracker with a given estimator and a set of functional CostTrackerOption values. -func NewCostTracker(estimator ActualCostEstimator, opts ...CostTrackerOption) (*CostTracker, error) { - tracker := &CostTracker{ - Estimator: estimator, - overloadTrackers: map[string]FunctionTracker{}, - presenceTestHasCost: true, - } - for _, opt := range opts { - err := opt(tracker) - if err != nil { - return nil, err - } - } - return tracker, nil -} - -// OverloadCostTracker binds an overload ID to a runtime FunctionTracker implementation. -// -// OverloadCostTracker instances augment or override ActualCostEstimator decisions, allowing for versioned and/or -// optional cost tracking changes. -func OverloadCostTracker(overloadID string, fnTracker FunctionTracker) CostTrackerOption { - return func(tracker *CostTracker) error { - tracker.overloadTrackers[overloadID] = fnTracker - return nil - } -} - -// FunctionTracker computes the actual cost of evaluating the functions with the given arguments and result. -type FunctionTracker func(args []ref.Val, result ref.Val) *uint64 - -// CostTracker represents the information needed for tracking runtime cost. -type CostTracker struct { - Estimator ActualCostEstimator - overloadTrackers map[string]FunctionTracker - Limit *uint64 - presenceTestHasCost bool - - cost uint64 - stack refValStack -} - -// Clone makes a shallow copy of the tracker. -// The different clones can be used independently from -// each other. -func (c *CostTracker) Clone() (*CostTracker, error) { - tracker := &CostTracker{ - Estimator: c.Estimator, - overloadTrackers: c.overloadTrackers, - Limit: c.Limit, - presenceTestHasCost: c.presenceTestHasCost, - } - return tracker, nil -} - -// ActualCost returns the runtime cost -func (c *CostTracker) ActualCost() uint64 { - return c.cost -} - -func (c *CostTracker) costCall(call InterpretableCall, args []ref.Val, result ref.Val) uint64 { - var cost uint64 - if len(c.overloadTrackers) != 0 { - if tracker, found := c.overloadTrackers[call.OverloadID()]; found { - callCost := tracker(args, result) - if callCost != nil { - cost = safeAdd(cost, *callCost) - return cost - } - } - } - if c.Estimator != nil { - callCost := c.Estimator.CallCost(call.Function(), call.OverloadID(), args, result) - if callCost != nil { - cost = safeAdd(cost, *callCost) - return cost - } - } - // if user didn't specify, the default way of calculating runtime cost would be used. - // if user has their own implementation of ActualCostEstimator, make sure to cover the mapping between overloadId and cost calculation - switch call.OverloadID() { - // O(n) functions - case overloads.StartsWithString, overloads.EndsWithString: - cost = safeAdd(cost, uint64(math.Ceil(float64(actualSize(args[1]))*common.StringTraversalCostFactor))) - case overloads.StringToBytes, overloads.BytesToString, overloads.ExtQuoteString, overloads.ExtFormatString: - cost = safeAdd(cost, uint64(math.Ceil(float64(actualSize(args[0]))*common.StringTraversalCostFactor))) - case overloads.InList: - // If a list is composed entirely of constant values this is O(1), but we don't account for that here. - // We just assume all list containment checks are O(n). - cost = safeAdd(cost, actualSize(args[1])) - // O(min(m, n)) functions - case overloads.LessString, overloads.GreaterString, overloads.LessEqualsString, overloads.GreaterEqualsString, - overloads.LessBytes, overloads.GreaterBytes, overloads.LessEqualsBytes, overloads.GreaterEqualsBytes, - overloads.Equals, overloads.NotEquals: - // When we check the equality of 2 scalar values (e.g. 2 integers, 2 floating-point numbers, 2 booleans etc.), - // the CostTracker.ActualSize() function by definition returns 1 for each operand, resulting in an overall cost - // of 1. - lhsSize := actualSize(args[0]) - rhsSize := actualSize(args[1]) - minSize := min(rhsSize, lhsSize) - cost = safeAdd(cost, uint64(math.Ceil(float64(minSize)*common.StringTraversalCostFactor))) - // O(m+n) functions - case overloads.AddString, overloads.AddBytes: - // In the worst case scenario, we would need to reallocate a new backing store and copy both operands over. - cost = safeAdd(cost, uint64(math.Ceil(float64(actualSize(args[0])+actualSize(args[1]))*common.StringTraversalCostFactor))) - // O(nm) functions - case overloads.Matches, overloads.MatchesString: - // https://swtch.com/~rsc/regexp/regexp1.html applies to RE2 implementation supported by CEL - // Add one to string length for purposes of cost calculation to prevent product of string and regex to be 0 - // in case where string is empty but regex is still expensive. - strCost := uint64(math.Ceil((1.0 + float64(actualSize(args[0]))) * common.StringTraversalCostFactor)) - // We don't know how many expressions are in the regex, just the string length (a huge - // improvement here would be to somehow get a count the number of expressions in the regex or - // how many states are in the regex state machine and use that to measure regex cost). - // For now, we're making a guess that each expression in a regex is typically at least 4 chars - // in length. - regexCost := uint64(math.Ceil(float64(actualSize(args[1])) * common.RegexStringLengthCostFactor)) - cost = safeAdd(cost, strCost*regexCost) - case overloads.ContainsString: - strCost := uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor)) - substrCost := uint64(math.Ceil(float64(actualSize(args[1])) * common.StringTraversalCostFactor)) - cost = safeAdd(cost, strCost*substrCost) - - default: - // The following operations are assumed to have O(1) complexity. - // - AddList due to the implementation. Index lookup can be O(c) the - // number of concatenated lists, but we don't track that is cost calculations. - // - Conversions, since none perform a traversal of a type of unbound length. - // - Computing the size of strings, byte sequences, lists and maps. - // - Logical operations and all operators on fixed width scalars (comparisons, equality) - // - Any functions that don't have a declared cost either here or in provided ActualCostEstimator. - cost = safeAdd(cost, 1) - - } - return cost -} - -// actualSize returns the size of the value for all traits.Sizer values, a fixed size for all proto-based -// objects, and a size of 1 for all other value types. -func actualSize(value ref.Val) uint64 { - if sz, ok := value.(traits.Sizer); ok { - return uint64(sz.Size().(types.Int)) - } - if opt, ok := value.(*types.Optional); ok && opt.HasValue() { - return actualSize(opt.GetValue()) - } - return 1 -} - -type stackVal struct { - Val ref.Val - ID int64 -} - -// refValStack keeps track of values of the stack for cost calculation purposes -type refValStack []stackVal - -func (s *refValStack) push(val ref.Val, id int64) { - value := stackVal{Val: val, ID: id} - *s = append(*s, value) -} - -// TODO: Allowing drop and dropArgs to remove stack items above the IDs they are provided is a workaround. drop and dropArgs -// should find and remove only the stack items matching the provided IDs once all attributes are properly pushed and popped from stack. - -// drop searches the stack for each ID and removes the ID and all stack items above it. -// If none of the IDs are found, the stack is not modified. -// WARNING: It is possible for multiple expressions with the same ID to exist (due to how macros are implemented) so it's -// possible that a dropped ID will remain on the stack. They should be removed when IDs on the stack are popped. -func (s *refValStack) drop(ids ...int64) { - for _, id := range ids { - for idx := len(*s) - 1; idx >= 0; idx-- { - if (*s)[idx].ID == id { - *s = (*s)[:idx] - break - } - } - } -} - -// dropArgs searches the stack for all the args by their IDs, accumulates their associated ref.Vals and drops any -// stack items above any of the arg IDs. If any of the IDs are not found the stack, false is returned. -// Args are assumed to be found in the stack in reverse order, i.e. the last arg is expected to be found highest in -// the stack. -// WARNING: It is possible for multiple expressions with the same ID to exist (due to how macros are implemented) so it's -// possible that a dropped ID will remain on the stack. They should be removed when IDs on the stack are popped. -func (s *refValStack) dropArgs(args []InterpretableV2) ([]ref.Val, bool) { - result := make([]ref.Val, len(args)) -argloop: - for nIdx := len(args) - 1; nIdx >= 0; nIdx-- { - for idx := len(*s) - 1; idx >= 0; idx-- { - if (*s)[idx].ID == args[nIdx].ID() { - el := (*s)[idx] - *s = (*s)[:idx] - result[nIdx] = el.Val - continue argloop - } - } - return nil, false - } - return result, true -} - -func safeAdd(x, y uint64, rest ...uint64) uint64 { - if y > 0 && x > math.MaxUint64-y { - return math.MaxUint64 - } - next := x + y - if len(rest) == 0 { - return next - } - return safeAdd(next, rest[0], rest[1:]...) -} - -func safeMul(x, y uint64) uint64 { - if y != 0 && x > math.MaxUint64/y { - return math.MaxUint64 - } - return x * y -} diff --git a/vendor/github.com/googleapis/gax-go/v2/CHANGES.md b/vendor/github.com/googleapis/gax-go/v2/CHANGES.md index 86c4828c8b..ed27c5ee71 100644 --- a/vendor/github.com/googleapis/gax-go/v2/CHANGES.md +++ b/vendor/github.com/googleapis/gax-go/v2/CHANGES.md @@ -1,5 +1,7 @@ # Changes +## [2.22.0](https://github.com/googleapis/google-cloud-go/releases/tag/v2.22.0) (2026-04-14) + ## [2.21.0](https://github.com/googleapis/google-cloud-go/releases/tag/v2.21.0) (2026-04-01) ### Features diff --git a/vendor/github.com/googleapis/gax-go/v2/internal/version.go b/vendor/github.com/googleapis/gax-go/v2/internal/version.go index 6ee13c8d0f..f324d1ab82 100644 --- a/vendor/github.com/googleapis/gax-go/v2/internal/version.go +++ b/vendor/github.com/googleapis/gax-go/v2/internal/version.go @@ -17,4 +17,4 @@ package internal // Version is the current tagged release of the library. -const Version = "2.21.0" +const Version = "2.22.0" diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go index 65ffcf5cf8..06762fe3f1 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go @@ -18,6 +18,50 @@ func (e InvalidTemplateError) Error() string { // Parse parses the string representation of path template func Parse(tmpl string) (Compiler, error) { + return parse(tmpl) +} + +// Segment is a top-level segment of a parsed path template. +type Segment struct { + // FieldPath is the field path bound by a variable segment, e.g. "name" + // for "{name=projects/*}". It is empty for literal and wildcard segments. + FieldPath string + // Value is the literal or wildcard ("*" or "**") of a non-variable + // segment, or the pattern of a variable segment, e.g. "projects/*" for + // "{name=projects/*}". A variable without an explicit pattern, such as + // "{name}", has the pattern "*". + Value string +} + +// SplitTemplate parses the string representation of path template and +// returns its top-level segments and its verb. The root template "/" has no +// segments. +func SplitTemplate(tmpl string) (segments []Segment, verb string, err error) { + t, err := parse(tmpl) + if err != nil { + return nil, "", err + } + for _, s := range t.segments { + switch s := s.(type) { + case literal: + if s == eof { + continue + } + segments = append(segments, Segment{Value: string(s)}) + case variable: + pattern := make([]string, 0, len(s.segments)) + for _, vs := range s.segments { + pattern = append(pattern, vs.String()) + } + segments = append(segments, Segment{FieldPath: s.path, Value: strings.Join(pattern, "/")}) + default: + segments = append(segments, Segment{Value: s.String()}) + } + } + return segments, t.verb, nil +} + +func parse(tmpl string) (template, error) { if !strings.HasPrefix(tmpl, "/") { return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"} } @@ -28,6 +72,9 @@ func Parse(tmpl string) (Compiler, error) { if err != nil { return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()} } + if err := expectPChars(verb); err != nil { + return template{}, InvalidTemplateError{tmpl: tmpl, msg: fmt.Sprintf("invalid verb: %v", err)} + } return template{ segments: segs, diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel index 04b4bebf3d..a98ef34763 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel @@ -38,6 +38,7 @@ go_library( "@org_golang_google_protobuf//reflect/protoreflect", "@org_golang_google_protobuf//reflect/protoregistry", "@org_golang_google_protobuf//types/known/durationpb", + "@org_golang_google_protobuf//types/known/emptypb", "@org_golang_google_protobuf//types/known/fieldmaskpb", "@org_golang_google_protobuf//types/known/structpb", "@org_golang_google_protobuf//types/known/timestamppb", @@ -49,9 +50,11 @@ go_test( name = "runtime_test", size = "small", srcs = [ + "context_internal_test.go", "context_test.go", "convert_test.go", "errors_test.go", + "fieldmask_empty_object_test.go", "fieldmask_test.go", "handler_test.go", "marshal_httpbodyproto_test.go", @@ -76,6 +79,7 @@ go_test( "@org_golang_google_genproto_googleapis_rpc//status", "@org_golang_google_grpc//:grpc", "@org_golang_google_grpc//codes", + "@org_golang_google_grpc//credentials/insecure", "@org_golang_google_grpc//health/grpc_health_v1", "@org_golang_google_grpc//metadata", "@org_golang_google_grpc//status", diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go index 00b2228a1d..f2403d2fc4 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "fmt" + "math" "net" "net/http" "net/textproto" @@ -147,6 +148,17 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM } } var pairs []string + // For backwards-compatibility, pass through 'authorization' header with no prefix. + // It is added before the header loop so that it is always the first + // "authorization" value: the loop iterates a map, so a header the matcher + // forwards under the same key (Grpc-Metadata-Authorization with the default + // matcher) would otherwise land ahead of it in random order, and a backend + // reading the first value would get the client-forwarded one. + for _, val := range req.Header.Values("Authorization") { + if isValidGRPCMetadataTextValue(val) { + pairs = append(pairs, "authorization", val) + } + } for key, vals := range req.Header { key = textproto.CanonicalMIMEHeaderKey(key) switch key { @@ -156,11 +168,17 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM } for _, val := range vals { - // For backwards-compatibility, pass through 'authorization' header with no prefix. - if key == "Authorization" { - pairs = append(pairs, "authorization", val) - } if h, ok := mux.incomingHeaderMatcher(key); ok { + // The gateway derives x-forwarded-host and x-forwarded-for below from + // the trusted request (Host / X-Forwarded-* / RemoteAddr), and backends + // rely on those metadata keys for client host/IP decisions. Refuse a + // forwarded header that the matcher strips into one of them (e.g. + // Grpc-Metadata-X-Forwarded-For) so a client cannot slip a spoofed value + // in ahead of the gateway-set one. + if strings.EqualFold(h, xForwardedFor) || strings.EqualFold(h, xForwardedHost) { + grpclog.Errorf("HTTP header %q maps to gateway-reserved metadata key %q; skipping", key, h) + continue + } if !isValidGRPCMetadataKey(h) { grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h) continue @@ -182,15 +200,23 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM } } } - if host := req.Header.Get(xForwardedHost); host != "" { + if host := req.Header.Get(xForwardedHost); host != "" && isValidGRPCMetadataTextValue(host) { pairs = append(pairs, strings.ToLower(xForwardedHost), host) - } else if req.Host != "" { + } else if req.Host != "" && isValidGRPCMetadataTextValue(req.Host) { pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host) } - xff := req.Header.Values(xForwardedFor) + // Validate each X-Forwarded-For value on its own, so that an invalid + // client-supplied value is dropped without also dropping the remote + // address the gateway appends. + var xff []string + for _, value := range req.Header.Values(xForwardedFor) { + if isValidGRPCMetadataTextValue(value) { + xff = append(xff, value) + } + } if addr := req.RemoteAddr; addr != "" { - if remoteIP, _, err := net.SplitHostPort(addr); err == nil { + if remoteIP, _, err := net.SplitHostPort(addr); err == nil && isValidGRPCMetadataTextValue(remoteIP) { xff = append(xff, remoteIP) } } @@ -202,9 +228,18 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM ctx, _ = context.WithTimeout(ctx, timeout) } md := metadata.Pairs(pairs...) + var annotated metadata.MD for _, mda := range mux.metadataAnnotators { - md = metadata.Join(md, mda(ctx, req)) + annotated = metadata.Join(annotated, mda(ctx, req)) } + // Annotators are the gateway's own code, so their values replace whatever + // the request headers put under the same key. Joining them after the + // header values would let a client send Grpc-Metadata- and have its + // value read first by a backend that trusts the annotator. + for k := range annotated { + delete(md, strings.ToLower(k)) + } + md = metadata.Join(md, annotated) if len(md) == 0 { return ctx, nil, nil } @@ -302,10 +337,16 @@ func timeoutDecode(s string) (time.Duration, error) { if !ok { return 0, fmt.Errorf("timeout unit is not recognized: %q", s) } - t, err := strconv.ParseInt(s[:size-1], 10, 64) + t, err := strconv.ParseUint(s[:size-1], 10, 64) if err != nil { return 0, err } + // Guard against overflowing time.Duration, which is an int64 nanosecond + // count: without this a large value wraps to a bogus (often negative) + // deadline instead of the long timeout the client asked for. + if t > uint64(math.MaxInt64)/uint64(d) { + return time.Duration(math.MaxInt64), nil + } return d * time.Duration(t), nil } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go index 2e50082ad1..8548f723e8 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go @@ -3,6 +3,7 @@ package runtime import ( "encoding/base64" "fmt" + "math" "strconv" "strings" @@ -44,9 +45,40 @@ func BoolSlice(val, sep string) ([]bool, error) { return values, nil } +// parseFloat parses a floating point value the way the proto3 JSON mapping +// does: a decimal number, or the exact strings "Infinity", "-Infinity" and +// "NaN". strconv.ParseFloat additionally accepts hexadecimal floats ("0x1p4"), +// underscore digit separators ("1_000") and alternate infinity/NaN spellings +// ("Inf", "nan", "infinity"), none of which protojson (and so the request body +// and backend) accept. Reject those so a value bound from a query or path +// parameter can't differ from the same value sent in the body. +func parseFloat(val string, bitSize int) (float64, error) { + switch val { + case "Infinity": + return math.Inf(1), nil + case "-Infinity": + return math.Inf(-1), nil + case "NaN": + return math.NaN(), nil + } + if strings.ContainsAny(val, "xX_") { + return 0, fmt.Errorf("invalid syntax %q", val) + } + f, err := strconv.ParseFloat(val, bitSize) + if err != nil { + return 0, err + } + // ParseFloat only yields Inf/NaN without an error for the alternate + // spellings handled above; overflow returns a range error instead. + if math.IsInf(f, 0) || math.IsNaN(f) { + return 0, fmt.Errorf("invalid syntax %q", val) + } + return f, nil +} + // Float64 converts the given string representation into representation of a floating point number into float64. func Float64(val string) (float64, error) { - return strconv.ParseFloat(val, 64) + return parseFloat(val, 64) } // Float64Slice converts 'val' where individual floating point numbers are separated by @@ -66,7 +98,7 @@ func Float64Slice(val, sep string) ([]float64, error) { // Float32 converts the given string representation of a floating point number into float32. func Float32(val string) (float32, error) { - f, err := strconv.ParseFloat(val, 32) + f, err := parseFloat(val, 32) if err != nil { return 0, err } @@ -90,7 +122,7 @@ func Float32Slice(val, sep string) ([]float32, error) { // Int64 converts the given string representation of an integer into int64. func Int64(val string) (int64, error) { - return strconv.ParseInt(val, 0, 64) + return strconv.ParseInt(val, 10, 64) } // Int64Slice converts 'val' where individual integers are separated by @@ -110,7 +142,7 @@ func Int64Slice(val, sep string) ([]int64, error) { // Int32 converts the given string representation of an integer into int32. func Int32(val string) (int32, error) { - i, err := strconv.ParseInt(val, 0, 32) + i, err := strconv.ParseInt(val, 10, 32) if err != nil { return 0, err } @@ -134,7 +166,7 @@ func Int32Slice(val, sep string) ([]int32, error) { // Uint64 converts the given string representation of an integer into uint64. func Uint64(val string) (uint64, error) { - return strconv.ParseUint(val, 0, 64) + return strconv.ParseUint(val, 10, 64) } // Uint64Slice converts 'val' where individual integers are separated by @@ -154,7 +186,7 @@ func Uint64Slice(val, sep string) ([]uint64, error) { // Uint32 converts the given string representation of an integer into uint32. func Uint32(val string) (uint32, error) { - i, err := strconv.ParseUint(val, 0, 32) + i, err := strconv.ParseUint(val, 10, 32) if err != nil { return 0, err } @@ -176,21 +208,22 @@ func Uint32Slice(val, sep string) ([]uint32, error) { return values, nil } -// Bytes converts the given string representation of a byte sequence into a slice of bytes -// A bytes sequence is encoded in URL-safe base64 without padding +// Bytes converts the given string representation of a byte sequence into a slice of bytes. +// Like the protobuf JSON mapping, it accepts standard or URL-safe base64, with or +// without padding. func Bytes(val string) ([]byte, error) { - b, err := base64.StdEncoding.DecodeString(val) - if err != nil { - b, err = base64.URLEncoding.DecodeString(val) - if err != nil { - return nil, err - } + enc := base64.StdEncoding + if strings.ContainsAny(val, "-_") { + enc = base64.URLEncoding + } + if len(val)%4 != 0 { + enc = enc.WithPadding(base64.NoPadding) } - return b, nil + return enc.DecodeString(val) } -// BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe -// base64 without padding, are separated by 'sep' into a slice of byte slices. +// BytesSlice converts 'val' where individual bytes sequences, encoded in standard or +// URL-safe base64, are separated by 'sep' into a slice of byte slices. func BytesSlice(val, sep string) ([][]byte, error) { s := strings.Split(val, sep) values := make([][]byte, len(s)) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go index 2fcd7af3c4..d235ede9b4 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "sort" + "strings" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" @@ -65,14 +66,16 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field } if isProtobufAnyMessage(fd.Message()) && !fd.IsList() { - _, hasTypeField := v.(map[string]interface{})["@type"] - if hasTypeField { - queue = append(queue, fieldMaskPathItem{path: k}) - continue - } else { + vm, _ := v.(map[string]interface{}) + if _, hasTypeField := vm["@type"]; !hasTypeField { return nil, fmt.Errorf("could not find field @type in %q in message %q", k, item.msg.Descriptor().FullName()) } - + newPath := string(fd.FullName().Name()) + if item.path != "" { + newPath = item.path + "." + newPath + } + queue = append(queue, fieldMaskPathItem{path: newPath}) + continue } child := fieldMaskPathItem{ @@ -96,10 +99,10 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field queue = append(queue, child) } } - case ok && len(m) == 0: - fallthrough case len(item.path) > 0: - // otherwise, it's a leaf node so print its path + // otherwise, it's a leaf node (an empty object counts as one) so + // print its path. The root has no path: an empty body such as {} + // sets nothing, and an empty path is not a valid FieldMask path. fm.Paths = append(fm.Paths, item.path) } } @@ -126,30 +129,55 @@ func isDynamicProtoMessage(md protoreflect.MessageDescriptor) bool { // passed in name and json value. func buildPathsBlindly(name string, in interface{}) []string { m, ok := in.(map[string]interface{}) - if !ok { + if !ok || len(m) == 0 { return []string{name} } + // A google.protobuf.Struct/Value field carries arbitrary client JSON, so + // its nesting depth is attacker controlled. Keep each queue entry pointing + // at its parent and its own segment rather than carrying the full path + // string, so a path is concatenated once at the leaf (O(depth)) instead of + // rebuilding the growing prefix at every level (O(depth^2)). A deeply + // nested object otherwise makes this allocate quadratically in the depth + // while producing only a handful of paths. + type pathNode struct { + parent *pathNode + segment string + } + type queueItem struct { + path *pathNode + node map[string]any + } + var paths []string - queue := []fieldMaskPathItem{{path: name, node: m}} + queue := []queueItem{{path: &pathNode{segment: name}, node: m}} for len(queue) > 0 { cur := queue[0] queue = queue[1:] - m, ok := cur.node.(map[string]interface{}) - if !ok { - // This should never happen since we should always check that we only add - // nodes of type map[string]interface{} to the queue. - continue - } - for k, v := range m { - if mi, ok := v.(map[string]interface{}); ok { - queue = append(queue, fieldMaskPathItem{path: cur.path + "." + k, node: mi}) - } else { - // This is not a struct, so there are no more levels to descend. - curPath := cur.path + "." + k - paths = append(paths, curPath) + for k, v := range cur.node { + child := &pathNode{parent: cur.path, segment: k} + if mi, ok := v.(map[string]any); ok && len(mi) > 0 { + queue = append(queue, queueItem{path: child, node: mi}) + continue + } + // No populated object remains, so there are no more levels to + // descend. Walk back to the root to materialize the path once. + var segments []string + n := 0 + for p := child; p != nil; p = p.parent { + segments = append(segments, p.segment) + n += len(p.segment) + 1 + } + var b strings.Builder + b.Grow(n - 1) + for i := len(segments) - 1; i >= 0; i-- { + b.WriteString(segments[i]) + if i > 0 { + b.WriteByte('.') + } } + paths = append(paths, b.String()) } } return paths diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go index 3d07063007..b6a605c34d 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "io" + "math" "reflect" "strconv" @@ -251,16 +252,31 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key()) } + var raw json.RawMessage + if err := d.Decode(&raw); err != nil { + return err + } m := make(map[string]*json.RawMessage) - if err := d.Decode(&m); err != nil { + if err := json.Unmarshal(raw, &m); err != nil { return err } + // encoding/json keeps the last value of a repeated key, while protojson + // rejects a duplicate map key, also when two spellings convert to the + // same key (e.g. "1" and "01"). Reject both here too. + if k, ok := duplicateObjectKey(raw); ok { + return fmt.Errorf("duplicate map key %q", k) + } + seen := make(map[any]struct{}, len(m)) for k, v := range m { result := conv.Call([]reflect.Value{reflect.ValueOf(k)}) if err := result[1].Interface(); err != nil { return err.(error) } bk := result[0] + if _, ok := seen[bk.Interface()]; ok { + return fmt.Errorf("duplicate map key %q", k) + } + seen[bk.Interface()] = struct{}{} bv := reflect.New(rv.Type().Elem()) if v == nil { null := json.RawMessage("null") @@ -311,6 +327,12 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions // TODO(yugui) Should use proto.StructProperties? return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface()) case float64: + // Enum values are int32 on the wire. A fractional or out-of-range + // number would otherwise be silently truncated/wrapped into a bogus + // enum here, unlike protojson which rejects it, so reject it too. + if v != math.Trunc(v) || v < math.MinInt32 || v > math.MaxInt32 { + return fmt.Errorf("%v is not a valid value for enum %T", repr, rv.Interface()) + } rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type())) return nil default: @@ -320,6 +342,32 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions return d.Decode(v) } +// duplicateObjectKey returns the first key that appears more than once in the +// JSON object in data. +func duplicateObjectKey(data []byte) (string, bool) { + d := json.NewDecoder(bytes.NewReader(data)) + if t, err := d.Token(); err != nil || t != json.Delim('{') { + return "", false + } + seen := make(map[string]struct{}) + for d.More() { + t, err := d.Token() + if err != nil { + return "", false + } + k, _ := t.(string) + if _, ok := seen[k]; ok { + return k, true + } + seen[k] = struct{}{} + var v json.RawMessage + if err := d.Decode(&v); err != nil { + return "", false + } + } + return "", false +} + type protoEnum interface { fmt.Stringer EnumDescriptor() ([]byte, []int) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go index 398c780dc2..22e8992040 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go @@ -40,6 +40,13 @@ func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder { if err != nil { return err } + // ReadAll drains the reader, so a call with nothing left to read has + // to report io.EOF like the other decoders. Otherwise it decodes an + // empty message every time, and a loop decoding until io.EOF, such as + // the generated client streaming handlers, never terminates. + if len(buffer) == 0 { + return io.EOF + } return marshaller.Unmarshal(buffer, value) }) } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go index 69edf5eff8..4166e715be 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "mime" "net/http" "net/textproto" "regexp" @@ -44,7 +45,9 @@ const ( UnescapingModeDefault = UnescapingModeLegacy ) -var encodedPathSplitter = regexp.MustCompile("(/|%2F)") +// Percent-encoding is case insensitive (RFC 3986, section 6.2.2.1), so an +// escaped path separator has to be recognized in either spelling. +var encodedPathSplitter = regexp.MustCompile("(/|%2[fF])") // A HandlerFunc handles a specific pair of path pattern and HTTP method. type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) @@ -75,6 +78,7 @@ type ServeMux struct { unescapingMode UnescapingMode writeContentLength bool disableChunkedEncoding bool + strictDeepWildcard bool } // ServeMuxOption is an option that can be given to a ServeMux on construction. @@ -137,6 +141,19 @@ func WithDisableChunkedEncoding() ServeMuxOption { } } +// WithStrictDeepWildcardMatching makes deep wildcards ("**") require at least +// one path segment when preceded by another segment. For example, +// "/v3/files/{path=**}" will not match "/v3/files". A trailing slash still +// provides an empty segment, so "/v3/files/" continues to match. +// +// This option applies to all patterns registered with the ServeMux, including +// generated routes and routes registered with HandlePath. +func WithStrictDeepWildcardMatching() ServeMuxOption { + return func(mux *ServeMux) { + mux.strictDeepWildcard = true + } +} + // SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters. // Configuring this will mean the generated OpenAPI output is no longer correct, and it should be // done with careful consideration. @@ -151,18 +168,49 @@ type HeaderMatcherFunc func(string) (string, bool) // DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header // keys (as specified by the IANA, e.g: Accept, Cookie, Host) to the gRPC metadata with the grpcgateway- prefix. If you want to know which headers are considered permanent, you can view the isPermanentHTTPHeader function. -// HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata after removing the prefix 'Grpc-Metadata-'. // Other headers are not added to the gRPC metadata. +// +// Earlier versions also mapped HTTP headers that start with 'Grpc-Metadata-' to gRPC metadata after removing the +// prefix. That let any HTTP client set an arbitrary metadata key, which a backend trusting a key as set by an +// interceptor or the gateway itself could not tell apart from the real value. Use LegacyHeaderMatcher, or the +// WithLegacyHeaderMatching option, to keep forwarding those headers. func DefaultHeaderMatcher(key string) (string, bool) { + if key = textproto.CanonicalMIMEHeaderKey(key); isPermanentHTTPHeader(key) { + return MetadataPrefix + key, true + } + return "", false +} + +// LegacyHeaderMatcher is the incoming header matcher earlier releases used by default. In addition to the +// permanent HTTP headers DefaultHeaderMatcher maps, HTTP headers that start with 'Grpc-Metadata-' are mapped +// to gRPC metadata after removing the prefix 'Grpc-Metadata-'. +// +// This lets any HTTP client set any metadata key the backend reads, except the ones the gateway reserves for +// itself, so only use it when the backend does not trust a metadata key to have been set by the gateway. +func LegacyHeaderMatcher(key string) (string, bool) { switch key = textproto.CanonicalMIMEHeaderKey(key); { case isPermanentHTTPHeader(key): return MetadataPrefix + key, true case strings.HasPrefix(key, MetadataHeaderPrefix): - return key[len(MetadataHeaderPrefix):], true + mdKey := key[len(MetadataHeaderPrefix):] + // The grpcgateway- namespace is reserved for permanent HTTP headers the + // gateway maps itself, so refuse to forward a Grpc-Metadata- header that + // strips into it. Otherwise Grpc-Metadata-grpcgateway-host lets a client + // inject a value indistinguishable from the gateway-set grpcgateway-host. + if strings.HasPrefix(strings.ToLower(mdKey), MetadataPrefix) { + return "", false + } + return mdKey, true } return "", false } +// WithLegacyHeaderMatching returns a ServeMuxOption that restores LegacyHeaderMatcher as the incoming header +// matcher, so HTTP headers that start with 'Grpc-Metadata-' are forwarded as gRPC metadata again. +func WithLegacyHeaderMatching() ServeMuxOption { + return WithIncomingHeaderMatcher(LegacyHeaderMatcher) +} + func defaultOutgoingHeaderMatcher(key string) (string, bool) { return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true } @@ -376,15 +424,28 @@ func NewServeMux(opts ...ServeMuxOption) *ServeMux { serveMux.outgoingTrailerMatcher = defaultOutgoingTrailerMatcher } + // Options such as WithHealthEndpointAt register handlers while the options + // are still being applied, so they were wrapped with only the middlewares + // configured before them. Rewrap them now that all middlewares are known. + if len(serveMux.middlewares) > 0 { + chain := chainMiddlewares(serveMux.middlewares) + for _, handlers := range serveMux.handlers { + for i := range handlers { + handlers[i].h = chain(handlers[i].raw) + } + } + } + return serveMux } // Handle associates "h" to the pair of HTTP method and path pattern. func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) { + raw := h if len(s.middlewares) > 0 { h = chainMiddlewares(s.middlewares)(h) } - s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...) + s.handlers[meth] = append([]handler{{pat: pat, h: h, raw: raw}}, s.handlers[meth]...) } // HandlePath allows users to configure custom path handlers. @@ -415,8 +476,17 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // TODO(v3): remove UnescapingModeLegacy - if s.unescapingMode != UnescapingModeLegacy && r.URL.RawPath != "" { - path = r.URL.RawPath + unescapingMode := s.unescapingMode + if unescapingMode != UnescapingModeLegacy { + if r.URL.RawPath != "" { + path = r.URL.RawPath + } else { + // net/url only sets RawPath when the request path is not in its + // default encoding. Without it, Path is all there is and it has + // already been unescaped once, so unescaping it again while matching + // would decode a sequence like %252F twice. + unescapingMode = UnescapingModeLegacy + } } if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) { @@ -434,7 +504,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { // in this escaping mode we would be double unescaping but in UnescapingModeAllCharacters, we still do as the // path is the RawPath (i.e. unescaped). That does mean that the behavior of this function will change its default // behavior when the UnescapingModeDefault gets changed from UnescapingModeLegacy to UnescapingModeAllExceptReserved - if s.unescapingMode == UnescapingModeAllCharacters { + if unescapingMode == UnescapingModeAllCharacters { pathComponents = encodedPathSplitter.Split(path[1:], -1) } else { pathComponents = strings.Split(path[1:], "/") @@ -460,19 +530,24 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { idx = len(lastPathComponent) - len(patVerb) - 1 } if idx == 0 { - _, outboundMarshaler := MarshalerForRequest(s, r) - s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound) - return + // The last component is the bare verb with nothing before it, + // which this pattern cannot match. Other patterns still might, so + // move on rather than ending the search with a 404. + continue } - comps := make([]string, len(pathComponents)) - copy(comps, pathComponents) - + // Only copy the components when the verb has to be split off the last + // one. MatchAndEscape never mutates its input, so sharing the slice + // across handlers is safe, and copying it per handler otherwise costs + // len(pathComponents) allocations for every registered pattern. + comps := pathComponents if idx > 0 { + comps = make([]string, len(pathComponents)) + copy(comps, pathComponents) comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:] } - pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode) + pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard) if err != nil { var mse MalformedSequenceError if ok := errors.As(err, &mse); ok { @@ -495,11 +570,24 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Note we are not eagerly checking the request here as we want to return the // right HTTP status code, and we need to process the fallback candidates in // order to do that. - for m, handlers := range s.handlers { + // GET is tried first when the request is subject to path length fallback: + // map iteration order is random, and a match for another method would + // otherwise return 405 before the GET handler is reached. + methods := make([]string, 0, len(s.handlers)) + if s.isPathLengthFallback(r) { + methods = append(methods, http.MethodGet) + } + for m := range s.handlers { + if m == http.MethodGet && s.isPathLengthFallback(r) { + continue + } + methods = append(methods, m) + } + for _, m := range methods { if m == r.Method { continue } - for _, h := range handlers { + for _, h := range s.handlers[m] { var verb string patVerb := h.pat.Verb() @@ -508,14 +596,14 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { idx = len(lastPathComponent) - len(patVerb) - 1 } - comps := make([]string, len(pathComponents)) - copy(comps, pathComponents) - + comps := pathComponents if idx > 0 { + comps = make([]string, len(pathComponents)) + copy(comps, pathComponents) comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:] } - pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode) + pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard) if err != nil { var mse MalformedSequenceError if ok := errors.As(err, &mse); ok { @@ -558,12 +646,16 @@ func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.Resp } func (s *ServeMux) isPathLengthFallback(r *http.Request) bool { - return !s.disablePathLengthFallback && r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + // Like net/http's ParseForm, ignore parameters such as charset. + mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + return !s.disablePathLengthFallback && r.Method == "POST" && err == nil && mediaType == "application/x-www-form-urlencoded" } type handler struct { pat Pattern h HandlerFunc + // raw is h before middlewares were applied. + raw HandlerFunc } func (s *ServeMux) handleHandler(h handler, w http.ResponseWriter, r *http.Request, pathParams map[string]string) { diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go index e54507145b..524e52f62f 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go @@ -43,6 +43,20 @@ type Pattern struct { tailLen int // verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part. verb string + // strictDeepWildcard makes a deep wildcard ("**") preceded by a segment require at least one + // remaining path component. + strictDeepWildcard bool +} + +// PatternOpt configures optional behavior of a Pattern. +type PatternOpt func(*Pattern) + +// WithStrictDeepWildcard makes a deep wildcard ("**") that is preceded by another +// segment refuse to match zero path segments. For example, "/v3/files/{path=**}" +// will not match "/v3/files". A bare "**" with nothing preceding it still matches +// zero segments. See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771. +func WithStrictDeepWildcard() PatternOpt { + return func(p *Pattern) { p.strictDeepWildcard = true } } // NewPattern returns a new Pattern from the given definition values. @@ -51,6 +65,12 @@ type Pattern struct { // "version" must be 1 for now. // It returns an error if the given definition is invalid. func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, error) { + return NewPatternWithOptions(version, ops, pool, verb) +} + +// NewPatternWithOptions is like NewPattern but additionally accepts options that modify +// the matching behavior of the returned Pattern, e.g. WithStrictDeepWildcard. +func NewPatternWithOptions(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error) { if version != 1 { grpclog.Errorf("unsupported version: %d", version) return Pattern{}, ErrInvalidPattern @@ -129,14 +149,18 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er } typedOps = append(typedOps, op) } - return Pattern{ + pat := Pattern{ ops: typedOps, pool: pool, vars: vars, stacksize: maxstack, tailLen: tailLen, verb: verb, - }, nil + } + for _, opt := range opts { + opt(&pat) + } + return pat, nil } // MustPattern is a helper function which makes it easier to call NewPattern in variable initialization. @@ -152,6 +176,10 @@ func MustPattern(p Pattern, err error) Pattern { // matched but contained malformed escape sequences. If successful, the function // returns a mapping from field paths to their captured values. func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode UnescapingMode) (map[string]string, error) { + return p.matchAndEscape(components, verb, unescapingMode, false) +} + +func (p Pattern) matchAndEscape(components []string, verb string, unescapingMode UnescapingMode, strictDeepWildcard bool) (map[string]string, error) { if p.verb != verb { if p.verb != "" { return nil, ErrNotMatch @@ -196,6 +224,16 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode return nil, ErrNotMatch } end -= p.tailLen + if (p.strictDeepWildcard || strictDeepWildcard) && pos > 0 && pos == end { + // A deep wildcard ("**") is allowed to match zero path segments when it is + // the first thing being matched in the pattern (pos == 0). But once a literal + // or variable segment has already consumed a component, "**" needs the request + // path to continue past that segment — it cannot succeed with nothing left to + // consume at all (though an empty trailing segment, e.g. from a trailing slash, + // still counts as a real component and is fine). + // See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771. + return nil, ErrNotMatch + } c := strings.Join(components[pos:end], "/") if c, err = unescape(c, unescapingMode, true); err != nil { return nil, err diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go index 8549dfb97a..4424775aa5 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go @@ -16,6 +16,7 @@ import ( "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/emptypb" field_mask "google.golang.org/protobuf/types/known/fieldmaskpb" "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" @@ -44,30 +45,67 @@ func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utili type DefaultQueryParser struct{} // Parse populates "values" into "msg". -// A value is ignored if its key starts with one of the elements in "filter". +// A value is ignored if its key starts with one of the elements in "filter", +// or names a field that contains one of them. func (*DefaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { + // A field is addressable by both its proto name and its JSON name, so two + // keys can set the same one. Record which fields have been set and refuse a + // second key for a field, the way protojson refuses a duplicate field in a + // body, instead of letting map iteration order pick the value that survives. + seen := make(map[string]struct{}, len(values)) for key, values := range values { + fieldKey, mapKey := key, "" if match := valuesKeyRegexp.FindStringSubmatch(key); len(match) == 3 { - key = match[1] + fieldKey, mapKey = match[1], "["+match[2]+"]" values = append([]string{match[2]}, values...) } msgValue := msg.ProtoReflect() - fieldPath := normalizeFieldPath(msgValue, strings.Split(key, ".")) - if filter.HasCommonPrefix(fieldPath) { + fieldPath := normalizeFieldPath(msgValue, strings.Split(fieldKey, ".")) + if filter.HasCommonPrefix(fieldPath) || containsFilteredField(filter, fieldPath) { continue } - if err := populateFieldValueFromPath(msgValue, fieldPath, values); err != nil { + field := strings.Join(fieldPath, ".") + mapKey + if _, ok := seen[field]; ok { + return fmt.Errorf("duplicate field %q", field) + } + seen[field] = struct{}{} + if err := populateFieldValueFromPath(msgValue, fieldPath, values, mapKey != ""); err != nil { return err } } return nil } +// containsFilteredField reports whether fieldPath names a field that contains +// one of the sequences in filter, such as "id" for a path parameter bound to +// "id.value". Setting such a field from the query, which the parser can do for +// well-known types like wrappers and timestamps, would replace the whole +// message and with it the value already bound from the path or body. +func containsFilteredField(filter *utilities.DoubleArray, fieldPath []string) bool { + if len(filter.Base) == 0 { + return false + } + + var i int + for _, t := range fieldPath { + code, ok := filter.Encoding[t] + if !ok { + return false + } + j := filter.Base[i] + code + if len(filter.Check) <= j || filter.Check[j] != i+1 { + return false + } + i = j + } + return true +} + // PopulateFieldFromPath sets a value in a nested Protobuf structure. func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error { fieldPath := strings.Split(fieldPathString, ".") - return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}) + return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}, false) } func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []string { @@ -102,7 +140,7 @@ func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []str return newFieldPath } -func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string) error { +func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string, hasMapKey bool) error { if len(fieldPath) < 1 { return errors.New("no field path") } @@ -149,6 +187,14 @@ func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []strin msgValue = msgValue.Mutable(fieldDescriptor).Message() } + // A key using the map syntax (field[key]=value) must name a map field. + // Otherwise the bracket content would be bound as if it were a regular + // value: appended as a phantom element of a repeated field, or counted + // as a second value for a singular one. + if hasMapKey && !fieldDescriptor.IsMap() { + return fmt.Errorf("field %q is not a map", fieldDescriptor.FullName().Name()) + } + switch { case fieldDescriptor.IsList(): return populateRepeatedField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values) @@ -224,7 +270,7 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro // Look for enum by name v := enum.Descriptor().Values().ByName(protoreflect.Name(value)) if v == nil { - i, err := strconv.Atoi(value) + i, err := strconv.ParseInt(value, 10, 32) if err != nil { return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value) } @@ -259,13 +305,13 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro } return protoreflect.ValueOfUint64(v), nil case protoreflect.FloatKind: - v, err := strconv.ParseFloat(value, 32) + v, err := parseFloat(value, 32) if err != nil { return protoreflect.Value{}, err } return protoreflect.ValueOfFloat32(float32(v)), nil case protoreflect.DoubleKind: - v, err := strconv.ParseFloat(value, 64) + v, err := parseFloat(value, 64) if err != nil { return protoreflect.Value{}, err } @@ -305,13 +351,13 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p } msg = durationpb.New(d) case "google.protobuf.DoubleValue": - v, err := strconv.ParseFloat(value, 64) + v, err := parseFloat(value, 64) if err != nil { return protoreflect.Value{}, err } msg = wrapperspb.Double(v) case "google.protobuf.FloatValue": - v, err := strconv.ParseFloat(value, 32) + v, err := parseFloat(value, 32) if err != nil { return protoreflect.Value{}, err } @@ -356,7 +402,9 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p msg = wrapperspb.Bytes(v) case "google.protobuf.FieldMask": fm := &field_mask.FieldMask{} - fm.Paths = append(fm.Paths, strings.Split(value, ",")...) + if value != "" { + fm.Paths = append(fm.Paths, strings.Split(value, ",")...) + } msg = fm case "google.protobuf.Value": var v structpb.Value @@ -370,6 +418,14 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p return protoreflect.Value{}, err } msg = &v + case "google.protobuf.Empty": + // An Empty carries nothing, so the only thing the value can say is that the + // field is present. Accept the two spellings of "no content" and reject + // anything else, rather than silently ignoring it. + if value != "" && value != "{}" { + return protoreflect.Value{}, fmt.Errorf("expected an empty value or %q, got %q", "{}", value) + } + msg = &emptypb.Empty{} default: return protoreflect.Value{}, fmt.Errorf("unsupported message type: %q", string(msgDescriptor.FullName())) } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go index dd99b0ed25..77186a32ae 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go @@ -72,6 +72,7 @@ func (n node) children(seqs [][]int) []*node { if lastVal == seqs[i][n.col+1] { continue } + lastVal = seqs[i][n.col+1] last.right = i last = &node{ row: i, @@ -156,6 +157,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool { var i int for _, t := range seq { + // A sequence ending at this node is already a prefix of seq, even if + // a longer sequence shares the path and the walk could carry on. + if da.hasTerminator(i) { + return true + } code, ok := da.Encoding[t] if !ok { break @@ -166,9 +172,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool { } i = j } + return da.hasTerminator(i) +} + +// hasTerminator reports whether a sequence in the DoubleArray ends at node i. +func (da *DoubleArray) hasTerminator(i int) bool { j := da.Base[i] + len(da.Encoding) - if len(da.Check) <= j || da.Check[j] != i+1 { - return false - } - return true + return j < len(da.Check) && da.Check[j] == i+1 } diff --git a/vendor/github.com/jackc/pgx/v5/.gitignore b/vendor/github.com/jackc/pgx/v5/.gitignore index a2ebbe9c60..ff05307713 100644 --- a/vendor/github.com/jackc/pgx/v5/.gitignore +++ b/vendor/github.com/jackc/pgx/v5/.gitignore @@ -22,6 +22,26 @@ _testmain.go *.exe .envrc -/.testdb + +# Per-checkout development state: this checkout's allocated TCP ports, the values derived from +# them, its decoded client certificates, and its own PostgreSQL/CockroachDB clusters. A git +# worktree is the native equivalent of a second devcontainer instance, so this is instance-local +# by definition -- never shared, never committed. See DEVELOPMENT.md. +/.dev/ + +# port-tamer writes this checkout's allocation to .dev/ports.env (the --state-file every task +# passes). These are where a bare `port-tamer` run at the repo root would put a stray second +# allocation instead; ignored so it cannot be committed by accident. +/.port-tamer.env +/.port-tamer.env.lock + +# Personal, machine-local mise overrides (mise.toml IS committed/shared). Git has no knowledge of +# mise's conventions, so this must be ignored explicitly. +/mise.local.toml + +# Provisioned on demand with `rake references:setup`; never committed. +/references/ .DS_Store + +/.vscode diff --git a/vendor/github.com/jackc/pgx/v5/Brewfile b/vendor/github.com/jackc/pgx/v5/Brewfile new file mode 100644 index 0000000000..e35acd7945 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/Brewfile @@ -0,0 +1,15 @@ +# Host dependencies only. Project tools and language runtimes belong in +# mise.toml; scripts/setup-host installs mise itself when necessary. + +# Server and client binaries for the checkout-local test matrix. +brew "postgresql@14" +brew "postgresql@15" +brew "postgresql@16" +brew "postgresql@17" +brew "postgresql@18" + +# mise compiles Ruby from source and links against these. +brew "openssl@3" +brew "readline" +brew "libyaml" +brew "gmp" diff --git a/vendor/github.com/jackc/pgx/v5/CHANGELOG.md b/vendor/github.com/jackc/pgx/v5/CHANGELOG.md index 12e633a4bb..98d8ff7f6b 100644 --- a/vendor/github.com/jackc/pgx/v5/CHANGELOG.md +++ b/vendor/github.com/jackc/pgx/v5/CHANGELOG.md @@ -1,3 +1,190 @@ +# 5.11.0 (September 7, 2026) + +This release adds direct PostgreSQL type scanning through `database/sql` on Go 1.27, improves compatibility with +libpq connection strings and PostgreSQL date/time values, and includes further decoder hardening. See Changes for +connection-string and date/time behavior changes that may affect existing applications. + +## Features + +* stdlib: support Go 1.27's `driver.RowsColumnScanner`, allowing PostgreSQL types such as arrays and ranges to be + scanned directly into Go values without `pgtype.Map.SQLScanner`. Existing `database/sql` scalar conversions and + `sql.Scanner` behavior are preserved. The minimum supported Go version remains 1.25. +* Add `Rows.TypeMap` to expose the type map used to decode rows, including rows created by `RowsFromResultReader` + that have no underlying `Conn`. Custom implementations of `Rows`, including mocks, must add this method. +* pgconn: add `Config.MaxProtocolMessageBodyLen` to configure the maximum incoming protocol message body size + (carter-ya) +* pgconn: add `ErrReadOnlyConnection`, `ErrReadWriteConnection`, `ErrPrimaryConnection`, and `ErrStandbyConnection` + sentinel errors for `target_session_attrs` validation, allowing callers to use `errors.Is` (Adrian-Stefan Mares) +* pgxpool: accept `pool_ping_timeout` in connection strings to configure `Config.PingTimeout`. The default is zero; + zero and negative durations mean no timeout (1991santhu) + +## Changes + +* Name-based row-to-struct mapping now matches explicit `db` tags case-insensitively, with exact matches taking + precedence so tags can still distinguish quoted column names that differ only by case (AlisinaDevelo) +* pgconn: resolve the OS user account only when no user is supplied by the connection string, environment, or service + file, avoiding unnecessary account lookups and crashes in some restricted container environments. Home-directory + defaults for password, service, and TLS files remain available independently of the account lookup. On Unix these + now use `$HOME` rather than the OS account's home directory (Mohamed MAACHE) + +* pgtype: `date`, `timestamp` and `timestamptz` text values are now parsed and written by a hand-written parser and + encoder for PostgreSQL's ISO date/time format instead of `time.Parse` and `time.Format`. Go's layout language cannot + express a variable-width year or the BC era, which is the root of the bugs below. The text scan path is roughly 2.5x + faster for `timestamp` and `timestamptz`. Bug fixes: + * `timestamp` and `timestamptz` no longer silently move February 29 of a BC leap year to March 1 when encoding. + `time.Date(-4712, 2, 29, ...)` was written as `4713-03-01 BC` and is now written as `4713-02-29 BC`. This + affected ordinary four-digit BC years, not only extended-range ones. `date` was never affected. + * `timestamp` and `timestamptz` can now scan BC leap days. `4713-02-29 BC` previously failed with + `day out of range`. `date` could already scan them. + * Years past 9999 can now be scanned. `10000-01-02 03:04:05` previously failed to parse, so `timestamp` and + `timestamptz` values at the high end of PostgreSQL's range were unreadable over the simple protocol and in any + other text-format result. + * `time.Time` arguments in the simple protocol now encode BC dates correctly, using the same timestamp encoder. + * Fractional seconds beyond microsecond precision are rounded the way the server rounds them (round half to even, + carrying into the rest of the value) instead of being kept at full precision. PostgreSQL never sends more than six + fractional digits, so this only affects values from other sources. + + Behavior changes: + * `date` now rejects impossible dates instead of normalizing them. `2024-02-30` returned `2024-03-01` and + `2024-13-01` returned `2025-01-01`; both are now errors. `timestamp` and `timestamptz` already rejected them. + * All three types now reject values outside PostgreSQL's range for that type, in the binary format as well as the + text format. PostgreSQL never sends out-of-range dates, so this only affects corrupt or hand-built input; the range + is checked in both formats so that whether a value is accepted does not depend on `QueryExecMode`. + `timestamptz` also rejects time zone displacements outside PostgreSQL's signed 32-bit seconds range, while accepting + the wider offsets emitted for POSIX time zones, such as `+16`. + * `timestamptz` values scanned from the text format are now returned in `time.Local`, or in `ScanLocation` when it is + set, matching what the binary format has always returned. Previously the text path kept whatever location + `time.Parse` derived from the offset the server sent, so the same value scanned in the two formats could report a + different `Location()` and `Zone()`. The instant is unchanged, but everything that renders the location changes + with it: `Timestamptz.MarshalJSON` now writes the client's offset rather than the server's, so a value the server + sent as `+05:30` marshals as `2024-01-01T13:34:05-08:00` on a UTC-8 client instead of `2024-01-02T03:04:05+05:30`, + and `DecodeDatabaseSQLValue` hands `database/sql` a `time.Time` in that same location. Set the codec's + `ScanLocation` to `time.UTC` to pin the location regardless of the client's zone. + * Error messages from these paths have changed. + +* pgconn: connection URIs (`postgres://...`) are now parsed by a new parser designed to exactly match libpq's URI + parser behavior instead of `net/url`, + making pgx accept and reject exactly the same URIs as libpq (verified by differential fuzzing against libpq itself). + Most connection strings are unaffected. Edge-case behavior changes, all matching libpq: + * `+` in query values is literal, no longer decoded as a space. + * Malformed percent-encoding is a parse error instead of the parameter being silently dropped. `%00` is rejected. + * Leading/trailing spaces in URI components are trimmed; interior spaces are a parse error (encode them as `%20`). + * `#` is ordinary data, not a fragment delimiter. + * The userinfo terminator is the first `@` before any `/` (previously the last `@`). + * When a query parameter is repeated, the last occurrence wins (previously the first). + * `ssl=true` is accepted as an alias for `sslmode=require` in URIs (JDBC compatibility). A repeated `ssl` key + follows the same last-occurrence-wins rule as other repeated parameters, even across the rewrite to `sslmode`. If + the final `ssl` value is not `true`, an independent explicit `sslmode` remains in effect. + * Multiple hosts with mixed port specs are positionally aligned: `postgres://h1,h2:5433/db` now means h1:5432 and + h2:5433 (previously both hosts got port 5433). A port list that is neither a single port nor exactly one port per + host is an error (`could not match N port numbers to M hosts`), also for keyword/value connection strings. + * An IPv6 address in a URI must be enclosed in brackets. A bare `postgres://::1/db` was previously accepted as host + `::1`; it is now read as an empty host followed by port `:1` and fails with an invalid port error. Write it as + `postgres://[::1]/db`. + * Empty host list elements (e.g. `h1,,h2`) get the default host instead of being dropped. Likewise, an empty host in + a keyword/value string (`host=`) now means the default host -- typically the Unix socket directory -- where it + previously meant a TCP connection to an empty hostname. + * An empty port (`?port=` in a URI or `port=` in a keyword/value string) now means the default port 5432 for the + affected hosts; previously it was an invalid port error. Like any connection-string port, a present-but-empty port + takes precedence over `PGPORT`. + * ASCII control characters (tab, newline, ...) in a URI are ordinary data bytes, as they are to libpq; `net/url` + rejected any URI containing one. The exception is a literal NUL byte, which is still rejected, as `net/url` did. + (libpq never sees one -- C strings end at the first NUL -- but in Go a raw NUL could otherwise pass through into + the NUL-delimited startup message and inject extra parameters.) + + Unlike libpq, unrecognized URI query parameters are still accepted (they become runtime parameters or pgx-specific + options). Parse error messages avoid quoting the unredacted connection string and redact recognizable password + fields on a best-effort basis. Invalid connection strings can be structurally ambiguous, so password redaction + cannot be guaranteed for every malformed input. + +* pgconn: keyword/value connection strings (`host=... user=...`) now match libpq's parser exactly, the same treatment + the URI parser received above and verified the same way, by differential fuzzing against libpq itself. Most + connection strings are unaffected. Behavior changes, all matching libpq: + * A backslash escapes whatever character follows it and is dropped, where previously only `\\` and `\'` were + unescaped and every other backslash was kept. A value containing a backslash must now escape it, as libpq + requires: `sslcert=C:\path\to\cert` reads as `C:pathtocert` and has to be written `sslcert=C:\\path\\to\\cert`. + This mainly affects Windows certificate and key paths, which previously came through intact without doubling. + * A trailing backslash in an unquoted value escapes the end of the string, so it is dropped and the value ends + there; it was previously rejected with `invalid backslash`. Inside a quoted value the escaped terminator leaves + the string unterminated, which is still an error. + * Whitespace inside a keyword is an error (`missing "=" after "us" in connection info string`) instead of becoming + part of the key. Whitespace around the `=` is unaffected. This most often shows up with an unquoted value + containing a space: `application_name=my app host=x` previously set neither parameter and sent `app host` to the + server as a runtime parameter, and now fails to parse. + + As with URIs, unrecognized keywords are still accepted where libpq rejects them, and an empty `user=` is still + dropped so that `PGUSER` and the OS user still apply. + +## Fixes + +* Keep the connection open after a recoverable PostgreSQL error from `Begin` or `BeginTx` + (Victor Alejandro Sanz Ararat) +* Call `TraceQueryEnd` when `Exec` fails while deallocating invalidated cached statements (Chris Bandy) +* Deallocate a failed prepare using the statement name actually sent to the server, and skip cleanup if Parse never + completed, avoiding leaked prepared statements and unnecessary cleanup errors (Eliran Ben-Zikri) +* Fix `LoadTypes` overwriting scalar codecs such as `box` and `point` with an incorrect `ArrayCodec` (Arsen Ozhetov) +* pgconn: retrieve field descriptions when cached descriptions are empty, such as for cursor `FETCH` statements, + including batch and pipeline execution (water) +* pgconn: keep batch statement descriptions and result formats aligned when commands return no rows or when + `Batch.ExecStatement` is mixed with other batch commands; preserve field descriptions for empty results +* pgconn: handle empty and comment-only queries in pipeline mode, discard stale statement data after bind errors, + and return a nil result from `Pipeline.GetResults` on error +* pgconn: skip reading the password file when a password is already set (Jared Fowkes) +* pgxpool: treat non-positive `MaxConnLifetime` values as unlimited instead of immediately expiring connections + (Aurelien Pillevesse) +* pgtype: support non-comma text array delimiters through `ArrayCodec.Delimiter`, including the semicolon delimiter + used by `box[]`. `LoadType` and `LoadTypes` now load the delimiter from PostgreSQL (Sueun Cho) +* pgtype: quote text array elements containing internal whitespace (Louisa Huang) +* pgtype: quote and escape text range bounds containing delimiters, quotes, or backslashes, and distinguish empty + string bounds from unbounded ranges (Sueun Cho) +* pgtype: preserve decimal precision in `Numeric.ScanScientific` and accept scientific notation in + `Numeric.UnmarshalJSON`; reject out-of-range scientific exponents and preserve the original input in parse errors + (Sueun Cho) +* pgtype: encode and decode numeric infinity in JSON as `"Infinity"` and `"-Infinity"` instead of encoding it as zero + (Vladimir Saraikin) +* pgtype: treat a valid `Numeric` with a nil `Int` as zero in `Int64Value`, and return errors when converting NaN or + infinity to an integer instead of panicking (Vladimir Saraikin) +* pgtype: fix an infinite loop when decoding binary numeric zero with a nonzero digit count (Vladimir Saraikin) +* pgtype: fix binary numeric digit-count overflow and trailing-byte handling. Binary encoding now rejects values + whose digit count, weight, or scale cannot fit the wire format, while accepting the full unsigned digit-count range. +* pgtype: fix scanning through multiple pointer levels, including SQL NULL and XML values, and return an error + instead of panicking when a pointer-to-pointer scan destination is nil (Rangel Reale) +* pgtype: use bounds-checked binary reads throughout the codecs and reject malformed lengths, counts, and trailing + data. This includes fixes for panics on malformed records and truncated multiranges (Vladimir Saraikin), and + validation of `bit` / `varbit` bit lengths against the actual data (g3m0sis). +* pgtype: return errors instead of panicking on malformed interval text (greymoth-jp), unterminated composite text + fields, and text arrays whose dimensions and element counts disagree +* pgtype: cap the initial allocation estimate when parsing hstore text to avoid excessive allocation from unvalidated + separator counts; valid hstores may still contain any number of pairs (AshSgDe29071999) +* pgtype: correct reversed bounds in integer scan error messages +* pgconn: a backslash as the last byte of a quoted value in a keyword/value connection string no longer panics with + `slice bounds out of range`. `host='a\` -- and the shorter `='\`, reachable through `pgx.ParseConfig` and + `pgxpool.ParseConfig` -- now return `unterminated quoted string in connection info string`, libpq's own message for + the same input. The unquoted branch has been guarded since be69c1c1; the quoted branch carried the same unguarded + increment since the parser was ported from pgx v3. Found by fuzzing (Maxim Korotkov) +* pgconn: error messages that embed the connection string now also redact `password` and `sslpassword` values supplied + as URI query parameters; previously only the userinfo password was redacted. Redaction matches keys the way the + parser does -- percent-encoded spellings such as `pass%77ord=` are recognized -- and masks the entire raw value, so + a password containing a space cannot leak its tail into the error message. Credentials stranded outside the + userinfo by a malformed URI are masked whole, and invalid-port errors no longer embed the offending text (which in + a malformed URI can be a mislaid password). Redaction of invalid connection strings is necessarily best effort: + their structure may be ambiguous, so some malformed inputs can still expose password text in an error. +* pgconn: `ParseConfigOptions.ConnStringAllowedKeys` no longer exempts an explicitly supplied empty port (`?port=` in + a URI or `port=` in a keyword/value string) from the allow-list. Only the implied all-empty port list of a + multi-host URI without ports (`postgres://h1,h2/db`) is exempt. An explicit empty port shadows `PGPORT` even though + it is empty, so it must be allowed like any other user-supplied key. The URI-only `ssl=true` alias is accepted when + either `ssl` or `sslmode` is allowed, and every `ssl`/`sslmode` spelling written in the URI is validated -- + including occurrences superseded by later repeated parameters. +* pgconn: drain socket before close in `asyncClose` so context cancellation produces a TCP FIN instead of RST, avoiding "connection reset by peer" on the server / proxy (Sean Chittenden at CrowdStrike, Inc.) +* pgproto3: `StartupMessage.Encode` rejects a NUL byte in any parameter name or value instead of writing it. The + startup message body is a run of NUL-delimited strings whose length is data-driven, so a NUL in a value ends that + parameter and everything after it is read by the server as further parameters -- an `application_name` of + `x\x00user\x00admin` changed the role the connection logged in as. libpq cannot reach this state because its + parameters are NUL-terminated C strings. `Connect` now fails with nothing written to the wire, which covers + settings that bypass connection string parsing: service files and direct assignment to `Config.RuntimeParams`, + `Config.User`, or `Config.Database`. +* pgconn: keyword/value connection strings containing a NUL byte are rejected by `ParseConfig`, as URIs already were. + # 5.10.0 (June 3, 2026) This release includes a significant amount of hardening against malicious or compromised PostgreSQL servers, diff --git a/vendor/github.com/jackc/pgx/v5/CLAUDE.md b/vendor/github.com/jackc/pgx/v5/CLAUDE.md index 71a8fc164d..3b9f3008af 100644 --- a/vendor/github.com/jackc/pgx/v5/CLAUDE.md +++ b/vendor/github.com/jackc/pgx/v5/CLAUDE.md @@ -8,41 +8,59 @@ pgx is a PostgreSQL driver and toolkit for Go (`github.com/jackc/pgx/v5`). It pr ## Build & Test Commands +Every checkout has its own PostgreSQL 14-18 and CockroachDB instances, supervised by +process-compose. `mise run dev` starts PostgreSQL 18; tests start other targets on demand and stop +them afterwards unless they were explicitly prewarmed. See DEVELOPMENT.md. + ```bash -# Run all tests (requires PGX_TEST_DATABASE to be set) -go test ./... +mise run dev # start PostgreSQL 18 and the database supervisor +mise run dev:all # eagerly start every available database +mise run dev -- -D # ... detached; then `mise run dev:wait`, and + # `mise run dev:down` when finished. Agents must do this. + +./test.sh # Full suite against PostgreSQL 18 (the default target) +./test.sh pg16 # Against PostgreSQL 16 +./test.sh crdb # Against CockroachDB +./test.sh all # Every target (pg14-18 + crdb) +./test.sh pg16 -run TestConnect # Trailing arguments are passed to `go test` + +go test ./... # Also works: mise loads the default target's PGX_TEST_* +go test -race ./... # With the race detector + +goimports -w . # Format (always run after making changes) +golangci-lint run ./... # Lint + +mise run dev:ports # This checkout's ports and where each server's data lives +mise run db:start pg16 crdb # Prewarm targets; tests then leave them running +mise run db:stop pg16 crdb # Stop prewarmed targets +mise run db:psql # psql against PostgreSQL 18; `mise run db:psql 16` for another +process-compose process logs pg16 # One server's output +``` -# Run a specific test -go test -run TestFunctionName ./... +Do not hardcode database ports. They are allocated per checkout by port-tamer and read from the +environment (`PGPORT`, `PGPORT_16`, `CRDB_PORT`) or `.dev/ports.env`; 5432 and 26257 mean nothing +here. -# Run tests for a specific package -go test ./pgconn/... +The `PGX_TEST_*` connection strings have one definition, `scripts/lib/test_targets.rb`. Add or +change a target there, never in a second copy. -# Run tests with race detector -go test -race ./... +## Test Database Setup -# DevContainer: run tests against specific PostgreSQL versions -./test.sh pg18 # Default: PostgreSQL 18 -./test.sh pg16 -run TestConnect # Specific test against PG16 -./test.sh crdb # CockroachDB -./test.sh all # All targets (pg14-18 + crdb) +The lifecycle scripts handle setup: a PostgreSQL server initializes its cluster on first start and +creates `pgx_test` with the extensions and auth roles from `testsetup/postgresql_setup.sql`. +CockroachDB recreates `pgx_test` after each in-memory restart. Nothing needs to be set up by hand. -# Format (always run after making changes) -goimports -w . +Contributors who would rather point pgx at a PostgreSQL server they already have can set +`PGX_TEST_DATABASE` themselves; see CONTRIBUTING.md. Many tests are skipped unless additional +`PGX_TEST_*` variables are set (for TLS, SCRAM, MD5, unix socket, PgBouncer testing). -# Lint -golangci-lint run ./... -``` +## Reference Material -## Test Database Setup - -Tests require `PGX_TEST_DATABASE` environment variable. In the devcontainer, `test.sh` handles this. For local development: - -```bash -export PGX_TEST_DATABASE="host=localhost user=postgres password=postgres dbname=pgx_test" -``` +`references/` holds read-only reference checkouts used when building pgx — currently the PostgreSQL source tree pinned to `REL_18_STABLE`. It is gitignored and provisioned on demand: bare mirrors are cached at a machine-level path (`/persist/shared/references` in a devcontainer, `~/.local/share/pgx/references` natively; `REFERENCES_MIRROR_DIR` overrides) and lightweight local checkouts are created in `references/` with `rake references:setup`. Each checkout has per-instance Git metadata while borrowing the shared mirror's object store. Related tasks: `rake references:update`, `rake references:status`, `rake references:clean`. -The test database needs extensions: `hstore`, `ltree`, and a `uint64` domain. See `testsetup/postgresql_setup.sql` for full setup. Many tests are skipped unless additional `PGX_TEST_*` env vars are set (for TLS, SCRAM, MD5, unix socket, PgBouncer testing). +- Do not automatically provision or update `references/`. +- Never run `rake references:setup`, `rake references:update`, or any large download on your own initiative. +- If reference sources are missing, work without them or ask the user. ## Architecture diff --git a/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md b/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md index 2283ae6700..c89ec1a133 100644 --- a/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md +++ b/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md @@ -24,21 +24,30 @@ Using AI is acceptable (not that it can really be stopped) under one the followi ## Development Environment Setup -pgx tests naturally require a PostgreSQL database. It will connect to the database specified in the `PGX_TEST_DATABASE` -environment variable. The `PGX_TEST_DATABASE` environment variable can either be a URL or key-value pairs. In addition, -the standard `PG*` environment variables will be respected. Consider using [direnv](https://github.com/direnv/direnv) to -simplify environment variable handling. +pgx tests naturally require a PostgreSQL database. It will connect to the database specified in the +`PGX_TEST_DATABASE` environment variable. The `PGX_TEST_DATABASE` environment variable can either be +a URL or key-value pairs. In addition, the standard `PG*` environment variables will be respected. -### Devcontainer +### The full environment -The easiest way to start development is with the included devcontainer. It includes containers for each supported -PostgreSQL version as well as CockroachDB. `./test.sh all` will run the tests against all database types. +[DEVELOPMENT.md](DEVELOPMENT.md) describes the maintained setup: [mise](https://mise.jdx.dev) +installs the toolchain, and each checkout has its own PostgreSQL 14-18 clusters and CockroachDB +node, so the whole test matrix is available locally. PostgreSQL 18 stays running; other servers +start and stop around their tests. It works natively on macOS and Linux, and in the included +devcontainer. -### Using an Existing PostgreSQL Cluster Outside of a Devcontainer +``` +mise install +mise run dev:init +mise run dev +./test.sh all +``` -If you already have a PostgreSQL development server this is the quickest way to start and run the majority of the pgx -test suite. Some tests will be skipped that require server configuration changes (e.g. those testing different -authentication methods). +### Using an existing PostgreSQL cluster + +If you already have a PostgreSQL development server this is the quickest way to run the majority of +the pgx test suite, and it needs nothing from the section above. Some tests will be skipped that +require server configuration changes (e.g. those testing different authentication methods). Create and setup a test database: @@ -50,86 +59,30 @@ psql -c 'create extension ltree;' psql -c 'create domain uint64 as numeric(20,0);' ``` -Ensure a `postgres` user exists. This happens by default in normal PostgreSQL installs, but some installation methods -such as Homebrew do not. +Ensure a `postgres` user exists. This happens by default in normal PostgreSQL installs, but some +installation methods such as Homebrew do not. ``` createuser -s postgres ``` -Ensure your `PGX_TEST_DATABASE` environment variable points to the database you just created and run the tests. +Ensure your `PGX_TEST_DATABASE` environment variable points to the database you just created and run +the tests. ``` export PGX_TEST_DATABASE="host=/private/tmp database=pgx_test" go test ./... ``` -This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing different connection methods). - -### Creating a New PostgreSQL Cluster Exclusively for Testing Outside of a Devcontainer - -The following environment variables need to be set both for initial setup and whenever the tests are run. (direnv is -highly recommended). Depending on your platform, you may need to change the host for `PGX_TEST_UNIX_SOCKET_CONN_STRING`. - -``` -export PGPORT=5015 -export PGUSER=postgres -export PGDATABASE=pgx_test -export POSTGRESQL_DATA_DIR=postgresql - -export PGX_TEST_DATABASE="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" -export PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/private/tmp database=pgx_test" -export PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" -export PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_scram password=secret database=pgx_test channel_binding=disable" -export PGX_TEST_SCRAM_PLUS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test channel_binding=require" -export PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" -export PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_pw password=secret" -export PGX_TEST_TLS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem channel_binding=disable" -export PGX_SSL_PASSWORD=certpw -export PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost user=pgx_sslcert sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test sslcert=`pwd`/.testdb/pgx_sslcert.crt sslkey=`pwd`/.testdb/pgx_sslcert.key" -``` - -Create a new database cluster. - -``` -initdb --locale=en_US -E UTF-8 --username=postgres .testdb/$POSTGRESQL_DATA_DIR - -echo "listen_addresses = '127.0.0.1'" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf -echo "port = $PGPORT" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf -cat testsetup/postgresql_ssl.conf >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf -cp testsetup/pg_hba.conf .testdb/$POSTGRESQL_DATA_DIR/pg_hba.conf - -cd .testdb - -# Generate CA, server, and encrypted client certificates. -go run ../testsetup/generate_certs.go - -# Copy certificates to server directory and set permissions. -cp ca.pem $POSTGRESQL_DATA_DIR/root.crt -cp localhost.key $POSTGRESQL_DATA_DIR/server.key -chmod 600 $POSTGRESQL_DATA_DIR/server.key -cp localhost.crt $POSTGRESQL_DATA_DIR/server.crt - -cd .. -``` - - -Start the new cluster. This will be necessary whenever you are running pgx tests. - -``` -postgres -D .testdb/$POSTGRESQL_DATA_DIR -``` - -Setup the test database in the new cluster. - -``` -createdb -psql --no-psqlrc -f testsetup/postgresql_setup.sql -``` +This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing +different connection methods). ### PgBouncer There are tests specific for PgBouncer that will be executed if `PGX_TEST_PGBOUNCER_CONN_STRING` is set. +The test PgBouncer must be version 1.21.0 or newer, use transaction pooling, and have `max_prepared_statements` set to a +non-zero value. This ensures the tests cover PgBouncer's protocol-level named prepared statement support in addition to +the pgx query modes that do not use named prepared statements. ### Optional Tests diff --git a/vendor/github.com/jackc/pgx/v5/DEVELOPMENT.md b/vendor/github.com/jackc/pgx/v5/DEVELOPMENT.md new file mode 100644 index 0000000000..d2a91f8dfd --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/DEVELOPMENT.md @@ -0,0 +1,239 @@ +# Developing pgx + +Two supported environments, one command set. Native macOS or Linux is the fast inner loop; the +devcontainer is a Linux compatibility and isolation option. Both run the same mise tasks against +the same `process-compose.yaml`, so nothing here is specific to one of them except the +prerequisites in §1. + +```sh +scripts/setup-host # native macOS or Ubuntu host prerequisites (once per machine) +export PATH="$HOME/.local/bin:$PATH" # if mise was just installed +mise trust # trust this checkout's configuration +mise install # tool versions from mise.toml +mise run dev:init # this checkout's ports and certificates +mise run dev # start PostgreSQL 18 and the on-demand database supervisor +./test.sh # the suite against PostgreSQL 18 +./test.sh all # every target; non-default servers start and stop around their tests +``` + +--- + +## 1. Prerequisites + +### Native + +[mise](https://mise.jdx.dev) provides Go, Ruby, CockroachDB, process-compose, and port-tamer. +PostgreSQL itself is the one thing it does not: pgx tests against five major versions, and they +come from the system package manager. + +```sh +scripts/setup-host +``` + +On macOS, install [Homebrew](https://brew.sh) first. The script uses `Brewfile` to install +PostgreSQL 14-18 and Ruby build dependencies. On Ubuntu, it uses sudo when needed, configures +the official PostgreSQL apt repository, and installs the same server versions and build +dependencies. Other Linux distributions require manual prerequisite installation. + +The Ubuntu installer temporarily disables automatic `main` cluster creation during server +installation and removes that override on exit, leaving the package-owned cluster configuration +unchanged. The macOS installer does not start Homebrew services. + +The dispatcher installs mise if it is missing and prints its executable path. It does not run +`mise trust`, install project tools, allocate ports, initialize databases, or start servers. Run +the remaining commands above explicitly as your regular development user. + +- **Do not** `brew services start` any of them, and on Debian do not let the packages create a + machine-wide cluster. pgx runs its own clusters per checkout. +- The Homebrew formulas are *keg-only*, so `psql` and `pg_isready` are not on your `PATH` after + install. `mise.toml` adds PostgreSQL 18's `bin` to `PATH` for this project — one client serves + every server, since libpq is backward compatible. +- Only the majors you actually test against need to be installed. `mise run dev` looks for each + one's server binaries and names any that are missing; `./test.sh pg15` reports a direct install + hint rather than trying to launch a missing server. `PGBIN_16` and friends override the search + for a major built or installed somewhere unusual. +- Clusters are created with the `en_US.UTF-8` locale where the system has it (matching CI and the + container images this replaced), falling back to `C.UTF-8` and then `C`. A stock Debian or Ubuntu + has only `C.UTF-8` unless you have run `locale-gen en_US.UTF-8`. + +### Devcontainer + +Reopen in the container; `.devcontainer/` handles the rest. It installs the same five PostgreSQL +servers and runs the same per-checkout clusters — it is a Linux shell around this same setup, not a +second architecture. + +--- + +## 2. Checkouts are the unit of isolation + +A git worktree is the native equivalent of a second devcontainer instance. Each one gets: + +``` +.dev/ # gitignored, per-checkout runtime state + ports.env # this checkout's TCP ports (port-tamer's state file) + derived.env # PG* defaults and the default target's PGX_TEST_* set + certs/ # the client certificates the TLS tests use + logs/ # one log per service + -/postgres/run # one socket directory, shared by all five servers (mode 0700) + -/postgres//data + -/crdb/ +``` + +The last three — the clusters, the CockroachDB store and the socket directory — move when +`PGX_DEV_RUNTIME_DIR` is set. The devcontainer sets it to `/persist/local/dev`, on its own named +volume: `.dev/` is inside the `/workspaces/pgx` bind mount, and `initdb` and Unix sockets do not +work reliably on Docker Desktop's macOS/Windows file sharing. (The per-version PostgreSQL +containers this setup replaced used named volumes for their data and socket directories for the +same reason.) Everything else stays in the checkout. + +```sh +git worktree add ../pgx-feature-x feature-x +cd ../pgx-feature-x +mise run dev:init && mise run dev +``` + +Both checkouts run simultaneously: different ports, independent database state, independent +process-compose instances. `mise run dev:ports` prints the allocation. + +Ports are allocated once per checkout by [port-tamer](https://github.com/jackc/port-tamer) and then +persisted. `port-tamer.toml` declares which ports a checkout needs — **append new entries at the +end**, since inserting or reordering renumbers the existing ones. A listening port never moves an +existing allocation, because it may well belong to this checkout's own running services; when two +checkouts genuinely collide, stop one and run `mise run dev:ports:overwrite`. + +The data directories are keyed by platform because a cluster `initdb`'d by the Linux devcontainer +cannot be read by a native macOS server, and one checkout may be opened both ways. After switching +a checkout between the two, re-run `mise run dev:ports:ensure` so the derived paths follow. + +**Reference sources** (`references/`) are provisioned per checkout with `rake references:setup`, +sharing one machine-level mirror (`/persist/shared` in a container, `~/.local/share/pgx` natively; +`REFERENCES_MIRROR_DIR` overrides). They are a multi-GB download; nothing provisions them +automatically. + +--- + +## 3. The databases + +`mise run dev` starts PostgreSQL 18 under +[process-compose](https://github.com/F1bonacc1/process-compose). PostgreSQL 14-17 and a single-node +in-memory CockroachDB are registered with the same supervisor but disabled initially, ready to be +started by a test or an explicit `db:start`. `mise run dev:all` eagerly starts every available +server. These are the same services the devcontainer used to run as containers; they are now +ordinary processes against this checkout's own clusters. + +Each PostgreSQL server initializes its cluster on first start — `initdb`, this project's +`pg_hba.conf`, and the TLS certificates — then creates `pgx_test` with its extensions and its +`pgx_md5` / `pgx_scram` / `pgx_pw` / `pgx_ssl` / `pgx_sslcert` roles. The default server uses its +follow-on `pg18-setup` process; the lazy lifecycle performs the same idempotent setup directly for +an on-demand target. Restarts are free once the cluster exists. If setup fails partway it drops the +half-built database so the next start retries rather than reporting it as present. + +CockroachDB has no separate setup process: its store is in memory, so every restart is an empty +cluster and its readiness probe creates `pgx_test` itself. + +```sh +process-compose process list # status, scriptable +process-compose process logs pg16 # one server's output +mise run db:start pg16 crdb # prewarm one or more targets +mise run db:stop pg16 crdb # stop them again +mise run db:start all # prewarm every target +process-compose down # stop this checkout's stack only +mise run db:psql # psql against the already-running PostgreSQL 18 +mise run db:start pg16 # prewarm PostgreSQL 16 before interactive use +mise run db:psql 16 # psql against PostgreSQL 16 +mise run db:psql 16 -c 'select 1' # arguments after the major go to psql +``` + +The `process-compose` commands need no flags: `PC_PORT_NUM` is part of this checkout's +environment, so they never reach another checkout's stack. + +`rake db:psql[16]` is the same as `mise run db:psql 16`. Note the brackets — a bare +`rake db:psql 16` is rake asking for a *task* named `16`, not an argument, so the `db:*` tasks +reject it rather than quietly acting on every cluster. + +`mise run db:reset` destroys and re-creates clusters and refuses to run while the selected servers +are up: removing a data directory under a live postmaster corrupts it. Stop selected targets with +`mise run db:stop`, or stop the whole supervisor with `mise run dev:down`. + +All five PostgreSQL servers share **one** Unix socket directory. Sockets are named +`.s.PGSQL.`, so the port picks the server — which is what lets a single +`PGX_TEST_UNIX_SOCKET_CONN_STRING` work for every major, exactly as the container's shared +`/var/run/postgresql` volume did. + +Tests preserve explicit choices: if `db:start` prewarmed a target, tests leave it running. If a +test had to start the target, it stops it in an `ensure` block whether the suite passes, fails, or +is interrupted. A per-target lock prevents concurrent test commands from stopping a server the +other is using. + +--- + +## 4. Running tests + +```sh +./test.sh # PostgreSQL 18, the default target +./test.sh pg14 # PostgreSQL 14 +./test.sh crdb # CockroachDB +./test.sh all # every target, sequentially +./test.sh pg16 -run TestConnect # trailing arguments go to `go test` +``` + +`mise run test` and `mise run test:all` are equivalent. All of them require the stack to be +running, but only their selected database target needs to be up. A stopped target is started, +bootstrapped, and stopped automatically. `./test.sh all` does this sequentially, so at most the +default PostgreSQL 18 plus one additional database is normally resident. + +A bare `go test ./...` also works: mise loads `.dev/derived.env`, which carries the default +target's full `PGX_TEST_*` set, so an activated shell is already pointed at PostgreSQL 18. + +Those connection strings have exactly one definition, `scripts/lib/test_targets.rb`. Both consumers +— the generated `.dev/derived.env` and `./test.sh ` — read it, so there is no second copy +to drift. + +Some tests only run when their environment variable is set. `go test ./... -v | grep SKIP` shows +what is being skipped; on a healthy stack that is the PgBouncer, OAuth, CrateDB, and libpq-oracle +tests, which are CI-only or manual. + +--- + +## 5. Everyday commands + +| Command | What it does | +|---|---| +| `mise run dev` | start PostgreSQL 18 and the on-demand database supervisor | +| `mise run dev:all` | eagerly start every available database | +| `mise run dev -- -D` | start the default stack detached, for CI and agents | +| `mise run dev:wait` / `dev:down` | wait for a detached stack / stop it | +| `mise run dev:init` | allocate this checkout's ports, decode its certificates | +| `mise run dev:ports` | the allocation, and where each server's data lives | +| `mise run test [target]` | the suite against one target | +| `mise run test:all` | every target | +| `mise run db:start [targets...]` / `db:stop` | prewarm or stop targets (`pg16`, `crdb`, or `all`) | +| `mise run db:init [major]` / `db:psql [major]` / `db:reset [major]` | create / open / rebuild the clusters | +| `mise run fmt` | `goimports -w .` | +| `mise run generate` | regenerate the ERB-templated sources | + +`rake ` remains equally valid and is where some of the logic lives; `rake -T` lists +everything, including tasks with no mise wrapper (`references:*`, `db:setup`). + +--- + +## 6. Notes + +- **`PGHOST` and `PGPORT` are a pair.** They come from `.dev/` via mise — `PGPORT` from the + allocation, `PGHOST` derived from it. Setting one without the other names a real port on the + wrong server, and the error will point at a socket nothing ever created. `mise run dev` asserts + the two agree with the cluster before starting anything. +- **`.dev/derived.env` is generated.** If it is ever hand-edited into something mise's dotenv + parser rejects, every `mise` command in the directory fails — including the one that would + rewrite it. Recover with `rm .dev/derived.env && mise run dev:ports:ensure`. +- **A `~/.psqlrc` that changes session defaults** can break the database bootstrap while leaving + interactive use fine. The scripts pass `--no-psqlrc` for that reason. +- **`./test.sh` needs Ruby 3.0+**, which `mise install` provides. If mise is installed but not yet + activated in your shell, `./test.sh` re-runs itself through `mise exec` rather than failing on + the system interpreter. +- **CI does not use any of this.** `.github/workflows/ci.yml` installs system PostgreSQL through + `ci/setup_test.bash` and carries its own copy of the connection strings. Local runs and CI + exercise the same auth paths — `PGX_TEST_DATABASE` connects as `pgx_md5`, and one + `testsetup/pg_hba.conf` serves both — but the two setups are still independent. +- **PgBouncer and the PG18 OAuth validator module** are exercised only in CI. Neither is part of + the local stack, and both were absent from the devcontainer too. diff --git a/vendor/github.com/jackc/pgx/v5/README.md b/vendor/github.com/jackc/pgx/v5/README.md index aa35e4a3d6..4dd8dddabf 100644 --- a/vendor/github.com/jackc/pgx/v5/README.md +++ b/vendor/github.com/jackc/pgx/v5/README.md @@ -12,7 +12,15 @@ The toolkit component is a related set of packages that implement PostgreSQL fun and type mapping between PostgreSQL and Go. These underlying packages can be used to implement alternative drivers, proxies, load balancers, logical replication clients, etc. -## Example Usage +## Quick Start + +### Installation + +```bash +go get github.com/jackc/pgx/v5 +``` + +### Example Usage ```go package main @@ -46,7 +54,18 @@ func main() { } ``` -See the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx) for more information. +### Connection Configuration + +`pgx.Connect` and `pgxpool.New` accept PostgreSQL connection URLs (such as `postgres://user:pass@host:5432/db?sslmode=verify-full`) as well as `key=value` strings. See [`pgconn.ParseConfig`](https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn#ParseConfig) and the [PostgreSQL connection string documentation](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) for supported options and environment variables. + +For a step-by-step walkthrough, see the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx). + +## Documentation + +Package documentation and API reference are available on [pkg.go.dev](https://pkg.go.dev/github.com/jackc/pgx/v5): +* [`pgx`](https://pkg.go.dev/github.com/jackc/pgx/v5) — base PostgreSQL driver +* [`pgxpool`](https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool) — concurrency-safe connection pool +* [`stdlib`](https://pkg.go.dev/github.com/jackc/pgx/v5/stdlib) — `database/sql` compatibility adapter ## Features @@ -82,9 +101,30 @@ The pgx interface is recommended when: It is also possible to use the `database/sql` interface and convert a connection to the lower-level pgx interface as needed. -## Testing +## Development and Testing + +Each checkout has its own PostgreSQL 14-18 clusters and CockroachDB node, so the whole test matrix +is available locally on macOS, on Linux, or in the included devcontainer. Only PostgreSQL 18 stays +running by default; other targets start and stop around their tests: + +```sh +scripts/setup-host # native macOS (Homebrew required) or Ubuntu: host packages and mise +export PATH="$HOME/.local/bin:$PATH" # if mise was just installed +mise trust +mise install # project tools +mise run dev:init # checkout ports and certificates +mise run dev # start PostgreSQL 18 and the on-demand database supervisor +./test.sh # the suite against PostgreSQL 18 +./test.sh all # every target, starting and stopping each server as needed +``` + +Host setup installs PostgreSQL 14-18 and Ruby build dependencies. It does not install project +tools or initialize the checkout; those remain separate steps above. The devcontainer already +provides the host prerequisites. -See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup instructions. +See [DEVELOPMENT.md](./DEVELOPMENT.md) for the full setup, and +[CONTRIBUTING.md](./CONTRIBUTING.md) for how to contribute — including how to run the tests against +a PostgreSQL server you already have, without any of the above. ## Architecture diff --git a/vendor/github.com/jackc/pgx/v5/Rakefile b/vendor/github.com/jackc/pgx/v5/Rakefile index 3e3aa5030d..57c605020d 100644 --- a/vendor/github.com/jackc/pgx/v5/Rakefile +++ b/vendor/github.com/jackc/pgx/v5/Rakefile @@ -1,4 +1,5 @@ require "erb" +require "fileutils" rule '.go' => '.go.erb' do |task| erb = ERB.new(File.read(task.source)) @@ -16,3 +17,293 @@ generated_code_files = [ desc "Generate code" task generate: generated_code_files + +# dev -- per-checkout development state. A git worktree is the native equivalent of a second +# devcontainer instance: same machine, same network stack, so the five PostgreSQL servers and +# CockroachDB that each owned a well-known port in their own container namespace now need distinct +# ones. `dev:ports:*` drives port-tamer (port-tamer.toml declares the names; the allocation lands +# in the gitignored .dev/ports.env) and writes the values derived from it -- scripts/devenv.rb. +namespace :dev do + namespace :ports do + desc "Allocate this checkout's TCP ports if it has none (idempotent)" + task :ensure do + sh RbConfig.ruby, "scripts/devenv.rb", "ensure" + end + + desc "Move this checkout to a different port group (stop its services first)" + task :overwrite do + sh RbConfig.ruby, "scripts/devenv.rb", "overwrite" + end + + desc "Print this checkout's port allocation and where each server's data lives" + task :show do + sh RbConfig.ruby, "scripts/devenv.rb", "show" + end + end +end + +# db -- this checkout's own PostgreSQL clusters, one per major (scripts/devdb.rb). Clusters per +# checkout rather than databases inside shared servers: destructive resets stay local, two +# checkouts run at once, and the layout matches the per-instance devcontainer model it replaces. +# The SERVERS run in the foreground under process-compose (process-compose.yaml); these are the +# one-shot half. Each task takes an optional major, defaulting to all of them. +# +# rake db:init initialize every cluster +# rake db:init[16] just PostgreSQL 16 +# rake db:psql[16] psql against PostgreSQL 16 (default: the newest major) +# +# The mise wrappers (`mise run db:init 16`) call scripts/devdb.rb directly rather than routing +# through these tasks — mise APPENDS its arguments, and `rake db:init 16` means "run task db:init, +# then run task 16", not "run db:init with the argument 16". +namespace :db do + # A bare major on the command line is the natural thing to type and the one rake cannot mean: + # it becomes a second TASK name, so `rake db:reset 16` runs db:reset with no major — every + # cluster — and only then fails on the unknown task, after the data is gone. Catch it first. + def db_major(task, args) + stray = Rake.application.top_level_tasks.find { |t| t =~ /\A\d+\z/ } + if stray + abort "rake: `#{stray}` is being read as a task name, not an argument. " \ + "Write `rake #{task.name}[#{stray}]` (or `mise run #{task.name} #{stray}`)." + end + + Array(args[:major]) + end + + desc "Create this checkout's PostgreSQL clusters under .dev (idempotent). Optional: rake db:init[16]" + task :init, [:major] do |task, args| + sh RbConfig.ruby, "scripts/devdb.rb", "init", *db_major(task, args) + end + + desc "psql against one of this checkout's clusters. Optional: rake db:psql[16]" + task :psql, [:major] do |task, args| + sh RbConfig.ruby, "scripts/devdb.rb", "psql", *db_major(task, args) + end + + desc "Create the pgx_test database and roles in a running cluster (idempotent)" + task :setup, [:major] do |task, args| + sh RbConfig.ruby, "scripts/devdb.rb", "setup", *db_major(task, args) + end + + desc "Destroy this checkout's clusters and re-initialize (destructive; CONFIRM=yes)" + task :reset, [:major] do |task, args| + sh RbConfig.ruby, "scripts/devdb.rb", "reset", *db_major(task, args) + end +end + +# references:* — provision local, read-only checkouts of reference material used +# when building pgx (currently the PostgreSQL source tree). +# +# Storage model: +# * A bare `--mirror` clone of each repo lives on the devcontainer's shared +# persist volume under MIRROR_ROOT. It holds the full history + all +# branches/tags, is downloaded once, and survives container rebuilds. It is +# the canonical copy, shared across every container for this project. +# * Each container creates a lightweight shared clone in ./references/. +# Its Git metadata is local to that checkout while its object store borrows +# from the mirror. Containers can therefore use the same in-container path +# without sharing Git worktree registrations or downloading history again. +# +# Provisioning a new container is therefore cheap: a local clone from the +# already-present mirror, with no network fetch or duplicate object store. + +# Each entry is one reference repo. `ref` is the branch/tag checked out into the +# local checkout. PostgreSQL is pinned to REL_18_STABLE to match the devcontainer's +# default PG18 test target. +REFERENCE_REPOS = [ + { name: "postgres", url: "https://github.com/postgres/postgres.git", ref: "REL_18_STABLE", license: "PostgreSQL License" }, +].freeze + +# Where the canonical bare mirrors live. They are machine-level state, not checkout-level: +# multiple GB, read-only, and identical for every checkout -- so they belong outside the tree, and +# every checkout on the machine shares one copy. +# +# * devcontainer -- the shared persist volume, so every container for this project reuses one +# download and a rebuild costs nothing. +# * native -- an XDG data directory under $HOME, where git worktrees of this repo share it the +# same way containers share the volume. +# +# REFERENCES_MIRROR_DIR overrides both (a second disk, a scratch location, a test). +def default_mirror_root + return "/persist/shared/references" if File.directory?("/persist/shared") + + xdg = ENV["XDG_DATA_HOME"] + base = xdg.nil? || xdg.empty? ? File.join(Dir.home, ".local", "share") : xdg + File.join(base, "pgx", "references") +end + +MIRROR_ROOT = ENV.fetch("REFERENCES_MIRROR_DIR") { default_mirror_root } +CHECKOUT_ROOT = File.join(__dir__, "references") + +def mirror_path(repo) = File.expand_path(File.join(MIRROR_ROOT, "#{repo[:name]}.git")) +def checkout_path(repo) = File.join(CHECKOUT_ROOT, repo[:name]) + +# File.exist? is false for dangling symlinks, which are still leftovers setup +# must replace (and clean must remove). +def path_present?(path) = File.exist?(path) || File.symlink?(path) + +# Run a git command against a bare mirror. Names the gitdir explicitly and lifts +# any safe.bareRepository=explicit guard. Raises on failure. +def git_bare(repo, *args) + sh "git", "-c", "safe.bareRepository=all", "--git-dir", mirror_path(repo), *args +end + +# Capture stdout of a command given as an argv array (no shell parsing, no +# quoting pitfalls). Returns [stdout_string, success_boolean]. +def capture(*args) + out = IO.popen(args, err: File::NULL, &:read) + [out.to_s, $?.success?] +end + +# A managed checkout has its own repository metadata, uses this exact mirror as +# its origin, and borrows that mirror's object database. This rejects ordinary +# clones, linked worktrees left by the old implementation, and dangling gitfiles. +def checkout_valid?(repo) + wp = checkout_path(repo) + git_dir = File.join(wp, ".git") + objects_dir = File.join(git_dir, "objects") + alternates_path = File.join(objects_dir, "info", "alternates") + + return false unless File.directory?(git_dir) && File.file?(alternates_path) + + inside, inside_ok = capture("git", "-C", wp, "rev-parse", "--is-inside-work-tree") + origin, origin_ok = capture("git", "-C", wp, "remote", "get-url", "origin") + return false unless inside_ok && inside.strip == "true" && origin_ok + return false unless File.identical?(File.expand_path(origin.strip, wp), mirror_path(repo)) + + File.foreach(alternates_path).any? do |alternate| + alternate = alternate.strip + next false if alternate.empty? + + File.identical?(File.expand_path(alternate, objects_dir), File.join(mirror_path(repo), "objects")) + end +rescue SystemCallError + false +end + +# A mirror is valid only if it exists AND has at least one ref — this rejects a +# directory left behind by an interrupted clone (which exists but is incomplete). +def mirror_valid?(repo) + return false unless File.directory?(mirror_path(repo)) + out, ok = capture("git", "-c", "safe.bareRepository=all", "--git-dir", mirror_path(repo), "for-each-ref", "--count=1") + ok && !out.strip.empty? +end + +# Clone the bare mirror onto the persist volume if it is missing or broken. +def ensure_mirror(repo) + if mirror_valid?(repo) + puts " mirror cached: #{mirror_path(repo)}" + else + FileUtils.rm_rf(mirror_path(repo)) # clear any partial/broken clone + puts " cloning mirror (full history): #{repo[:url]}" + sh "git", "clone", "--mirror", repo[:url], mirror_path(repo) + end +end + +# Serialize mirror creation and updates across devcontainer instances. Local +# checkouts do not share metadata, but they all read from the same object store. +def with_mirror_lock(repo) + FileUtils.mkdir_p(MIRROR_ROOT) + File.open(File.join(MIRROR_ROOT, ".#{repo[:name]}.lock"), File::RDWR | File::CREAT, 0o644) do |lock| + lock.flock(File::LOCK_EX) + yield + end +end + +# Check out (or re-point) the local clone at the configured ref. Resolve the +# commit in the freshly updated mirror so an existing checkout cannot remain +# stale merely because only the mirror was fetched. +def ensure_checkout(repo) + wp = checkout_path(repo) + ref = repo[:ref] + + commit, ok = capture("git", "-c", "safe.bareRepository=all", "--git-dir", mirror_path(repo), + "rev-parse", "--verify", "#{ref}^{commit}") + raise "ref #{ref.inspect} not found in #{mirror_path(repo)}" unless ok && !commit.strip.empty? + + if checkout_valid?(repo) + puts " checkout present: #{wp} -> #{ref}" + else + puts " replacing invalid checkout: #{wp}" if path_present?(wp) + FileUtils.rm_rf(wp) if path_present?(wp) + puts " cloning checkout: #{wp} -> #{ref}" + sh "git", "clone", "--shared", "--no-checkout", mirror_path(repo), wp + raise "checkout at #{wp} is not linked to #{mirror_path(repo)}" unless checkout_valid?(repo) + end + + sh "git", "-C", wp, "checkout", "--detach", commit.strip +end + +# Run a block per repo, collecting failures so one bad repo does not abort the rest. +def for_each_repo + failures = [] + REFERENCE_REPOS.each do |repo| + puts "#{repo[:name]}:" + begin + yield repo + rescue => e + warn " FAILED: #{e.message}" + failures << repo[:name] + end + end + abort "references: failed for #{failures.join(', ')}" unless failures.empty? +end + +namespace :references do + desc "Clone/refresh reference mirrors on persist and create checkouts in references/" + task :setup do + FileUtils.mkdir_p(MIRROR_ROOT) + FileUtils.mkdir_p(CHECKOUT_ROOT) + for_each_repo do |repo| + with_mirror_lock(repo) do + ensure_mirror(repo) + ensure_checkout(repo) + end + end + puts + puts "Done. Reference sources are in #{CHECKOUT_ROOT}" + Rake::Task["references:status"].invoke + end + + desc "Fetch latest upstream for all mirrors and re-point checkouts" + task :update do + for_each_repo do |repo| + with_mirror_lock(repo) do + abort "mirror missing for #{repo[:name]}; run `rake references:setup`" unless mirror_valid?(repo) + git_bare(repo, "remote", "update", "--prune") + ensure_checkout(repo) + end + end + end + + desc "Show provisioned reference repos, their pinned ref, and current HEAD" + task :status do + puts + puts format(" %-16s %-14s %-14s %s", "REPO", "REF", "HEAD", "LICENSE") + REFERENCE_REPOS.each do |repo| + wp = checkout_path(repo) + state = + if checkout_valid?(repo) + head, ok = capture("git", "-C", wp, "rev-parse", "--short", "HEAD") + ok && !head.strip.empty? ? head.strip : "(invalid)" + elsif path_present?(wp) + "(invalid)" + else + "(not set up)" + end + puts format(" %-16s %-14s %-14s %s", repo[:name], repo[:ref], state, repo[:license]) + end + puts + puts " mirrors: #{MIRROR_ROOT}" + puts " checkouts: #{CHECKOUT_ROOT}" + end + + desc "Remove checkouts from references/ (keeps the cached mirrors on persist)" + task :clean do + REFERENCE_REPOS.each do |repo| + wp = checkout_path(repo) + next unless path_present?(wp) + puts "removing checkout: #{wp}" + FileUtils.rm_rf(wp) + end + end +end diff --git a/vendor/github.com/jackc/pgx/v5/conn.go b/vendor/github.com/jackc/pgx/v5/conn.go index bc5d064939..1e60af2d85 100644 --- a/vendor/github.com/jackc/pgx/v5/conn.go +++ b/vendor/github.com/jackc/pgx/v5/conn.go @@ -36,9 +36,10 @@ type ConnConfig struct { DescriptionCacheCapacity int // DefaultQueryExecMode controls the default mode for executing queries. By default pgx uses the extended protocol - // and automatically prepares and caches prepared statements. However, this may be incompatible with proxies such as - // PGBouncer. In this case it may be preferable to use [QueryExecModeExec] or [QueryExecModeSimpleProtocol]. The same - // functionality can be controlled on a per query basis by passing a [QueryExecMode] as the first query argument. + // and automatically prepares and caches prepared statements. This may be incompatible with proxies such as PgBouncer + // unless they are configured to support protocol-level prepared statements. In an incompatible configuration it may + // be preferable to use [QueryExecModeExec] or [QueryExecModeSimpleProtocol]. The same functionality can be controlled + // on a per query basis by passing a [QueryExecMode] as the first query argument. DefaultQueryExecMode QueryExecMode createdByParseConfig bool // Used to enforce created by ParseConfig rule. @@ -358,8 +359,13 @@ func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.Statem sd, err = c.pgConn.Prepare(ctx, psName, sql, nil) if err != nil { var pErr *pgconn.PrepareError - if errors.As(err, &pErr) { - c.failedDescribeStatement = psKey + if errors.As(err, &pErr) && pErr.ParseComplete { + // The server-side statement was created under psName — the name sent in + // Parse. In the name == sql case psKey is the SQL text, and deallocating + // by it would close a nonexistent statement while leaking the real one. + // When Parse never completed no statement was created at all, so there + // is nothing to clean up. + c.failedDescribeStatement = psName } return nil, err } @@ -475,6 +481,9 @@ func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.C } if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil { + if c.queryTracer != nil { + c.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{Err: err}) + } return pgconn.CommandTag{}, err } @@ -742,7 +751,7 @@ type QueryRewriter interface { // collected before processing rather than processed while receiving each row. This avoids the possibility of the // application processing rows from a query that the server rejected. The CollectRows function is useful here. // -// An implementor of QueryRewriter may be passed as the first element of args. It can rewrite the sql and change or +// An implementer of QueryRewriter may be passed as the first element of args. It can rewrite the sql and change or // replace args. For example, NamedArgs is QueryRewriter that implements named arguments. // // For extra control over how the query is executed, the types QueryExecMode, QueryResultFormats, and @@ -1305,7 +1314,7 @@ func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, err switch typtype { case "b": // array - elementOID, err := c.getArrayElementOID(ctx, oid) + elementOID, delimiter, err := c.getArrayElementOIDAndDelimiter(ctx, oid) if err != nil { return nil, err } @@ -1315,7 +1324,7 @@ func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, err return nil, errors.New("array element OID not registered") } - return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.ArrayCodec{ElementType: dt}}, nil + return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.ArrayCodec{ElementType: dt, Delimiter: delimiter}}, nil case "c": // composite fields, err := c.getCompositeFields(ctx, oid) if err != nil { @@ -1361,15 +1370,16 @@ func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, err } } -func (c *Conn) getArrayElementOID(ctx context.Context, oid uint32) (uint32, error) { +func (c *Conn) getArrayElementOIDAndDelimiter(ctx context.Context, oid uint32) (uint32, byte, error) { var typelem uint32 + var typdelim string - err := c.QueryRow(ctx, "select typelem from pg_type where oid=$1", oid).Scan(&typelem) + err := c.QueryRow(ctx, "select typelem, typdelim::text from pg_type where oid=$1", oid).Scan(&typelem, &typdelim) if err != nil { - return 0, err + return 0, 0, err } - return typelem, nil + return typelem, parseTypeDelimiter(typdelim), nil } func (c *Conn) getRangeElementOID(ctx context.Context, oid uint32) (uint32, error) { diff --git a/vendor/github.com/jackc/pgx/v5/derived_types.go b/vendor/github.com/jackc/pgx/v5/derived_types.go index 3916006bee..e588c7c659 100644 --- a/vendor/github.com/jackc/pgx/v5/derived_types.go +++ b/vendor/github.com/jackc/pgx/v5/derived_types.go @@ -64,9 +64,12 @@ UNION ALL -- As can be seen, there are 3 ways this can occur (the last of which -- is due to being a composite class, where the composite fields are children) pc(parent, child) AS ( + -- typtype = 'b' AND typelem != 0 is not sufficient to identify an array type: some + -- scalar types (box, point, line, lseg, name, ...) also set typelem to describe their + -- internal C representation. typcategory = 'A' is the reliable "is an array" signal. SELECT parent.oid, parent.typelem FROM pg_type parent - WHERE parent.typtype = 'b' AND parent.typelem != 0 + WHERE parent.typtype = 'b' AND parent.typelem != 0 AND parent.typcategory = 'A' UNION ALL SELECT parent.oid, parent.typbasetype FROM pg_type parent @@ -113,6 +116,7 @@ SELECT typname, typtype, typbasetype, typelem, + typdelim, pg_type.oid,`) if supportsMultirange { parts = append(parts, ` @@ -135,9 +139,13 @@ SELECT typname, parts = append(parts, ` LEFT OUTER JOIN composite USING (oid) LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid) - WHERE NOT (typtype = 'b' AND typelem = 0)`) + -- Only emit typtype = 'b' rows that are true arrays (typcategory = 'A'). Other base + -- types, including ones with a non-zero typelem for non-array reasons (box, point, + -- line, lseg, name, ...), already have a codec registered and must not be re-emitted, + -- or LoadTypes will overwrite their correct codec with a bogus ArrayCodec. + WHERE NOT (typtype = 'b' AND NOT (typelem != 0 AND typcategory = 'A'))`) parts = append(parts, ` - GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, pg_type.oid, pg_range.rngsubtype,`) + GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, typdelim, pg_type.oid, pg_range.rngsubtype,`) if supportsMultirange { parts = append(parts, ` multirange.rngtypid,`) @@ -150,11 +158,18 @@ SELECT typname, type derivedTypeInfo struct { Oid, Typbasetype, Typelem, Rngsubtype, Rngtypid uint32 - TypeName, Typtype, NspName string + TypeName, Typtype, NspName, Typdelim string Attnames []string Atttypids []uint32 } +func parseTypeDelimiter(typdelim string) byte { + if typdelim == "" { + return 0 + } + return typdelim[0] +} + // LoadTypes performs a single (complex) query, returning all the required // information to register the named types, as well as any other types directly // or indirectly required to complete the registration. @@ -177,7 +192,7 @@ func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Typ result := make([]*pgtype.Type, 0, 100) for rows.Next() { ti := derivedTypeInfo{} - err = rows.Scan(&ti.TypeName, &ti.NspName, &ti.Typtype, &ti.Typbasetype, &ti.Typelem, &ti.Oid, &ti.Rngtypid, &ti.Rngsubtype, &ti.Attnames, &ti.Atttypids) + err = rows.Scan(&ti.TypeName, &ti.NspName, &ti.Typtype, &ti.Typbasetype, &ti.Typelem, &ti.Typdelim, &ti.Oid, &ti.Rngtypid, &ti.Rngsubtype, &ti.Attnames, &ti.Atttypids) if err != nil { return nil, fmt.Errorf("While scanning type information: %w", err) } @@ -188,7 +203,7 @@ func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Typ if !ok { return nil, fmt.Errorf("Array element OID %v not registered while loading pgtype %q", ti.Typelem, ti.TypeName) } - type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.ArrayCodec{ElementType: dt}} + type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.ArrayCodec{ElementType: dt, Delimiter: parseTypeDelimiter(ti.Typdelim)}} case "c": // composite var fields []pgtype.CompositeCodecField for i, fieldName := range ti.Attnames { diff --git a/vendor/github.com/jackc/pgx/v5/doc.go b/vendor/github.com/jackc/pgx/v5/doc.go index 5e4870191a..f20b3f68fe 100644 --- a/vendor/github.com/jackc/pgx/v5/doc.go +++ b/vendor/github.com/jackc/pgx/v5/doc.go @@ -210,8 +210,18 @@ implemented on top of [pgconn.PgConn]. The [Conn.PgConn] method can be used to a PgBouncer -By default pgx automatically uses prepared statements. Prepared statements are incompatible with PgBouncer. This can be -disabled by setting a different [QueryExecMode] in [ConnConfig.DefaultQueryExecMode]. +By default pgx automatically uses protocol-level named prepared statements. PgBouncer 1.21.0 and newer can use these +prepared statements in transaction and statement pooling modes when its max_prepared_statements setting is greater than +zero. In this configuration the default [QueryExecModeCacheStatement] mode may be used. See the PgBouncer documentation +for limitations and configuration details: https://www.pgbouncer.org/config.html#max_prepared_statements. + +When using an older PgBouncer version or when prepared statement support is disabled, set +[ConnConfig.DefaultQueryExecMode] to [QueryExecModeExec]. [QueryExecModeCacheDescribe] and +[QueryExecModeSimpleProtocol] are also compatible with PgBouncer. Prefer [QueryExecModeExec] over +[QueryExecModeSimpleProtocol] whenever possible. Do not use [QueryExecModeDescribeExec] with transaction pooling because +PgBouncer may assign a different server connection between the describe and execute steps. + +SQL-level prepared statements created with PREPARE are not supported by PgBouncer in transaction pooling mode. */ package pgx diff --git a/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go b/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go index abc41f657f..4f133b68bf 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go +++ b/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go @@ -33,7 +33,7 @@ func Get(size int) *[]byte { return &buf } - ptrBuf := (pools[i].Get().(*[]byte)) + ptrBuf := pools[i].Get().(*[]byte) *ptrBuf = (*ptrBuf)[:size] return ptrBuf diff --git a/vendor/github.com/jackc/pgx/v5/internal/pgdatetime/pgdatetime.go b/vendor/github.com/jackc/pgx/v5/internal/pgdatetime/pgdatetime.go new file mode 100644 index 0000000000..306d0c7503 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/pgdatetime/pgdatetime.go @@ -0,0 +1,118 @@ +// Package pgdatetime writes PostgreSQL's ISO date/time text format. +// +// The format is the one EncodeDateTime and AppendSeconds produce in +// src/backend/utils/adt/datetime.c under the default ISO DateStyle: +// +// stamp = date [ SP time [ zone ] ] [ " BC" ] +// date = year "-" 2DIGIT "-" 2DIGIT +// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT [ "." 1*6DIGIT ] +// +// The year is zero-padded to four digits and then grows as wide as it needs, the +// fractional part is omitted when it is zero and never carries trailing zeros, and " BC" +// comes last, after any time zone. Go's layout language can express none of those, which +// is why the format is written out here rather than left to time.Format. +// +// This is the only implementation of the format in pgx. pgtype's date, timestamp and +// timestamptz text encoders and the simple protocol's query sanitizer all go through it, +// so they cannot drift apart. +package pgdatetime + +import ( + "strconv" + "time" +) + +// AppendDate appends t's date. The fields are read from t in its own location. +func AppendDate(buf []byte, t time.Time) []byte { + year, bc := splitBCYear(t.Year()) + buf = appendDate(buf, year, int(t.Month()), t.Day()) + return appendEra(buf, bc) +} + +// AppendTimestamp appends t's date and time of day followed by zone, which goes before +// the era suffix because PostgreSQL writes " BC" last. zone is "Z" for a value already +// converted to UTC and "" for a type that carries no time zone at all. +// +// The fields are read from t in its own location, so a caller that wants the UTC instant +// must convert first. Sub-microsecond precision is discarded, matching the resolution of +// the wire format. +func AppendTimestamp(buf []byte, t time.Time, zone string) []byte { + year, bc := splitBCYear(t.Year()) + buf = appendDate(buf, year, int(t.Month()), t.Day()) + buf = append(buf, ' ') + buf = appendTime(buf, t.Hour(), t.Minute(), t.Second(), t.Nanosecond()) + buf = append(buf, zone...) + return appendEra(buf, bc) +} + +// splitBCYear converts an astronomical year, in which 1 BC is 0 and 2 BC is -1, to the +// year and era PostgreSQL writes. +func splitBCYear(year int) (displayYear int, bc bool) { + if year <= 0 { + return 1 - year, true + } + return year, false +} + +func appendEra(buf []byte, bc bool) []byte { + if bc { + buf = append(buf, " BC"...) + } + return buf +} + +// appendDate appends year-month-day. year is a displayed year from splitBCYear rather +// than an astronomical one. +func appendDate(buf []byte, year, month, day int) []byte { + buf = appendYear(buf, year) + buf = append(buf, '-') + buf = append2Digits(buf, month) + buf = append(buf, '-') + return append2Digits(buf, day) +} + +func appendTime(buf []byte, hour, min, sec, nsec int) []byte { + buf = append2Digits(buf, hour) + buf = append(buf, ':') + buf = append2Digits(buf, min) + buf = append(buf, ':') + buf = append2Digits(buf, sec) + + usec := nsec / 1000 + if usec == 0 { + return buf + } + + var frac [6]byte + for i := 5; i >= 0; i-- { + frac[i] = byte('0' + usec%10) + usec /= 10 + } + + // The server trims trailing zeros, so ".5" rather than ".500000". + end := len(frac) + for end > 1 && frac[end-1] == '0' { + end-- + } + + buf = append(buf, '.') + return append(buf, frac[:end]...) +} + +// append2Digits appends v as exactly two digits. Every field but the year is fixed width +// and comes from a time.Time accessor, so v is always in [0, 99] and the general routine +// below is not needed. +func append2Digits(buf []byte, v int) []byte { + return append(buf, byte('0'+v/10), byte('0'+v%10)) +} + +// appendYear appends v zero-padded to four digits, or wider when the year needs it. v is +// a displayed year from splitBCYear and so is always positive. +func appendYear(buf []byte, v int) []byte { + var tmp [20]byte + s := strconv.AppendInt(tmp[:0], int64(v), 10) + for i := len(s); i < 4; i++ { + buf = append(buf, '0') + } + return append(buf, s...) +} diff --git a/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go b/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go index ef2dcc7f72..60e2fbbe20 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go +++ b/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go @@ -1,6 +1,8 @@ -// Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol. +// Package pgio is a low-level toolkit for building and parsing messages in the +// PostgreSQL wire protocol. /* pgio provides functions for appending integers to a []byte while doing byte -order conversion. +order conversion, and a bounds-checked Reader for parsing binary values from +untrusted input. */ package pgio diff --git a/vendor/github.com/jackc/pgx/v5/internal/pgio/read.go b/vendor/github.com/jackc/pgx/v5/internal/pgio/read.go new file mode 100644 index 0000000000..9ea42c890b --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/pgio/read.go @@ -0,0 +1,250 @@ +package pgio + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" +) + +// ErrInsufficientBytes is wrapped by all Reader errors caused by a read past +// the end of the source. +var ErrInsufficientBytes = errors.New("insufficient bytes") + +// Reader is a bounds-checked reader for the PostgreSQL binary format. It is +// designed so that decoders of untrusted input cannot forget a length check: +// every read validates against the remaining bytes, and the first failure +// sticks. After a failure all subsequent reads return zero values, so a +// decoder can read an entire structure without intermediate error checks and +// inspect Err or Finish once at the end. +// +// Reads never panic. A decoder that branches on a value it just read (e.g. an +// element count used to size an allocation) should check Err before acting on +// the value. +type Reader struct { + s []byte + rp int + err error +} + +func NewReader(s []byte) *Reader { + return &Reader{s: s} +} + +func (r *Reader) fail(err error) { + if r.err == nil { + r.err = err + } +} + +// need reports whether n more bytes are available, recording an error if not. +// +// The error is built by failShort rather than here so that need stays within +// the inliner's budget. Reads of fixed-size values are the hottest path in the +// driver, and an un-inlined bounds check costs more than the read itself. +func (r *Reader) need(n int) bool { + if r.err != nil { + return false + } + if len(r.s)-r.rp < n { + r.failShort(n) + return false + } + return true +} + +func (r *Reader) failShort(n int) { + r.fail(fmt.Errorf("%w: %d needed at offset %d, %d remain", ErrInsufficientBytes, n, r.rp, len(r.s)-r.rp)) +} + +// Err returns the first error encountered, if any. +func (r *Reader) Err() error { + return r.err +} + +// Remaining returns the number of unread bytes. +func (r *Reader) Remaining() int { + return len(r.s) - r.rp +} + +func (r *Reader) Byte() byte { + if !r.need(1) { + return 0 + } + b := r.s[r.rp] + r.rp += 1 + return b +} + +func (r *Reader) Uint16() uint16 { + if !r.need(2) { + return 0 + } + n := binary.BigEndian.Uint16(r.s[r.rp:]) + r.rp += 2 + return n +} + +func (r *Reader) Int16() int16 { + return int16(r.Uint16()) +} + +func (r *Reader) Uint32() uint32 { + if !r.need(4) { + return 0 + } + n := binary.BigEndian.Uint32(r.s[r.rp:]) + r.rp += 4 + return n +} + +func (r *Reader) Int32() int32 { + return int32(r.Uint32()) +} + +func (r *Reader) Uint64() uint64 { + if !r.need(8) { + return 0 + } + n := binary.BigEndian.Uint64(r.s[r.rp:]) + r.rp += 8 + return n +} + +func (r *Reader) Int64() int64 { + return int64(r.Uint64()) +} + +// Bytes reads the next n bytes. The returned slice aliases the source; it is +// not a copy. +func (r *Reader) Bytes(n int) []byte { + if n < 0 { + r.fail(fmt.Errorf("invalid byte count %d at offset %d", n, r.rp)) + return nil + } + if !r.need(n) { + return nil + } + b := r.s[r.rp : r.rp+n] + r.rp += n + return b +} + +// CString reads a NUL-terminated string, returning the bytes before the +// terminator and consuming the terminator. The returned slice aliases the +// source; it is not a copy. +func (r *Reader) CString() []byte { + if r.err != nil { + return nil + } + i := bytes.IndexByte(r.s[r.rp:], 0) + if i < 0 { + r.fail(fmt.Errorf("%w: unterminated string at offset %d", ErrInsufficientBytes, r.rp)) + return nil + } + b := r.s[r.rp : r.rp+i] + r.rp += i + 1 + return b +} + +// Count reads an int32 element count and validates it against the remaining +// bytes: the count must be non-negative, and since each element occupies at +// least minElemSize bytes, count*minElemSize must not exceed the remaining +// message. This bounds allocations sized from the count against a malicious +// or corrupt message claiming a huge count. Returns 0 on any failure. +func (r *Reader) Count(minElemSize int) int { + offset := r.rp + count := int(r.Int32()) + if r.err != nil { + return 0 + } + if count < 0 { + r.fail(fmt.Errorf("invalid element count %d at offset %d", count, offset)) + return 0 + } + if minElemSize < 1 { + minElemSize = 1 + } + if count > r.Remaining()/minElemSize { + r.fail(fmt.Errorf("element count %d at offset %d exceeds %d remaining bytes", count, offset, r.Remaining())) + return 0 + } + return count +} + +// Value reads an int32 length followed by that many bytes — the standard +// PostgreSQL binary representation of a value. A length of -1 means NULL and +// returns (nil, true). Any other negative length is an error. The returned +// slice aliases the source; null is only meaningful if Err returns nil. +func (r *Reader) Value() (data []byte, null bool) { + offset := r.rp + length := r.Int32() + if r.err != nil { + return nil, false + } + if length == -1 { + return nil, true + } + if length < 0 { + r.fail(fmt.Errorf("invalid value length %d at offset %d", length, offset)) + return nil, false + } + return r.Bytes(int(length)), false +} + +// Finish returns the first error encountered, or an error if unread bytes +// remain. Decoders that must consume the entire source should end with Finish. +func (r *Reader) Finish() error { + if r.err != nil { + return r.err + } + if r.rp != len(r.s) { + return r.errTrailing() + } + return nil +} + +func (r *Reader) errTrailing() error { + return fmt.Errorf("%d unexpected trailing bytes at offset %d", len(r.s)-r.rp, r.rp) +} + +// ErrInvalidLength is wrapped by the errors returned from the exact-length +// read functions below. +var ErrInvalidLength = errors.New("invalid length") + +func errLength(want, got int) error { + return fmt.Errorf("%w: expected %d bytes, got %d", ErrInvalidLength, want, got) +} + +// The Uint*Exact functions read a single fixed-size value that makes up an +// entire message, which is what the scan plans for the fixed-size PostgreSQL +// types receive. They are the counterpart to Reader for values that have no +// internal structure: there is no position to track and no error to make +// sticky, just an exact-length assertion the caller cannot skip. Keeping them +// separate from Reader is deliberate — these are the hottest decode paths in +// the driver and they are small enough for the compiler to inline, which a +// Reader method carrying a bounds check and a read pointer is not. + +// Uint16Exact returns the big-endian uint16 in src, which must be exactly 2 bytes. +func Uint16Exact(src []byte) (uint16, error) { + if len(src) != 2 { + return 0, errLength(2, len(src)) + } + return binary.BigEndian.Uint16(src), nil +} + +// Uint32Exact returns the big-endian uint32 in src, which must be exactly 4 bytes. +func Uint32Exact(src []byte) (uint32, error) { + if len(src) != 4 { + return 0, errLength(4, len(src)) + } + return binary.BigEndian.Uint32(src), nil +} + +// Uint64Exact returns the big-endian uint64 in src, which must be exactly 8 bytes. +func Uint64Exact(src []byte) (uint64, error) { + if len(src) != 8 { + return 0, errLength(8, len(src)) + } + return binary.BigEndian.Uint64(src), nil +} diff --git a/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go b/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go index 033a4143b8..2e0230b672 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go +++ b/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go @@ -11,6 +11,8 @@ import ( "sync" "time" "unicode/utf8" + + "github.com/jackc/pgx/v5/internal/pgdatetime" ) // Part is either a string or an int. A string is raw SQL. An int is a @@ -81,8 +83,12 @@ func (q *Query) Sanitize(args ...any) (string, error) { case string: p = QuoteString(buf.AvailableBuffer(), arg) case time.Time: - p = arg.Truncate(time.Microsecond). - AppendFormat(buf.AvailableBuffer(), "'2006-01-02 15:04:05.999999999Z07:00:00'") + // pgtype's timestamptz text encoder writes the same format. Going through + // the same code keeps the two from drifting apart, and time.Format cannot + // express PostgreSQL's BC era or its variable width year anyway. + p = append(buf.AvailableBuffer(), '\'') + p = pgdatetime.AppendTimestamp(p, arg.UTC(), "Z") + p = append(p, '\'') default: return "", fmt.Errorf("invalid arg type: %T", arg) } diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go index b677d29cb9..63173b0d97 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go +++ b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go @@ -62,7 +62,7 @@ func (c *LRUCache) Put(sd *pgconn.StatementDescription) { return } - // The statement may have been invalidated but not yet handled. Do not readd it to the cache. + // The statement may have been invalidated but not yet handled. Do not re-add it to the cache. if _, invalidated := c.invalidSet[sd.SQL]; invalidated { return } diff --git a/vendor/github.com/jackc/pgx/v5/mise.toml b/vendor/github.com/jackc/pgx/v5/mise.toml index 78610d4ccc..97078ec1a6 100644 --- a/vendor/github.com/jackc/pgx/v5/mise.toml +++ b/vendor/github.com/jackc/pgx/v5/mise.toml @@ -1,8 +1,173 @@ +# mise is this project's single development entry point: the same `mise run ` works on +# native macOS, on native Linux, and inside the devcontainer. See DEVELOPMENT.md. +# +# The division of labour: +# mise tool versions, this checkout's environment, one-shot tasks +# process-compose long-running services (process-compose.yaml) — five PostgreSQL clusters + CRDB +# port-tamer this checkout's TCP ports (port-tamer.toml -> .dev/ports.env) +# +# PostgreSQL itself is the one prerequisite mise does not provide; DEVELOPMENT.md §1 lists it. + [tools] -go = '1.26.3' +go = '1.27.0' +ruby = '4.0.4' "go:github.com/go-critic/go-critic/cmd/gocritic" = "latest" "go:github.com/gordonklaus/ineffassign" = "latest" "go:github.com/mdempsky/unconvert" = "latest" "go:golang.org/x/tools/cmd/goimports" = "latest" "go:mvdan.cc/gofumpt" = "latest" -ruby = '4.0.4' + +# The linter .golangci.yml configures and CLAUDE.md documents. It was never actually provisioned +# by the devcontainer, so `golangci-lint run ./...` only worked if you had installed it yourself. +golangci-lint = '2.13.2' + +# The process supervisor for the long-running development services. Pinned like every other tool +# so macOS, Linux, and the devcontainer run the same version. +process-compose = '1.122.0' + +# Per-checkout TCP port allocation. The `github:` backend takes the prebuilt release binary, so it +# does not depend on the Go toolchain this repo pins. +"github:jackc/port-tamer" = '0.1.0' + +# The CockroachDB test target. Previously a container image; the version tracks the one CI installs +# in ci/setup_test.bash. +cockroach = '25.4.4' + +# --- Environment --------------------------------------------------------------------------------- +# +# This checkout's own service endpoints. Loading them here is what makes the per-checkout clusters +# the DEFAULT: a bare `psql` and a bare `go test ./...` read PG*/PGX_TEST_* from the environment, +# so pointing those at .dev/ in one place moves every consumer at once. +# +# Two files with two owners, and the order matters — the derived values are read after the +# allocation they come from: +# +# .dev/ports.env port-tamer's state file (port-tamer.toml declares the names). NAME= +# lines only; port-tamer rewrites it canonically and rejects anything else. +# .dev/derived.env PGHOST/PGPORT/PGUSER/PGDATABASE plus the default target's PGX_TEST_* set — +# scripts/devenv.rb, via scripts/lib/test_targets.rb. +# +# Both are generated per checkout and gitignored; `mise run dev:init` creates them. Their absence +# is not an error — mise skips a missing file and PG* falls back to whatever the shell already had. +[env] +_.file = ['.dev/ports.env', '.dev/derived.env'] + +# Homebrew's postgresql@ formulas are KEG-ONLY: nothing is linked into the prefix bin, so +# psql and pg_isready are not on PATH after `brew install`. The scripts that need the SERVER +# binaries resolve them per major explicitly (scripts/lib/pg_bin.rb), but the CLIENT tools are +# invoked by name from the readiness probes, `rake db:psql`, and the database bootstrap. +# +# The newest major's client is used for every server: libpq is backward compatible, so one psql +# talks to all five clusters. Both standard Homebrew prefixes are listed (Apple silicon, then +# Intel). Neither exists on Linux, where a nonexistent PATH entry is simply ignored, so this is +# inert in the devcontainer. +_.path = [ + '/opt/homebrew/opt/postgresql@18/bin', + '/usr/local/opt/postgresql@18/bin', +] + +# process-compose's control API address. The port comes from this checkout's allocation +# (PC_PORT_NUM in .dev/ports.env), so every `process-compose ...` command reaches THIS checkout's +# stack with no flags. +PC_ADDRESS = "127.0.0.1" + +# Kept separate deliberately: `mise run dev` writes the supervisor log, and a client command such +# as `process-compose process list` would otherwise truncate the log of the stack it is inspecting. +PC_SERVER_LOG_FILE = "{{config_root}}/.dev/process-compose.log" +PC_LOG_FILE = "{{config_root}}/.dev/process-compose-client.log" + +# --- Tasks: the project's development interface --------------------------------------------------- +# +# Thin wrappers. The logic lives in scripts/ and the Rakefile; these exist so a workflow is +# reachable without knowing what is underneath, and so the same command works in every environment. + +[tasks."dev:init"] +description = "Bootstrap this checkout: allocate its ports, decode its certificates" +run = "ruby scripts/devenv.rb ensure" + +[tasks.dev] +description = "Start PostgreSQL 18 and this checkout's on-demand database supervisor" +run = "ruby scripts/dev.rb" + +[tasks."dev:all"] +description = "Start PostgreSQL 14-18 and CockroachDB eagerly under process-compose" +run = "ruby scripts/dev.rb all" + +[tasks."dev:down"] +description = "Stop this checkout's development stack" +run = "ruby scripts/dev.rb down" + +[tasks."dev:wait"] +description = "Wait for a detached development stack to become ready" +run = "ruby scripts/dev_ready.rb --wait" + +[tasks."dev:ready"] +description = "Require the development stack to be running" +run = "ruby scripts/dev_ready.rb" +hide = true + +[tasks."dev:ports"] +description = "Print this checkout's port allocation and where each server's data lives" +run = "rake dev:ports:show" + +[tasks."dev:ports:ensure"] +description = "Allocate this checkout's ports if it has none (idempotent)" +run = "rake dev:ports:ensure" + +[tasks."dev:ports:overwrite"] +description = "Move this checkout to a different port group (stop its services first)" +run = "rake dev:ports:overwrite" + +# --- Databases ----------------------------------------------------------------------------------- + +[tasks."db:start"] +description = "Prewarm database targets (default: pg18); e.g. mise run db:start pg16 crdb" +run = "ruby scripts/dev_services.rb start" + +[tasks."db:stop"] +description = "Stop database targets (default: pg18); e.g. mise run db:stop pg16 crdb" +run = "ruby scripts/dev_services.rb stop" + +# These call scripts/devdb.rb rather than the equivalent rake tasks. mise APPENDS a task's +# arguments to its `run` line, and `rake db:reset 16` does not mean "db:reset with the argument +# 16" — rake reads the 16 as a SECOND TASK, runs db:reset with no major (which is every cluster), +# and only then fails on the unknown task. devdb.rb takes the major as an ordinary argument, so +# `mise run db:reset 16` reaches it as written. `rake db:reset[16]` is still the rake spelling. + +[tasks."db:init"] +description = "Create this checkout's PostgreSQL clusters under .dev (idempotent); e.g. mise run db:init 16" +run = "ruby scripts/devdb.rb init" + +[tasks."db:psql"] +description = "psql against one of this checkout's clusters (default: the newest major)" +run = "ruby scripts/devdb.rb psql" + +[tasks."db:setup"] +description = "Create pgx_test and its roles in a running cluster (idempotent)" +run = "ruby scripts/devdb.rb setup" + +[tasks."db:reset"] +description = "Destroy and recreate this checkout's clusters (destructive; CONFIRM=yes, stack down)" +run = "ruby scripts/devdb.rb reset" + +# --- Test, format, generate ------------------------------------------------------------------------ + +[tasks.test] +description = "Run the test suite against one target (default pg18); e.g. mise run test pg16" +run = "./test.sh" + +[tasks."test:all"] +description = "Run the test suite against every target: PostgreSQL 14-18 and CockroachDB" +run = "./test.sh all" + +[tasks.fmt] +description = "Format all Go sources with goimports" +run = "goimports -w ." + +[tasks.lint] +description = "Run the linters configured in .golangci.yml" +run = "golangci-lint run ./..." + +[tasks.generate] +description = "Regenerate the ERB-templated Go sources" +run = "rake generate" diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/config.go b/vendor/github.com/jackc/pgx/v5/pgconn/config.go index eec7de6394..b521a69037 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/config.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/config.go @@ -10,7 +10,6 @@ import ( "maps" "math" "net" - "net/url" "os" "path/filepath" "strconv" @@ -43,6 +42,11 @@ type Config struct { LookupFunc LookupFunc // e.g. net.Resolver.LookupHost BuildFrontend BuildFrontendFunc + // MaxProtocolMessageBodyLen is the maximum length of a PostgreSQL wire protocol message body in octets. If a + // message body exceeds this length, reading the message will fail with pgproto3.ExceededMaxBodyLenErr. The default + // value is 0, which means no maximum is enforced. + MaxProtocolMessageBodyLen int + // BuildContextWatcherHandler is called to create a ContextWatcherHandler for a connection. The handler is called // when a context passed to a PgConn method is canceled. BuildContextWatcherHandler func(*PgConn) ctxwatch.Handler @@ -109,6 +113,11 @@ type Config struct { createdByParseConfig bool // Used to enforce created by ParseConfig rule. } +// defaultPort is the port used when neither the connection string, the environment, nor the +// service file supplies one. It is also the per-element fallback for empty entries in a +// multi-host port list. +const defaultPort = "5432" + // connStringKeyAliases maps libpq parameter keywords to the canonical key names this package // uses internally in the parsed-settings map. Most keywords are already canonical; this map // holds only those whose pgx-internal name differs from the libpq spelling. @@ -137,7 +146,11 @@ type ParseConfigOptions struct { // defaults are not checked: only keys that originate from the connString argument. // // Keys may be given in either their libpq spelling ("dbname") or pgx-internal spelling - // ("database"); both are accepted. + // ("database"); both are accepted. The URI-only ssl=true alias for sslmode=require is + // accepted when either "ssl" or "sslmode" is allowed; an explicit sslmode key or a + // non-"true" ssl value only matches its own spelling. Every ssl/sslmode occurrence in + // the connection string is validated, including occurrences superseded by a later + // repeated parameter. // // A nil slice (the default) applies no restriction and matches libpq behaviour. An empty // non-nil slice rejects every key, i.e. connString must be empty. @@ -232,10 +245,10 @@ func NetworkAddress(host string, port uint16) (network, address string) { // to only read from the environment. If a password is not supplied it will attempt to read the .pgpass file. // // # Example Keyword/Value -// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca +// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-full // // # Example URL -// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca +// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-full // // The returned *Config may be modified. However, it is strongly recommended that any configuration that can be done // through the connection string be done there. In particular the fields Host, Port, TLSConfig, and Fallbacks can be @@ -307,6 +320,21 @@ func NetworkAddress(host string, port uint16) (network, address string) { // When multiple hosts are specified, libpq allows them to have different passwords set via the .pgpass file. pgconn // does not. // +// URL query parameters that libpq does not recognize cause libpq to fail with an "invalid URI query parameter" error. +// ParseConfig accepts them: they become runtime parameters or pgx-specific options (e.g. pool_max_conns). +// +// Connection strings containing a NUL byte are rejected, in both URI and keyword/value form. libpq cannot encounter +// one because its conninfo strings are NUL-terminated C strings, but a Go string can carry a NUL into the startup +// packet, where it delimits parameters rather than being data. Settings reaching Config by other routes (a service +// file, or direct assignment to Config.RuntimeParams, User, or Database) are not checked here; a NUL in those is +// caught when the startup message is encoded, and Connect fails rather than sending it. +// +// Error messages from ParseConfig avoid quoting the unredacted connection string and attempt to redact recognizable +// password fields, while libpq quotes the failing input verbatim. This redaction is best effort. An invalid connection +// string can be structurally ambiguous, so pgconn cannot guarantee that every password in malformed input will be +// identified or redacted. Applications should not assume that parse errors are safe to expose when connection strings +// may contain secrets. +// // In addition, ParseConfig accepts the following options: // // - servicefile. @@ -325,11 +353,12 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con envSettings := parseEnvSettings() connStringSettings := make(map[string]string) + var urlMeta parseURLMeta if connString != "" { var err error // connString may be a database URL or in PostgreSQL keyword/value format if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") { - connStringSettings, err = parseURLSettings(connString) + connStringSettings, urlMeta, err = parseURLSettings(connString) if err != nil { return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as URL", err: err} } @@ -346,14 +375,77 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con for _, k := range options.ConnStringAllowedKeys { allowed[canonicalConnStringKey(k)] = struct{}{} } + notAllowed := func(k string) error { + return &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("connection string key %q is not in ConnStringAllowedKeys", k)} + } + _, sslAllowed := allowed["ssl"] + _, sslmodeAllowed := allowed["sslmode"] + + // Repeated-key handling and the URI ssl=true alias rewrite can remove + // ssl/sslmode occurrences from the final settings map, so those two keys + // are validated from what the user actually wrote -- every occurrence, + // fail closed -- rather than from what survived. The alias itself is + // accepted under either spelling, the same way dbname/database are + // interchangeable; an explicit sslmode key or a non-"true" ssl value + // only matches its own spelling. + if urlMeta.sawRawSSLKey && !sslAllowed { + return nil, notAllowed("ssl") + } + if urlMeta.sawExplicitSSLModeKey && !sslmodeAllowed { + return nil, notAllowed("sslmode") + } + if urlMeta.sawSSLTrueAlias && !sslAllowed && !sslmodeAllowed { + return nil, notAllowed("ssl") + } + for k := range connStringSettings { - if _, ok := allowed[k]; !ok { - return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("connection string key %q is not in ConnStringAllowedKeys", k)} + if _, ok := allowed[k]; ok { + continue + } + // A multi-host URI with no explicit ports produces an implied + // all-empty port list (e.g. ","), matching libpq. Only that list + // -- identified by the parser from the raw syntax, not inferred + // from the value -- is exempt from the allow-list: it carries no + // user-supplied port text. An explicit empty port (?port= in a + // URI or port= in keyword/value form) is user-supplied, and + // because a present-but-empty port still shadows PGPORT it must + // pass the allow-list like any other key. + if k == "port" && urlMeta.impliedEmptyPortList { + continue + } + // A surviving ssl or sslmode entry from a URI was already + // validated above against every spelling the user wrote. + if k == "ssl" && urlMeta.sawRawSSLKey { + continue + } + if k == "sslmode" && (urlMeta.sawSSLTrueAlias || urlMeta.sawExplicitSSLModeKey) { + continue } + return nil, notAllowed(k) } } settings := mergeSettings(defaultSettings, envSettings, connStringSettings) + + // The home-directory-derived defaults (passfile, servicefile, sslcert, + // sslkey, sslrootcert) are already present in settings at this point: + // defaultSettings resolves them via the user's home directory, which is + // safe and cheap to look up (see defaults.go / defaults_windows.go). + // + // The default PostgreSQL user name is different: resolving it requires + // looking up the OS user account, which can be slow or, in some + // restricted container environments, crash the process. So that lookup + // is memoized and only performed lazily below, the first time it is + // actually needed -- i.e. only when a connection string or environment + // does not already supply a user. + var cachedOSUserSettings map[string]string + lazyOSUserSettings := func() map[string]string { + if cachedOSUserSettings == nil { + cachedOSUserSettings = osUserSettings() + } + return cachedOSUserSettings + } + if service, present := settings["service"]; present { serviceSettings, err := parseServiceSettings(settings["servicefile"], service) if err != nil { @@ -363,6 +455,13 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con settings = mergeSettings(defaultSettings, envSettings, serviceSettings, connStringSettings) } + // Only fall back to the OS user account for the default PostgreSQL user + // name when it was not already supplied by the connection string, + // environment, or service file. + if settings["user"] == "" { + settings = mergeSettings(lazyOSUserSettings(), settings) + } + config := &Config{ createdByParseConfig: true, Database: settings["database"], @@ -442,17 +541,41 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con hosts := strings.Split(settings["host"], ",") ports := strings.Split(settings["port"], ",") + // Like libpq, if exactly one port is given it applies to all hosts; + // otherwise there must be exactly one port per host. Empty list elements + // mean "use the default". + if len(ports) > 1 && len(ports) != len(hosts) { + return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("could not match %d port numbers to %d hosts", len(ports), len(hosts))} + } + + // defaultHost stats candidate socket directories, so resolve it at most + // once even when several host list elements are empty. It never returns "". + resolvedDefaultHost := "" for i, host := range hosts { - var portStr string - if i < len(ports) { + if host == "" { + if resolvedDefaultHost == "" { + resolvedDefaultHost = defaultHost() + } + host = resolvedDefaultHost + } + + portStr := ports[0] + if len(ports) > 1 { portStr = ports[i] - } else { - portStr = ports[0] + } + if portStr == "" { + portStr = defaultPort } + // The strconv error is deliberately not wrapped: it quotes the + // offending text, and in a malformed URI the bytes that land in the + // port position can be a mislaid password (postgres://u:sec:ret@h + // parses "sec:ret@h" as the port). The best-effort-redacted connection + // string in ParseConfigError provides the available context without + // deliberately quoting the offending port text again. port, err := parsePort(portStr) if err != nil { - return nil, &ParseConfigError{ConnString: connString, msg: "invalid port", err: err} + return nil, &ParseConfigError{ConnString: connString, msg: "invalid port"} } var tlsConfigs []*tls.Config @@ -483,14 +606,13 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con config.Fallbacks = fallbacks[1:] config.SSLNegotiation = settings["sslnegotiation"] - passfile, err := pgpassfile.ReadPassfile(settings["passfile"]) - if err == nil { - if config.Password == "" { + if config.Password == "" { + passfile, err := pgpassfile.ReadPassfile(settings["passfile"]) + if err == nil { host := config.Host if network, _ := NetworkAddress(config.Host, config.Port); network == "unix" { host = "localhost" } - config.Password = passfile.FindPassword(host, strconv.Itoa(int(config.Port)), config.Database, config.User) } } @@ -616,76 +738,46 @@ func parseEnvSettings() map[string]string { return settings } -func parseURLSettings(connString string) (map[string]string, error) { - settings := make(map[string]string) - - parsedURL, err := url.Parse(connString) - if err != nil { - if urlErr := new(url.Error); errors.As(err, &urlErr) { - return nil, urlErr.Err - } - return nil, err - } +var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1} - if parsedURL.User != nil { - if u := parsedURL.User.Username(); u != "" { - settings["user"] = u - } - if password, present := parsedURL.User.Password(); present { - settings["password"] = password - } +// unescapeKeywordValue applies libpq's backslash rule to the raw text of a +// keyword/value value: a backslash is dropped and whatever follows it is taken +// literally, whatever that character is. A backslash at the very end escapes +// the end of the string, so it is dropped and contributes nothing -- which is +// how libpq accepts `host=a\`. Only the unquoted branch can reach that case; +// inside quotes the escaped terminator leaves the string unterminated and the +// caller has already rejected it. +func unescapeKeywordValue(s string) string { + if !strings.ContainsRune(s, '\\') { + return s } - // Handle multiple host:port's in url.Host by splitting them into host,host,host and port,port,port. - var hosts []string - var ports []string - for host := range strings.SplitSeq(parsedURL.Host, ",") { - if host == "" { - continue - } - if isIPOnly(host) { - hosts = append(hosts, strings.Trim(host, "[]")) - continue - } - h, p, err := net.SplitHostPort(host) - if err != nil { - return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err) - } - if h != "" { - hosts = append(hosts, h) - } - if p != "" { - ports = append(ports, p) + var sb strings.Builder + sb.Grow(len(s)) + for i := 0; i < len(s); i++ { + if s[i] == '\\' { + i++ + if i == len(s) { + break + } } + sb.WriteByte(s[i]) } - if len(hosts) > 0 { - settings["host"] = strings.Join(hosts, ",") - } - if len(ports) > 0 { - settings["port"] = strings.Join(ports, ",") - } - - database := strings.TrimLeft(parsedURL.Path, "/") - if database != "" { - settings["database"] = database - } - - for k, v := range parsedURL.Query() { - settings[canonicalConnStringKey(k)] = v[0] - } - - return settings, nil -} - -func isIPOnly(host string) bool { - return net.ParseIP(strings.Trim(host, "[]")) != nil || !strings.Contains(host, ":") + return sb.String() } -var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1} - func parseKeywordValueSettings(s string) (map[string]string, error) { settings := make(map[string]string) + // Reject NUL bytes up front, as parseURLSettings does. libpq never sees one + // because its conninfo strings are NUL-terminated C strings; a Go string can + // carry a NUL through to the startup packet, where it acts as a parameter + // delimiter rather than data. StartupMessage.Encode refuses such parameters, + // but failing here reports the problem against the input that caused it. + if strings.IndexByte(s, 0) >= 0 { + return nil, errors.New("forbidden NUL byte in connection string") + } + // Trim any leading whitespace so that the loop exits cleanly when only // spaces remain (e.g. trailing spaces after the last value). s = strings.TrimLeft(s, " \t\n\r\v\f") @@ -697,6 +789,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) { } key = strings.Trim(s[:eqIdx], " \t\n\r\v\f") + // libpq reads a keyword as a run of non-space characters and then + // requires the next non-space character to be '=', so whitespace + // inside a keyword terminates it and is an error. Trimming alone would + // accept the space as part of the key and turn a typo into a bogus + // RuntimeParam that only the server rejects. Report it as libpq does, + // naming the keyword it had read. + if i := strings.IndexAny(key, " \t\n\r\v\f"); i >= 0 { + return nil, fmt.Errorf(`missing "=" after %q in connection info string`, key[:i]) + } s = strings.TrimLeft(s[eqIdx+1:], " \t\n\r\v\f") switch { case len(s) == 0: @@ -708,12 +809,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) { } if s[end] == '\\' { end++ + // A trailing backslash escapes the end of the string. + // libpq drops it and ends the value there. Break rather + // than let the loop's post-increment push end past len(s). if end == len(s) { - return nil, errors.New("invalid backslash") + break } } } - val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'") + val = unescapeKeywordValue(s[:end]) // Consume the value and trim any subsequent whitespace so that // multiple trailing spaces don't cause a spurious parse failure. s = strings.TrimLeft(s[end:], " \t\n\r\v\f") @@ -726,12 +830,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) { } if s[end] == '\\' { end++ + if end == len(s) { + return nil, errors.New("unterminated quoted string in connection info string") + } } } if end == len(s) { return nil, errors.New("unterminated quoted string in connection info string") } - val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'") + val = unescapeKeywordValue(s[:end]) // Consume the closing quote and any subsequent whitespace. s = strings.TrimLeft(s[end+1:], " \t\n\r\v\f") } @@ -1001,6 +1108,17 @@ func makeConnectTimeoutDialFunc(timeout time.Duration) DialFunc { return d.DialContext } +var ( + // ErrReadOnlyConnection is returned when a read-write connection is required but the connection is read-only. + ErrReadOnlyConnection = errors.New("read only connection") + // ErrReadWriteConnection is returned when a read-only connection is required but the connection is read-write. + ErrReadWriteConnection = errors.New("connection is not read only") + // ErrPrimaryConnection is returned when a standby connection is required but the server is primary. + ErrPrimaryConnection = errors.New("server is not in hot standby mode") + // ErrStandbyConnection is returned when a primary connection is required but the server is in standby mode. + ErrStandbyConnection = errors.New("server is in standby mode") +) + // ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible // target_session_attrs=read-write. func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error { @@ -1010,7 +1128,7 @@ func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgC } if string(result[0].Rows[0][0]) == "on" { - return errors.New("read only connection") + return ErrReadOnlyConnection } return nil @@ -1025,7 +1143,7 @@ func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgCo } if string(result[0].Rows[0][0]) != "on" { - return errors.New("connection is not read only") + return ErrReadWriteConnection } return nil @@ -1040,7 +1158,7 @@ func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgCon } if string(result[0].Rows[0][0]) != "t" { - return errors.New("server is not in hot standby mode") + return ErrPrimaryConnection } return nil @@ -1055,7 +1173,7 @@ func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgCon } if string(result[0].Rows[0][0]) == "t" { - return errors.New("server is in standby mode") + return ErrStandbyConnection } return nil @@ -1070,7 +1188,7 @@ func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn } if string(result[0].Rows[0][0]) != "t" { - return &NotPreferredError{err: errors.New("server is not in hot standby mode")} + return &NotPreferredError{err: ErrPrimaryConnection} } return nil diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go b/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go index 1dd514ff44..03b0d330fb 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go @@ -1,5 +1,4 @@ //go:build !windows -// +build !windows package pgconn @@ -9,22 +8,46 @@ import ( "path/filepath" ) +// currentOSUser resolves the current OS user account. It is a seam so tests +// can simulate os/user.Current failing -- including the unrecoverable +// crashes reported in some restricted/broken-NSS container environments -- +// without needing such an environment. +var currentOSUser = user.Current + +// userHomeDir resolves the current user's home directory. It is a seam so +// tests can simulate os.UserHomeDir failing without needing to unset $HOME +// for the whole process. +// +// os.UserHomeDir only reads the $HOME environment variable on this platform; +// it never calls into cgo or NSS, so unlike os/user.Current it cannot crash +// in restricted/broken container environments. That also means it can +// resolve a different directory than the OS account's passwd-file home +// directory if $HOME has been overridden -- this is an accepted tradeoff so +// that home-directory-derived defaults (pgpass, pg_service.conf, client SSL +// certificate/key/root files) keep resolving even when the OS user account +// lookup itself is unavailable or unsafe to call. +var userHomeDir = os.UserHomeDir + func defaultSettings() map[string]string { settings := make(map[string]string) settings["host"] = defaultHost() - settings["port"] = "5432" + settings["port"] = defaultPort + settings["target_session_attrs"] = "any" - // Default to the OS user name. Purposely ignoring err getting user name from - // OS. The client application will simply have to specify the user in that - // case (which they typically will be doing anyway). - user, err := user.Current() - if err == nil { - settings["user"] = user.Username - settings["passfile"] = filepath.Join(user.HomeDir, ".pgpass") - settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf") - sslcert := filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") - sslkey := filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") + // The home-directory-derived defaults (~/.pgpass, ~/.pg_service.conf, + // and the client SSL certificate/key/root files under ~/.postgresql) + // only need the user's home directory, not the full OS user account, so + // they are resolved unconditionally here via os.UserHomeDir. This keeps + // them available even when looking up the OS user account (needed only + // for the default PostgreSQL user name, see osUserSettings) is slow, + // fails, or -- in some restricted container environments with a broken + // NSS/CGO setup -- would crash the process. + if homeDir, err := userHomeDir(); err == nil { + settings["passfile"] = filepath.Join(homeDir, ".pgpass") + settings["servicefile"] = filepath.Join(homeDir, ".pg_service.conf") + sslcert := filepath.Join(homeDir, ".postgresql", "postgresql.crt") + sslkey := filepath.Join(homeDir, ".postgresql", "postgresql.key") if _, err := os.Stat(sslcert); err == nil { if _, err := os.Stat(sslkey); err == nil { // Both the cert and key must be present to use them, or do not use either @@ -32,13 +55,33 @@ func defaultSettings() map[string]string { settings["sslkey"] = sslkey } } - sslrootcert := filepath.Join(user.HomeDir, ".postgresql", "root.crt") + sslrootcert := filepath.Join(homeDir, ".postgresql", "root.crt") if _, err := os.Stat(sslrootcert); err == nil { settings["sslrootcert"] = sslrootcert } } - settings["target_session_attrs"] = "any" + return settings +} + +// osUserSettings returns the default PostgreSQL user name derived from the +// current OS user account. +// +// Resolving this requires looking up the OS user account, which can be slow +// or, in some restricted container environments (e.g. distroless images +// with a broken NSS/CGO setup), crash the process. Callers must only call +// osUserSettings when the default user name is not already supplied by the +// connection string, environment, or service file. +func osUserSettings() map[string]string { + settings := make(map[string]string) + + // Default to the OS user name. Purposely ignoring err getting user name from + // OS. The client application will simply have to specify the user in that + // case (which they typically will be doing anyway). + user, err := currentOSUser() + if err == nil { + settings["user"] = user.Username + } return settings } diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go b/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go index 33b4a1ff85..f59e251fd2 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go @@ -7,28 +7,44 @@ import ( "strings" ) +// currentOSUser resolves the current OS user account. It is a seam so tests +// can simulate os/user.Current failing -- including the unrecoverable +// crashes reported in some restricted/broken-NSS container environments -- +// without needing such an environment. +var currentOSUser = user.Current + +// userHomeDir resolves the current user's home directory. It is a seam so +// tests can simulate os.UserHomeDir failing without needing to unset the +// relevant environment variables for the whole process. +// +// os.UserHomeDir only reads %USERPROFILE% (falling back to +// %HOMEDRIVE%+%HOMEPATH%) on this platform; it never calls into the Windows +// user account APIs, so unlike os/user.Current it cannot crash in +// restricted/broken container environments. That also means it can resolve +// a different directory than the OS account API's reported home directory +// if those environment variables have been overridden -- this is an +// accepted tradeoff so that home-directory-derived defaults (pg_service.conf) +// keep resolving even when the OS user account lookup itself is unavailable +// or unsafe to call. +var userHomeDir = os.UserHomeDir + func defaultSettings() map[string]string { settings := make(map[string]string) settings["host"] = defaultHost() - settings["port"] = "5432" - - // Default to the OS user name. Purposely ignoring err getting user name from - // OS. The client application will simply have to specify the user in that - // case (which they typically will be doing anyway). - user, err := user.Current() - appData := os.Getenv("APPDATA") - if err == nil { - // Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`, - // but the libpq default is just the `user` portion, so we strip off the first part. - username := user.Username - if strings.Contains(username, "\\") { - username = username[strings.LastIndex(username, "\\")+1:] - } + settings["port"] = defaultPort + settings["target_session_attrs"] = "any" - settings["user"] = username + // The %APPDATA%\postgresql-derived defaults (pgpass.conf and the client + // SSL certificate/key/root files) only need the APPDATA environment + // variable, not the full OS user account, so they are resolved + // unconditionally here. This keeps them available even when looking up + // the OS user account (needed only for the default PostgreSQL user + // name, see osUserSettings) is slow, fails, or -- in some restricted + // container environments with a broken NSS/CGO setup -- would crash the + // process. + if appData := os.Getenv("APPDATA"); appData != "" { settings["passfile"] = filepath.Join(appData, "postgresql", "pgpass.conf") - settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf") sslcert := filepath.Join(appData, "postgresql", "postgresql.crt") sslkey := filepath.Join(appData, "postgresql", "postgresql.key") if _, err := os.Stat(sslcert); err == nil { @@ -44,7 +60,41 @@ func defaultSettings() map[string]string { } } - settings["target_session_attrs"] = "any" + // The default ~/.pg_service.conf location is derived from the user's + // home directory, resolved the same crash-safe way as on other + // platforms (see defaults.go). + if homeDir, err := userHomeDir(); err == nil { + settings["servicefile"] = filepath.Join(homeDir, ".pg_service.conf") + } + + return settings +} + +// osUserSettings returns the default PostgreSQL user name derived from the +// current OS user account. +// +// Resolving this requires looking up the OS user account, which can be slow +// or, in some restricted container environments (e.g. distroless images +// with a broken NSS/CGO setup), crash the process. Callers must only call +// osUserSettings when the default user name is not already supplied by the +// connection string, environment, or service file. +func osUserSettings() map[string]string { + settings := make(map[string]string) + + // Default to the OS user name. Purposely ignoring err getting user name from + // OS. The client application will simply have to specify the user in that + // case (which they typically will be doing anyway). + user, err := currentOSUser() + if err == nil { + // Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`, + // but the libpq default is just the `user` portion, so we strip off the first part. + username := user.Username + if strings.Contains(username, "\\") { + username = username[strings.LastIndex(username, "\\")+1:] + } + + settings["user"] = username + } return settings } diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/errors.go b/vendor/github.com/jackc/pgx/v5/pgconn/errors.go index 9fbe68cb65..5f38fdd529 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/errors.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/errors.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "net" - "net/url" "regexp" "strings" ) @@ -118,9 +117,11 @@ func (e *connLockError) Unwrap() error { return nil } -// ParseConfigError is the error returned when a connection string cannot be parsed. +// ParseConfigError is the error returned when a connection string cannot be +// parsed. Its error text masks recognizable passwords on a best-effort basis, +// but malformed input can be too ambiguous to redact completely. type ParseConfigError struct { - ConnString string // The connection string that could not be parsed. + ConnString string // The original, unredacted connection string that could not be parsed. msg string err error } @@ -134,9 +135,11 @@ func NewParseConfigError(conn, msg string, err error) error { } func (e *ParseConfigError) Error() string { - // Now that ParseConfigError is public and ConnString is available to the developer, perhaps it would be better only - // return a static string. That would ensure that the error message cannot leak a password. The ConnString field would - // allow access to the original string if desired and Unwrap would allow access to the underlying error. + // redactPW is necessarily best effort: an invalid connection string can be + // too ambiguous to identify every password. Returning only a static string + // would be the way to guarantee that Error cannot leak one. The public + // ConnString field would still allow access to the original string if + // desired, and Unwrap would allow access to the underlying error. connString := redactPW(e.ConnString) if e.err == nil { return fmt.Sprintf("cannot parse `%s`: %s", connString, e.msg) @@ -227,11 +230,12 @@ func newContextAlreadyDoneError(ctx context.Context) (err error) { return &errTimeout{&contextAlreadyDoneError{err: ctx.Err()}} } +// redactPW masks recognizable password fields on a best-effort basis. It +// cannot guarantee redaction when malformed input makes component boundaries +// ambiguous. func redactPW(connString string) string { if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") { - if u, err := url.Parse(connString); err == nil { - return redactURL(u) - } + return redactURLPassword(connString) } quotedKV := regexp.MustCompile(`password='[^']*'`) connString = quotedKV.ReplaceAllLiteralString(connString, "password=xxxxx") @@ -242,14 +246,164 @@ func redactPW(connString string) string { return connString } -func redactURL(u *url.URL) string { - if u == nil { - return "" +// redactURLPassword masks recognizable password values in a connection URI. +// For a URI that parses cleanly the component boundaries are certain, and +// every password position -- the userinfo password and password/sslpassword +// query values -- is reliably masked with the rest of the string left intact. +// It is also deliberately usable without a successful parse -- the strings +// that reach ParseConfigError are often exactly the ones that failed to parse +// -- but malformed syntax can make component boundaries ambiguous, so for +// such input redaction is best-effort and may over-mask. +// +// For URI shapes it recognizes, it mirrors parseURLSettings structurally +// rather than pattern-matching the raw text: the userinfo password is whatever +// follows the first ':' before the terminating '@' (found with the parser's +// lookahead), and a query value is masked when its percent-decoded key +// canonicalizes to password or sslpassword. This uses the same decoding as the +// parser, so encoded spellings like pass%77ord are caught and the whole +// recognized raw value is masked no matter what bytes it contains. +func redactURLPassword(connString string) string { + const mask = "xxxxx" + var b strings.Builder + b.Grow(len(connString)) + + p := connString + for _, prefix := range []string{"postgresql://", "postgres://"} { + if rest, ok := strings.CutPrefix(connString, prefix); ok { + b.WriteString(prefix) + p = rest + break + } + } + + // Userinfo: same lookahead as parseURLSettings. + if i := strings.IndexAny(p, "@/"); i >= 0 && p[i] == '@' { + user, _, hasPassword := strings.Cut(p[:i], ":") + p = p[i+1:] + b.WriteString(user) + if hasPassword { + b.WriteString(":" + mask) + } + b.WriteByte('@') + } + + // Nothing after the userinfo is a password position, but a password can + // land there in malformed URIs: an unencoded '/' or '?' in a userinfo + // password turns everything after it into path or query, stranding the + // '@' (postgres://user:pass/word?x=y@host). As a best-effort heuristic, + // while an '@' remains, mask everything shaped like + // ":candidate-credential@" across the whole + // remainder -- before the query is split off, or a stranded '@' inside + // the query would hide the pattern, and greedily up to each '@', so a + // ':' inside the stranded password (user:sec:ret@host) cannot split the + // mask and leak the part before it. + // + // The heuristic must not run when the connection string is structurally + // unambiguous: then nothing can be stranded, a remaining '@' is ordinary + // data (typically in a query value), and the greedy mask would swallow + // the '/' and '?' delimiters -- hiding the query from the password-key + // masking below, so a password=... query parameter would leak. Valid + // URIs must always redact exactly; the heuristic is reserved for + // malformed input, where only best effort is possible. + if strings.IndexByte(p, '@') >= 0 && !uriStructureUnambiguous(connString) { + brokenUserinfo := regexp.MustCompile(`:[^@]+@`) + p = brokenUserinfo.ReplaceAllLiteralString(p, ":xxxxxx@") + } + + qi := uriQueryStart(p) + if qi < 0 { + b.WriteString(p) + return b.String() + } + b.WriteString(p[:qi]) + query := p[qi+1:] + b.WriteByte('?') + + for i, pair := range strings.Split(query, "&") { + if i > 0 { + b.WriteByte('&') + } + rawKey, _, hasValue := strings.Cut(pair, "=") + if !hasValue { + b.WriteString(pair) + continue + } + switch canonicalConnStringKey(uriDecodeLenient(rawKey)) { + case "password", "sslpassword": + b.WriteString(rawKey) + b.WriteByte('=') + b.WriteString(mask) + default: + b.WriteString(pair) + } + } + return b.String() +} + +// uriStructureUnambiguous reports whether connString parses as a connection +// URI whose component boundaries are certain, meaning redactURLPassword's +// structural walk is exact and no password bytes can sit outside the two +// positions it masks (the userinfo password and password-keyed query values). +// That requires parseURLSettings to accept the string and every port element +// to be numeric or empty: the parser accepts arbitrary text in the port slot +// (postgres://a@u:sec:ret@h parses with port "sec:ret@h"), so a non-numeric +// port may be a mislaid password and keeps the string in best-effort +// territory. +func uriStructureUnambiguous(connString string) bool { + settings, _, err := parseURLSettings(connString) + if err != nil { + return false + } + for part := range strings.SplitSeq(settings["port"], ",") { + for i := 0; i < len(part); i++ { + if part[i] < '0' || part[i] > '9' { + return false + } + } + } + return true +} + +// uriQueryStart returns the index of the '?' that begins the query component +// of p (the post-scheme, post-userinfo part of a connection URI), or -1 if +// there is none. It follows parseURLSettings' structure: '[' at the start of +// a netloc element opens an IPv6 bracket whose contents -- deliberately +// unvalidated -- may contain a literal '?' that is host data, not the query +// delimiter. On an unterminated bracket (the parser errors there) it falls +// back to the first '?' anywhere. With no valid structure to follow, +// over-including text gives the best-effort redactor more candidate pairs to +// inspect. +func uriQueryStart(p string) int { + i := 0 + for { + if i < len(p) && p[i] == '[' { + end := strings.IndexByte(p[i:], ']') + if end < 0 { + return strings.IndexByte(p, '?') + } + i += end + 1 + } + // Host and port data: everything up to a '/', '?', or ','. + for i < len(p) && p[i] != '/' && p[i] != '?' && p[i] != ',' { + i++ + } + if i < len(p) && p[i] == ',' { + i++ + continue + } + break + } + if i == len(p) { + return -1 + } + if p[i] == '?' { + return i } - if _, pwSet := u.User.Password(); pwSet { - u.User = url.UserPassword(u.User.Username(), "xxxxx") + // p[i] == '/': a path follows; the first '?' after it starts the query. + if j := strings.IndexByte(p[i:], '?'); j >= 0 { + return i + j } - return u.String() + return -1 } type NotPreferredError struct { diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/parse_url.go b/vendor/github.com/jackc/pgx/v5/pgconn/parse_url.go new file mode 100644 index 0000000000..3cc8d91895 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/parse_url.go @@ -0,0 +1,397 @@ +package pgconn + +import ( + "errors" + "fmt" + "maps" + "strings" +) + +// This file parses PostgreSQL connection URIs using a parser designed to +// exactly match libpq's URI parser behavior (conninfo_uri_parse_options, +// conninfo_uri_parse_params, and conninfo_uri_decode in +// src/interfaces/libpq/fe-connect.c), so that pgx accepts and rejects exactly +// the same URIs as libpq, including libpq's multiple-host extension +// (postgresql://host1:port1,host2:port2/db), which is not valid RFC 3986 syntax. +// +// Deliberate differences from libpq: +// +// - Query parameters that libpq does not recognize are accepted. They become +// runtime parameters or pgx-specific options (e.g. pool_max_conns) instead +// of failing the parse. +// - Error messages avoid quoting the unredacted connection string and mask +// recognizable password fields on a best-effort basis. Invalid connection +// strings can be structurally ambiguous, so password redaction cannot be +// guaranteed for every malformed input. libpq quotes the failing input +// verbatim, which can leak a password into error messages and logs. +// - Literal NUL bytes are rejected. libpq never sees them because C strings +// end at the first NUL; a Go string can carry one into the startup packet, +// where it would act as a protocol delimiter and inject extra parameters. + +// parseURLMeta reports provenance facts about a parsed URI that +// ParseConfigWithOptions needs for ConnStringAllowedKeys validation and that +// cannot be recovered from the settings map itself. +type parseURLMeta struct { + // impliedEmptyPortList: the "port" entry is an all-empty list synthesized + // from the host list (postgres://h1,h2 yields port=",") with no port + // bytes supplied by the user. Determined from the raw port syntax, not + // the decoded value: a port of literal spaces (postgres://h: /db) + // decodes to empty but was user-supplied. + impliedEmptyPortList bool + // sawRawSSLKey / sawSSLTrueAlias / sawExplicitSSLModeKey record which + // spellings of the ssl and sslmode query keys appeared anywhere in the + // URI -- including occurrences later superseded under last-occurrence- + // wins. The ssl=true alias rewrite and ordinary repeated-key handling can + // remove those occurrences from the final settings map, so + // ConnStringAllowedKeys cannot fail closed from that map alone; it must see + // every key the user actually wrote. + sawRawSSLKey bool // key "ssl" with a value other than "true" + sawSSLTrueAlias bool // key "ssl" with value "true" (stored as sslmode=require) + sawExplicitSSLModeKey bool // key "sslmode" +} + +// parseURLSettings parses a connection URI into a settings map. connString +// must start with "postgres://" or "postgresql://". +// +// Multiple hosts are represented in the returned map the same way libpq +// represents them internally: settings["host"] and settings["port"] are +// comma-separated lists that are positionally aligned, with empty elements +// meaning "use the default". The lists are split in ParseConfigWithOptions. +func parseURLSettings(connString string) (settings map[string]string, meta parseURLMeta, err error) { + settings = make(map[string]string) + + if strings.IndexByte(connString, 0) >= 0 { + return nil, meta, errors.New("forbidden NUL byte in connection string") + } + + p, ok := strings.CutPrefix(connString, "postgresql://") + if !ok { + p, ok = strings.CutPrefix(connString, "postgres://") + } + if !ok { + return nil, meta, errors.New("invalid URI propagated to internal parser routine") + } + + // Look ahead for a possible user credentials designator. Like libpq, only + // a '/' stops the search, so a '@' anywhere before the path -- even inside + // what looks like a query string -- is treated as the userinfo terminator. + if i := strings.IndexAny(p, "@/"); i >= 0 && p[i] == '@' { + user, password, hasPassword := strings.Cut(p[:i], ":") + p = p[i+1:] + if user != "" { + val, err := uriDecode(user, "") + if err != nil { + return nil, meta, err + } + settings["user"] = val + } + if hasPassword && password != "" { + val, err := uriDecode(password, "password") + if err != nil { + return nil, meta, err + } + settings["password"] = val + } + } + + // Parse the comma-separated list of netloc[:port] specifications. Hosts + // and ports accumulate into positionally aligned comma-joined lists: every + // separator appends a comma to both, so postgres://h1,h2:5433 yields + // host="h1,h2" port=",5433". + var hostBuf, portBuf strings.Builder + + for { + if peekByte(p) == '[' { + // IPv6 address. The bracket contents are not validated, matching libpq. + end := strings.IndexByte(p, ']') + if end < 0 { + return nil, meta, errors.New(`end of string reached when looking for matching "]" in IPv6 host address in URI`) + } + if end == 1 { + return nil, meta, errors.New("IPv6 host address may not be empty in URI") + } + hostBuf.WriteString(p[1:end]) + p = p[end+1:] + if c := peekByte(p); c != 0 && c != ':' && c != '/' && c != '?' && c != ',' { + return nil, meta, fmt.Errorf(`unexpected character "%c" at position %d in URI (expected ":" or "/")`, c, len(connString)-len(p)+1) + } + } else { + // DNS-named or IPv4 netloc: everything up to a ':', '/', '?', or ','. + i := strings.IndexAny(p, ":/?,") + if i < 0 { + i = len(p) + } + hostBuf.WriteString(p[:i]) + p = p[i:] + } + + if peekByte(p) == ':' { + p = p[1:] + i := strings.IndexAny(p, "/?,") + if i < 0 { + i = len(p) + } + portBuf.WriteString(p[:i]) + p = p[i:] + } + + if peekByte(p) != ',' { + break + } + p = p[1:] + hostBuf.WriteByte(',') + portBuf.WriteByte(',') + } + + // The joined lists are percent-decoded as a unit, after joining. This + // means %2C decodes to a comma that later splits like a real separator -- + // a host name containing a literal comma is inexpressible, as in libpq. + if hostBuf.Len() > 0 { + hostList, err := uriDecode(hostBuf.String(), "") + if err != nil { + return nil, meta, err + } + settings["host"] = hostList + } + // Like libpq, the port list is stored even when every element is empty + // (postgres://h1,h2 yields port=","). This matters: a connection string + // port shadows PGPORT during settings merge, so with PGPORT=1,2 a + // three-host URI without ports must use the default port for every host, + // not fail the port/host count check. Such an implied all-empty list + // carries no user-supplied port text, which is what + // meta.impliedEmptyPortList reports -- judged on the raw bytes, before + // percent-decoding trims spaces, so a port the user actually typed never + // counts as implied even when it decodes to empty. + if portBuf.Len() > 0 { + meta.impliedEmptyPortList = strings.Trim(portBuf.String(), ",") == "" + portList, err := uriDecode(portBuf.String(), "") + if err != nil { + return nil, meta, err + } + settings["port"] = portList + } + + if peekByte(p) == '/' { + p = p[1:] + dbname := p + p = "" + if i := strings.IndexByte(dbname, '?'); i >= 0 { + p = dbname[i:] + dbname = dbname[:i] + } + // Like libpq, an empty path component leaves dbname unset so the + // default stays in effect. + if dbname != "" { + val, err := uriDecode(dbname, "") + if err != nil { + return nil, meta, err + } + settings["database"] = val + } + } + + if peekByte(p) == '?' { + // Query parameters land in their own map first: an explicit ?port= + // overrides the netloc-derived port list and is user-supplied port + // text, so it cancels the implied-list exemption even when its value + // is empty. + query := make(map[string]string) + if err := parseURLQueryParams(p[1:], query, &meta); err != nil { + return nil, meta, err + } + if _, ok := query["port"]; ok { + meta.impliedEmptyPortList = false + } + maps.Copy(settings, query) + } + + return settings, meta, nil +} + +// peekByte returns the first byte of s, or 0 if s is empty. A NUL byte is a +// safe end-of-input sentinel because parseURLSettings rejects literal NULs. +func peekByte(s string) byte { + if len(s) == 0 { + return 0 + } + return s[0] +} + +// parseURLQueryParams parses the query part of a connection URI into settings, +// mirroring libpq's conninfo_uri_parse_params: '&'-separated pairs, exactly +// one raw '=' per pair, both halves percent-decoded, last occurrence wins. It +// records in meta which spellings of the ssl/sslmode keys it saw (see +// parseURLMeta). +func parseURLQueryParams(params string, settings map[string]string, meta *parseURLMeta) error { + // sslWasLast records whether ssl or sslmode was encountered most recently. + // This matters if the final repeated ssl value is "true": the alias wins + // only when it occurs after the final explicit sslmode. + sslWasLast := false + + for params != "" { + pair := params + if i := strings.IndexByte(params, '&'); i >= 0 { + pair = params[:i] + params = params[i+1:] + } else { + params = "" + } + + rawKey, rawValue, found := strings.Cut(pair, "=") + if !found { + return fmt.Errorf(`missing key/value separator "=" in URI query parameter: "%s"`, rawKey) + } + if strings.IndexByte(rawValue, '=') >= 0 { + return fmt.Errorf(`extra key/value separator "=" in URI query parameter: "%s"`, rawKey) + } + + key, err := uriDecode(rawKey, "") + if err != nil { + return err + } + key = canonicalConnStringKey(key) + + secretName := "" + if key == "password" || key == "sslpassword" { + secretName = key + } + value, err := uriDecode(rawValue, secretName) + if err != nil { + return err + } + + // Resolve repeated ssl values under their raw key before applying the + // JDBC compatibility alias. Otherwise ssl=true would overwrite an + // independent explicit sslmode that must reappear if a later ssl value + // supersedes the alias. The alias is URI-only and applies only to the + // literal value "true". + switch key { + case "ssl": + sslWasLast = true + if value == "true" { + meta.sawSSLTrueAlias = true + } else { + meta.sawRawSSLKey = true + } + case "sslmode": + sslWasLast = false + meta.sawExplicitSSLModeKey = true + } + + settings[key] = value + } + + if value, ok := settings["ssl"]; ok && value == "true" { + delete(settings, "ssl") + if sslWasLast { + settings["sslmode"] = "require" + } + } + + return nil +} + +// uriDecode percent-decodes a URI component with the same rules as libpq's +// conninfo_uri_decode: '%' followed by exactly two case-insensitive hex +// digits, %00 forbidden, leading and trailing ASCII spaces skipped, interior +// spaces rejected. Decoded bytes are emitted raw with no character set +// validation. +// +// If secretName is non-empty, error messages identify that component by name +// instead of quoting its raw value. This prevents the known component's raw +// contents from being copied into the decode error; it does not make the +// separate, best-effort redaction of an invalid connection string complete. +func uriDecode(raw, secretName string) (string, error) { + // The component may be a secret; every error must be built by fail so the + // quote-the-raw-value-or-not redaction decision lives in exactly one place. + fail := func(secretFormat, publicFormat string) (string, error) { + if secretName != "" { + return "", fmt.Errorf(secretFormat, secretName) + } + return "", fmt.Errorf(publicFormat, raw) + } + + var b strings.Builder + b.Grow(len(raw)) + + i := 0 + for i < len(raw) && raw[i] == ' ' { + i++ + } + for i < len(raw) && raw[i] != ' ' { + if raw[i] != '%' { + b.WriteByte(raw[i]) + i++ + continue + } + + var hi, lo byte + var ok1, ok2 bool + if i+1 < len(raw) { + hi, ok1 = hexDigit(raw[i+1]) + } + if i+2 < len(raw) { + lo, ok2 = hexDigit(raw[i+2]) + } + if !ok1 || !ok2 { + return fail("invalid percent-encoded token in %s", `invalid percent-encoded token: "%s"`) + } + + c := hi<<4 | lo + if c == 0 { + return fail("forbidden value %%00 in percent-encoded value in %s", `forbidden value %%00 in percent-encoded value: "%s"`) + } + b.WriteByte(c) + i += 3 + } + for i < len(raw) && raw[i] == ' ' { + i++ + } + if i < len(raw) { + return fail("unexpected spaces found in %s, use percent-encoded spaces (%%20) instead", `unexpected spaces found in "%s", use percent-encoded spaces (%%20) instead`) + } + + return b.String(), nil +} + +// uriDecodeLenient is a non-failing variant of uriDecode used for best-effort +// redaction: valid percent-encodings are decoded, anything uriDecode would +// reject passes through unchanged. Redaction processing itself must not fail, +// and it must see the same key spelling the parser would (pass%77ord decodes +// to password), so encoded password keys are recognized even in connection +// strings that do not parse. This helps recognize keys but cannot make +// redaction complete when malformed input has ambiguous component boundaries. +func uriDecodeLenient(raw string) string { + raw = strings.Trim(raw, " ") + + var b strings.Builder + b.Grow(len(raw)) + + for i := 0; i < len(raw); { + if raw[i] == '%' && i+2 < len(raw) { + hi, ok1 := hexDigit(raw[i+1]) + lo, ok2 := hexDigit(raw[i+2]) + if ok1 && ok2 { + b.WriteByte(hi<<4 | lo) + i += 3 + continue + } + } + b.WriteByte(raw[i]) + i++ + } + + return b.String() +} + +func hexDigit(c byte) (byte, bool) { + switch { + case c >= '0' && c <= '9': + return c - '0', true + case c >= 'A' && c <= 'F': + return c - 'A' + 10, true + case c >= 'a' && c <= 'f': + return c - 'a' + 10, true + } + return 0, false +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go b/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go index d181f7f5f2..08bfd8aebe 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go @@ -13,6 +13,7 @@ import ( "maps" "math" "net" + "slices" "strconv" "strings" "sync" @@ -392,6 +393,9 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo pgConn.slowWriteTimer.Stop() pgConn.bgReaderStarted = make(chan struct{}) pgConn.frontend = config.BuildFrontend(pgConn.bgReader, pgConn.conn) + if config.MaxProtocolMessageBodyLen > 0 { + pgConn.frontend.SetMaxBodyLen(config.MaxProtocolMessageBodyLen) + } startupMsg := pgproto3.StartupMessage{ ProtocolVersion: maxProtocolVersion, @@ -469,13 +473,7 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo clientFinishedAuth = true case *pgproto3.AuthenticationSASL: // Check if OAUTHBEARER is supported - serverSupportsOAuthBearer := false - for _, mech := range msg.AuthMechanisms { - if mech == "OAUTHBEARER" { - serverSupportsOAuthBearer = true - break - } - } + serverSupportsOAuthBearer := slices.Contains(msg.AuthMechanisms, "OAUTHBEARER") if serverSupportsOAuthBearer && pgConn.config.OAuthTokenProvider != nil { if err := requireAuthPolicy.check(authMethodOAuth); err != nil { @@ -574,10 +572,10 @@ func (pgConn *PgConn) signalMessage() chan struct{} { panic("BUG: signalMessage when already in progress") } + ch := make(chan struct{}) pgConn.bufferingReceive = true pgConn.bufferingReceiveMux.Lock() - ch := make(chan struct{}) go func() { pgConn.bufferingReceiveMsg, pgConn.bufferingReceiveErr = pgConn.frontend.Receive() pgConn.bufferingReceiveMux.Unlock() @@ -790,6 +788,16 @@ func (pgConn *PgConn) asyncClose() { pgConn.frontend.Send(&pgproto3.Terminate{}) pgConn.flushWithPotentialWriteReadDeadlock() + + // Drain any data already in flight from the server (DataRows that were sent before the + // CancelRequest landed, the resulting ErrorResponse, ReadyForQuery, and finally the server's + // own close after it processes Terminate). Closing a TCP socket while unread data remains in + // the kernel receive buffer causes the OS to send RST instead of FIN, which surfaces on the + // server or proxy as "connection reset by peer". The deadline set above bounds how long this + // will block; on timeout we fall through to Close() and accept the abortive close. + // + // See https://github.com/jackc/pgx/issues/2584 + io.Copy(io.Discard, pgConn.conn) }() } @@ -1295,7 +1303,9 @@ func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramVa // // This differs from [PgConn.ExecPrepared] in that it takes a [*StatementDescription] instead of the prepared statement name. // Because it has the [*StatementDescription] it can avoid the Describe Portal message that [PgConn.ExecPrepared] must send to get -// the result column descriptions. +// the result column descriptions. However, if the statement description has no fields then a Describe is still sent, as +// an empty Fields may mean the results were not knowable at prepare time, e.g. a FETCH from a cursor that did not exist +// yet. // // paramValues are the parameter values. It must be encoded in the format given by paramFormats. // @@ -1356,7 +1366,10 @@ func (pgConn *PgConn) execExtendedPrefix(ctx context.Context, paramValues [][]by } func (pgConn *PgConn) execExtendedSuffix(result *ResultReader, statementDescription *StatementDescription, resultFormats []int16) { - if statementDescription == nil { + if statementDescription == nil || len(statementDescription.Fields) == 0 { + // The cached field descriptions are missing or empty. Empty field descriptions can occur when the statement's + // result set was not known at prepare time, e.g. a FETCH from a cursor that did not exist yet. Send a Describe + // so the server supplies the actual row description when the statement is executed. pgConn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) } pgConn.frontend.SendExecute(&pgproto3.Execute{}) @@ -1572,10 +1585,15 @@ type MultiResultReader struct { rr *ResultReader - // Data from when the batch was queued. + // Data from when the batch was queued. There is one entry per command in the batch. Entries are nil for commands + // other than Batch.ExecStatement, which is the only command that does not request a RowDescription from the server. statementDescriptions []*StatementDescription resultFormats [][]int16 + // Statement data for the command currently being processed. Popped from the queues above at each BindComplete. + currentStatementDescription *StatementDescription + currentResultFormats []int16 + closed bool err error } @@ -1619,19 +1637,19 @@ func (mrr *MultiResultReader) NextResult() bool { for !mrr.closed && mrr.err == nil { msg, _ := mrr.pgConn.peekMessage() if _, ok := msg.(*pgproto3.DataRow); ok { - if len(mrr.statementDescriptions) > 0 { + if sd := mrr.currentStatementDescription; sd != nil { rr := ResultReader{ pgConn: mrr.pgConn, multiResultReader: mrr, ctx: mrr.ctx, } - // This result corresponds to a prepared statement description that was provided when queuing the batch. - sd := mrr.statementDescriptions[0] - mrr.statementDescriptions = mrr.statementDescriptions[1:] - - resultFormats := mrr.resultFormats[0] - mrr.resultFormats = mrr.resultFormats[1:] + // This result corresponds to a Batch.ExecStatement command. No RowDescription was requested from the + // server so the field descriptions come from the statement description that was provided when queuing + // the batch. + resultFormats := mrr.currentResultFormats + mrr.currentStatementDescription = nil + mrr.currentResultFormats = nil sdFields := sd.Fields rr.fieldDescriptions = rr.pgConn.getFieldDescriptionSlice(len(sdFields)) @@ -1656,7 +1674,24 @@ func (mrr *MultiResultReader) NextResult() bool { } switch msg := msg.(type) { + case *pgproto3.BindComplete: + // Every command in a batch begins with a BindComplete. Pop this command's statement data so that the + // following messages are matched with the correct statement description. It must be popped here rather than + // when a DataRow is peeked because a command that returns no rows would otherwise leave its entry in the + // queue, misaligning the statement descriptions for all subsequent commands. + if len(mrr.statementDescriptions) > 0 { + mrr.currentStatementDescription = mrr.statementDescriptions[0] + mrr.statementDescriptions = mrr.statementDescriptions[1:] + mrr.currentResultFormats = mrr.resultFormats[0] + mrr.resultFormats = mrr.resultFormats[1:] + } else { + mrr.currentStatementDescription = nil + mrr.currentResultFormats = nil + } case *pgproto3.RowDescription: + mrr.currentStatementDescription = nil + mrr.currentResultFormats = nil + mrr.pgConn.resultReader = ResultReader{ pgConn: mrr.pgConn, multiResultReader: mrr, @@ -1668,11 +1703,25 @@ func (mrr *MultiResultReader) NextResult() bool { mrr.rr = &mrr.pgConn.resultReader return true case *pgproto3.CommandComplete: - mrr.pgConn.resultReader = ResultReader{ + rr := ResultReader{ commandTag: mrr.pgConn.makeCommandTag(msg.CommandTag), commandConcluded: true, closed: true, } + + if sd := mrr.currentStatementDescription; sd != nil { + // A Batch.ExecStatement command that returned no rows. Attach the field descriptions from the statement + // description so the result reports its columns the same as a result that was described by the server. + rr.fieldDescriptions = mrr.pgConn.getFieldDescriptionSlice(len(sd.Fields)) + err := combineFieldDescriptionsAndResultFormats(rr.fieldDescriptions, sd.Fields, mrr.currentResultFormats) + if err != nil { + rr.err = err + } + mrr.currentStatementDescription = nil + mrr.currentResultFormats = nil + } + + mrr.pgConn.resultReader = rr mrr.rr = &mrr.pgConn.resultReader return true case *pgproto3.EmptyQueryResponse: @@ -1953,6 +2002,11 @@ func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFor return } + // The statement data queues must have one entry per command so results can be matched with the correct statement + // description. This command requests a RowDescription from the server so it queues a nil placeholder. + batch.statementDescriptions = append(batch.statementDescriptions, nil) + batch.resultFormats = append(batch.resultFormats, nil) + batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf) if batch.err != nil { return @@ -1968,7 +2022,9 @@ func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFor // // This differs from ExecPrepared in that it takes a *StatementDescription instead of just the prepared statement name. // Because it has the *StatementDescription it can avoid the Describe Portal message that ExecPrepared must send to get -// the result column descriptions. +// the result column descriptions. However, if the statement description has no fields then a Describe is still sent, as +// an empty Fields may mean the results were not knowable at prepare time, e.g. a FETCH from a cursor that did not exist +// yet. func (batch *Batch) ExecStatement(statementDescription *StatementDescription, paramValues [][]byte, paramFormats, resultFormats []int16) { if batch.err != nil { return @@ -1979,6 +2035,16 @@ func (batch *Batch) ExecStatement(statementDescription *StatementDescription, pa return } + if len(statementDescription.Fields) == 0 { + // The cached field descriptions are empty, which can occur when the statement's result set was not known at + // prepare time, e.g. a FETCH from a cursor that did not exist yet. Send a Describe so the server supplies the + // actual row description when the statement is executed. + batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf) + if batch.err != nil { + return + } + } + batch.statementDescriptions = append(batch.statementDescriptions, statementDescription) batch.resultFormats = append(batch.resultFormats, resultFormats) @@ -2242,6 +2308,9 @@ func Construct(hc *HijackedConn) (*PgConn, error) { pgConn.slowWriteTimer.Stop() pgConn.bgReaderStarted = make(chan struct{}) pgConn.frontend = hc.Config.BuildFrontend(pgConn.bgReader, pgConn.conn) + if hc.Config.MaxProtocolMessageBodyLen > 0 { + pgConn.frontend.SetMaxBodyLen(hc.Config.MaxProtocolMessageBodyLen) + } return pgConn, nil } @@ -2512,6 +2581,12 @@ func (p *Pipeline) SendQueryStatement(statementDescription *StatementDescription } p.conn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: statementDescription.Name, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) + if len(statementDescription.Fields) == 0 { + // The cached field descriptions are empty. This can occur when the statement's result set is + // not known at prepare time, e.g. a FETCH from a cursor that did not exist yet. Send a + // Describe so the server supplies the actual row description when the statement is executed. + p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) + } p.conn.frontend.SendExecute(&pgproto3.Execute{}) p.state.PushBackRequestType(pipelineQueryStatement) p.state.PushBackStatementData(statementDescription, resultFormats) @@ -2607,22 +2682,29 @@ func (p *Pipeline) getResults() (results any, err error) { case pipelineNil: return nil, nil case pipelinePrepare: - return p.getResultsPrepare() + results, err = p.getResultsPrepare() case pipelineQueryParams: - return p.getResultsQueryParams() + results, err = p.getResultsQueryParams() case pipelineQueryPrepared: - return p.getResultsQueryPrepared() + results, err = p.getResultsQueryPrepared() case pipelineQueryStatement: - return p.getResultsQueryStatement() + results, err = p.getResultsQueryStatement() case pipelineDeallocate: - return p.getResultsDeallocate() + results, err = p.getResultsDeallocate() case pipelineSyncRequest: - return p.getResultsSync() + results, err = p.getResultsSync() case pipelineFlushRequest: return nil, errors.New("BUG: pipelineFlushRequest should not be in request queue") default: return nil, errors.New("BUG: unknown pipeline request type") } + + if err != nil { + // Return an untyped nil instead of an interface containing a typed nil pointer so that callers can compare + // results to nil. + return nil, err + } + return results, nil } func (p *Pipeline) getResultsPrepare() (*StatementDescription, error) { @@ -2699,21 +2781,48 @@ func (p *Pipeline) getResultsQueryPrepared() (*ResultReader, error) { } func (p *Pipeline) getResultsQueryStatement() (*ResultReader, error) { + // The statement data must be extracted even if an error occurs. Otherwise, it would still be in the queue and + // subsequent QueryStatement results would be misaligned with their statement descriptions. + sd, resultFormats := p.state.ExtractFrontStatementData() + if sd == nil { + return nil, errors.New("BUG: missing statement description or result formats for QueryStatement") + } + err := p.receiveBindComplete("QueryStatement") if err != nil { return nil, err } + sdFields := sd.Fields + if len(sdFields) == 0 { + // A Describe was sent for this statement (see SendQueryStatement). Read the server-provided + // row description which may include fields that were not known at prepare time. + msg, err := p.receiveMessage() + if err != nil { + return nil, err + } + + switch msg := msg.(type) { + case *pgproto3.RowDescription: + sdFields = make([]FieldDescription, len(msg.Fields)) + convertRowDescription(sdFields, msg) + case *pgproto3.NoData: + // Statement returns no rows. + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + p.conn.resultReader.closed = true + return nil, pgErr + default: + return nil, p.handleUnexpectedMessage("QueryStatement RowDescription or NoData", msg) + } + } + msg, err := p.receiveMessage() if err != nil { return nil, err } - sd, resultFormats := p.state.ExtractFrontStatementData() - if sd == nil { - return nil, errors.New("BUG: missing statement description or result formats for QueryStatement") - } - sdFields := sd.Fields fieldDescriptions := p.conn.getFieldDescriptionSlice(len(sdFields)) err = combineFieldDescriptionsAndResultFormats(fieldDescriptions, sdFields, resultFormats) if err != nil { @@ -2739,6 +2848,12 @@ func (p *Pipeline) getResultsQueryStatement() (*ResultReader, error) { fieldDescriptions: fieldDescriptions, } return &p.conn.resultReader, nil + case *pgproto3.EmptyQueryResponse: + p.conn.resultReader = ResultReader{ + commandConcluded: true, + closed: true, + } + return &p.conn.resultReader, nil case *pgproto3.ErrorResponse: pgErr := ErrorResponseToPgError(msg) p.state.HandleError(pgErr) @@ -2866,6 +2981,15 @@ func (p *Pipeline) receiveDescribedResultReader(errStr string) (*ResultReader, e closed: true, } return &p.conn.resultReader, nil + + // EmptyQueryResponse is returned instead of CommandComplete when the query is empty. e.g. A comment-only query. + case *pgproto3.EmptyQueryResponse: + p.conn.resultReader = ResultReader{ + commandConcluded: true, + closed: true, + } + return &p.conn.resultReader, nil + case *pgproto3.ErrorResponse: pgErr := ErrorResponseToPgError(msg) p.state.HandleError(pgErr) diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go b/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go index 43bd7ec636..936576a050 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go @@ -34,7 +34,7 @@ func (dst *NegotiateProtocolVersion) Decode(src []byte) error { capHint = remaining } dst.UnrecognizedOptions = make([]string, 0, capHint) - for i := 0; i < optionCount; i++ { + for range optionCount { if rp >= len(src) { return &invalidMessageFormatErr{messageType: "NegotiateProtocolVersion"} } diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go b/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go index eb48f72bf0..69cf99ac72 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "strings" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -75,6 +76,24 @@ func (src *StartupMessage) Encode(dst []byte) ([]byte, error) { dst = pgio.AppendUint32(dst, src.ProtocolVersion) for k, v := range src.Parameters { + // The startup message body is a run of NUL-delimited strings whose + // length is data-driven: the server keeps reading name/value pairs + // until the empty name that terminates the list. Other messages have a + // field count fixed by the message type, so a stray NUL there leaves + // trailing bytes and the server rejects the message; here it simply + // yields more parameters. A libpq caller cannot reach this state + // because its parameters are NUL-terminated C strings, but a Go string + // can carry a NUL, so an application_name of "x\x00user\x00admin" + // would silently change the role the connection logs in as. Refuse to + // encode instead. + if strings.IndexByte(k, 0) >= 0 { + return nil, errors.New("startup message parameter name contains NUL byte") + } + if strings.IndexByte(v, 0) >= 0 { + // Name the parameter but not the value: values can hold secrets. + return nil, fmt.Errorf("startup message parameter %q contains NUL byte in value", k) + } + dst = append(dst, k...) dst = append(dst, 0) dst = append(dst, v...) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/array.go b/vendor/github.com/jackc/pgx/v5/pgtype/array.go index 26505fb841..64a8498df6 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/array.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/array.go @@ -2,7 +2,6 @@ package pgtype import ( "bytes" - "encoding/binary" "fmt" "io" "strconv" @@ -45,39 +44,30 @@ func cardinality(dimensions []ArrayDimension) int { return elementCount } -func (dst *arrayHeader) DecodeBinary(m *Map, src []byte) (int, error) { - if len(src) < 12 { - return 0, fmt.Errorf("array header too short: %d", len(src)) +func (dst *arrayHeader) DecodeBinary(r *pgio.Reader) error { + // Each dimension is 8 bytes, which also bounds the Dimensions allocation below. + numDims := r.Count(8) + if err := r.Err(); err != nil { + return fmt.Errorf("array header: %w", err) } - rp := 0 - - numDims := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - if numDims > 6 { - return 0, fmt.Errorf("array has too many dimensions: %d", numDims) + return fmt.Errorf("array has too many dimensions: %d", numDims) } - dst.ContainsNull = binary.BigEndian.Uint32(src[rp:]) == 1 - rp += 4 - - dst.ElementOID = binary.BigEndian.Uint32(src[rp:]) - rp += 4 + dst.ContainsNull = r.Uint32() == 1 + dst.ElementOID = r.Uint32() - if len(src) < 12+numDims*8 { - return 0, fmt.Errorf("array header too short for %d dimensions: %d", numDims, len(src)) - } dst.Dimensions = make([]ArrayDimension, numDims) for i := range dst.Dimensions { - dst.Dimensions[i].Length = int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - dst.Dimensions[i].LowerBound = int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 + dst.Dimensions[i].Length = r.Int32() + dst.Dimensions[i].LowerBound = r.Int32() } - return rp, nil + if err := r.Err(); err != nil { + return fmt.Errorf("array header: %w", err) + } + return nil } func (src arrayHeader) EncodeBinary(buf []byte) []byte { @@ -105,7 +95,11 @@ type untypedTextArray struct { Dimensions []ArrayDimension } -func parseUntypedTextArray(src string) (*untypedTextArray, error) { +func parseUntypedTextArray(src string, delimiter byte) (*untypedTextArray, error) { + if delimiter == 0 { + delimiter = ',' + } + dst := &untypedTextArray{ Elements: []string{}, Quoted: []bool{}, @@ -212,7 +206,7 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { implicitDimensions[currentDim].Length++ } currentDim++ - case ',': + case rune(delimiter): case '}': currentDim-- if currentDim < counterDim { @@ -220,7 +214,7 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { } default: buf.UnreadRune() - value, quoted, err := arrayParseValue(buf) + value, quoted, err := arrayParseValue(buf, delimiter) if err != nil { return nil, fmt.Errorf("invalid array value: %w", err) } @@ -264,7 +258,7 @@ func skipWhitespace(buf *bytes.Buffer) { } } -func arrayParseValue(buf *bytes.Buffer) (string, bool, error) { +func arrayParseValue(buf *bytes.Buffer, delimiter byte) (string, bool, error) { r, _, err := buf.ReadRune() if err != nil { return "", false, err @@ -283,7 +277,7 @@ func arrayParseValue(buf *bytes.Buffer) (string, bool, error) { } switch r { - case ',', '}': + case rune(delimiter), '}': buf.UnreadRune() return s.String(), false, nil } @@ -370,14 +364,12 @@ func quoteArrayElement(src string) string { return `"` + quoteArrayReplacer.Replace(src) + `"` } -func isSpace(ch byte) bool { - // see array_isspace: - // https://github.com/postgres/postgres/blob/master/src/backend/utils/adt/arrayfuncs.c - return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\v' || ch == '\f' -} +func quoteArrayElementIfNeeded(src string, delimiter byte) string { + if delimiter == 0 { + delimiter = ',' + } -func quoteArrayElementIfNeeded(src string) string { - if src == "" || (len(src) == 4 && strings.EqualFold(src, "null")) || isSpace(src[0]) || isSpace(src[len(src)-1]) || strings.ContainsAny(src, `{},"\`) { + if src == "" || (len(src) == 4 && strings.EqualFold(src, "null")) || strings.ContainsAny(src, " \t\n\r\v\f") || strings.ContainsAny(src, `{},"\`) || strings.ContainsRune(src, rune(delimiter)) { return quoteArrayElement(src) } return src diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go index ac01496ad1..1c9acc900b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "reflect" @@ -39,6 +38,16 @@ type ArraySetter interface { // ArrayCodec is a codec for any array type. type ArrayCodec struct { ElementType *Type + // Delimiter is the character PostgreSQL uses to separate array elements for this type. + // If unset, "," is used. + Delimiter byte +} + +func (c *ArrayCodec) delimiter() byte { + if c.Delimiter == 0 { + return ',' + } + return c.Delimiter } func (c *ArrayCodec) FormatSupported(format int16) bool { @@ -118,9 +127,10 @@ func (p *encodePlanArrayCodecText) Encode(value any, buf []byte) (newBuf []byte, var encodePlan EncodePlan var lastElemType reflect.Type inElemBuf := make([]byte, 0, 32) + delimiter := p.ac.delimiter() for i := range elementCount { if i > 0 { - buf = append(buf, ',') + buf = append(buf, delimiter) } for _, dec := range dimElemCounts { @@ -155,7 +165,7 @@ func (p *encodePlanArrayCodecText) Encode(value any, buf []byte) (newBuf []byte, if elemBuf == nil { buf = append(buf, `NULL`...) } else { - buf = append(buf, quoteArrayElementIfNeeded(string(elemBuf))...) + buf = append(buf, quoteArrayElementIfNeeded(string(elemBuf), delimiter)...) } for _, dec := range dimElemCounts { @@ -261,8 +271,9 @@ func (c *ArrayCodec) PlanScan(m *Map, oid uint32, format int16, target any) Scan } func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array ArraySetter) error { + r := pgio.NewReader(src) var arrayHeader arrayHeader - rp, err := arrayHeader.DecodeBinary(m, src) + err := arrayHeader.DecodeBinary(r) if err != nil { return err } @@ -271,8 +282,8 @@ func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array Arr // Each element carries at minimum a 4-byte length header, so elementCount cannot exceed the // remaining bytes / 4. This bounds the allocation in SetDimensions and the loop below against a // malicious server claiming huge dimensions in a small message. - if maxElements := len(src[rp:]) / 4; elementCount > maxElements { - return fmt.Errorf("array claims %d elements but only %d bytes remain", elementCount, len(src[rp:])) + if maxElements := r.Remaining() / 4; elementCount > maxElements { + return fmt.Errorf("array claims %d elements but only %d bytes remain", elementCount, r.Remaining()) } err = array.SetDimensions(arrayHeader.Dimensions) @@ -281,7 +292,7 @@ func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array Arr } if elementCount == 0 { - return nil + return r.Finish() } elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, BinaryFormatCode, array.ScanIndex(0)) @@ -290,19 +301,10 @@ func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array Arr } for i := range elementCount { - if len(src[rp:]) < 4 { - return fmt.Errorf("array body truncated at element %d", i) - } elem := array.ScanIndex(i) - elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - var elemSrc []byte - if elemLen >= 0 { - if len(src[rp:]) < elemLen { - return fmt.Errorf("array element %d length %d exceeds remaining %d bytes", i, elemLen, len(src[rp:])) - } - elemSrc = src[rp : rp+elemLen] - rp += elemLen + elemSrc, _ := r.Value() + if err := r.Err(); err != nil { + return fmt.Errorf("array element %d: %w", i, err) } err = elementScanPlan.Scan(elemSrc, elem) if err != nil { @@ -310,15 +312,21 @@ func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array Arr } } - return nil + return r.Finish() } func (c *ArrayCodec) decodeText(m *Map, arrayOID uint32, src []byte, array ArraySetter) error { - uta, err := parseUntypedTextArray(string(src)) + uta, err := parseUntypedTextArray(string(src), c.delimiter()) if err != nil { return err } + // The element loop below indexes the value sized by SetDimensions, so the + // dimensions and the parsed elements must agree. + if elementCount := cardinality(uta.Dimensions); elementCount != len(uta.Elements) { + return fmt.Errorf("array dimensions describe %d elements but %d were parsed", elementCount, len(uta.Elements)) + } + err = array.SetDimensions(uta.Dimensions) if err != nil { return err diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bits.go b/vendor/github.com/jackc/pgx/v5/pgtype/bits.go index 986fe2311a..052c157f4e 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bits.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bits.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "github.com/jackc/pgx/v5/internal/pgio" @@ -162,20 +161,31 @@ func (c BitsCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (an type scanPlanBinaryBitsToBitsScanner struct{} func (scanPlanBinaryBitsToBitsScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BitsScanner) + scanner := dst.(BitsScanner) if src == nil { return scanner.ScanBits(Bits{}) } - if len(src) < 4 { - return fmt.Errorf("invalid length for bit/varbit: %v", len(src)) + r := pgio.NewReader(src) + + bitLen := r.Int32() + if err := r.Err(); err != nil { + return fmt.Errorf("invalid length for bit/varbit: %w", err) + } + if bitLen < 0 { + return fmt.Errorf("invalid length for bit/varbit: bitLen=%d", bitLen) + } + + // Finish rejects trailing bytes, so together with the read below the data + // must be exactly the number of bytes bitLen calls for. + data := r.Bytes((int(bitLen) + 7) / 8) + if err := r.Finish(); err != nil { + return fmt.Errorf("invalid length for bit/varbit: bitLen=%d: %w", bitLen, err) } - bitLen := int32(binary.BigEndian.Uint32(src)) - rp := 4 - buf := make([]byte, len(src[rp:])) - copy(buf, src[rp:]) + buf := make([]byte, len(data)) + copy(buf, data) return scanner.ScanBits(Bits{Bytes: buf, Len: bitLen, Valid: true}) } @@ -183,7 +193,7 @@ func (scanPlanBinaryBitsToBitsScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToBitsScanner struct{} func (scanPlanTextAnyToBitsScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BitsScanner) + scanner := dst.(BitsScanner) if src == nil { return scanner.ScanBits(Bits{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bool.go b/vendor/github.com/jackc/pgx/v5/pgtype/bool.go index 077668e79d..986ae19487 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bool.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bool.go @@ -252,7 +252,7 @@ func (scanPlanBinaryBoolToBool) Scan(src []byte, dst any) error { return fmt.Errorf("invalid length for bool: %v", len(src)) } - p, ok := (dst).(*bool) + p, ok := dst.(*bool) if !ok { return ErrScanTargetTypeChanged } @@ -273,7 +273,7 @@ func (scanPlanTextAnyToBool) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan empty string into %T", dst) } - p, ok := (dst).(*bool) + p, ok := dst.(*bool) if !ok { return ErrScanTargetTypeChanged } @@ -291,7 +291,7 @@ func (scanPlanTextAnyToBool) Scan(src []byte, dst any) error { type scanPlanBinaryBoolToBoolScanner struct{} func (scanPlanBinaryBoolToBoolScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(BoolScanner) + s, ok := dst.(BoolScanner) if !ok { return ErrScanTargetTypeChanged } @@ -310,7 +310,7 @@ func (scanPlanBinaryBoolToBoolScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToBoolScanner struct{} func (scanPlanTextAnyToBoolScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(BoolScanner) + s, ok := dst.(BoolScanner) if !ok { return ErrScanTargetTypeChanged } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/box.go b/vendor/github.com/jackc/pgx/v5/pgtype/box.go index 8270aafd57..d05bef22a9 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/box.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/box.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -145,20 +144,22 @@ func (BoxCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryBoxToBoxScanner struct{} func (scanPlanBinaryBoxToBoxScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BoxScanner) + scanner := dst.(BoxScanner) if src == nil { return scanner.ScanBox(Box{}) } - if len(src) != 32 { - return fmt.Errorf("invalid length for Box: %v", len(src)) - } + r := pgio.NewReader(src) - x1 := binary.BigEndian.Uint64(src) - y1 := binary.BigEndian.Uint64(src[8:]) - x2 := binary.BigEndian.Uint64(src[16:]) - y2 := binary.BigEndian.Uint64(src[24:]) + x1 := r.Uint64() + y1 := r.Uint64() + x2 := r.Uint64() + y2 := r.Uint64() + + if err := r.Finish(); err != nil { + return fmt.Errorf("Box: %w", err) + } return scanner.ScanBox(Box{ P: [2]Vec2{ @@ -172,7 +173,7 @@ func (scanPlanBinaryBoxToBoxScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToBoxScanner struct{} func (scanPlanTextAnyToBoxScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BoxScanner) + scanner := dst.(BoxScanner) if src == nil { return scanner.ScanBox(Box{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go b/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go index a412763a9b..bfae662ab7 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go @@ -599,7 +599,7 @@ func (w *netipAddrWrapper) ScanNetipPrefix(v netip.Prefix) error { } func (w netipAddrWrapper) NetipPrefixValue() (netip.Prefix, error) { - addr := (netip.Addr)(w) + addr := netip.Addr(w) if !addr.IsValid() { return netip.Prefix{}, nil } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go b/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go index 6c4f0c5eaf..32c026efb1 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go @@ -185,7 +185,7 @@ func (scanPlanBinaryBytesToBytes) Scan(src []byte, dst any) error { type scanPlanBinaryBytesToBytesScanner struct{} func (scanPlanBinaryBytesToBytesScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BytesScanner) + scanner := dst.(BytesScanner) return scanner.ScanBytes(src) } @@ -210,7 +210,7 @@ func (scanPlanTextByteaToBytes) Scan(src []byte, dst any) error { type scanPlanTextByteaToBytesScanner struct{} func (scanPlanTextByteaToBytesScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BytesScanner) + scanner := dst.(BytesScanner) buf, err := decodeHexBytea(src) if err != nil { return err diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/circle.go b/vendor/github.com/jackc/pgx/v5/pgtype/circle.go index ea1d629958..c72c2fe07b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/circle.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/circle.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -161,19 +160,21 @@ func (c CircleCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) ( type scanPlanBinaryCircleToCircleScanner struct{} func (scanPlanBinaryCircleToCircleScanner) Scan(src []byte, dst any) error { - scanner := (dst).(CircleScanner) + scanner := dst.(CircleScanner) if src == nil { return scanner.ScanCircle(Circle{}) } - if len(src) != 24 { - return fmt.Errorf("invalid length for Circle: %v", len(src)) - } + rd := pgio.NewReader(src) - x := binary.BigEndian.Uint64(src) - y := binary.BigEndian.Uint64(src[8:]) - r := binary.BigEndian.Uint64(src[16:]) + x := rd.Uint64() + y := rd.Uint64() + r := rd.Uint64() + + if err := rd.Finish(); err != nil { + return fmt.Errorf("Circle: %w", err) + } return scanner.ScanCircle(Circle{ P: Vec2{math.Float64frombits(x), math.Float64frombits(y)}, @@ -185,7 +186,7 @@ func (scanPlanBinaryCircleToCircleScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToCircleScanner struct{} func (scanPlanTextAnyToCircleScanner) Scan(src []byte, dst any) error { - scanner := (dst).(CircleScanner) + scanner := dst.(CircleScanner) if src == nil { return scanner.ScanCircle(Circle{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/composite.go b/vendor/github.com/jackc/pgx/v5/pgtype/composite.go index 7f96ab4902..ae1b6eb0b2 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/composite.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/composite.go @@ -130,7 +130,7 @@ type scanPlanBinaryCompositeToCompositeIndexScanner struct { } func (plan *scanPlanBinaryCompositeToCompositeIndexScanner) Scan(src []byte, target any) error { - targetScanner := (target).(CompositeIndexScanner) + targetScanner := target.(CompositeIndexScanner) if src == nil { return targetScanner.ScanNull() @@ -139,14 +139,17 @@ func (plan *scanPlanBinaryCompositeToCompositeIndexScanner) Scan(src []byte, tar scanner := NewCompositeBinaryScanner(plan.m, src) for i, field := range plan.cc.Fields { if scanner.Next() { - fieldTarget := targetScanner.ScanIndex(i) + fieldTarget, err := compositeFieldTarget(targetScanner, i) + if err != nil { + return err + } if fieldTarget != nil { fieldPlan := plan.m.PlanScan(field.Type.OID, BinaryFormatCode, fieldTarget) if fieldPlan == nil { return fmt.Errorf("unable to encode %v into OID %d in binary format", field, field.Type.OID) } - err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) + err = fieldPlan.Scan(scanner.Bytes(), fieldTarget) if err != nil { return err } @@ -169,7 +172,7 @@ type scanPlanTextCompositeToCompositeIndexScanner struct { } func (plan *scanPlanTextCompositeToCompositeIndexScanner) Scan(src []byte, target any) error { - targetScanner := (target).(CompositeIndexScanner) + targetScanner := target.(CompositeIndexScanner) if src == nil { return targetScanner.ScanNull() @@ -277,9 +280,8 @@ func (c *CompositeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byt } type CompositeBinaryScanner struct { - m *Map - rp int - src []byte + m *Map + r *pgio.Reader fieldCount int32 fieldBytes []byte @@ -289,19 +291,18 @@ type CompositeBinaryScanner struct { // NewCompositeBinaryScanner a scanner over a binary encoded composite value. func NewCompositeBinaryScanner(m *Map, src []byte) *CompositeBinaryScanner { - rp := 0 - if len(src[rp:]) < 4 { - return &CompositeBinaryScanner{err: fmt.Errorf("Record incomplete %v", src)} - } + r := pgio.NewReader(src) - fieldCount := int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 + // Each field requires at least 8 bytes: 4 for the OID and 4 for the length prefix. + fieldCount := r.Count(8) + if err := r.Err(); err != nil { + return &CompositeBinaryScanner{err: fmt.Errorf("Record incomplete: %w", err)} + } return &CompositeBinaryScanner{ m: m, - rp: rp, - src: src, - fieldCount: fieldCount, + r: r, + fieldCount: int32(fieldCount), } } @@ -312,30 +313,16 @@ func (cfs *CompositeBinaryScanner) Next() bool { return false } - if cfs.rp == len(cfs.src) { + if cfs.r.Remaining() == 0 { return false } - if len(cfs.src[cfs.rp:]) < 8 { - cfs.err = fmt.Errorf("Record incomplete %v", cfs.src) + cfs.fieldOID = cfs.r.Uint32() + cfs.fieldBytes, _ = cfs.r.Value() + if err := cfs.r.Err(); err != nil { + cfs.err = fmt.Errorf("Record incomplete: %w", err) return false } - cfs.fieldOID = binary.BigEndian.Uint32(cfs.src[cfs.rp:]) - cfs.rp += 4 - - fieldLen := int(int32(binary.BigEndian.Uint32(cfs.src[cfs.rp:]))) - cfs.rp += 4 - - if fieldLen >= 0 { - if len(cfs.src[cfs.rp:]) < fieldLen { - cfs.err = fmt.Errorf("Record incomplete rp=%d src=%v", cfs.rp, cfs.src) - return false - } - cfs.fieldBytes = cfs.src[cfs.rp : cfs.rp+fieldLen] - cfs.rp += fieldLen - } else { - cfs.fieldBytes = nil - } return true } @@ -344,6 +331,17 @@ func (cfs *CompositeBinaryScanner) FieldCount() int { return int(cfs.fieldCount) } +// compositeFieldTarget returns the scan target for field i. CompositeFields is +// a slice, so indexing past its end would panic. A source with more fields than +// the destination is a mismatch that must be reported as an error. +func compositeFieldTarget(targetScanner CompositeIndexScanner, i int) (any, error) { + if cf, ok := targetScanner.(CompositeFields); ok && i >= len(cf) { + return nil, fmt.Errorf("cannot scan composite field %d into CompositeFields of length %d", i, len(cf)) + } + + return targetScanner.ScanIndex(i), nil +} + // Bytes returns the bytes of the field most recently read by Scan(). func (cfs *CompositeBinaryScanner) Bytes() []byte { return cfs.fieldBytes @@ -396,7 +394,7 @@ func (cfs *CompositeTextScanner) Next() bool { return false } - if cfs.rp == len(cfs.src) { + if cfs.rp >= len(cfs.src) { return false } @@ -410,12 +408,18 @@ func (cfs *CompositeTextScanner) Next() bool { cfs.fieldBytes = make([]byte, 0, 16) quotedValue: for { + // A quote or escape may have consumed the final ')', leaving an + // unterminated quoted field. + if cfs.rp >= len(cfs.src) { + cfs.err = fmt.Errorf("composite text format unterminated quoted field") + return false + } ch := cfs.src[cfs.rp] switch ch { case '"': cfs.rp++ - if cfs.src[cfs.rp] == '"' { + if cfs.rp < len(cfs.src) && cfs.src[cfs.rp] == '"' { cfs.fieldBytes = append(cfs.fieldBytes, '"') cfs.rp++ } else { @@ -423,6 +427,10 @@ func (cfs *CompositeTextScanner) Next() bool { } case '\\': cfs.rp++ + if cfs.rp >= len(cfs.src) { + cfs.err = fmt.Errorf("composite text format unterminated quoted field") + return false + } cfs.fieldBytes = append(cfs.fieldBytes, cfs.src[cfs.rp]) cfs.rp++ default: diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/date.go b/vendor/github.com/jackc/pgx/v5/pgtype/date.go index 305d83c31a..82c5e74958 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/date.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/date.go @@ -2,12 +2,11 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" - "strconv" "time" + "github.com/jackc/pgx/v5/internal/pgdatetime" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -189,33 +188,7 @@ func (encodePlanDateCodecText) Encode(value any, buf []byte) (newBuf []byte, err switch date.InfinityModifier { case Finite: - // Year 0000 is 1 BC - bc := false - year := date.Time.Year() - if year <= 0 { - year = -year + 1 - bc = true - } - - yearBytes := strconv.AppendInt(make([]byte, 0, 6), int64(year), 10) - for i := len(yearBytes); i < 4; i++ { - buf = append(buf, '0') - } - buf = append(buf, yearBytes...) - buf = append(buf, '-') - if date.Time.Month() < 10 { - buf = append(buf, '0') - } - buf = strconv.AppendInt(buf, int64(date.Time.Month()), 10) - buf = append(buf, '-') - if date.Time.Day() < 10 { - buf = append(buf, '0') - } - buf = strconv.AppendInt(buf, int64(date.Time.Day()), 10) - - if bc { - buf = append(buf, " BC"...) - } + buf = pgdatetime.AppendDate(buf, date.Time) case Infinity: buf = append(buf, "infinity"...) case NegativeInfinity: @@ -243,17 +216,18 @@ func (DateCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryDateToDateScanner struct{} func (scanPlanBinaryDateToDateScanner) Scan(src []byte, dst any) error { - scanner := (dst).(DateScanner) + scanner := dst.(DateScanner) if src == nil { return scanner.ScanDate(Date{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for date: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("date: %w", err) } - dayOffset := int32(binary.BigEndian.Uint32(src)) + dayOffset := int32(raw) switch dayOffset { case infinityDayOffset: @@ -262,6 +236,10 @@ func (scanPlanBinaryDateToDateScanner) Scan(src []byte, dst any) error { return scanner.ScanDate(Date{InfinityModifier: -Infinity, Valid: true}) default: t := time.Date(2000, 1, int(1+dayOffset), 0, 0, 0, 0, time.UTC) + if t.Before(minDateTime) || !t.Before(endDate) { + return fmt.Errorf("date %d days from 2000-01-01 is out of range", dayOffset) + } + return scanner.ScanDate(Date{Time: t, Valid: true}) } } @@ -269,112 +247,33 @@ func (scanPlanBinaryDateToDateScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToDateScanner struct{} func (scanPlanTextAnyToDateScanner) Scan(src []byte, dst any) error { - scanner := (dst).(DateScanner) + scanner := dst.(DateScanner) if src == nil { return scanner.ScanDate(Date{}) } - // Check infinity cases first - if len(src) == 8 && string(src) == "infinity" { - return scanner.ScanDate(Date{InfinityModifier: Infinity, Valid: true}) - } - if len(src) == 9 && string(src) == "-infinity" { - return scanner.ScanDate(Date{InfinityModifier: -Infinity, Valid: true}) - } - - // Format: YYYY-MM-DD or YYYY...-MM-DD BC - // Minimum: 10 chars (2000-01-01), with BC: 13 chars - if len(src) < 10 { - return fmt.Errorf("invalid date format") - } - - // Check for BC suffix - bc := false - datePart := src - if len(src) >= 13 && string(src[len(src)-3:]) == " BC" { - bc = true - datePart = src[:len(src)-3] - } - - // Find year-month separator (first dash after at least 4 digits) - yearEnd := -1 - for i := 4; i < len(datePart); i++ { - if datePart[i] == '-' { - yearEnd = i - break - } - if datePart[i] < '0' || datePart[i] > '9' { - return fmt.Errorf("invalid date format") - } - } - if yearEnd == -1 || yearEnd+6 > len(datePart) { - return fmt.Errorf("invalid date format") - } - - // Validate: -MM-DD structure after year - if datePart[yearEnd+3] != '-' { - return fmt.Errorf("invalid date format") - } - - // Parse year - year, err := parseDigits(datePart[:yearEnd]) + dt, err := parseTextDateTime(src) if err != nil { - return fmt.Errorf("invalid date format") - } - - // Parse month (2 digits) - month, err := parse2Digits(datePart[yearEnd+1 : yearEnd+3]) - if err != nil { - return fmt.Errorf("invalid date format") + return err } - // Parse day (2 digits) - day, err := parse2Digits(datePart[yearEnd+4 : yearEnd+6]) - if err != nil { - return fmt.Errorf("invalid date format") + if dt.infinity != Finite { + return scanner.ScanDate(Date{InfinityModifier: dt.infinity, Valid: true}) } - // Ensure nothing extra after day - if yearEnd+6 != len(datePart) { - return fmt.Errorf("invalid date format") + if dt.hasTime { + return badDateTime(src) } - if bc { - year = -year + 1 + t, err := dt.toTime(src, "date", endDate) + if err != nil { + return err } - t := time.Date(int(year), time.Month(month), int(day), 0, 0, 0, 0, time.UTC) return scanner.ScanDate(Date{Time: t, Valid: true}) } -// parse2Digits parses exactly 2 ASCII digits. -func parse2Digits(b []byte) (int64, error) { - if len(b) != 2 { - return 0, fmt.Errorf("expected 2 digits") - } - d1, d2 := b[0], b[1] - if d1 < '0' || d1 > '9' || d2 < '0' || d2 > '9' { - return 0, fmt.Errorf("expected digits") - } - return int64(d1-'0')*10 + int64(d2-'0'), nil -} - -// parseDigits parses a sequence of ASCII digits. -func parseDigits(b []byte) (int64, error) { - if len(b) == 0 { - return 0, fmt.Errorf("empty") - } - var n int64 - for _, c := range b { - if c < '0' || c > '9' { - return 0, fmt.Errorf("non-digit") - } - n = n*10 + int64(c-'0') - } - return n, nil -} - func (c DateCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { if src == nil { return nil, nil diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/datetime_text.go b/vendor/github.com/jackc/pgx/v5/pgtype/datetime_text.go new file mode 100644 index 0000000000..6a7ff76580 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/datetime_text.go @@ -0,0 +1,378 @@ +package pgtype + +import ( + "fmt" + "math" + "strconv" + "time" +) + +// PostgreSQL's ISO date/time output grammar, from EncodeDateTime, EncodeTimezone and +// AppendSeconds in src/backend/utils/adt/datetime.c (the USE_ISO_DATES branch): +// +// value = "infinity" / "-infinity" / stamp +// stamp = date [ SP time [ offset ] ] [ " BC" ] +// date = year "-" 2DIGIT "-" 2DIGIT +// year = 4*DIGIT ; zero-padded to exactly 4, never wider than necessary +// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT [ "." 1*6DIGIT ] +// offset = ("+" / "-") 2*DIGIT [ ":" 2DIGIT [ ":" 2DIGIT ] ] +// +// " BC" is always last, after any offset. Fractional seconds are omitted entirely when +// zero and never carry trailing zeros. This is only the shape the server emits under the +// default ISO DateStyle; the other styles are not supported. +// +// Writing the format is the other half of this and lives in internal/pgdatetime, which the +// simple protocol's query sanitizer shares. + +const ( + secondsPerHour = 60 * 60 + + // maxDateTimeYearDigits is the width of the largest year PostgreSQL can represent, + // which is date's 5874897. Capping the digit count keeps the accumulated year inside + // an int on 32 bit platforms as well as 64 bit ones. + maxDateTimeYearDigits = 7 +) + +// PostgreSQL's valid ranges, from src/include/datatype/timestamp.h. They differ by type: +// date runs to 5874897 AD (JULIAN_MAXYEAR) while timestamp stops at 294276 AD +// (END_TIMESTAMP). Both share a lower bound of 4714-11-24 BC. +var ( + minDateTime = time.Date(-4713, 11, 24, 0, 0, 0, 0, time.UTC) + endDate = time.Date(5874898, 1, 1, 0, 0, 0, 0, time.UTC) + endTimestamp = time.Date(294277, 1, 1, 0, 0, 0, 0, time.UTC) +) + +// textDateTime is a date/time value parsed from PostgreSQL's text format. It holds the +// fields as written on the wire rather than a time.Time so that each codec can apply its +// own range limits and time zone rules. +type textDateTime struct { + // year uses astronomical numbering: 1 BC is 0, 2 BC is -1. + year int + month int + day int + + hour int + min int + sec int + // nsec is always a multiple of 1000. Fractional seconds are rounded to microseconds + // the way the server rounds them. + nsec int + + // offset is seconds east of UTC and is only meaningful when hasOffset is true. + offset int + + hasTime bool + hasOffset bool + + infinity InfinityModifier +} + +// in builds the parsed fields as a time.Time in loc. The fields are a wall clock reading, +// so this reinterprets them in loc rather than converting an instant into it. +func (dt textDateTime) in(loc *time.Location) time.Time { + return time.Date(dt.year, time.Month(dt.month), dt.day, dt.hour, dt.min, dt.sec, dt.nsec, loc) +} + +// toTime resolves the parsed fields to the instant they name, applying any time zone +// offset, and rejects anything outside the range of the type named by name. The upper +// limit differs by type -- date reaches 5874897 AD while timestamp stops at 294276 AD -- +// so end is supplied by the caller and is exclusive. src is only used to build the error. +func (dt textDateTime) toTime(src []byte, name string, end time.Time) (time.Time, error) { + t := dt.in(time.UTC).Add(-time.Duration(dt.offset) * time.Second) + if t.Before(minDateTime) || !t.Before(end) { + return time.Time{}, fmt.Errorf("%s %q is out of range", name, src) + } + + return t, nil +} + +// parseTextDateTime parses the grammar above. It validates the grammar and the calendar +// but applies no range limits, because PostgreSQL's limits differ by type: date reaches +// 5874897 AD while timestamp stops at 294276 AD. +func parseTextDateTime(src []byte) (textDateTime, error) { + var dt textDateTime + + switch string(src) { + case "infinity": + dt.infinity = Infinity + return dt, nil + case "-infinity": + dt.infinity = NegativeInfinity + return dt, nil + } + + s := src + bc := false + if len(s) > 3 && s[len(s)-3] == ' ' && s[len(s)-2] == 'B' && s[len(s)-1] == 'C' { + s = s[:len(s)-3] + bc = true + } + + i := 0 + + // Year. Variable width, so it runs to the first non-digit rather than a fixed offset. + yearStart := i + for i < len(s) && isDigit(s[i]) { + if i-yearStart >= maxDateTimeYearDigits { + return dt, badDateTime(src) + } + dt.year = dt.year*10 + int(s[i]-'0') + i++ + } + if i-yearStart < 4 || dt.year < 1 { + return dt, badDateTime(src) + } + + var ok bool + if i, ok = expect(s, i, '-'); !ok { + return dt, badDateTime(src) + } + if dt.month, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + if i, ok = expect(s, i, '-'); !ok { + return dt, badDateTime(src) + } + if dt.day, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + + if bc { + dt.year = 1 - dt.year + } + + if dt.month < 1 || dt.month > 12 || dt.day < 1 || dt.day > daysInMonth(dt.year, dt.month) { + return dt, badDateTime(src) + } + + // Time of day. + var carrySecond bool + if i < len(s) && s[i] == ' ' { + i++ + dt.hasTime = true + + if dt.hour, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + if i, ok = expect(s, i, ':'); !ok { + return dt, badDateTime(src) + } + if dt.min, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + if i, ok = expect(s, i, ':'); !ok { + return dt, badDateTime(src) + } + if dt.sec, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + if dt.hour > 23 || dt.min > 59 || dt.sec > 59 { + return dt, badDateTime(src) + } + + if i < len(s) && s[i] == '.' { + i++ + fracStart := i + for i < len(s) && isDigit(s[i]) { + i++ + } + if i == fracStart { + return dt, badDateTime(src) + } + + usec, err := roundFractionToMicroseconds(s[fracStart:i]) + if err != nil { + return dt, badDateTime(src) + } + if usec == microsecondsPerSecond { + usec = 0 + carrySecond = true + } + dt.nsec = usec * 1000 + } + + // Time zone displacement. + if i < len(s) { + switch s[i] { + case 'Z': + // Not something the server emits, but pgx's own text encoder writes it. + i++ + dt.hasOffset = true + case '+', '-': + if dt.offset, i, ok = parseOffset(s, i); !ok { + return dt, badDateTime(src) + } + dt.hasOffset = true + } + } + } + + if i != len(s) { + return dt, badDateTime(src) + } + + if carrySecond { + dt.addSecond() + } + + return dt, nil +} + +// addSecond advances by one second, carrying through to the year. It is only reached when +// rounding the fractional part rolls over, and it assumes the fields are already valid. +func (dt *textDateTime) addSecond() { + dt.sec++ + if dt.sec < 60 { + return + } + dt.sec = 0 + + dt.min++ + if dt.min < 60 { + return + } + dt.min = 0 + + dt.hour++ + if dt.hour < 24 { + return + } + dt.hour = 0 + + dt.day++ + if dt.day <= daysInMonth(dt.year, dt.month) { + return + } + dt.day = 1 + + dt.month++ + if dt.month <= 12 { + return + } + dt.month = 1 + + // Astronomical numbering has a year 0, so this needs no adjustment for the AD/BC + // boundary. + dt.year++ +} + +// roundFractionToMicroseconds converts fractional second digits to microseconds. The +// result may be microsecondsPerSecond, which the caller must carry. +func roundFractionToMicroseconds(digits []byte) (int, error) { + if len(digits) <= 6 { + usec := 0 + for _, c := range digits { + usec = usec*10 + int(c-'0') + } + for i := len(digits); i < 6; i++ { + usec *= 10 + } + return usec, nil + } + + // PostgreSQL's ParseFractionalSecond reads the fraction with strtod and rounds with + // rint, which is round-half-to-even on a binary double. Mirror that arithmetic + // exactly rather than rounding the decimal digits, so that values the server rounds + // down are not rounded up here: the server turns .0000005 into 0, while rounding the + // digits half away from zero would produce 1 microsecond. + // + // The server never emits more than six digits, so this path only handles input from + // other sources. + f, err := strconv.ParseFloat("0."+string(digits), 64) + if err != nil { + return 0, err + } + + return int(math.RoundToEven(f * 1e6)), nil +} + +func parseOffset(s []byte, i int) (offset, next int, ok bool) { + neg := s[i] == '-' + i++ + + var hour, min, sec int + if hour, i, ok = parse2Digits(s, i); !ok { + return 0, i, false + } + // PostgreSQL's MAX_TZDISP_HOUR limits numeric input, not output from named + // or POSIX time zones. These can emit offsets with more than two hour digits. + // Bound by the server's int32 seconds representation instead. + for i < len(s) && isDigit(s[i]) { + hour = hour*10 + int(s[i]-'0') + i++ + if hour > math.MaxInt32/secondsPerHour { + return 0, i, false + } + } + if i, ok = expect(s, i, ':'); ok { + if min, i, ok = parse2Digits(s, i); !ok { + return 0, i, false + } + if i, ok = expect(s, i, ':'); ok { + if sec, i, ok = parse2Digits(s, i); !ok { + return 0, i, false + } + } + } + + if min > 59 || sec > 59 { + return 0, i, false + } + + seconds := int64(hour)*secondsPerHour + int64(min*60+sec) + if neg { + seconds = -seconds + } + if seconds < math.MinInt32 || seconds > math.MaxInt32 { + return 0, i, false + } + + return int(seconds), i, true +} + +func parse2Digits(s []byte, i int) (v, next int, ok bool) { + if i+1 >= len(s) || !isDigit(s[i]) || !isDigit(s[i+1]) { + return 0, i, false + } + return int(s[i]-'0')*10 + int(s[i+1]-'0'), i + 2, true +} + +func expect(s []byte, i int, c byte) (next int, ok bool) { + if i >= len(s) || s[i] != c { + return i, false + } + return i + 1, true +} + +func isDigit(c byte) bool { return c >= '0' && c <= '9' } + +func badDateTime(src []byte) error { + const maxLen = 64 + s := string(src) + if len(s) > maxLen { + s = s[:maxLen] + "..." + } + return fmt.Errorf("invalid PostgreSQL date/time value %q", s) +} + +// isLeapYear reports whether year, in astronomical numbering, is a leap year in the +// proleptic Gregorian calendar. Go's % keeps the sign of the dividend, so the usual +// divisibility tests hold for years at or below zero. +func isLeapYear(year int) bool { + return year%4 == 0 && (year%100 != 0 || year%400 == 0) +} + +func daysInMonth(year, month int) int { + switch month { + case 1, 3, 5, 7, 8, 10, 12: + return 31 + case 4, 6, 9, 11: + return 30 + case 2: + if isLeapYear(year) { + return 29 + } + return 28 + } + return 0 +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go index 5e787c1e29..f4173ad734 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go @@ -88,7 +88,7 @@ func (plan *scanPlanTextAnyToEnumString) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - p := (dst).(*string) + p := dst.(*string) *p = plan.codec.lookupAndCacheString(src) return nil @@ -99,7 +99,7 @@ type scanPlanTextAnyToEnumTextScanner struct { } func (plan *scanPlanTextAnyToEnumTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/float4.go b/vendor/github.com/jackc/pgx/v5/pgtype/float4.go index a43553f672..8c3c1bfb5b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/float4.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/float4.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" "math" @@ -208,12 +207,13 @@ func (scanPlanBinaryFloat4ToFloat32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("float4: %w", err) } - n := int32(binary.BigEndian.Uint32(src)) - f := (dst).(*float32) + n := int32(raw) + f := dst.(*float32) *f = math.Float32frombits(uint32(n)) return nil @@ -222,34 +222,36 @@ func (scanPlanBinaryFloat4ToFloat32) Scan(src []byte, dst any) error { type scanPlanBinaryFloat4ToFloat64Scanner struct{} func (scanPlanBinaryFloat4ToFloat64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Float64Scanner) + s := dst.(Float64Scanner) if src == nil { return s.ScanFloat64(Float8{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("float4: %w", err) } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) return s.ScanFloat64(Float8{Float64: float64(math.Float32frombits(uint32(n))), Valid: true}) } type scanPlanBinaryFloat4ToInt64Scanner struct{} func (scanPlanBinaryFloat4ToInt64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Int64Scanner) + s := dst.(Int64Scanner) if src == nil { return s.ScanInt64(Int8{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("float4: %w", err) } - ui32 := int32(binary.BigEndian.Uint32(src)) + ui32 := int32(raw) f32 := math.Float32frombits(uint32(ui32)) i64 := int64(f32) if f32 != float32(i64) { @@ -262,17 +264,18 @@ func (scanPlanBinaryFloat4ToInt64Scanner) Scan(src []byte, dst any) error { type scanPlanBinaryFloat4ToTextScanner struct{} func (scanPlanBinaryFloat4ToTextScanner) Scan(src []byte, dst any) error { - s := (dst).(TextScanner) + s := dst.(TextScanner) if src == nil { return s.ScanText(Text{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("float4: %w", err) } - ui32 := int32(binary.BigEndian.Uint32(src)) + ui32 := int32(raw) f32 := math.Float32frombits(uint32(ui32)) return s.ScanText(Text{String: strconv.FormatFloat(float64(f32), 'f', -1, 32), Valid: true}) @@ -290,7 +293,7 @@ func (scanPlanTextAnyToFloat32) Scan(src []byte, dst any) error { return err } - f := (dst).(*float32) + f := dst.(*float32) *f = float32(n) return nil diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/float8.go b/vendor/github.com/jackc/pgx/v5/pgtype/float8.go index 6234231d7a..ec55bd801c 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/float8.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/float8.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" "math" @@ -246,12 +245,13 @@ func (scanPlanBinaryFloat8ToFloat64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("float8: %w", err) } - n := int64(binary.BigEndian.Uint64(src)) - f := (dst).(*float64) + n := int64(raw) + f := dst.(*float64) *f = math.Float64frombits(uint64(n)) return nil @@ -260,34 +260,36 @@ func (scanPlanBinaryFloat8ToFloat64) Scan(src []byte, dst any) error { type scanPlanBinaryFloat8ToFloat64Scanner struct{} func (scanPlanBinaryFloat8ToFloat64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Float64Scanner) + s := dst.(Float64Scanner) if src == nil { return s.ScanFloat64(Float8{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("float8: %w", err) } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) return s.ScanFloat64(Float8{Float64: math.Float64frombits(uint64(n)), Valid: true}) } type scanPlanBinaryFloat8ToInt64Scanner struct{} func (scanPlanBinaryFloat8ToInt64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Int64Scanner) + s := dst.(Int64Scanner) if src == nil { return s.ScanInt64(Int8{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("float8: %w", err) } - ui64 := int64(binary.BigEndian.Uint64(src)) + ui64 := int64(raw) f64 := math.Float64frombits(uint64(ui64)) i64 := int64(f64) if f64 != float64(i64) { @@ -300,17 +302,18 @@ func (scanPlanBinaryFloat8ToInt64Scanner) Scan(src []byte, dst any) error { type scanPlanBinaryFloat8ToTextScanner struct{} func (scanPlanBinaryFloat8ToTextScanner) Scan(src []byte, dst any) error { - s := (dst).(TextScanner) + s := dst.(TextScanner) if src == nil { return s.ScanText(Text{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("float8: %w", err) } - ui64 := int64(binary.BigEndian.Uint64(src)) + ui64 := int64(raw) f64 := math.Float64frombits(uint64(ui64)) return s.ScanText(Text{String: strconv.FormatFloat(f64, 'f', -1, 64), Valid: true}) @@ -328,7 +331,7 @@ func (scanPlanTextAnyToFloat64) Scan(src []byte, dst any) error { return err } - f := (dst).(*float64) + f := dst.(*float64) *f = n return nil @@ -337,7 +340,7 @@ func (scanPlanTextAnyToFloat64) Scan(src []byte, dst any) error { type scanPlanTextAnyToFloat64Scanner struct{} func (scanPlanTextAnyToFloat64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Float64Scanner) + s := dst.(Float64Scanner) if src == nil { return s.ScanFloat64(Float8{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go b/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go index 4a2bb0a5bf..58137686df 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "errors" "fmt" "strings" @@ -180,29 +179,19 @@ func (HstoreCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPl type scanPlanBinaryHstoreToHstoreScanner struct{} func (scanPlanBinaryHstoreToHstoreScanner) Scan(src []byte, dst any) error { - scanner := (dst).(HstoreScanner) + scanner := dst.(HstoreScanner) if src == nil { return scanner.ScanHstore(Hstore(nil)) } - rp := 0 + r := pgio.NewReader(src) - const uint32Len = 4 - if len(src[rp:]) < uint32Len { - return fmt.Errorf("hstore incomplete %v", src) - } - pairCount := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += uint32Len - - if pairCount < 0 { - return fmt.Errorf("hstore invalid pair count: %d", pairCount) - } - // Each pair carries at minimum two int32 length headers (key, value), so pairCount cannot - // exceed the remaining bytes / 8. This bounds the up-front make() against a malicious server - // claiming a huge pair count in a small message. - if maxPairs := len(src[rp:]) / (2 * uint32Len); pairCount > maxPairs { - return fmt.Errorf("hstore invalid pair count %d for %d remaining bytes", pairCount, len(src[rp:])) + // Each pair carries at minimum two int32 length headers (key, value). This bounds the + // up-front make() against a malicious server claiming a huge pair count in a small message. + pairCount := r.Count(8) + if err := r.Err(); err != nil { + return fmt.Errorf("hstore: %w", err) } hstore := make(Hstore, pairCount) @@ -210,47 +199,34 @@ func (scanPlanBinaryHstoreToHstoreScanner) Scan(src []byte, dst any) error { valueStrings := make([]string, pairCount) for i := range pairCount { - if len(src[rp:]) < uint32Len { - return fmt.Errorf("hstore incomplete %v", src) - } - keyLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += uint32Len - - if keyLen < 0 { - return fmt.Errorf("hstore invalid key length: %d", keyLen) - } - if len(src[rp:]) < keyLen { - return fmt.Errorf("hstore incomplete %v", src) + keyBytes, keyNull := r.Value() + valueBytes, valueNull := r.Value() + if err := r.Err(); err != nil { + return fmt.Errorf("hstore pair %d: %w", i, err) } - key := string(src[rp : rp+keyLen]) - rp += keyLen - - if len(src[rp:]) < uint32Len { - return fmt.Errorf("hstore incomplete %v", src) + if keyNull { + return fmt.Errorf("hstore pair %d: key cannot be NULL", i) } - valueLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - if valueLen >= 0 { - if len(src[rp:]) < valueLen { - return fmt.Errorf("hstore incomplete %v", src) - } - valueStrings[i] = string(src[rp : rp+valueLen]) - rp += valueLen - - hstore[key] = &valueStrings[i] - } else { + key := string(keyBytes) + if valueNull { hstore[key] = nil + } else { + valueStrings[i] = string(valueBytes) + hstore[key] = &valueStrings[i] } } + if err := r.Finish(); err != nil { + return fmt.Errorf("hstore: %w", err) + } return scanner.ScanHstore(hstore) } type scanPlanTextAnyToHstoreScanner struct{} func (s scanPlanTextAnyToHstoreScanner) Scan(src []byte, dst any) error { - scanner := (dst).(HstoreScanner) + scanner := dst.(HstoreScanner) if src == nil { return scanner.ScanHstore(Hstore(nil)) @@ -455,8 +431,13 @@ func parseHstore(s string) (Hstore, error) { p := newHSP(s) // This is an over-estimate of the number of key/value pairs. Use '>' because I am guessing it - // is less likely to occur in keys/values than '=' or ','. + // is less likely to occur in keys/values than '=' or ','. Clamp so an unvalidated + // separator count cannot pre-size a huge map from garbage input. + const maxHstorePairsEstimate = 1024 numPairsEstimate := strings.Count(s, ">") + if numPairsEstimate > maxHstorePairsEstimate { + numPairsEstimate = maxHstorePairsEstimate + } // makes one allocation of strings for the entire Hstore, rather than one allocation per value. valueStrings := make([]string, 0, numPairsEstimate) result := make(Hstore, numPairsEstimate) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/inet.go b/vendor/github.com/jackc/pgx/v5/pgtype/inet.go index 2592a5b5b3..23155fe676 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/inet.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/inet.go @@ -146,7 +146,7 @@ func (c InetCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (an type scanPlanBinaryInetToNetipPrefixScanner struct{} func (scanPlanBinaryInetToNetipPrefixScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NetipPrefixScanner) + scanner := dst.(NetipPrefixScanner) if src == nil { return scanner.ScanNetipPrefix(netip.Prefix{}) @@ -172,7 +172,7 @@ func (scanPlanBinaryInetToNetipPrefixScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToNetipPrefixScanner struct{} func (scanPlanTextAnyToNetipPrefixScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NetipPrefixScanner) + scanner := dst.(NetipPrefixScanner) if src == nil { return scanner.ScanNetipPrefix(netip.Prefix{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int.go b/vendor/github.com/jackc/pgx/v5/pgtype/int.go index 95032e5a27..ddcfe54763 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/int.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/int.go @@ -4,7 +4,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" "math" @@ -303,8 +302,9 @@ func (scanPlanBinaryInt2ToInt8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int8) @@ -312,7 +312,7 @@ func (scanPlanBinaryInt2ToInt8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < math.MinInt8 { return fmt.Errorf("%d is less than minimum value for int8", n) } else if n > math.MaxInt8 { @@ -331,8 +331,9 @@ func (scanPlanBinaryInt2ToUint8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint8) @@ -340,7 +341,7 @@ func (scanPlanBinaryInt2ToUint8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint8", n) } @@ -361,8 +362,9 @@ func (scanPlanBinaryInt2ToInt16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int16) @@ -370,7 +372,7 @@ func (scanPlanBinaryInt2ToInt16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int16(binary.BigEndian.Uint16(src)) + *p = int16(raw) return nil } @@ -382,8 +384,9 @@ func (scanPlanBinaryInt2ToUint16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint16) @@ -391,7 +394,7 @@ func (scanPlanBinaryInt2ToUint16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint16", n) } @@ -408,8 +411,9 @@ func (scanPlanBinaryInt2ToInt32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int32) @@ -417,7 +421,7 @@ func (scanPlanBinaryInt2ToInt32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int32(int16(binary.BigEndian.Uint16(src))) + *p = int32(int16(raw)) return nil } @@ -429,8 +433,9 @@ func (scanPlanBinaryInt2ToUint32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint32) @@ -438,7 +443,7 @@ func (scanPlanBinaryInt2ToUint32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint32", n) } @@ -455,8 +460,9 @@ func (scanPlanBinaryInt2ToInt64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int64) @@ -464,7 +470,7 @@ func (scanPlanBinaryInt2ToInt64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int64(int16(binary.BigEndian.Uint16(src))) + *p = int64(int16(raw)) return nil } @@ -476,8 +482,9 @@ func (scanPlanBinaryInt2ToUint64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint64) @@ -485,7 +492,7 @@ func (scanPlanBinaryInt2ToUint64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint64", n) } @@ -502,8 +509,9 @@ func (scanPlanBinaryInt2ToInt) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int) @@ -511,7 +519,7 @@ func (scanPlanBinaryInt2ToInt) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int(int16(binary.BigEndian.Uint16(src))) + *p = int(int16(raw)) return nil } @@ -523,8 +531,9 @@ func (scanPlanBinaryInt2ToUint) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint) @@ -532,7 +541,7 @@ func (scanPlanBinaryInt2ToUint) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(int16(binary.BigEndian.Uint16(src))) + n := int64(int16(raw)) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint", n) } @@ -554,11 +563,12 @@ func (scanPlanBinaryInt2ToInt64Scanner) Scan(src []byte, dst any) error { return s.ScanInt64(Int8{}) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } - n := int64(int16(binary.BigEndian.Uint16(src))) + n := int64(int16(raw)) return s.ScanInt64(Int8{Int64: n, Valid: true}) } @@ -575,11 +585,12 @@ func (scanPlanBinaryInt2ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } - n := int64(int16(binary.BigEndian.Uint16(src))) + n := int64(int16(raw)) return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) } @@ -866,8 +877,9 @@ func (scanPlanBinaryInt4ToInt8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int8) @@ -875,7 +887,7 @@ func (scanPlanBinaryInt4ToInt8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < math.MinInt8 { return fmt.Errorf("%d is less than minimum value for int8", n) } else if n > math.MaxInt8 { @@ -894,8 +906,9 @@ func (scanPlanBinaryInt4ToUint8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint8) @@ -903,7 +916,7 @@ func (scanPlanBinaryInt4ToUint8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint8", n) } @@ -924,8 +937,9 @@ func (scanPlanBinaryInt4ToInt16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int16) @@ -933,7 +947,7 @@ func (scanPlanBinaryInt4ToInt16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < math.MinInt16 { return fmt.Errorf("%d is less than minimum value for int16", n) } else if n > math.MaxInt16 { @@ -952,8 +966,9 @@ func (scanPlanBinaryInt4ToUint16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint16) @@ -961,7 +976,7 @@ func (scanPlanBinaryInt4ToUint16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint16", n) } @@ -982,8 +997,9 @@ func (scanPlanBinaryInt4ToInt32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int32) @@ -991,7 +1007,7 @@ func (scanPlanBinaryInt4ToInt32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int32(binary.BigEndian.Uint32(src)) + *p = int32(raw) return nil } @@ -1003,8 +1019,9 @@ func (scanPlanBinaryInt4ToUint32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint32) @@ -1012,7 +1029,7 @@ func (scanPlanBinaryInt4ToUint32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint32", n) } @@ -1029,8 +1046,9 @@ func (scanPlanBinaryInt4ToInt64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int64) @@ -1038,7 +1056,7 @@ func (scanPlanBinaryInt4ToInt64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int64(int32(binary.BigEndian.Uint32(src))) + *p = int64(int32(raw)) return nil } @@ -1050,8 +1068,9 @@ func (scanPlanBinaryInt4ToUint64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint64) @@ -1059,7 +1078,7 @@ func (scanPlanBinaryInt4ToUint64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint64", n) } @@ -1076,8 +1095,9 @@ func (scanPlanBinaryInt4ToInt) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int) @@ -1085,7 +1105,7 @@ func (scanPlanBinaryInt4ToInt) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int(int32(binary.BigEndian.Uint32(src))) + *p = int(int32(raw)) return nil } @@ -1097,8 +1117,9 @@ func (scanPlanBinaryInt4ToUint) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint) @@ -1106,7 +1127,7 @@ func (scanPlanBinaryInt4ToUint) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(int32(binary.BigEndian.Uint32(src))) + n := int64(int32(raw)) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint", n) } @@ -1128,11 +1149,12 @@ func (scanPlanBinaryInt4ToInt64Scanner) Scan(src []byte, dst any) error { return s.ScanInt64(Int8{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } - n := int64(int32(binary.BigEndian.Uint32(src))) + n := int64(int32(raw)) return s.ScanInt64(Int8{Int64: n, Valid: true}) } @@ -1149,11 +1171,12 @@ func (scanPlanBinaryInt4ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } - n := int64(int32(binary.BigEndian.Uint32(src))) + n := int64(int32(raw)) return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) } @@ -1215,7 +1238,7 @@ func (dst *Int8) Scan(src any) error { } if n < math.MinInt64 { - return fmt.Errorf("%d is greater than maximum value for Int8", n) + return fmt.Errorf("%d is less than minimum value for Int8", n) } if n > math.MaxInt64 { return fmt.Errorf("%d is greater than maximum value for Int8", n) @@ -1440,8 +1463,9 @@ func (scanPlanBinaryInt8ToInt8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int8) @@ -1449,7 +1473,7 @@ func (scanPlanBinaryInt8ToInt8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < math.MinInt8 { return fmt.Errorf("%d is less than minimum value for int8", n) } else if n > math.MaxInt8 { @@ -1468,8 +1492,9 @@ func (scanPlanBinaryInt8ToUint8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint8) @@ -1477,7 +1502,7 @@ func (scanPlanBinaryInt8ToUint8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint8", n) } @@ -1498,8 +1523,9 @@ func (scanPlanBinaryInt8ToInt16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int16) @@ -1507,7 +1533,7 @@ func (scanPlanBinaryInt8ToInt16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < math.MinInt16 { return fmt.Errorf("%d is less than minimum value for int16", n) } else if n > math.MaxInt16 { @@ -1526,8 +1552,9 @@ func (scanPlanBinaryInt8ToUint16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint16) @@ -1535,7 +1562,7 @@ func (scanPlanBinaryInt8ToUint16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint16", n) } @@ -1556,8 +1583,9 @@ func (scanPlanBinaryInt8ToInt32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int32) @@ -1565,7 +1593,7 @@ func (scanPlanBinaryInt8ToInt32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < math.MinInt32 { return fmt.Errorf("%d is less than minimum value for int32", n) } else if n > math.MaxInt32 { @@ -1584,8 +1612,9 @@ func (scanPlanBinaryInt8ToUint32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint32) @@ -1593,7 +1622,7 @@ func (scanPlanBinaryInt8ToUint32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint32", n) } @@ -1614,8 +1643,9 @@ func (scanPlanBinaryInt8ToInt64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int64) @@ -1623,7 +1653,7 @@ func (scanPlanBinaryInt8ToInt64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int64(binary.BigEndian.Uint64(src)) + *p = int64(raw) return nil } @@ -1635,8 +1665,9 @@ func (scanPlanBinaryInt8ToUint64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint64) @@ -1644,7 +1675,7 @@ func (scanPlanBinaryInt8ToUint64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint64", n) } @@ -1661,8 +1692,9 @@ func (scanPlanBinaryInt8ToInt) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int) @@ -1670,7 +1702,7 @@ func (scanPlanBinaryInt8ToInt) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < math.MinInt { return fmt.Errorf("%d is less than minimum value for int", n) } else if n > math.MaxInt { @@ -1689,8 +1721,9 @@ func (scanPlanBinaryInt8ToUint) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint) @@ -1698,7 +1731,7 @@ func (scanPlanBinaryInt8ToUint) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(int64(binary.BigEndian.Uint64(src))) + n := int64(int64(raw)) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint", n) } @@ -1724,11 +1757,12 @@ func (scanPlanBinaryInt8ToInt64Scanner) Scan(src []byte, dst any) error { return s.ScanInt64(Int8{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } - n := int64(int64(binary.BigEndian.Uint64(src))) + n := int64(int64(raw)) return s.ScanInt64(Int8{Int64: n, Valid: true}) } @@ -1745,11 +1779,12 @@ func (scanPlanBinaryInt8ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } - n := int64(int64(binary.BigEndian.Uint64(src))) + n := int64(int64(raw)) return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb b/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb index c2d40f60b9..4be6d932a7 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb +++ b/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb @@ -79,7 +79,7 @@ func (dst *Int<%= pg_byte_size %>) Scan(src any) error { } if n < math.MinInt<%= pg_bit_size %> { - return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n) + return fmt.Errorf("%d is less than minimum value for Int<%= pg_byte_size %>", n) } if n > math.MaxInt<%= pg_bit_size %> { return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n) @@ -306,8 +306,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %>) Scan(src []b return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("int<%= pg_byte_size %>: %w", err) } p, ok := (dst).(*int<%= dst_bit_size %>) @@ -316,7 +317,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %>) Scan(src []b } <% if dst_bit_size < pg_bit_size %> - n := int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + n := int<%= pg_bit_size %>(raw) if n < math.MinInt<%= dst_bit_size %> { return fmt.Errorf("%d is less than minimum value for int<%= dst_bit_size %>", n) } else if n > math.MaxInt<%= dst_bit_size %> { @@ -325,9 +326,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %>) Scan(src []b *p = int<%= dst_bit_size %>(n) <% elsif dst_bit_size == pg_bit_size %> - *p = int<%= dst_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + *p = int<%= dst_bit_size %>(raw) <% else %> - *p = int<%= dst_bit_size %>(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + *p = int<%= dst_bit_size %>(int<%= pg_bit_size %>(raw)) <% end %> return nil @@ -340,8 +341,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToUint<%= dst_bit_size %>) Scan(src [] return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for uint<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("uint<%= pg_byte_size %>: %w", err) } p, ok := (dst).(*uint<%= dst_bit_size %>) @@ -349,7 +351,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToUint<%= dst_bit_size %>) Scan(src [] return ErrScanTargetTypeChanged } - n := int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + n := int<%= pg_bit_size %>(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint<%= dst_bit_size %>", n) } @@ -372,8 +374,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt) Scan(src []byte, dst any) error return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("int<%= pg_byte_size %>: %w", err) } p, ok := (dst).(*int) @@ -382,7 +385,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt) Scan(src []byte, dst any) error } <% if 32 < pg_bit_size %> - n := int64(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + n := int64(raw) if n < math.MinInt { return fmt.Errorf("%d is less than minimum value for int", n) } else if n > math.MaxInt { @@ -391,7 +394,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt) Scan(src []byte, dst any) error *p = int(n) <% else %> - *p = int(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + *p = int(int<%= pg_bit_size %>(raw)) <% end %> return nil @@ -404,8 +407,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToUint) Scan(src []byte, dst any) erro return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for uint<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("uint<%= pg_byte_size %>: %w", err) } p, ok := (dst).(*uint) @@ -413,7 +417,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToUint) Scan(src []byte, dst any) erro return ErrScanTargetTypeChanged } - n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + n := int64(int<%= pg_bit_size %>(raw)) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint", n) } @@ -440,12 +444,13 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt64Scanner) Scan(src []byte, dst a return s.ScanInt64(Int8{}) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("int<%= pg_byte_size %>: %w", err) } - n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + n := int64(int<%= pg_bit_size %>(raw)) return s.ScanInt64(Int8{Int64: n, Valid: true}) } @@ -463,12 +468,13 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToTextScanner) Scan(src []byte, dst an return s.ScanText(Text{}) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("int<%= pg_byte_size %>: %w", err) } - n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + n := int64(int<%= pg_bit_size %>(raw)) return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/interval.go b/vendor/github.com/jackc/pgx/v5/pgtype/interval.go index be8decdd12..51a4381da2 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/interval.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/interval.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "strconv" "strings" @@ -175,19 +174,21 @@ func (IntervalCodec) PlanScan(m *Map, oid uint32, format int16, target any) Scan type scanPlanBinaryIntervalToIntervalScanner struct{} func (scanPlanBinaryIntervalToIntervalScanner) Scan(src []byte, dst any) error { - scanner := (dst).(IntervalScanner) + scanner := dst.(IntervalScanner) if src == nil { return scanner.ScanInterval(Interval{}) } - if len(src) != 16 { - return fmt.Errorf("Received an invalid size for an interval: %d", len(src)) - } + r := pgio.NewReader(src) + + microseconds := r.Int64() + days := r.Int32() + months := r.Int32() - microseconds := int64(binary.BigEndian.Uint64(src)) - days := int32(binary.BigEndian.Uint32(src[8:])) - months := int32(binary.BigEndian.Uint32(src[12:])) + if err := r.Finish(); err != nil { + return fmt.Errorf("Received an invalid size for an interval: %w", err) + } return scanner.ScanInterval(Interval{Microseconds: microseconds, Days: days, Months: months, Valid: true}) } @@ -195,7 +196,7 @@ func (scanPlanBinaryIntervalToIntervalScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToIntervalScanner struct{} func (scanPlanTextAnyToIntervalScanner) Scan(src []byte, dst any) error { - scanner := (dst).(IntervalScanner) + scanner := dst.(IntervalScanner) if src == nil { return scanner.ScanInterval(Interval{}) @@ -232,7 +233,7 @@ func (scanPlanTextAnyToIntervalScanner) Scan(src []byte, dst any) error { } var negative bool - if timeParts[0][0] == '-' { + if len(timeParts[0]) > 0 && timeParts[0][0] == '-' { negative = true timeParts[0] = timeParts[0][1:] } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/line.go b/vendor/github.com/jackc/pgx/v5/pgtype/line.go index 73b0636494..8fb02bb008 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/line.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/line.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -147,19 +146,21 @@ func (LineCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryLineToLineScanner struct{} func (scanPlanBinaryLineToLineScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LineScanner) + scanner := dst.(LineScanner) if src == nil { return scanner.ScanLine(Line{}) } - if len(src) != 24 { - return fmt.Errorf("invalid length for line: %v", len(src)) - } + r := pgio.NewReader(src) - a := binary.BigEndian.Uint64(src) - b := binary.BigEndian.Uint64(src[8:]) - c := binary.BigEndian.Uint64(src[16:]) + a := r.Uint64() + b := r.Uint64() + c := r.Uint64() + + if err := r.Finish(); err != nil { + return fmt.Errorf("line: %w", err) + } return scanner.ScanLine(Line{ A: math.Float64frombits(a), @@ -172,7 +173,7 @@ func (scanPlanBinaryLineToLineScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToLineScanner struct{} func (scanPlanTextAnyToLineScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LineScanner) + scanner := dst.(LineScanner) if src == nil { return scanner.ScanLine(Line{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go b/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go index 438b45b622..a239c09a8f 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -145,20 +144,22 @@ func (LsegCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryLsegToLsegScanner struct{} func (scanPlanBinaryLsegToLsegScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LsegScanner) + scanner := dst.(LsegScanner) if src == nil { return scanner.ScanLseg(Lseg{}) } - if len(src) != 32 { - return fmt.Errorf("invalid length for lseg: %v", len(src)) - } + r := pgio.NewReader(src) - x1 := binary.BigEndian.Uint64(src) - y1 := binary.BigEndian.Uint64(src[8:]) - x2 := binary.BigEndian.Uint64(src[16:]) - y2 := binary.BigEndian.Uint64(src[24:]) + x1 := r.Uint64() + y1 := r.Uint64() + x2 := r.Uint64() + y2 := r.Uint64() + + if err := r.Finish(); err != nil { + return fmt.Errorf("lseg: %w", err) + } return scanner.ScanLseg(Lseg{ P: [2]Vec2{ @@ -172,7 +173,7 @@ func (scanPlanBinaryLsegToLsegScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToLsegScanner struct{} func (scanPlanTextAnyToLsegScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LsegScanner) + scanner := dst.(LsegScanner) if src == nil { return scanner.ScanLseg(Lseg{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go b/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go index 6af3177944..760706083f 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go @@ -21,7 +21,7 @@ func (l LtreeCodec) PreferredFormat() int16 { func (l LtreeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { switch format { case TextFormatCode: - return (TextCodec)(l).PlanEncode(m, oid, format, value) + return TextCodec(l).PlanEncode(m, oid, format, value) case BinaryFormatCode: switch value.(type) { case string: @@ -72,7 +72,7 @@ func (encodeLtreeCodecBinaryTextValuer) Encode(value any, buf []byte) (newBuf [] func (l LtreeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { switch format { case TextFormatCode: - return (TextCodec)(l).PlanScan(m, oid, format, target) + return TextCodec(l).PlanScan(m, oid, format, target) case BinaryFormatCode: switch target.(type) { case *string: @@ -93,7 +93,7 @@ func (scanPlanBinaryLtreeToString) Scan(src []byte, target any) error { return fmt.Errorf("unsupported ltree version %d", version) } - p := (target).(*string) + p := target.(*string) *p = string(src[1:]) return nil @@ -107,16 +107,16 @@ func (scanPlanBinaryLtreeToTextScanner) Scan(src []byte, target any) error { return fmt.Errorf("unsupported ltree version %d", version) } - scanner := (target).(TextScanner) + scanner := target.(TextScanner) return scanner.ScanText(Text{String: string(src[1:]), Valid: true}) } // DecodeDatabaseSQLValue returns src decoded into a value compatible with the sql.Scanner interface. func (l LtreeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return (TextCodec)(l).DecodeDatabaseSQLValue(m, oid, format, src) + return TextCodec(l).DecodeDatabaseSQLValue(m, oid, format, src) } // DecodeValue returns src decoded into its default format. func (l LtreeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - return (TextCodec)(l).DecodeValue(m, oid, format, src) + return TextCodec(l).DecodeValue(m, oid, format, src) } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go b/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go index e913ec9034..045975eb54 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go @@ -116,7 +116,7 @@ func (scanPlanBinaryMacaddrToHardwareAddr) Scan(src []byte, dst any) error { type scanPlanBinaryMacaddrToTextScanner struct{} func (scanPlanBinaryMacaddrToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go b/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go index 11f30b448f..f47091c80d 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go @@ -3,7 +3,6 @@ package pgtype import ( "bytes" "database/sql/driver" - "encoding/binary" "fmt" "reflect" @@ -205,14 +204,12 @@ func (c *MultirangeCodec) PlanScan(m *Map, oid uint32, format int16, target any) } func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, multirange MultirangeSetter) error { - rp := 0 - - elementCount := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 + r := pgio.NewReader(src) // Each element requires at least 4 bytes for its length prefix. - if elementCount > len(src)/4 { - return fmt.Errorf("multirange element count %d exceeds available data", elementCount) + elementCount := r.Count(4) + if err := r.Err(); err != nil { + return fmt.Errorf("multirange: %w", err) } err := multirange.SetLen(elementCount) @@ -221,7 +218,7 @@ func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, } if elementCount == 0 { - return nil + return r.Finish() } elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, BinaryFormatCode, multirange.ScanIndex(0)) @@ -231,18 +228,9 @@ func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, for i := range elementCount { elem := multirange.ScanIndex(i) - if len(src[rp:]) < 4 { - return fmt.Errorf("multirange body truncated at element %d", i) - } - elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - var elemSrc []byte - if elemLen >= 0 { - if len(src[rp:]) < elemLen { - return fmt.Errorf("multirange element %d length %d exceeds remaining %d bytes", i, elemLen, len(src[rp:])) - } - elemSrc = src[rp : rp+elemLen] - rp += elemLen + elemSrc, _ := r.Value() + if err := r.Err(); err != nil { + return fmt.Errorf("multirange element %d: %w", i, err) } err = elementScanPlan.Scan(elemSrc, elem) if err != nil { @@ -250,7 +238,7 @@ func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, } } - return nil + return r.Finish() } func (c *MultirangeCodec) decodeText(m *Map, multirangeOID uint32, src []byte, multirange MultirangeSetter) error { diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go b/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go index caf5ff17b6..15ad6e41b5 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go @@ -3,7 +3,7 @@ package pgtype import ( "bytes" "database/sql/driver" - "encoding/binary" + "errors" "fmt" "math" "math/big" @@ -16,6 +16,14 @@ import ( // PostgreSQL internal numeric storage uses 16-bit "digits" with base of 10,000 const nbase = 10_000 +// Numeric's binary representation stores the exponent through a base-10,000 +// weight and an int16 dscale. These are also the largest exponents that can be +// safely materialized by the text encoders. +const ( + minNumericExponent = -math.MaxInt16 + maxNumericExponent = math.MaxInt16*4 + 3 +) + const ( pgNumericNaN = 0x00000000c0000000 pgNumericNaNSign = 0xc000 @@ -133,12 +141,7 @@ func (n *Numeric) ScanScientific(src string) error { return scanPlanTextAnyToNumericScanner{}.Scan([]byte(src), n) } - if bigF, ok := new(big.Float).SetString(src); ok { - smallF, _ := bigF.Float64() - src = strconv.FormatFloat(smallF, 'f', -1, 64) - } - - num, exp, err := parseNumericString(src) + num, exp, err := parseScientificNumericString(src) if err != nil { return err } @@ -148,7 +151,45 @@ func (n *Numeric) ScanScientific(src string) error { return nil } +func parseScientificNumericString(str string) (n *big.Int, exp int32, err error) { + idx := strings.IndexAny(str, "eE") + if idx == -1 { + return parseNumericString(str) + } + + mantissa := str[:idx] + scientificExp, err := strconv.ParseInt(str[idx+1:], 10, 32) + if err != nil { + if errors.Is(err, strconv.ErrRange) { + return nil, 0, fmt.Errorf("%s exponent out of range", str) + } + return nil, 0, fmt.Errorf("%s is not a number", str) + } + + num, mantissaExp, err := parseNumericString(mantissa) + if err != nil { + return nil, 0, fmt.Errorf("%s is not a number", str) + } + + combinedExp := int64(mantissaExp) + scientificExp + if combinedExp < minNumericExponent || combinedExp > maxNumericExponent { + return nil, 0, fmt.Errorf("%s exponent out of range", str) + } + + return num, int32(combinedExp), nil +} + func (n *Numeric) toBigInt() (*big.Int, error) { + if n.NaN { + return nil, fmt.Errorf("cannot convert NaN to integer") + } else if n.InfinityModifier != Finite { + return nil, fmt.Errorf("cannot convert %v to integer", n.InfinityModifier) + } + + if n.Int == nil { + return big.NewInt(0), nil + } + if n.Exp == 0 { return n.Int, nil } @@ -173,40 +214,41 @@ func (n *Numeric) toBigInt() (*big.Int, error) { } func parseNumericString(str string) (n *big.Int, exp int32, err error) { - idx := strings.IndexByte(str, '.') + // Keep str intact so errors report what the caller actually passed in. + digits := str + idx := strings.IndexByte(digits, '.') if idx == -1 { - for len(str) > 1 && str[len(str)-1] == '0' && str[len(str)-2] != '-' { - str = str[:len(str)-1] + for len(digits) > 1 && digits[len(digits)-1] == '0' && digits[len(digits)-2] != '-' { + digits = digits[:len(digits)-1] exp++ } } else { - exp = int32(-(len(str) - idx - 1)) - str = str[:idx] + str[idx+1:] + exp = int32(-(len(digits) - idx - 1)) + digits = digits[:idx] + digits[idx+1:] } accum := &big.Int{} - if _, ok := accum.SetString(str, 10); !ok { + if _, ok := accum.SetString(digits, 10); !ok { return nil, 0, fmt.Errorf("%s is not a number", str) } return accum, exp, nil } -func nbaseDigitsToInt64(src []byte) (accum int64, bytesRead, digitsRead int) { - digits := min(len(src)/2, 4) - - rp := 0 +// nbaseDigitsToInt64 reads up to 4 nbase digits and packs them into an int64. +// It stops early at digitsLeft or at the end of r, whichever comes first. +func nbaseDigitsToInt64(r *pgio.Reader, digitsLeft int) (accum int64, digitsRead int) { + digits := min(digitsLeft, r.Remaining()/2, 4) for i := range digits { if i > 0 { accum *= nbase } - accum += int64(binary.BigEndian.Uint16(src[rp:])) - rp += 2 + accum += int64(r.Uint16()) } - return accum, rp, digits + return accum, digits } // Scan implements the [database/sql.Scanner] interface. @@ -242,8 +284,13 @@ func (n Numeric) MarshalJSON() ([]byte, error) { return []byte("null"), nil } - if n.NaN { + switch { + case n.NaN: return []byte(`"NaN"`), nil + case n.InfinityModifier == Infinity: + return []byte(`"Infinity"`), nil + case n.InfinityModifier == NegativeInfinity: + return []byte(`"-Infinity"`), nil } return n.numberTextBytes(), nil @@ -259,7 +306,17 @@ func (n *Numeric) UnmarshalJSON(src []byte) error { *n = Numeric{NaN: true, Valid: true} return nil } - return scanPlanTextAnyToNumericScanner{}.Scan(src, n) + if bytes.Equal(src, []byte(`"Infinity"`)) { + *n = Numeric{InfinityModifier: Infinity, Valid: true} + return nil + } + if bytes.Equal(src, []byte(`"-Infinity"`)) { + *n = Numeric{InfinityModifier: NegativeInfinity, Valid: true} + return nil + } + // JSON numbers may use scientific notation even when the producer did not + // write it that way: encoding/json emits 1e+21 for float64(1e21). + return n.ScanScientific(string(src)) } // numberString returns a string of the number. undefined if NaN, infinite, or NULL @@ -416,6 +473,14 @@ func encodeNumericBinary(n Numeric, buf []byte) (newBuf []byte, err error) { sign = 16384 } + // The binary format stores ndigits as uint16 and weight and dscale as int16, + // so values that do not fit must be rejected rather than silently truncated. + // Exp maps directly onto dscale, so check it before doing any big.Int work: a very + // negative exponent would otherwise build an enormous divisor below. + if n.Exp < -math.MaxInt16 { + return nil, fmt.Errorf("cannot encode numeric: exponent %d is out of range", n.Exp) + } + absInt := &big.Int{} wholePart := &big.Int{} fracPart := &big.Int{} @@ -443,7 +508,7 @@ func encodeNumericBinary(n Numeric, buf []byte) (newBuf []byte, err error) { if exp < 0 { divisor := &big.Int{} - divisor.Exp(big10, big.NewInt(int64(-exp)), nil) + divisor.Exp(big10, big.NewInt(-int64(exp)), nil) wholePart.DivMod(absInt, divisor, fracPart) fracPart.Add(fracPart, divisor) } else { @@ -464,18 +529,25 @@ func encodeNumericBinary(n Numeric, buf []byte) (newBuf []byte, err error) { } } - buf = pgio.AppendInt16(buf, int16(len(wholeDigits)+len(fracDigits))) + ndigits := len(wholeDigits) + len(fracDigits) + if ndigits > math.MaxUint16 { + return nil, fmt.Errorf("cannot encode numeric: %d digits is out of range", ndigits) + } + buf = pgio.AppendUint16(buf, uint16(ndigits)) - var weight int16 + var weight int64 if len(wholeDigits) > 0 { - weight = int16(len(wholeDigits) - 1) + weight = int64(len(wholeDigits) - 1) if exp > 0 { - weight += int16(exp / 4) + weight += int64(exp) / 4 } } else { - weight = int16(exp/4) - 1 + int16(len(fracDigits)) + weight = int64(exp)/4 - 1 + int64(len(fracDigits)) + } + if weight > math.MaxInt16 || weight < math.MinInt16 { + return nil, fmt.Errorf("cannot encode numeric: exponent %d is out of range", n.Exp) } - buf = pgio.AppendInt16(buf, weight) + buf = pgio.AppendInt16(buf, int16(weight)) buf = pgio.AppendInt16(buf, sign) @@ -600,25 +672,21 @@ func (NumericCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanP type scanPlanBinaryNumericToNumericScanner struct{} func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NumericScanner) + scanner := dst.(NumericScanner) if src == nil { return scanner.ScanNumeric(Numeric{}) } - if len(src) < 8 { - return fmt.Errorf("numeric incomplete %v", src) - } + r := pgio.NewReader(src) - rp := 0 - ndigits := binary.BigEndian.Uint16(src[rp:]) - rp += 2 - weight := int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - sign := binary.BigEndian.Uint16(src[rp:]) - rp += 2 - dscale := int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 + ndigits := r.Uint16() + weight := r.Int16() + sign := r.Uint16() + dscale := r.Int16() + if err := r.Err(); err != nil { + return fmt.Errorf("numeric incomplete: %w", err) + } switch sign { case pgNumericNaNSign: @@ -633,15 +701,16 @@ func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { return scanner.ScanNumeric(Numeric{Int: big.NewInt(0), Valid: true}) } - if len(src[rp:]) < int(ndigits)*2 { + if r.Remaining() < int(ndigits)*2 { return fmt.Errorf("numeric incomplete %v", src) } accum := &big.Int{} - for i := 0; i < int(ndigits+3)/4; i++ { - int64accum, bytesRead, digitsRead := nbaseDigitsToInt64(src[rp:]) - rp += bytesRead + // int(ndigits) before the addition: ndigits is a uint16, so ndigits+3 + // would wrap for counts above 65532 and skip the loop entirely. + for i := 0; i < (int(ndigits)+3)/4; i++ { + int64accum, digitsRead := nbaseDigitsToInt64(r, int(ndigits)-i*4) if i > 0 { var mul *big.Int @@ -663,6 +732,10 @@ func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { accum.Add(accum, big.NewInt(int64accum)) } + if err := r.Finish(); err != nil { + return fmt.Errorf("numeric: %w", err) + } + exp := (int32(weight) - int32(ndigits) + 1) * 4 if dscale > 0 { @@ -687,7 +760,7 @@ func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { reduced := &big.Int{} remainder := &big.Int{} - if exp >= 0 { + if exp >= 0 && accum.Sign() != 0 { for { reduced.DivMod(accum, big10, remainder) if remainder.Sign() != 0 { @@ -708,7 +781,7 @@ func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { type scanPlanBinaryNumericToFloat64Scanner struct{} func (scanPlanBinaryNumericToFloat64Scanner) Scan(src []byte, dst any) error { - scanner := (dst).(Float64Scanner) + scanner := dst.(Float64Scanner) if src == nil { return scanner.ScanFloat64(Float8{}) @@ -732,7 +805,7 @@ func (scanPlanBinaryNumericToFloat64Scanner) Scan(src []byte, dst any) error { type scanPlanBinaryNumericToInt64Scanner struct{} func (scanPlanBinaryNumericToInt64Scanner) Scan(src []byte, dst any) error { - scanner := (dst).(Int64Scanner) + scanner := dst.(Int64Scanner) if src == nil { return scanner.ScanInt64(Int8{}) @@ -760,7 +833,7 @@ func (scanPlanBinaryNumericToInt64Scanner) Scan(src []byte, dst any) error { type scanPlanBinaryNumericToTextScanner struct{} func (scanPlanBinaryNumericToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) @@ -784,7 +857,7 @@ func (scanPlanBinaryNumericToTextScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToNumericScanner struct{} func (scanPlanTextAnyToNumericScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NumericScanner) + scanner := dst.(NumericScanner) if src == nil { return scanner.ScanNumeric(Numeric{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/path.go b/vendor/github.com/jackc/pgx/v5/pgtype/path.go index 6398b58152..0afceaca76 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/path.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/path.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -172,34 +171,32 @@ func (PathCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryPathToPathScanner struct{} func (scanPlanBinaryPathToPathScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PathScanner) + scanner := dst.(PathScanner) if src == nil { return scanner.ScanPath(Path{}) } - if len(src) < 5 { - return fmt.Errorf("invalid length for Path: %v", len(src)) - } - - closed := src[0] == 1 - pointCount := int(binary.BigEndian.Uint32(src[1:])) + r := pgio.NewReader(src) - rp := 5 - - if 5+pointCount*16 != len(src) { - return fmt.Errorf("invalid length for Path with %d points: %v", pointCount, len(src)) + closed := r.Byte() == 1 + // Each point is two float64s. + pointCount := r.Count(16) + if err := r.Err(); err != nil { + return fmt.Errorf("invalid length for Path: %w", err) } points := make([]Vec2, pointCount) for i := range points { - x := binary.BigEndian.Uint64(src[rp:]) - rp += 8 - y := binary.BigEndian.Uint64(src[rp:]) - rp += 8 + x := r.Uint64() + y := r.Uint64() points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)} } + if err := r.Finish(); err != nil { + return fmt.Errorf("invalid length for Path with %d points: %w", pointCount, err) + } + return scanner.ScanPath(Path{ P: points, Closed: closed, @@ -210,7 +207,7 @@ func (scanPlanBinaryPathToPathScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToPathScanner struct{} func (scanPlanTextAnyToPathScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PathScanner) + scanner := dst.(PathScanner) if src == nil { return scanner.ScanPath(Path{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go index 46b892bfb4..98f5b3bdea 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go @@ -412,7 +412,7 @@ func (scanPlanString) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - p := (dst).(*string) + p := dst.(*string) *p = string(src) return nil } @@ -497,7 +497,12 @@ type pointerPointerScanPlan struct { func (plan *pointerPointerScanPlan) SetNext(next ScanPlan) { plan.next = next } func (plan *pointerPointerScanPlan) Scan(src []byte, dst any) error { - el := reflect.ValueOf(dst).Elem() + dstValue := reflect.ValueOf(dst) + if dstValue.Kind() != reflect.Pointer || dstValue.IsNil() { + return fmt.Errorf("cannot scan into non-pointer or nil destinations %T", dst) + } + + el := dstValue.Elem() if src == nil { el.Set(reflect.Zero(el.Type())) return nil @@ -510,11 +515,11 @@ func (plan *pointerPointerScanPlan) Scan(src []byte, dst any) error { // TryPointerPointerScanPlan handles a pointer to a pointer by setting the target to nil for SQL NULL and allocating and // scanning for non-NULL. func TryPointerPointerScanPlan(target any) (plan WrappedScanPlanNextSetter, nextTarget any, ok bool) { - if dstValue := reflect.ValueOf(target); dstValue.Kind() == reflect.Pointer { - elemValue := dstValue.Elem() - if elemValue.Kind() == reflect.Pointer { - plan = &pointerPointerScanPlan{dstType: dstValue.Type()} - return plan, reflect.Zero(elemValue.Type()).Interface(), true + if dstType := reflect.TypeOf(target); dstType != nil && dstType.Kind() == reflect.Pointer { + elemType := dstType.Elem() + if elemType.Kind() == reflect.Pointer { + plan = &pointerPointerScanPlan{dstType: dstType} + return plan, reflect.Zero(elemType).Interface(), true } } @@ -575,8 +580,7 @@ func TryFindUnderlyingTypeScanPlan(dst any) (plan WrappedScanPlanNextSetter, nex if nextDstType == nil { if elemValue.Kind() == reflect.Slice { if elemValue.Type().Elem().Kind() == reflect.Uint8 { - var v *[]byte - nextDstType = reflect.TypeOf(v) + nextDstType = reflect.TypeFor[*[]byte]() } } @@ -1828,19 +1832,19 @@ func TryWrapSliceEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextVa // Avoid using reflect path for common types. switch value := value.(type) { case []int16: - return &wrapSliceEncodePlan[int16]{}, (FlatArray[int16])(value), true + return &wrapSliceEncodePlan[int16]{}, FlatArray[int16](value), true case []int32: - return &wrapSliceEncodePlan[int32]{}, (FlatArray[int32])(value), true + return &wrapSliceEncodePlan[int32]{}, FlatArray[int32](value), true case []int64: - return &wrapSliceEncodePlan[int64]{}, (FlatArray[int64])(value), true + return &wrapSliceEncodePlan[int64]{}, FlatArray[int64](value), true case []float32: - return &wrapSliceEncodePlan[float32]{}, (FlatArray[float32])(value), true + return &wrapSliceEncodePlan[float32]{}, FlatArray[float32](value), true case []float64: - return &wrapSliceEncodePlan[float64]{}, (FlatArray[float64])(value), true + return &wrapSliceEncodePlan[float64]{}, FlatArray[float64](value), true case []string: - return &wrapSliceEncodePlan[string]{}, (FlatArray[string])(value), true + return &wrapSliceEncodePlan[string]{}, FlatArray[string](value), true case []time.Time: - return &wrapSliceEncodePlan[time.Time]{}, (FlatArray[time.Time])(value), true + return &wrapSliceEncodePlan[time.Time]{}, FlatArray[time.Time](value), true } if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Slice { @@ -1860,7 +1864,7 @@ type wrapSliceEncodePlan[T any] struct { func (plan *wrapSliceEncodePlan[T]) SetNext(next EncodePlan) { plan.next = next } func (plan *wrapSliceEncodePlan[T]) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode((FlatArray[T])(value.([]T)), buf) + return plan.next.Encode(FlatArray[T](value.([]T)), buf) } type wrapSliceEncodeReflectPlan struct { @@ -1999,6 +2003,9 @@ func (m *Map) Encode(oid uint32, formatCode int16, value any, buf []byte) (newBu // // This uses the type of v to look up the PostgreSQL OID that v presumably came from. This means v must be registered // with m by calling RegisterDefaultPgType. +// +// As of Go 1.27, database/sql calls the driver directly to scan columns when using pgx's stdlib package, so this is +// no longer necessary. func (m *Map) SQLScanner(v any) sql.Scanner { if s, ok := v.(sql.Scanner); ok { return s diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go index 42b39d827d..2b9e8fe5d7 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go @@ -131,7 +131,7 @@ func initDefaultMap() { defaultMap.RegisterType(&Type{Name: "_aclitem", OID: ACLItemArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[ACLItemOID]}}) defaultMap.RegisterType(&Type{Name: "_bit", OID: BitArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BitOID]}}) defaultMap.RegisterType(&Type{Name: "_bool", OID: BoolArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoolOID]}}) - defaultMap.RegisterType(&Type{Name: "_box", OID: BoxArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoxOID]}}) + defaultMap.RegisterType(&Type{Name: "_box", OID: BoxArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoxOID], Delimiter: ';'}}) defaultMap.RegisterType(&Type{Name: "_bpchar", OID: BPCharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BPCharOID]}}) defaultMap.RegisterType(&Type{Name: "_bytea", OID: ByteaArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[ByteaOID]}}) defaultMap.RegisterType(&Type{Name: "_char", OID: QCharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[QCharOID]}}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/point.go b/vendor/github.com/jackc/pgx/v5/pgtype/point.go index d90cb7033e..4536e1e6d7 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/point.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/point.go @@ -3,7 +3,6 @@ package pgtype import ( "bytes" "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -215,18 +214,20 @@ func (c PointCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (a type scanPlanBinaryPointToPointScanner struct{} func (scanPlanBinaryPointToPointScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PointScanner) + scanner := dst.(PointScanner) if src == nil { return scanner.ScanPoint(Point{}) } - if len(src) != 16 { - return fmt.Errorf("invalid length for point: %v", len(src)) - } + r := pgio.NewReader(src) - x := binary.BigEndian.Uint64(src) - y := binary.BigEndian.Uint64(src[8:]) + x := r.Uint64() + y := r.Uint64() + + if err := r.Finish(); err != nil { + return fmt.Errorf("point: %w", err) + } return scanner.ScanPoint(Point{ P: Vec2{math.Float64frombits(x), math.Float64frombits(y)}, @@ -237,7 +238,7 @@ func (scanPlanBinaryPointToPointScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToPointScanner struct{} func (scanPlanTextAnyToPointScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PointScanner) + scanner := dst.(PointScanner) if src == nil { return scanner.ScanPoint(Point{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go b/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go index 34aa0a6a5f..c9e2df02dd 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -157,32 +156,31 @@ func (PolygonCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanP type scanPlanBinaryPolygonToPolygonScanner struct{} func (scanPlanBinaryPolygonToPolygonScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PolygonScanner) + scanner := dst.(PolygonScanner) if src == nil { return scanner.ScanPolygon(Polygon{}) } - if len(src) < 5 { - return fmt.Errorf("invalid length for polygon: %v", len(src)) - } - - pointCount := int(binary.BigEndian.Uint32(src)) - rp := 4 + r := pgio.NewReader(src) - if 4+pointCount*16 != len(src) { - return fmt.Errorf("invalid length for Polygon with %d points: %v", pointCount, len(src)) + // Each point is two float64s. + pointCount := r.Count(16) + if err := r.Err(); err != nil { + return fmt.Errorf("invalid length for polygon: %w", err) } points := make([]Vec2, pointCount) for i := range points { - x := binary.BigEndian.Uint64(src[rp:]) - rp += 8 - y := binary.BigEndian.Uint64(src[rp:]) - rp += 8 + x := r.Uint64() + y := r.Uint64() points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)} } + if err := r.Finish(); err != nil { + return fmt.Errorf("invalid length for Polygon with %d points: %w", pointCount, err) + } + return scanner.ScanPolygon(Polygon{ P: points, Valid: true, @@ -192,7 +190,7 @@ func (scanPlanBinaryPolygonToPolygonScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToPolygonScanner struct{} func (scanPlanTextAnyToPolygonScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PolygonScanner) + scanner := dst.(PolygonScanner) if src == nil { return scanner.ScanPolygon(Polygon{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range.go b/vendor/github.com/jackc/pgx/v5/pgtype/range.go index dec153e509..dba88fbc0d 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/range.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/range.go @@ -2,8 +2,9 @@ package pgtype import ( "bytes" - "encoding/binary" "fmt" + + "github.com/jackc/pgx/v5/internal/pgio" ) type BoundType byte @@ -201,17 +202,16 @@ const ( func parseUntypedBinaryRange(src []byte) (*untypedBinaryRange, error) { ubr := &untypedBinaryRange{} + r := pgio.NewReader(src) - if len(src) == 0 { + rangeType := r.Byte() + if r.Err() != nil { return nil, fmt.Errorf("range too short: %v", len(src)) } - rangeType := src[0] - rp := 1 - if rangeType&emptyMask > 0 { - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing empty range: %v", len(src[rp:])) + if err := r.Finish(); err != nil { + return nil, fmt.Errorf("empty range: %w", err) } ubr.LowerType = Empty ubr.UpperType = Empty @@ -236,50 +236,24 @@ func parseUntypedBinaryRange(src []byte) (*untypedBinaryRange, error) { ubr.UpperType = Exclusive } - if ubr.LowerType == Unbounded && ubr.UpperType == Unbounded { - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing unbounded range: %v", len(src[rp:])) - } - return ubr, nil - } - - if len(src[rp:]) < 4 { - return nil, fmt.Errorf("too few bytes for size: %v", src[rp:]) - } - valueLen := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - if valueLen < 0 || len(src[rp:]) < valueLen { - return nil, fmt.Errorf("range lower bound length %d exceeds remaining %d bytes", valueLen, len(src[rp:])) - } - val := src[rp : rp+valueLen] - rp += valueLen - if ubr.LowerType != Unbounded { - ubr.Lower = val - } else { - ubr.Upper = val - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing range: %v", len(src[rp:])) + val, null := r.Value() + if null { + return nil, fmt.Errorf("range lower bound cannot be NULL") } - return ubr, nil + ubr.Lower = val } if ubr.UpperType != Unbounded { - if len(src[rp:]) < 4 { - return nil, fmt.Errorf("too few bytes for size: %v", src[rp:]) + val, null := r.Value() + if null { + return nil, fmt.Errorf("range upper bound cannot be NULL") } - valueLen := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - if valueLen < 0 || len(src[rp:]) < valueLen { - return nil, fmt.Errorf("range upper bound length %d exceeds remaining %d bytes", valueLen, len(src[rp:])) - } - ubr.Upper = src[rp : rp+valueLen] - rp += valueLen + ubr.Upper = val } - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing range: %v", len(src[rp:])) + if err := r.Finish(); err != nil { + return nil, fmt.Errorf("range: %w", err) } return ubr, nil diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go index dc1ac8b06b..81ad2062ef 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go @@ -3,6 +3,7 @@ package pgtype import ( "database/sql/driver" "fmt" + "strings" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -192,6 +193,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) return nil, fmt.Errorf("cannot encode %v as element of range", lower) } + boundStart := len(buf) buf, err = lowerPlan.Encode(lower, buf) if err != nil { return nil, fmt.Errorf("failed to encode %v as element of range: %w", lower, err) @@ -199,6 +201,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) if buf == nil { return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") } + buf = append(buf[:boundStart], quoteRangeBoundIfNeeded(string(buf[boundStart:]))...) } buf = append(buf, ',') @@ -213,6 +216,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) return nil, fmt.Errorf("cannot encode %v as element of range", upper) } + boundStart := len(buf) buf, err = upperPlan.Encode(upper, buf) if err != nil { return nil, fmt.Errorf("failed to encode %v as element of range: %w", upper, err) @@ -220,6 +224,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) if buf == nil { return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") } + buf = append(buf[:boundStart], quoteRangeBoundIfNeeded(string(buf[boundStart:]))...) } switch upperType { @@ -234,6 +239,13 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) return buf, nil } +func quoteRangeBoundIfNeeded(src string) string { + if src == "" || strings.ContainsAny(src, "\"\\,()[]") { + return quoteArrayElement(src) + } + return src +} + func (c *RangeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { switch format { case BinaryFormatCode: @@ -255,7 +267,7 @@ type scanPlanBinaryRangeToRangeScanner struct { } func (plan *scanPlanBinaryRangeToRangeScanner) Scan(src []byte, target any) error { - rangeScanner := (target).(RangeScanner) + rangeScanner := target.(RangeScanner) if src == nil { return rangeScanner.ScanNull() @@ -305,7 +317,7 @@ type scanPlanTextRangeToRangeScanner struct { } func (plan *scanPlanTextRangeToRangeScanner) Scan(src []byte, target any) error { - rangeScanner := (target).(RangeScanner) + rangeScanner := target.(RangeScanner) if src == nil { return rangeScanner.ScanNull() diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go index a663e4dc22..6fef94ef10 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go @@ -40,7 +40,7 @@ type scanPlanBinaryRecordToCompositeIndexScanner struct { } func (plan *scanPlanBinaryRecordToCompositeIndexScanner) Scan(src []byte, target any) error { - targetScanner := (target).(CompositeIndexScanner) + targetScanner := target.(CompositeIndexScanner) if src == nil { return targetScanner.ScanNull() @@ -48,14 +48,17 @@ func (plan *scanPlanBinaryRecordToCompositeIndexScanner) Scan(src []byte, target scanner := NewCompositeBinaryScanner(plan.m, src) for i := 0; scanner.Next(); i++ { - fieldTarget := targetScanner.ScanIndex(i) + fieldTarget, err := compositeFieldTarget(targetScanner, i) + if err != nil { + return err + } if fieldTarget != nil { fieldPlan := plan.m.PlanScan(scanner.OID(), BinaryFormatCode, fieldTarget) if fieldPlan == nil { return fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), fieldTarget) } - err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) + err = fieldPlan.Scan(scanner.Bytes(), fieldTarget) if err != nil { return err } @@ -96,8 +99,11 @@ func (RecordCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (an return string(src), nil case BinaryFormatCode: scanner := NewCompositeBinaryScanner(m, src) - values := make([]any, scanner.FieldCount()) - for i := 0; scanner.Next(); i++ { + // The field count is a hint for the initial allocation only. Append the + // values actually present rather than indexing into a presized slice, as + // the source may carry more or fewer fields than the header claims. + values := make([]any, 0, scanner.FieldCount()) + for scanner.Next() { var v any fieldPlan := m.PlanScan(scanner.OID(), BinaryFormatCode, &v) if fieldPlan == nil { @@ -109,7 +115,7 @@ func (RecordCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (an return nil, err } - values[i] = v + values = append(values, v) } if err := scanner.Err(); err != nil { diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/text.go b/vendor/github.com/jackc/pgx/v5/pgtype/text.go index e08b12549e..f20cf2a2b4 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/text.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/text.go @@ -186,7 +186,7 @@ func (scanPlanTextAnyToString) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - p := (dst).(*string) + p := dst.(*string) *p = string(src) return nil @@ -195,7 +195,7 @@ func (scanPlanTextAnyToString) Scan(src []byte, dst any) error { type scanPlanAnyToNewByteSlice struct{} func (scanPlanAnyToNewByteSlice) Scan(src []byte, dst any) error { - p := (dst).(*[]byte) + p := dst.(*[]byte) if src == nil { *p = nil } else { @@ -209,14 +209,14 @@ func (scanPlanAnyToNewByteSlice) Scan(src []byte, dst any) error { type scanPlanAnyToByteScanner struct{} func (scanPlanAnyToByteScanner) Scan(src []byte, dst any) error { - p := (dst).(BytesScanner) + p := dst.(BytesScanner) return p.ScanBytes(src) } type scanPlanTextAnyToTextScanner struct{} func (scanPlanTextAnyToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/tid.go b/vendor/github.com/jackc/pgx/v5/pgtype/tid.go index 98d067a652..a572e862d7 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/tid.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/tid.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "strconv" "strings" @@ -152,19 +151,24 @@ func (TIDCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryTIDToTIDScanner struct{} func (scanPlanBinaryTIDToTIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TIDScanner) + scanner := dst.(TIDScanner) if src == nil { return scanner.ScanTID(TID{}) } - if len(src) != 6 { - return fmt.Errorf("invalid length for tid: %v", len(src)) + r := pgio.NewReader(src) + + blockNumber := r.Uint32() + offsetNumber := r.Uint16() + + if err := r.Finish(); err != nil { + return fmt.Errorf("tid: %w", err) } return scanner.ScanTID(TID{ - BlockNumber: binary.BigEndian.Uint32(src), - OffsetNumber: binary.BigEndian.Uint16(src[4:]), + BlockNumber: blockNumber, + OffsetNumber: offsetNumber, Valid: true, }) } @@ -172,18 +176,20 @@ func (scanPlanBinaryTIDToTIDScanner) Scan(src []byte, dst any) error { type scanPlanBinaryTIDToTextScanner struct{} func (scanPlanBinaryTIDToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) } - if len(src) != 6 { - return fmt.Errorf("invalid length for tid: %v", len(src)) - } + r := pgio.NewReader(src) + + blockNumber := r.Uint32() + offsetNumber := r.Uint16() - blockNumber := binary.BigEndian.Uint32(src) - offsetNumber := binary.BigEndian.Uint16(src[4:]) + if err := r.Finish(); err != nil { + return fmt.Errorf("tid: %w", err) + } return scanner.ScanText(Text{ String: fmt.Sprintf(`(%d,%d)`, blockNumber, offsetNumber), @@ -194,7 +200,7 @@ func (scanPlanBinaryTIDToTextScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToTIDScanner struct{} func (scanPlanTextAnyToTIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TIDScanner) + scanner := dst.(TIDScanner) if src == nil { return scanner.ScanTID(TID{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/time.go b/vendor/github.com/jackc/pgx/v5/pgtype/time.go index 72cdb50035..a8c2fdb463 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/time.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/time.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "strconv" @@ -158,17 +157,18 @@ func (TimeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryTimeToTimeScanner struct{} func (scanPlanBinaryTimeToTimeScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimeScanner) + scanner := dst.(TimeScanner) if src == nil { return scanner.ScanTime(Time{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for time: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("time: %w", err) } - usec := int64(binary.BigEndian.Uint64(src)) + usec := int64(raw) return scanner.ScanTime(Time{Microseconds: usec, Valid: true}) } @@ -176,7 +176,7 @@ func (scanPlanBinaryTimeToTimeScanner) Scan(src []byte, dst any) error { type scanPlanBinaryTimeToTextScanner struct{} func (scanPlanBinaryTimeToTextScanner) Scan(src []byte, dst any) error { - ts, ok := (dst).(TextScanner) + ts, ok := dst.(TextScanner) if !ok { return ErrScanTargetTypeChanged } @@ -185,11 +185,12 @@ func (scanPlanBinaryTimeToTextScanner) Scan(src []byte, dst any) error { return ts.ScanText(Text{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for time: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("time: %w", err) } - usec := int64(binary.BigEndian.Uint64(src)) + usec := int64(raw) tim := Time{Microseconds: usec, Valid: true} @@ -204,7 +205,7 @@ func (scanPlanBinaryTimeToTextScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToTimeScanner struct{} func (scanPlanTextAnyToTimeScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimeScanner) + scanner := dst.(TimeScanner) if src == nil { return scanner.ScanTime(Time{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go b/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go index 405c77e96b..33c2b9427f 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go @@ -2,18 +2,16 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" - "strings" "time" + "github.com/jackc/pgx/v5/internal/pgdatetime" "github.com/jackc/pgx/v5/internal/pgio" ) const ( - pgTimestampFormat = "2006-01-02 15:04:05.999999999" - jsonISO8601 = "2006-01-02T15:04:05.999999999" + jsonISO8601 = "2006-01-02T15:04:05.999999999" ) type TimestampScanner interface { @@ -201,33 +199,17 @@ func (encodePlanTimestampCodecText) Encode(value any, buf []byte) (newBuf []byte return nil, nil } - var s string - switch ts.InfinityModifier { case Finite: - t := discardTimeZone(ts.Time) - - // Year 0000 is 1 BC - bc := false - if year := t.Year(); year <= 0 { - year = -year + 1 - t = time.Date(year, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) - bc = true - } - - s = t.Truncate(time.Microsecond).Format(pgTimestampFormat) - - if bc { - s += " BC" - } + // The fields are read in ts.Time's own location, so there is no zone to discard + // and nothing to append after the time. + buf = pgdatetime.AppendTimestamp(buf, ts.Time, "") case Infinity: - s = "infinity" + buf = append(buf, "infinity"...) case NegativeInfinity: - s = "-infinity" + buf = append(buf, "-infinity"...) } - buf = append(buf, s...) - return buf, nil } @@ -257,18 +239,19 @@ func (c *TimestampCodec) PlanScan(m *Map, oid uint32, format int16, target any) type scanPlanBinaryTimestampToTimestampScanner struct{ location *time.Location } func (plan *scanPlanBinaryTimestampToTimestampScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestampScanner) + scanner := dst.(TimestampScanner) if src == nil { return scanner.ScanTimestamp(Timestamp{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for timestamp: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("timestamp: %w", err) } var ts Timestamp - microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) + microsecSinceY2K := int64(raw) switch microsecSinceY2K { case infinityMicrosecondOffset: @@ -280,6 +263,9 @@ func (plan *scanPlanBinaryTimestampToTimestampScanner) Scan(src []byte, dst any) microsecFromUnixEpochToY2K/1_000_000+microsecSinceY2K/1_000_000, (microsecFromUnixEpochToY2K%1_000_000*1_000)+(microsecSinceY2K%1_000_000*1000), ).UTC() + if tim.Before(minDateTime) || !tim.Before(endTimestamp) { + return fmt.Errorf("timestamp %d microseconds from 2000-01-01 is out of range", microsecSinceY2K) + } if plan.location != nil { tim = time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), plan.location) } @@ -292,37 +278,34 @@ func (plan *scanPlanBinaryTimestampToTimestampScanner) Scan(src []byte, dst any) type scanPlanTextTimestampToTimestampScanner struct{ location *time.Location } func (plan *scanPlanTextTimestampToTimestampScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestampScanner) + scanner := dst.(TimestampScanner) if src == nil { return scanner.ScanTimestamp(Timestamp{}) } + dt, err := parseTextDateTime(src) + if err != nil { + return err + } + var ts Timestamp - sbuf := string(src) - switch sbuf { - case "infinity": - ts = Timestamp{Valid: true, InfinityModifier: Infinity} - case "-infinity": - ts = Timestamp{Valid: true, InfinityModifier: -Infinity} - default: - bc := false - if strings.HasSuffix(sbuf, " BC") { - sbuf = sbuf[:len(sbuf)-3] - bc = true + if dt.infinity != Finite { + ts = Timestamp{Valid: true, InfinityModifier: dt.infinity} + } else { + if !dt.hasTime || dt.hasOffset { + return badDateTime(src) } - tim, err := time.Parse(pgTimestampFormat, sbuf) + + tim, err := dt.toTime(src, "timestamp", endTimestamp) if err != nil { return err } - if bc { - year := -tim.Year() + 1 - tim = time.Date(year, tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), tim.Location()) - } - + // timestamp has no time zone, so ScanLocation reinterprets the same wall clock + // reading rather than converting the instant. if plan.location != nil { - tim = time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), plan.location) + tim = dt.in(plan.location) } ts = Timestamp{Time: tim, Valid: true} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go b/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go index 139312a591..f05e384811 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go @@ -2,19 +2,15 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" - "strings" "time" + "github.com/jackc/pgx/v5/internal/pgdatetime" "github.com/jackc/pgx/v5/internal/pgio" ) const ( - pgTimestamptzHourFormat = "2006-01-02 15:04:05.999999999Z07" - pgTimestamptzMinuteFormat = "2006-01-02 15:04:05.999999999Z07:00" - pgTimestamptzSecondFormat = "2006-01-02 15:04:05.999999999Z07:00:00" microsecFromUnixEpochToY2K = 946_684_800 * 1_000_000 ) @@ -199,34 +195,15 @@ func (encodePlanTimestamptzCodecText) Encode(value any, buf []byte) (newBuf []by return nil, nil } - var s string - switch ts.InfinityModifier { case Finite: - - t := ts.Time.UTC().Truncate(time.Microsecond) - - // Year 0000 is 1 BC - bc := false - if year := t.Year(); year <= 0 { - year = -year + 1 - t = time.Date(year, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) - bc = true - } - - s = t.Format(pgTimestamptzSecondFormat) - - if bc { - s += " BC" - } + buf = pgdatetime.AppendTimestamp(buf, ts.Time.UTC(), "Z") case Infinity: - s = "infinity" + buf = append(buf, "infinity"...) case NegativeInfinity: - s = "-infinity" + buf = append(buf, "-infinity"...) } - buf = append(buf, s...) - return buf, nil } @@ -248,18 +225,19 @@ func (c *TimestamptzCodec) PlanScan(m *Map, oid uint32, format int16, target any type scanPlanBinaryTimestamptzToTimestamptzScanner struct{ location *time.Location } func (plan *scanPlanBinaryTimestamptzToTimestamptzScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestamptzScanner) + scanner := dst.(TimestamptzScanner) if src == nil { return scanner.ScanTimestamptz(Timestamptz{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for timestamptz: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("timestamptz: %w", err) } var tstz Timestamptz - microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) + microsecSinceY2K := int64(raw) switch microsecSinceY2K { case infinityMicrosecondOffset: @@ -271,6 +249,9 @@ func (plan *scanPlanBinaryTimestamptzToTimestamptzScanner) Scan(src []byte, dst microsecFromUnixEpochToY2K/1_000_000+microsecSinceY2K/1_000_000, (microsecFromUnixEpochToY2K%1_000_000*1_000)+(microsecSinceY2K%1_000_000*1_000), ) + if tim.Before(minDateTime) || !tim.Before(endTimestamp) { + return fmt.Errorf("timestamptz %d microseconds from 2000-01-01 is out of range", microsecSinceY2K) + } if plan.location != nil { tim = tim.In(plan.location) } @@ -283,51 +264,38 @@ func (plan *scanPlanBinaryTimestamptzToTimestamptzScanner) Scan(src []byte, dst type scanPlanTextTimestamptzToTimestamptzScanner struct{ location *time.Location } func (plan *scanPlanTextTimestamptzToTimestamptzScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestamptzScanner) + scanner := dst.(TimestamptzScanner) if src == nil { return scanner.ScanTimestamptz(Timestamptz{}) } - var tstz Timestamptz - sbuf := string(src) - switch sbuf { - case "infinity": - tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} - case "-infinity": - tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} - default: - bc := false - if strings.HasSuffix(sbuf, " BC") { - sbuf = sbuf[:len(sbuf)-3] - bc = true - } + dt, err := parseTextDateTime(src) + if err != nil { + return err + } - var format string - switch { - case len(sbuf) >= 9 && (sbuf[len(sbuf)-9] == '-' || sbuf[len(sbuf)-9] == '+'): - format = pgTimestamptzSecondFormat - case len(sbuf) >= 6 && (sbuf[len(sbuf)-6] == '-' || sbuf[len(sbuf)-6] == '+'): - format = pgTimestamptzMinuteFormat - default: - format = pgTimestamptzHourFormat + var tstz Timestamptz + if dt.infinity != Finite { + tstz = Timestamptz{Valid: true, InfinityModifier: dt.infinity} + } else { + if !dt.hasTime || !dt.hasOffset { + return badDateTime(src) } - tim, err := time.Parse(format, sbuf) + tim, err := dt.toTime(src, "timestamptz", endTimestamp) if err != nil { return err } - if bc { - year := -tim.Year() + 1 - tim = time.Date(year, tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), tim.Location()) - } - + // The binary path builds its value with time.Unix, which returns time.Local. Match + // it, so that the same value scanned in either format produces the same time.Time. + loc := time.Local if plan.location != nil { - tim = tim.In(plan.location) + loc = plan.location } - tstz = Timestamptz{Time: tim, Valid: true} + tstz = Timestamptz{Time: tim.In(loc), Valid: true} } return scanner.ScanTimestamptz(tstz) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go b/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go index cc7b831671..195481b1d9 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go @@ -1,9 +1,7 @@ package pgtype import ( - "bytes" "database/sql/driver" - "encoding/binary" "fmt" "strconv" "strings" @@ -184,33 +182,20 @@ func (encodePlanTSVectorCodecBinary) Encode(value any, buf []byte) ([]byte, erro type scanPlanBinaryTSVectorToTSVectorScanner struct{} func (scanPlanBinaryTSVectorToTSVectorScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TSVectorScanner) + scanner := dst.(TSVectorScanner) if src == nil { return scanner.ScanTSVector(TSVector{}) } - rp := 0 + r := pgio.NewReader(src) - const ( - uint16Len = 2 - uint32Len = 4 - ) - - if len(src[rp:]) < uint32Len { - return fmt.Errorf("tsvector incomplete %v", src) - } - entryCount := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += uint32Len - - if entryCount < 0 { - return fmt.Errorf("tsvector invalid lexeme count: %d", entryCount) - } - // Each lexeme carries at minimum a 1-byte NUL terminator and a 2-byte position count, so - // entryCount cannot exceed remaining/3. This bounds the up-front make() against a malicious - // server claiming a huge lexeme count in a small message. - if maxEntries := len(src[rp:]) / 3; entryCount > maxEntries { - return fmt.Errorf("tsvector invalid lexeme count %d for %d remaining bytes", entryCount, len(src[rp:])) + // Each lexeme carries at minimum a 1-byte NUL terminator and a 2-byte position count. This + // bounds the up-front make() against a malicious server claiming a huge lexeme count in a + // small message. + entryCount := r.Count(3) + if err := r.Err(); err != nil { + return fmt.Errorf("tsvector: %w", err) } var tsv TSVector @@ -219,41 +204,35 @@ func (scanPlanBinaryTSVectorToTSVectorScanner) Scan(src []byte, dst any) error { } for i := range entryCount { - nullIndex := bytes.IndexByte(src[rp:], 0x00) - if nullIndex == -1 { - return fmt.Errorf("invalid tsvector binary format: missing null terminator") - } - - lexeme := TSVectorLexeme{Word: string(src[rp : rp+nullIndex])} - rp += nullIndex + 1 // skip past null terminator + lexeme := TSVectorLexeme{Word: string(r.CString())} - // Read position count. - if len(src[rp:]) < uint16Len { - return fmt.Errorf("invalid tsvector binary format: incomplete position count") - } - - numPositions := int(binary.BigEndian.Uint16(src[rp:])) - rp += uint16Len - - // Read each packed position: weight (2 bits) | position (14 bits) - if len(src[rp:]) < numPositions*uint16Len { - return fmt.Errorf("invalid tsvector binary format: incomplete positions") + numPositions := int(r.Uint16()) + if err := r.Err(); err != nil { + return fmt.Errorf("invalid tsvector binary format: lexeme %d: %w", i, err) } + // Each packed position is weight (2 bits) | position (14 bits). numPositions came from a + // uint16, so it cannot ask for an unreasonable allocation here. if numPositions > 0 { lexeme.Positions = make([]TSVectorPosition, numPositions) for pos := range numPositions { - packed := binary.BigEndian.Uint16(src[rp:]) - rp += uint16Len + packed := r.Uint16() lexeme.Positions[pos] = TSVectorPosition{ Position: packed & 0x3FFF, Weight: tsvectorWeightFromBinary(packed >> 14), } } + if err := r.Err(); err != nil { + return fmt.Errorf("invalid tsvector binary format: lexeme %d positions: %w", i, err) + } } tsv.Lexemes[i] = lexeme } + + if err := r.Finish(); err != nil { + return fmt.Errorf("tsvector: %w", err) + } tsv.Valid = true return scanner.ScanTSVector(tsv) @@ -318,7 +297,7 @@ func (TSVectorCodec) PlanScan(m *Map, oid uint32, format int16, target any) Scan type scanPlanTextAnyToTSVectorScanner struct{} func (s scanPlanTextAnyToTSVectorScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TSVectorScanner) + scanner := dst.(TSVectorScanner) if src == nil { return scanner.ScanTSVector(TSVector{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go b/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go index e6d4b1cf6e..d6eed52c4c 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" "math" @@ -280,12 +279,13 @@ func (scanPlanBinaryUint32ToUint32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint32: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint32: %w", err) } - p := (dst).(*uint32) - *p = binary.BigEndian.Uint32(src) + p := dst.(*uint32) + *p = raw return nil } @@ -293,7 +293,7 @@ func (scanPlanBinaryUint32ToUint32) Scan(src []byte, dst any) error { type scanPlanBinaryUint32ToUint32Scanner struct{} func (scanPlanBinaryUint32ToUint32Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint32Scanner) + s, ok := dst.(Uint32Scanner) if !ok { return ErrScanTargetTypeChanged } @@ -302,19 +302,18 @@ func (scanPlanBinaryUint32ToUint32Scanner) Scan(src []byte, dst any) error { return s.ScanUint32(Uint32{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint32: %v", len(src)) + n, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint32: %w", err) } - n := binary.BigEndian.Uint32(src) - return s.ScanUint32(Uint32{Uint32: n, Valid: true}) } type scanPlanBinaryUint32ToTextScanner struct{} func (scanPlanBinaryUint32ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) + s, ok := dst.(TextScanner) if !ok { return ErrScanTargetTypeChanged } @@ -323,18 +322,19 @@ func (scanPlanBinaryUint32ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint32: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint32: %w", err) } - n := uint64(binary.BigEndian.Uint32(src)) + n := uint64(raw) return s.ScanText(Text{String: strconv.FormatUint(n, 10), Valid: true}) } type scanPlanTextAnyToUint32Scanner struct{} func (scanPlanTextAnyToUint32Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint32Scanner) + s, ok := dst.(Uint32Scanner) if !ok { return ErrScanTargetTypeChanged } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go b/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go index fc407bdb62..76a2b66f89 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -251,12 +250,13 @@ func (scanPlanBinaryUint64ToUint64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint64: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint64: %w", err) } - p := (dst).(*uint64) - *p = binary.BigEndian.Uint64(src) + p := dst.(*uint64) + *p = raw return nil } @@ -264,7 +264,7 @@ func (scanPlanBinaryUint64ToUint64) Scan(src []byte, dst any) error { type scanPlanBinaryUint64ToUint64Scanner struct{} func (scanPlanBinaryUint64ToUint64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint64Scanner) + s, ok := dst.(Uint64Scanner) if !ok { return ErrScanTargetTypeChanged } @@ -273,19 +273,18 @@ func (scanPlanBinaryUint64ToUint64Scanner) Scan(src []byte, dst any) error { return s.ScanUint64(Uint64{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint64: %v", len(src)) + n, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint64: %w", err) } - n := binary.BigEndian.Uint64(src) - return s.ScanUint64(Uint64{Uint64: n, Valid: true}) } type scanPlanBinaryUint64ToTextScanner struct{} func (scanPlanBinaryUint64ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) + s, ok := dst.(TextScanner) if !ok { return ErrScanTargetTypeChanged } @@ -294,18 +293,18 @@ func (scanPlanBinaryUint64ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint64: %v", len(src)) + n, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint64: %w", err) } - n := binary.BigEndian.Uint64(src) return s.ScanText(Text{String: strconv.FormatUint(n, 10), Valid: true}) } type scanPlanTextAnyToUint64Scanner struct{} func (scanPlanTextAnyToUint64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint64Scanner) + s, ok := dst.(Uint64Scanner) if !ok { return ErrScanTargetTypeChanged } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go b/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go index 476889a8db..725defec0e 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go @@ -211,7 +211,7 @@ func (UUIDCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryUUIDToUUIDScanner struct{} func (scanPlanBinaryUUIDToUUIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(UUIDScanner) + scanner := dst.(UUIDScanner) if src == nil { return scanner.ScanUUID(UUID{}) @@ -230,7 +230,7 @@ func (scanPlanBinaryUUIDToUUIDScanner) Scan(src []byte, dst any) error { type scanPlanBinaryUUIDToTextScanner struct{} func (scanPlanBinaryUUIDToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) @@ -249,7 +249,7 @@ func (scanPlanBinaryUUIDToTextScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToUUIDScanner struct{} func (scanPlanTextAnyToUUIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(UUIDScanner) + scanner := dst.(UUIDScanner) if src == nil { return scanner.ScanUUID(UUID{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/xml.go b/vendor/github.com/jackc/pgx/v5/pgtype/xml.go index 66e6dffdae..7536e2ba7c 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/xml.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/xml.go @@ -104,23 +104,6 @@ func (c *XMLCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPl switch target.(type) { case *string: return scanPlanAnyToString{} - - case **string: - // This is to fix **string scanning. It seems wrong to special case **string, but it's not clear what a better - // solution would be. - // - // https://github.com/jackc/pgx/issues/1470 -- **string - // https://github.com/jackc/pgx/issues/1691 -- ** anything else - - if wrapperPlan, nextDst, ok := TryPointerPointerScanPlan(target); ok { - if nextPlan := m.planScan(oid, format, nextDst, 0); nextPlan != nil { - if _, failed := nextPlan.(*scanPlanFail); !failed { - wrapperPlan.SetNext(nextPlan) - return wrapperPlan - } - } - } - case *[]byte: return scanPlanXMLToByteSlice{} case BytesScanner: @@ -133,6 +116,17 @@ func (c *XMLCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPl return &scanPlanSQLScanner{formatCode: format} } + // Map.planScan only tries the wrap scan plan funcs when the codec returns nil, and the fallback below is never nil. + // So explicitly return nil for a pointer to a pointer to let TryPointerPointerScanPlan handle it. It sets the target + // to nil for SQL NULL and otherwise allocates through any amount of pointer indirection before scanning. + // + // https://github.com/jackc/pgx/issues/1470 -- **string + // https://github.com/jackc/pgx/issues/1691 -- ** anything else + if targetType := reflect.TypeOf(target); targetType != nil && targetType.Kind() == reflect.Pointer && + targetType.Elem().Kind() == reflect.Pointer { + return nil + } + return &scanPlanXMLToXMLUnmarshal{ unmarshal: c.Unmarshal, } diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go b/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go index 5c740b1f2f..bcf7bfef13 100644 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go @@ -22,6 +22,7 @@ var ( defaultMaxConnLifetime = time.Hour defaultMaxConnIdleTime = time.Minute * 30 defaultHealthCheckPeriod = time.Minute + defaultPingTimeout = time.Duration(0) ) type connResource struct { @@ -342,20 +343,22 @@ func NewWithConfig(ctx context.Context, config *Config) (*Pool, error) { // ParseConfig builds a Config from connString. It parses connString with the same behavior as [pgx.ParseConfig] with the // addition of the following variables: // -// - pool_max_conns: integer greater than 0 (default 4) +// - pool_max_conns: integer greater than 0 (default is the greater of 4 or runtime.NumCPU()) // - pool_min_conns: integer 0 or greater (default 0) +// - pool_min_idle_conns: integer 0 or greater (default 0) // - pool_max_conn_lifetime: duration string (default 1 hour) // - pool_max_conn_idle_time: duration string (default 30 minutes) // - pool_health_check_period: duration string (default 1 minute) // - pool_max_conn_lifetime_jitter: duration string (default 0) +// - pool_ping_timeout: duration string (default 0, meaning no timeout) // // See Config for definitions of these arguments. // // # Example Keyword/Value -// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca pool_max_conns=10 pool_max_conn_lifetime=1h30m +// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-full pool_max_conns=10 pool_max_conn_lifetime=1h30m // // # Example URL -// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca&pool_max_conns=10&pool_max_conn_lifetime=1h30m +// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-full&pool_max_conns=10&pool_max_conn_lifetime=1h30m func ParseConfig(connString string) (*Config, error) { connConfig, err := pgx.ParseConfig(connString) if err != nil { @@ -448,6 +451,17 @@ func ParseConfig(connString string) (*Config, error) { config.MaxConnLifetimeJitter = d } + if s, ok := config.ConnConfig.Config.RuntimeParams["pool_ping_timeout"]; ok { + delete(connConfig.Config.RuntimeParams, "pool_ping_timeout") + d, err := time.ParseDuration(s) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_ping_timeout", err) + } + config.PingTimeout = d + } else { + config.PingTimeout = defaultPingTimeout + } + return config, nil } @@ -461,6 +475,9 @@ func (p *Pool) Close() { } func (p *Pool) isExpired(res *puddle.Resource[*connResource]) bool { + if p.maxConnLifetime <= 0 { + return false + } return time.Now().After(res.Value().maxAgeTime) } diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go b/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go index f834b7ec30..842511657f 100644 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go @@ -3,6 +3,7 @@ package pgxpool import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" ) type errRows struct { @@ -18,6 +19,7 @@ func (e errRows) Scan(dest ...any) error { return e.err } func (e errRows) Values() ([]any, error) { return nil, e.err } func (e errRows) RawValues() [][]byte { return nil } func (e errRows) Conn() *pgx.Conn { return nil } +func (e errRows) TypeMap() *pgtype.Map { return nil } type errRow struct { err error @@ -90,6 +92,10 @@ func (rows *poolRows) Conn() *pgx.Conn { return rows.r.Conn() } +func (rows *poolRows) TypeMap() *pgtype.Map { + return rows.r.TypeMap() +} + type poolRow struct { r pgx.Row c *Conn diff --git a/vendor/github.com/jackc/pgx/v5/port-tamer.toml b/vendor/github.com/jackc/pgx/v5/port-tamer.toml new file mode 100644 index 0000000000..2931519583 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/port-tamer.toml @@ -0,0 +1,70 @@ +# port-tamer — this project's TCP port allocation (https://github.com/jackc/port-tamer). +# +# WHY. pgx's test matrix is five PostgreSQL majors plus CockroachDB running at once. In the +# devcontainer every database service sat in the app container's network namespace, so each could +# own a well-known port (5414..5417, 5432, 26257) and a second devcontainer instance was simply a +# second namespace. Natively there is one network stack, and a git worktree is the equivalent of +# that second instance — two checkouts would collide on all six. +# +# port-tamer assigns each checkout one consecutive group of free ports and writes it to a dotenv +# file (.dev/ports.env — gitignored, per-checkout state). mise loads that file, which is how a +# plain shell, process-compose, and ./test.sh all see the same numbers. THIS file is the committed +# declaration of which ports a checkout needs; the allocation itself is not committed. +# +# The devcontainer uses it too. It has its own network namespace and so does not NEED distinct +# ports, but it runs the same per-checkout clusters, so the allocation is the single description +# of where this checkout's servers are, on either platform. +# +# mise run dev:ports show the allocation and whether each port is listening +# mise run dev:ports:ensure allocate on first use; idempotent afterwards +# mise run dev:ports:overwrite deliberately move to a different group (stop services first) +# +# A listening port does NOT move an existing allocation — it may well belong to this checkout's +# own running services. Moving is always the explicit `--overwrite` above. +# +# APPEND new entries at the END. Ports are assigned consecutively in the order below, so inserting +# or reordering renumbers the existing ones — which invalidates every saved allocation and forces +# each checkout to overwrite. Appending is compatible and costs nothing. + +version = 1 + +# The default range (10000..44999) overlaps the ephemeral ports Linux hands out for client sockets +# (32768..60999), so the kernel could occupy a port inside an allocated group while its service is +# down and then break the restart. This range clears both platforms' ephemeral ranges (macOS +# starts at 49152). +[allocation] +minimum = 16000 +maximum = 31000 +bind_address = "127.0.0.1" + +# One PostgreSQL cluster per major (scripts/devdb.rb). All five share one Unix socket directory — +# sockets are named .s.PGSQL., so the port is what distinguishes them, exactly as the +# devcontainer's shared /var/run/postgresql volume worked. +[[ports]] +name = "PGPORT_14" + +[[ports]] +name = "PGPORT_15" + +[[ports]] +name = "PGPORT_16" + +[[ports]] +name = "PGPORT_17" + +[[ports]] +name = "PGPORT_18" + +# CockroachDB (scripts/devcrdb.rb): SQL and the admin HTTP UI. The HTTP port must be allocated +# even though no test uses it — cockroach binds it unconditionally, and letting it pick its own +# default (8080) would collide between checkouts. +[[ports]] +name = "CRDB_PORT" + +[[ports]] +name = "CRDB_HTTP_PORT" + +# process-compose control API. The name is process-compose's own: every `process-compose ...` +# command in this checkout then targets THIS checkout's stack with no flags. +[[ports]] +name = "PC_PORT_NUM" diff --git a/vendor/github.com/jackc/pgx/v5/process-compose.yaml b/vendor/github.com/jackc/pgx/v5/process-compose.yaml new file mode 100644 index 0000000000..8a1b18bf4d --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/process-compose.yaml @@ -0,0 +1,189 @@ +# process-compose — the long-running half of this checkout's development environment. +# +# The division of labour (identical natively and in the devcontainer): +# +# mise one-shot work: bootstrap, ports, initdb, test, format +# process-compose long-running work: the five PostgreSQL servers and CockroachDB +# +# These are exactly the services .devcontainer/docker-compose.yml used to run as containers. They +# now run as ordinary processes against this checkout's own clusters under .dev, so the same +# command set works on macOS, on Linux, and inside the container. +# +# Note what this file does NOT contain: no ports, no resolved paths, no per-process environment +# blocks, no database bootstrap. Ports arrive through the environment (.dev/, exported by the +# launcher — scripts/dev.rb); data directories, binary locations and the socket directory are +# resolved once inside scripts/devdb.rb, so a server and its readiness probe cannot disagree; and +# one-shot work (initdb, creating pgx_test) stays in scripts this file merely sequences. +# +# Two kinds of environment variable ARE read here, both set by scripts/dev.rb and both with a +# default that makes a direct `process-compose up` start only PostgreSQL 18: +# +# PGX_LOGS_DIR DevPaths::LOGS_DIR — the layout belongs to that module, not to ten literals +# PGX_DISABLE_* "true" for an on-demand target, or for a PostgreSQL major whose binaries are +# missing. Disabled processes remain available for `db:start` and lazy tests. +# +# The five servers are identical apart from their major, so pg14 carries the YAML anchors and the +# rest alias them. Anchors are resolved by the YAML parser before process-compose sees the +# document, so a probe threshold or a shutdown signal is now one edit rather than five that can +# drift apart. +# +# mise run dev start PostgreSQL 18 and the supervisor +# mise run dev:all start every database +# mise run db:start pg16 crdb prewarm selected targets +# process-compose process list status, scriptable +# process-compose process logs pg16 logs for one server +# process-compose down stop this checkout's stack only +# +# Each checkout runs its own instance on its own control port (PC_PORT_NUM, from this checkout's +# allocation), which process-compose reads from the environment — so the commands above need no +# flags and never reach another checkout's stack. +version: "0.5" + +# A process whose dependency failed should not be reported as merely skipped, and shutdown should +# unwind in dependency order rather than all at once. +is_strict: true +ordered_shutdown: true + +processes: + # PostgreSQL 14, and the template for 15-18. `serve` initdb's the cluster if this checkout has + # none, then execs the server in the foreground — so a fresh checkout goes straight to + # `mise run dev` with no documented prerequisite step, and process-compose supervises the real + # postmaster. + pg14: &pg + disabled: ${PGX_DISABLE_PG14:-true} + command: ruby scripts/devdb.rb serve 14 + readiness_probe: &pg-probe + exec: + command: ruby scripts/devdb.rb ready 14 + initial_delay_seconds: 1 + period_seconds: 1 + failure_threshold: 30 + # SIGINT is PostgreSQL's fast shutdown: roll back open transactions and exit, rather than + # waiting for clients to disconnect. + shutdown: + signal: 2 + timeout_seconds: 20 + availability: + restart: on_failure + # Bounded: `on_failure` alone retries a PERMANENT error forever (a cluster built by the other + # platform, a corrupt PGDATA), burying the real message under a restart loop. Five attempts + # then stop, so the cause stays on screen. + max_restarts: 5 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg14.log + + # Creates pgx_test with its extensions and its md5/scram/password/cert roles once the server is + # up, then exits. A no-op when the database already exists, so restarting the stack is free. + # + # This is a one-shot, and process-compose does not re-run one when its dependency restarts. + # On-demand starts therefore run the same idempotent setup through scripts/dev_services.rb. + # CockroachDB, whose store is in memory, creates its database from its readiness probe instead. + pg14-setup: &pg-setup + disabled: ${PGX_DISABLE_PG14:-true} + command: ruby scripts/devdb.rb setup 14 + depends_on: + pg14: + condition: process_healthy + availability: + restart: "no" + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg14-setup.log + + pg15: + <<: *pg + disabled: ${PGX_DISABLE_PG15:-true} + command: ruby scripts/devdb.rb serve 15 + readiness_probe: + <<: *pg-probe + exec: + command: ruby scripts/devdb.rb ready 15 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg15.log + + pg15-setup: + <<: *pg-setup + disabled: ${PGX_DISABLE_PG15:-true} + command: ruby scripts/devdb.rb setup 15 + depends_on: + pg15: + condition: process_healthy + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg15-setup.log + + pg16: + <<: *pg + disabled: ${PGX_DISABLE_PG16:-true} + command: ruby scripts/devdb.rb serve 16 + readiness_probe: + <<: *pg-probe + exec: + command: ruby scripts/devdb.rb ready 16 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg16.log + + pg16-setup: + <<: *pg-setup + disabled: ${PGX_DISABLE_PG16:-true} + command: ruby scripts/devdb.rb setup 16 + depends_on: + pg16: + condition: process_healthy + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg16-setup.log + + pg17: + <<: *pg + disabled: ${PGX_DISABLE_PG17:-true} + command: ruby scripts/devdb.rb serve 17 + readiness_probe: + <<: *pg-probe + exec: + command: ruby scripts/devdb.rb ready 17 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg17.log + + pg17-setup: + <<: *pg-setup + disabled: ${PGX_DISABLE_PG17:-true} + command: ruby scripts/devdb.rb setup 17 + depends_on: + pg17: + condition: process_healthy + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg17-setup.log + + pg18: + <<: *pg + disabled: ${PGX_DISABLE_PG18:-false} + command: ruby scripts/devdb.rb serve 18 + readiness_probe: + <<: *pg-probe + exec: + command: ruby scripts/devdb.rb ready 18 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg18.log + + pg18-setup: + <<: *pg-setup + disabled: ${PGX_DISABLE_PG18:-false} + command: ruby scripts/devdb.rb setup 18 + depends_on: + pg18: + condition: process_healthy + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg18-setup.log + + # CockroachDB, the `crdb` test target. Insecure, single-node and entirely in memory — the same + # configuration the cockroachdb/cockroach container ran with. + # + # It has NO setup process, deliberately. The store is in memory, so every restart of this node is + # an empty cluster, and a completed one-shot is not re-run when its dependency restarts: after a + # crash-restart the node reported Ready with no pgx_test in it and `./test.sh crdb` failed every + # test. `devcrdb.rb ready` therefore creates the database itself, which makes the probe true on + # the first start and on every restart alike. + crdb: + disabled: ${PGX_DISABLE_CRDB:-true} + command: ruby scripts/devcrdb.rb serve + readiness_probe: + exec: + command: ruby scripts/devcrdb.rb ready + initial_delay_seconds: 2 + period_seconds: 1 + failure_threshold: 45 + shutdown: + signal: 15 + timeout_seconds: 20 + availability: + restart: on_failure + max_restarts: 5 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/crdb.log diff --git a/vendor/github.com/jackc/pgx/v5/rows.go b/vendor/github.com/jackc/pgx/v5/rows.go index 4e5cf95d05..33332ddbcc 100644 --- a/vendor/github.com/jackc/pgx/v5/rows.go +++ b/vendor/github.com/jackc/pgx/v5/rows.go @@ -54,6 +54,9 @@ type Rows interface { // Scan reads the values from the current row into dest values positionally. dest can include pointers to core types, // values implementing the Scanner interface, and nil. nil will skip the value entirely. It is an error to call Scan // without first calling Next() and checking that it returned true. Rows is automatically closed upon error. + // + // As a special case, if dest is a single value implementing [RowScanner], the whole row is given to its ScanRow + // method instead of being scanned positionally. Scan(dest ...any) error // Values returns the decoded row values. As with Scan(), it is an error to @@ -68,6 +71,11 @@ type Rows interface { // Conn returns the underlying *Conn on which the query was executed. This may return nil if Rows did not come from a // *Conn (e.g. if it was created by RowsFromResultReader) Conn() *Conn + + // TypeMap returns the [pgtype.Map] the values of this Rows are decoded with. It is available even when [Rows.Conn] + // is nil, such as for a Rows created by [RowsFromResultReader]. It may return nil if the Rows carries no values, + // such as one representing only an error. + TypeMap() *pgtype.Map } // Row is a convenience wrapper over [Rows] that is returned by [Conn.QueryRow]. @@ -83,7 +91,21 @@ type Row interface { Scan(dest ...any) error } -// RowScanner scans an entire row at a time into the RowScanner. +// RowScanner scans an entire row at a time into the RowScanner. It is only used when it is the sole destination passed +// to [Rows.Scan] or [Row.Scan]. When passed alongside other destinations it is scanned as an ordinary single value. +// +// ScanRow always takes precedence over the destination's other scanning interfaces, such as +// [pgtype.CompositeIndexScanner]. A type implementing both must therefore dispatch within ScanRow, because the number of +// columns is not known until the row arrives: +// +// func (p *Person) ScanRow(rows pgx.Rows) error { +// if fds := rows.FieldDescriptions(); len(fds) == 1 { +// // Scan the single column via p's pgtype.CompositeIndexScanner implementation. rows.Scan(p) would +// // call ScanRow again. +// return rows.TypeMap().Scan(fds[0].DataTypeOID, fds[0].Format, rows.RawValues()[0], p) +// } +// return rows.Scan(&p.Name, &p.Age) +// } type RowScanner interface { // ScanRows scans the row. ScanRow(rows Rows) error @@ -336,6 +358,10 @@ func (rows *baseRows) RawValues() [][]byte { return rows.values } +func (rows *baseRows) TypeMap() *pgtype.Map { + return rows.typeMap +} + func (rows *baseRows) Conn() *Conn { return rows.conn } @@ -836,6 +862,13 @@ func fieldPosByName(fldDescs []pgconn.FieldDescription, field string, normalize if normalize { field = strings.ReplaceAll(field, "_", "") + } else { + // Explicit db tags can distinguish quoted identifiers that differ only by case. + for i, desc := range fldDescs { + if desc.Name == field { + return i + } + } } for i, desc := range fldDescs { if normalize { @@ -843,7 +876,7 @@ func fieldPosByName(fldDescs []pgconn.FieldDescription, field string, normalize return i } } else { - if desc.Name == field { + if strings.EqualFold(desc.Name, field) { return i } } diff --git a/vendor/github.com/jackc/pgx/v5/stdlib/sql.go b/vendor/github.com/jackc/pgx/v5/stdlib/sql.go index 576d3c60f8..fc8376df6f 100644 --- a/vendor/github.com/jackc/pgx/v5/stdlib/sql.go +++ b/vendor/github.com/jackc/pgx/v5/stdlib/sql.go @@ -57,12 +57,25 @@ // // # PostgreSQL Specific Data Types // -// The pgtype package provides support for PostgreSQL specific types. *pgtype.Map.SQLScanner is an adapter that makes -// these types usable as a sql.Scanner. +// As of Go 1.27, database/sql allows drivers to implement their own scanning logic by implementing the +// driver.RowsColumnScanner interface. This allows PostgreSQL types such as arrays to be scanned directly into Go +// values such as slices. +// +// var a []int64 +// err := db.QueryRow("select '{1,2,3}'::bigint[]").Scan(&a) +// +// In older versions of Go, *pgtype.Map.SQLScanner can be used as an adapter that makes these types usable as a +// sql.Scanner. // // m := pgtype.NewMap() // var a []int64 // err := db.QueryRow("select '{1,2,3}'::bigint[]").Scan(m.SQLScanner(&a)) +// +// The pgtype package provides support for PostgreSQL specific types. These types can be used directly in Go 1.27 and +// with *pgtype.Map.SQLScanner in older Go versions. +// +// var r pgtype.Range[pgtype.Int4] +// err := db.QueryRow("select int4range(1, 5)").Scan(&r) package stdlib import ( @@ -726,7 +739,9 @@ func (r *Rows) Close() error { return r.rows.Err() } -func (r *Rows) Next(dest []driver.Value) error { +// initValueFuncs prepares the database/sql representation of each column. Both +// Next and ScanColumn use these conversions so their driver.Values agree. +func (r *Rows) initValueFuncs() { m := r.conn.conn.TypeMap() fieldDescriptions := r.rows.FieldDescriptions() @@ -857,6 +872,10 @@ func (r *Rows) Next(dest []driver.Value) error { } } } +} + +func (r *Rows) Next(dest []driver.Value) error { + r.initValueFuncs() var more bool if r.skipNext { diff --git a/vendor/github.com/jackc/pgx/v5/stdlib/sql_go1.27.go b/vendor/github.com/jackc/pgx/v5/stdlib/sql_go1.27.go new file mode 100644 index 0000000000..7faac041cc --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/stdlib/sql_go1.27.go @@ -0,0 +1,115 @@ +//go:build go1.27 + +package stdlib + +import ( + "database/sql" + "database/sql/driver" + "errors" + "io" + "reflect" + "time" + + "github.com/jackc/pgx/v5/pgtype" +) + +// Rows implements driver.RowsColumnScanner as of Go 1.27. +var _ driver.RowsColumnScanner = (*Rows)(nil) + +// NextRow implements the driver.RowsColumnScanner interface. It advances to the +// next row of data and returns io.EOF when there are no more rows. +func (r *Rows) NextRow() error { + var more bool + if r.skipNext { + more = r.skipNextMore + r.skipNext = false + } else { + more = r.rows.Next() + } + + if !more { + if err := r.rows.Err(); err != nil { + return err + } + return io.EOF + } + + return nil +} + +// ScanColumn implements the driver.RowsColumnScanner interface. It preserves +// database/sql conversions for scalar destinations and sql.Scanner implementations. +// Other destinations, such as Go slices, pgtype.Array, and pgtype.Range, are +// scanned directly using the pgx type map. +func (r *Rows) ScanColumn(scanCtx driver.ScanContext, index int, dest any) error { + if dest == nil { + return errors.New("destination not a pointer") + } + rv := reflect.ValueOf(dest) + if rv.Kind() == reflect.Pointer && rv.IsNil() { + return errors.New("destination pointer is nil") + } + + src := r.rows.RawValues()[index] + if isSQLScanDestination(rv.Type()) { + var value driver.Value + if src != nil { + r.initValueFuncs() + var err error + value, err = r.valueFuncs[index](src) + if err != nil { + return err + } + } + return sql.ConvertAssign(scanCtx, dest, value) + } + + m := r.conn.conn.TypeMap() + fd := r.rows.FieldDescriptions()[index] + return m.Scan(fd.DataTypeOID, fd.Format, src, dest) +} + +// isSQLScanDestination includes named scalar types and nullable pointers to +// database/sql destinations. Select the conversion before scanning: retrying a +// failed scan could call user code twice or discard its error. +func isSQLScanDestination(t reflect.Type) bool { + var namedPointers map[reflect.Type]bool + for { + if t.Implements(reflect.TypeFor[sql.Scanner]()) { + return true + } + // These interfaces distinguish native byte slices, such as + // FlatArray[byte] and PreallocBytes, from ordinary []byte destinations. + if t.Implements(reflect.TypeFor[pgtype.ArraySetter]()) || t.Implements(reflect.TypeFor[pgtype.BytesScanner]()) { + return false + } + if t.Kind() != reflect.Pointer { + break + } + // Only defined pointer types can form a cycle without reaching a + // non-pointer type. Leave those to pgx's bounded scan planning. + if t.Name() != "" { + if namedPointers[t] { + return false + } + if namedPointers == nil { + namedPointers = make(map[reflect.Type]bool) + } + namedPointers[t] = true + } + t = t.Elem() + } + + switch t.Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64, reflect.String, reflect.Interface: + return true + case reflect.Slice: + return t.Elem().Kind() == reflect.Uint8 + case reflect.Struct: + return t.ConvertibleTo(reflect.TypeFor[time.Time]()) + default: + return false + } +} diff --git a/vendor/github.com/jackc/pgx/v5/test.sh b/vendor/github.com/jackc/pgx/v5/test.sh index 8bab2d280c..254217ea57 100644 --- a/vendor/github.com/jackc/pgx/v5/test.sh +++ b/vendor/github.com/jackc/pgx/v5/test.sh @@ -1,170 +1,35 @@ #!/usr/bin/env bash -set -euo pipefail - -# test.sh - Run pgx tests against specific database targets +# test.sh - Run the pgx test suite against a database target. # -# Usage: -# ./test.sh [target] [go test flags...] +# ./test.sh PostgreSQL 18 (default) +# ./test.sh pg14 PostgreSQL 14 +# ./test.sh crdb CockroachDB +# ./test.sh all every target, sequentially +# ./test.sh pg16 -run TestConnect trailing arguments are passed to `go test` # -# Targets: -# pg14 - PostgreSQL 14 (port 5414) -# pg15 - PostgreSQL 15 (port 5415) -# pg16 - PostgreSQL 16 (port 5416) -# pg17 - PostgreSQL 17 (port 5417) -# pg18 - PostgreSQL 18 (port 5432) [default] -# crdb - CockroachDB (port 26257) -# all - Run against all targets sequentially +# `mise run dev` starts PostgreSQL 18 and the supervisor. Other targets start for a test and stop +# afterwards unless they were explicitly prewarmed with `mise run db:start`. See DEVELOPMENT.md. # -# Examples: -# ./test.sh # Test against PG18 -# ./test.sh pg14 # Test against PG14 -# ./test.sh crdb # Test against CockroachDB -# ./test.sh all # Test against all targets -# ./test.sh pg16 -run TestConnect # Test specific test against PG16 -# ./test.sh pg18 -count=1 -v # Verbose, no cache, PG18 +# The logic lives in scripts/runtests.rb, which builds each target's PGX_TEST_* environment from +# scripts/lib/test_targets.rb — the one place those connection strings are defined. This wrapper +# exists so `./test.sh` keeps working; `mise run test` is equivalent. +set -euo pipefail -# Color output (disabled if not a terminal) -if [ -t 1 ]; then - GREEN='\033[0;32m' - RED='\033[0;31m' - BLUE='\033[0;34m' - NC='\033[0m' +root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +runtests="$root/scripts/runtests.rb" + +# `mise exec` is not only how this wrapper gets the pinned Ruby. It also puts process-compose, Go, +# and CockroachDB on PATH and loads this checkout's .dev/*.env files. Prefer it whenever it is +# available, including when the shell has a new-enough system Ruby but mise has not been activated. +# Invoking it from `mise run test` is harmless: this execs Ruby directly, so there is no task +# recursion. +if command -v mise > /dev/null 2>&1; then + exec mise exec -- ruby "$runtests" "$@" +elif ruby -e 'exit(RUBY_VERSION.split(".")[0].to_i >= 3 ? 0 : 1)' > /dev/null 2>&1; then + exec ruby "$runtests" "$@" else - GREEN='' - RED='' - BLUE='' - NC='' + echo "test.sh: needs Ruby 3.0 or newer (mise.toml pins one)." >&2 + echo " Install mise (https://mise.jdx.dev), then: mise install" >&2 + echo " See DEVELOPMENT.md." >&2 + exit 1 fi - -log_info() { echo -e "${BLUE}==> $*${NC}"; } -log_ok() { echo -e "${GREEN}==> $*${NC}"; } -log_err() { echo -e "${RED}==> $*${NC}" >&2; } - -# Wait for a database to accept connections -wait_for_ready() { - local connstr="$1" - local label="$2" - local max_attempts=30 - local attempt=0 - - log_info "Waiting for $label to be ready..." - while ! psql "$connstr" -c "SELECT 1" > /dev/null 2>&1; do - attempt=$((attempt + 1)) - if [ "$attempt" -ge "$max_attempts" ]; then - log_err "$label did not become ready after $max_attempts attempts" - return 1 - fi - sleep 1 - done - log_ok "$label is ready" -} - -# Directory containing this script (used to locate testsetup/) -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CERTS_DIR="$SCRIPT_DIR/testsetup/certs" - -# Copy client certificates to /tmp for TLS tests -setup_client_certs() { - if [ -d "$CERTS_DIR" ]; then - base64 -d "$CERTS_DIR/ca.pem.b64" > /tmp/ca.pem - base64 -d "$CERTS_DIR/pgx_sslcert.crt.b64" > /tmp/pgx_sslcert.crt - base64 -d "$CERTS_DIR/pgx_sslcert.key.b64" > /tmp/pgx_sslcert.key - fi -} - -# Initialize CockroachDB (create database if not exists) -init_crdb() { - local connstr="postgresql://root@localhost:26257/?sslmode=disable" - wait_for_ready "$connstr" "CockroachDB" - log_info "Ensuring pgx_test database exists on CockroachDB..." - psql "$connstr" -c "CREATE DATABASE IF NOT EXISTS pgx_test" 2>/dev/null || true -} - -# Run tests against a single target -run_tests() { - local target="$1" - shift - local extra_args=("$@") - - local label="" - local port="" - - case "$target" in - pg14) label="PostgreSQL 14"; port=5414 ;; - pg15) label="PostgreSQL 15"; port=5415 ;; - pg16) label="PostgreSQL 16"; port=5416 ;; - pg17) label="PostgreSQL 17"; port=5417 ;; - pg18) label="PostgreSQL 18"; port=5432 ;; - crdb) - label="CockroachDB (port 26257)" - init_crdb - log_info "Testing against $label" - if ! PGX_TEST_DATABASE="postgresql://root@localhost:26257/pgx_test?sslmode=disable&experimental_enable_temp_tables=on" \ - go test -count=1 "${extra_args[@]}" ./...; then - log_err "Tests FAILED against $label" - return 1 - fi - log_ok "Tests passed against $label" - return 0 - ;; - *) - log_err "Unknown target: $target" - log_err "Valid targets: pg14, pg15, pg16, pg17, pg18, crdb, all" - return 1 - ;; - esac - - setup_client_certs - - log_info "Testing against $label (port $port)" - if ! PGX_TEST_DATABASE="host=localhost port=$port user=postgres password=postgres dbname=pgx_test" \ - PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/var/run/postgresql port=$port user=postgres dbname=pgx_test" \ - PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 port=$port user=pgx_md5 password=secret dbname=pgx_test" \ - PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 port=$port user=pgx_md5 password=secret dbname=pgx_test" \ - PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 port=$port user=pgx_scram password=secret dbname=pgx_test channel_binding=disable" \ - PGX_TEST_SCRAM_PLUS_CONN_STRING="host=localhost port=$port user=pgx_ssl password=secret sslmode=verify-full sslrootcert=/tmp/ca.pem dbname=pgx_test channel_binding=require" \ - PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 port=$port user=pgx_pw password=secret dbname=pgx_test" \ - PGX_TEST_TLS_CONN_STRING="host=localhost port=$port user=pgx_ssl password=secret sslmode=verify-full sslrootcert=/tmp/ca.pem dbname=pgx_test channel_binding=disable" \ - PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost port=$port user=pgx_sslcert sslmode=verify-full sslrootcert=/tmp/ca.pem sslcert=/tmp/pgx_sslcert.crt sslkey=/tmp/pgx_sslcert.key dbname=pgx_test" \ - PGX_SSL_PASSWORD=certpw \ - go test -count=1 "${extra_args[@]}" ./...; then - log_err "Tests FAILED against $label" - return 1 - fi - log_ok "Tests passed against $label" -} - -# Main -main() { - local target="${1:-pg18}" - - if [ "$target" = "all" ]; then - shift || true - local targets=(pg14 pg15 pg16 pg17 pg18 crdb) - local failed=() - - for t in "${targets[@]}"; do - echo "" - log_info "==========================================" - log_info "Target: $t" - log_info "==========================================" - if ! run_tests "$t" "$@"; then - failed+=("$t") - log_err "FAILED: $t" - fi - done - - echo "" - if [ ${#failed[@]} -gt 0 ]; then - log_err "Failed targets: ${failed[*]}" - return 1 - else - log_ok "All targets passed" - fi - else - shift || true - run_tests "$target" "$@" - fi -} - -main "$@" diff --git a/vendor/github.com/jackc/pgx/v5/tx.go b/vendor/github.com/jackc/pgx/v5/tx.go index 3f93a6f247..dcb0feb433 100644 --- a/vendor/github.com/jackc/pgx/v5/tx.go +++ b/vendor/github.com/jackc/pgx/v5/tx.go @@ -100,9 +100,12 @@ func (c *Conn) Begin(ctx context.Context) (Tx, error) { func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) { _, err := c.Exec(ctx, txOptions.beginSQL()) if err != nil { - // begin should never fail unless there is an underlying connection issue or - // a context timeout. In either case, the connection is possibly broken. - c.die() + // begin kills the connection upon receiving fatal, panic or non PGError errors, + // but does not otherwise as the connection should be reusable. + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || isConnectionFatal(pgErr) { + c.die() + } return nil, err } @@ -112,6 +115,14 @@ func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) { }, nil } +func isConnectionFatal(pgErr *pgconn.PgError) bool { + severity := pgErr.SeverityUnlocalized + if severity == "" { + severity = pgErr.Severity + } + return severity == "FATAL" || severity == "PANIC" +} + // Tx represents a database transaction. // // Tx is an interface instead of a struct to enable connection pools to be implemented without relying on internal pgx diff --git a/vendor/github.com/jackc/puddle/v2/CHANGELOG.md b/vendor/github.com/jackc/puddle/v2/CHANGELOG.md index d0d202c74a..4af1b03778 100644 --- a/vendor/github.com/jackc/puddle/v2/CHANGELOG.md +++ b/vendor/github.com/jackc/puddle/v2/CHANGELOG.md @@ -1,3 +1,9 @@ +# 2.2.3 (October 5, 2026) + +* Fix: Destroy resources when background construction started by TryAcquire finishes after Close or Reset. + Previously, Close could wait indefinitely and Reset could allow a stale resource to be reused. (bensynapse) +* Replace custom logarithm calculation with math/bits. (Andy Walker) + # 2.2.2 (September 10, 2024) * Add empty acquire time to stats (Maxim Ivanov) diff --git a/vendor/github.com/jackc/puddle/v2/README.md b/vendor/github.com/jackc/puddle/v2/README.md index fa82a9d46f..47d1acfff8 100644 --- a/vendor/github.com/jackc/puddle/v2/README.md +++ b/vendor/github.com/jackc/puddle/v2/README.md @@ -73,7 +73,23 @@ Puddle is stable and feature complete. ## Supported Go Versions -puddle supports the same versions of Go that are supported by the Go project. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases. This means puddle supports Go 1.19 and higher. +puddle supports the same versions of Go that are supported by the Go project: the [two most recent major releases](https://go.dev/doc/devel/release#policy). The minimum Go version declared in `go.mod` is 1.19, which is also tested in CI as a compatibility baseline. + +## Differences with Go sync.Pool + +They are intended for entirely different types of resources: + +* [sync.Pool](https://pkg.go.dev/sync#Pool) would generally be used for in memory objects. +* Puddle would generally be used for handles to external objects such as connections, file handles, etc. + +Specific differences: + +* sync.Pool does not have a way to limit max resources in pool. +* sync.Pool does not have a way to ensure at least min resources in pool. +* sync.Pool can drop resources in pool at any time - not ideal for expensive to create connections. +* sync.Pool does not have a cleanup / release function. Resources are GCed without a chance to close cleanly. +* sync.Pool does not have a way to handle errors creating the resource +* sync.Pool does not support context to limit time to wait creating a resource ## License diff --git a/vendor/github.com/jackc/puddle/v2/log.go b/vendor/github.com/jackc/puddle/v2/log.go deleted file mode 100644 index b21b946305..0000000000 --- a/vendor/github.com/jackc/puddle/v2/log.go +++ /dev/null @@ -1,32 +0,0 @@ -package puddle - -import "unsafe" - -type ints interface { - int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 -} - -// log2Int returns log2 of an integer. This function panics if val < 0. For val -// == 0, returns 0. -func log2Int[T ints](val T) uint8 { - if val <= 0 { - panic("log2 of non-positive number does not exist") - } - - return log2IntRange(val, 0, uint8(8*unsafe.Sizeof(val))) -} - -func log2IntRange[T ints](val T, begin, end uint8) uint8 { - length := end - begin - if length == 1 { - return begin - } - - delim := begin + length/2 - mask := T(1) << delim - if mask > val { - return log2IntRange(val, begin, delim) - } else { - return log2IntRange(val, delim, end) - } -} diff --git a/vendor/github.com/jackc/puddle/v2/mise.toml b/vendor/github.com/jackc/puddle/v2/mise.toml new file mode 100644 index 0000000000..a015672e61 --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/mise.toml @@ -0,0 +1,2 @@ +[tools] +go = "1.27.1" diff --git a/vendor/github.com/jackc/puddle/v2/pool.go b/vendor/github.com/jackc/puddle/v2/pool.go index c411d2f6ef..b3363f18c0 100644 --- a/vendor/github.com/jackc/puddle/v2/pool.go +++ b/vendor/github.com/jackc/puddle/v2/pool.go @@ -3,6 +3,7 @@ package puddle import ( "context" "errors" + "math/bits" "sync" "sync/atomic" "time" @@ -513,6 +514,11 @@ func (p *Pool[T]) TryAcquire(ctx context.Context) (*Resource[T], error) { } res.value = value + if p.closed || res.poolResetCount != p.resetCount { + p.allResources.remove(res) + go p.destructResourceValue(value) + return + } res.status = resourceStatusIdle p.idleResources.Push(res) }() @@ -543,12 +549,14 @@ func (p *Pool[T]) TryAcquire(ctx context.Context) (*Resource[T], error) { // TODO: Replace this with acquireSem.TryAcquireAll() if it gets to // upstream. https://github.com/golang/sync/pull/19 func acquireSemAll(sem *semaphore.Weighted, num int) int { + if num <= 0 { + panic("aquireSemAll: num <= 0") + } if sem.TryAcquire(int64(num)) { return num } - var acquired int - for i := int(log2Int(num)); i >= 0; i-- { + for i := bits.Len64(uint64(num)) - 1; i >= 0; i-- { val := 1 << i if sem.TryAcquire(int64(val)) { acquired += val diff --git a/vendor/github.com/klauspost/compress/README.md b/vendor/github.com/klauspost/compress/README.md index 0e9f170d01..bf31b905f8 100644 --- a/vendor/github.com/klauspost/compress/README.md +++ b/vendor/github.com/klauspost/compress/README.md @@ -6,7 +6,9 @@ This package provides various compression algorithms. * [S2](https://github.com/klauspost/compress/tree/master/s2#s2-compression) is a high performance replacement for Snappy. * Optimized [deflate](https://godoc.org/github.com/klauspost/compress/flate) packages which can be used as a dropin replacement for [gzip](https://godoc.org/github.com/klauspost/compress/gzip), [zip](https://godoc.org/github.com/klauspost/compress/zip) and [zlib](https://godoc.org/github.com/klauspost/compress/zlib). * [snappy](https://github.com/klauspost/compress/tree/master/snappy) is a drop-in replacement for `github.com/golang/snappy` offering better compression and concurrent streams. +* [lzw](https://github.com/klauspost/compress/tree/master/lzw) is a drop-in replacement for `compress/lzw` with 1.4-4x faster decompression and 1.1-2.7x faster compression, depending on the data. * [huff0](https://github.com/klauspost/compress/tree/master/huff0) and [FSE](https://github.com/klauspost/compress/tree/master/fse) implementations for raw entropy encoding. +* [Xpress](https://github.com/klauspost/compress/tree/master/xpress) decompression of the Microsoft XPRESS (MS-XCA) plain LZ77 and LZ77+Huffman formats (the LZ77+Huffman variant is the one used in WIM images and Windows Compact OS / WOF data). * [gzhttp](https://github.com/klauspost/compress/tree/master/gzhttp) Provides client and server wrappers for handling gzipped/zstd HTTP requests efficiently. * [pgzip](https://github.com/klauspost/pgzip) is a separate package that provides a very fast parallel gzip implementation. diff --git a/vendor/github.com/klauspost/compress/flate/deflate.go b/vendor/github.com/klauspost/compress/flate/deflate.go index 57d17eeab9..238b1bcdc3 100644 --- a/vendor/github.com/klauspost/compress/flate/deflate.go +++ b/vendor/github.com/klauspost/compress/flate/deflate.go @@ -95,6 +95,11 @@ type advancedState struct { index int hashMatch [maxMatchLength + minMatchLength]uint32 + // litBits[i] is the number of bits needed to encode window[index:i] + // as literals, where index is the window index at the start of the + // current deflateLazy call. Only allocated when d.chain > 100 (level 9). + litBits []int32 + // Input hash chains // hashHead[hashValue] contains the largest inputIndex with the specified hash value // If hashHead[hashValue] is within the current window, then @@ -260,6 +265,7 @@ func (d *compressor) fillWindow(b []byte) { } // Update window information. d.windowEnd += n + d.blockStart = d.windowEnd s.index = n } @@ -283,7 +289,9 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of minIndex := max(pos-windowSize, 0) offset = 0 - if d.chain < 100 { + // The gain estimate below needs the tables that deflateLazy only + // generates when d.chain > 100, so the conditions must match. + if d.chain <= 100 { for i := prevHead; tries > 0; tries-- { if wEnd == win[i+length] { n := matchLen(win[i:i+minMatchLook], wPos) @@ -311,21 +319,25 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of } // Minimum gain to accept a match. - cGain := 4 + cGain := int32(4) // Some like it higher (CSV), some like it lower (JSON) const baseCost = 3 // Base is 4 bytes at with an additional cost. // Matches must be better than this. + s := d.state + hashPrev := &s.hashPrev + hashOffset := s.hashOffset + litBits := s.litBits[pos : pos+minMatchLook+1] + for i := prevHead; tries > 0; tries-- { if wEnd == win[i+length] { n := matchLen(win[i:i+minMatchLook], wPos) if n > length { // Calculate gain. Estimate - newGain := d.h.bitLengthRaw(wPos[:n]) - int(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int(lengthExtraBits[lengthCodes[(n-3)&255]]) + newGain := litBits[n] - litBits[0] - int32(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int32(lengthExtraBits[lengthCodes[(n-3)&255]]) - //fmt.Println("gain:", newGain, "prev:", cGain, "raw:", d.h.bitLengthRaw(wPos[:n]), "this-len:", n, "prev-len:", length) if newGain > cGain { length = n offset = pos - i @@ -343,7 +355,7 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of // hashPrev[i & windowMask] has already been overwritten, so stop now. break } - i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset + i = int(hashPrev[i&windowMask]) - hashOffset if i < minIndex { break } @@ -427,6 +439,20 @@ func (d *compressor) deflateLazy() { tmp[v]++ } d.h.generate(tmp[:], 15) + + // Compute the cumulative cost of encoding the window as literals, + // so findMatch can look up the cost of any range in constant time. + if s.litBits == nil { + s.litBits = make([]int32, 2*windowSize+1) + } + codes := d.h.codes[:256] + litBits := s.litBits[s.index : d.windowEnd+1] + total := int32(0) + litBits[0] = 0 + for i, v := range d.window[s.index:d.windowEnd] { + total += int32(codes[v].len()) + litBits[i+1] = total + } } s.maxInsertIndex = d.windowEnd - (minMatchLength - 1) diff --git a/vendor/github.com/klauspost/compress/flate/fast_encoder.go b/vendor/github.com/klauspost/compress/flate/fast_encoder.go index 791c9dcbfd..a8cdc5c991 100644 --- a/vendor/github.com/klauspost/compress/flate/fast_encoder.go +++ b/vendor/github.com/klauspost/compress/flate/fast_encoder.go @@ -9,6 +9,7 @@ import ( "fmt" "github.com/klauspost/compress/internal/le" + "github.com/klauspost/compress/internal/regmask" ) type fastEnc interface { @@ -108,7 +109,7 @@ type tableEntryPrev struct { // hash7 returns the hash of the lowest 7 bytes of u to fit in a hash table with h bits. // Preferably h should be a constant and should always be <64. func hash7(u uint64, h uint8) uint32 { - return uint32(((u << (64 - 56)) * prime7bytes) >> ((64 - h) & reg8SizeMask64)) + return uint32(((u << (64 - 56)) * prime7bytes) >> ((64 - h) & regmask.Shift64ByUint8)) } // hashLen returns a hash of the lowest mls bytes of with length output bits. diff --git a/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go b/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go index 7151140ccd..a0c918aeef 100644 --- a/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go +++ b/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go @@ -32,14 +32,12 @@ const ( // bufferFlushSize indicates the buffer size // after which bytes are flushed to the writer. - // Should preferably be a multiple of 6, since - // we accumulate 6 bytes between writes to the buffer. + // Between checks, at most 7 bytes are added to the buffer, + // and writes are done as unconditional 8-byte stores, so the + // buffer must have at least bufferFlushSize+7+8 bytes. bufferFlushSize = 246 ) -// Minimum length code that emits bits. -const lengthExtraBitsMinCode = 8 - // The number of extra bits needed by length code X - LENGTH_CODES_START. var lengthExtraBits = [32]uint8{ /* 257 */ 0, 0, 0, @@ -55,9 +53,6 @@ var lengthBase = [32]uint8{ 64, 80, 96, 112, 128, 160, 192, 224, 255, } -// Minimum offset code that emits bits. -const offsetExtraBitsMinCode = 4 - // offset code word extra bits. var offsetExtraBits = [32]int8{ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, @@ -67,8 +62,24 @@ var offsetExtraBits = [32]int8{ 14, 14, } +// offsetCombined combines the number of extra bits and the base offset +// of each offset code in a single table: extra bits in the low 8 bits, +// and the base offset (already reduced by baseMatchOffset) in the upper bits. +// Entries for the extended window codes 30 and 31 are unused. var offsetCombined = [32]uint32{} +// lengthCombined combines, for each match length (reduced by +// baseMatchLength), the length code (relative to lengthCodesStart) in +// bits 0-4, the number of extra bits in bits 5-7 and the value of the +// extra bits in bits 8-12. +var lengthCombined = func() (t [256]uint32) { + for i := range t { + code := lengthCodes[i] + t[i] = uint32(code) | uint32(lengthExtraBits[code])<<5 | uint32(uint8(i)-lengthBase[code])<<8 + } + return t +}() + func init() { var offsetBase = [32]uint32{ /* normal deflate */ @@ -85,7 +96,7 @@ func init() { for i := range offsetCombined[:] { // Don't use extended window values... - if offsetExtraBits[i] == 0 || offsetBase[i] > 0x006000 { + if offsetBase[i] > 0x006000 { continue } offsetCombined[i] = uint32(offsetExtraBits[i]) | (offsetBase[i] << 8) @@ -115,10 +126,14 @@ type huffmanBitWriter struct { lastHeader int // Set between 0 (reused block can be up to 2x the size) logNewTablePenalty uint - bytes [256 + 8]byte - literalFreq [lengthCodesStart + 32]uint16 - offsetFreq [32]uint16 - codegenFreq [codegenCodeCount]uint16 + + // bytes must hold at least bufferFlushSize+7+8 bytes (see bufferFlushSize). + // Its size is rounded up to a multiple of 8 to keep the following + // fields aligned, which is measurably faster in writeBlockHuff. + bytes [(bufferFlushSize + 7 + 8 + 7) &^ 7]byte + literalFreq [lengthCodesStart + 32]uint16 + offsetFreq [32]uint16 + codegenFreq [codegenCodeCount]uint16 // codegen must have an extra space for the final symbol. codegen [literalCount + offsetCodeCount + 1]uint8 @@ -842,124 +857,75 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) lengths := leCodes[lengthCodesStart:] lengths = lengths[:32] - // Go 1.16 LOVES having these on stack. + // Keeping these on the stack instead of in w is significantly faster. bits, nbits, nbytes := w.bits, w.nbits, w.nbytes - for _, t := range tokens { - if t < 256 { - //w.writeCode(lits[t.literal()]) - c := lits[t] - bits |= c.code64() << (nbits & 63) - nbits += c.len() - if nbits >= 48 { - le.Store64(w.bytes[:], nbytes, bits) - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - } - continue + // Flush whole bytes, so that nbits <= 7 when entering the loop below. + le.Store64(w.bytes[:], nbytes, bits) + nbytes += nbits >> 3 + bits >>= nbits & 56 + nbits &= 7 + if nbytes >= bufferFlushSize { + _, w.err = w.writer.Write(w.bytes[:nbytes]) + nbytes = 0 + if w.err != nil { + return } + } - // Write the length - length := t.length() - lengthCode := lengthCode(length) & 31 - if false { - w.writeCode(lengths[lengthCode]) - } else { - // inlined - c := lengths[lengthCode] + // The loop below flushes whole bytes at the end of every iteration, + // so that nbits <= 7 at the top of every iteration. + // A literal adds at most 15 bits and a match at most + // 15+5+15+13 = 48 bits, so up to three literals or a single match + // can be added to the 64-bit accumulator without an intermediate flush. + // Unconditionally storing 8 bytes and advancing by the number of + // whole bytes avoids a poorly predicted branch per token. + for i := 0; i < len(tokens); i++ { + t := tokens[i] + if t < 256 { + c := lits[t] bits |= c.code64() << (nbits & 63) nbits += c.len() - if nbits >= 48 { - le.Store64(w.bytes[:], nbytes, bits) - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - } - } - - if lengthCode >= lengthExtraBitsMinCode { - extraLengthBits := lengthExtraBits[lengthCode] - //w.writeBits(extraLength, extraLengthBits) - extraLength := int32(length - lengthBase[lengthCode]) - bits |= uint64(extraLength) << (nbits & 63) - nbits += extraLengthBits - if nbits >= 48 { - le.Store64(w.bytes[:], nbytes, bits) - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 + // Add up to two more literals before flushing. + if i+1 < len(tokens) && tokens[i+1] < 256 { + i++ + c := lits[tokens[i]] + bits |= c.code64() << (nbits & 63) + nbits += c.len() + if i+1 < len(tokens) && tokens[i+1] < 256 { + i++ + c := lits[tokens[i]] + bits |= c.code64() << (nbits & 63) + nbits += c.len() } } - } - // Write the offset - offset := t.offset() - offsetCode := (offset >> 16) & 31 - if false { - w.writeCode(offs[offsetCode]) } else { - // inlined - c := offs[offsetCode] - bits |= c.code64() << (nbits & 63) - nbits += c.len() - if nbits >= 48 { - le.Store64(w.bytes[:], nbytes, bits) - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - } + // Write the length code and its extra bits as one unit. + lc := lengthCombined[t.length()] + c := lengths[lc&31] + bits |= (c.code64() | uint64(lc>>8)<<(c.len()&63)) << (nbits & 63) + nbits += c.len() + uint8(lc>>5)&7 + + // Write the offset code and its extra bits as one unit. + offset := t.offset() + offCode := (offset >> 16) & 31 + c = offs[offCode] + offComb := offsetCombined[offCode] + extra := (offset - (offComb >> 8)) & matchOffsetOnlyMask + bits |= (c.code64() | uint64(extra)<<(c.len()&63)) << (nbits & 63) + nbits += c.len() + uint8(offComb) } - - if offsetCode >= offsetExtraBitsMinCode { - offsetComb := offsetCombined[offsetCode] - //w.writeBits(extraOffset, extraOffsetBits) - bits |= uint64((offset-(offsetComb>>8))&matchOffsetOnlyMask) << (nbits & 63) - nbits += uint8(offsetComb) - if nbits >= 48 { - le.Store64(w.bytes[:], nbytes, bits) - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } + le.Store64(w.bytes[:], nbytes, bits) + nbytes += nbits >> 3 + bits >>= nbits & 56 + nbits &= 7 + if nbytes >= bufferFlushSize { + if w.err != nil { + nbytes = 0 + return } + _, w.err = w.writer.Write(w.bytes[:nbytes]) + nbytes = 0 } } // Restore... @@ -1094,8 +1060,8 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) { if debugDeflate { count -= int(nbytes)*8 + int(nbits) } - // Unroll, write 3 codes/loop. - // Fastest number of unrolls. + // Write 3 codes per iteration. The three codes are combined first, + // independently of the accumulator, and merged with a single shift. for len(input) > 3 { // We must have at least 48 bits free. if nbits >= 8 { @@ -1116,13 +1082,13 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) { _, w.err = w.writer.Write(w.bytes[:nbytes]) nbytes = 0 } - a, b := encoding[input[0]], encoding[input[1]] - bits |= a.code64() << (nbits & 63) - bits |= b.code64() << ((nbits + a.len()) & 63) - c := encoding[input[2]] - nbits += b.len() + a.len() - bits |= c.code64() << (nbits & 63) - nbits += c.len() + a, b, c := encoding[input[0]], encoding[input[1]], encoding[input[2]] + v := a.code64() | b.code64()<<(a.len()&63) + n := a.len() + b.len() + v |= c.code64() << (n & 63) + n += c.len() + bits |= v << (nbits & 63) + nbits += n input = input[3:] } diff --git a/vendor/github.com/klauspost/compress/flate/huffman_code.go b/vendor/github.com/klauspost/compress/flate/huffman_code.go index 4b312dea3e..6082bee364 100644 --- a/vendor/github.com/klauspost/compress/flate/huffman_code.go +++ b/vendor/github.com/klauspost/compress/flate/huffman_code.go @@ -38,6 +38,9 @@ type huffmanEncoder struct { // Possible lengths are codegenCodeCount, offsetCodeCount and literalCount. // The largest of these is literalCount, so we allocate for that case. freqcache [literalCount + 1]literalNode + + // sortcache is scratch space for sortByFreq. + sortcache [literalCount + 1]literalNode } type literalNode struct { @@ -139,14 +142,6 @@ func (h *huffmanEncoder) bitLength(freq []uint16) int { return total } -func (h *huffmanEncoder) bitLengthRaw(b []byte) int { - var total int - for _, f := range b { - total += int(h.codes[f].len()) - } - return total -} - // canReuseBits returns the number of bits or math.MaxInt32 if the encoder cannot be reused. func (h *huffmanEncoder) canReuseBits(freq []uint16) int { var total int @@ -309,27 +304,93 @@ func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 { } // Look at the leaves and assign them a bit count and an encoding as specified -// in RFC 1951 3.2.2 -func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) { - code := uint16(0) +// in RFC 1951 3.2.2. +// list must be sorted by increasing frequency and codes must have +// all entries for literals not in list set to zero. +func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode, codes []hcode) { + // The literals list[len(list)-bits] .. list[len(list)-1] + // are encoded using "bits" bits. Record the length of each literal + // temporarily in codes. for n, bits := range bitCount { - code <<= 1 if n == 0 || bits == 0 { continue } - // The literals list[len(list)-bits] .. list[len(list)-bits] - // are encoded using "bits" bits, and get the values - // code, code + 1, .... The code values are - // assigned in literal order (not frequency order). - chunk := list[len(list)-int(bits):] - - sortByLiteral(chunk) - for _, node := range chunk { - h.codes[node.literal] = newhcode(reverseBits(code, uint8(n)), uint8(n)) - code++ + for _, node := range list[len(list)-int(bits):] { + codes[node.literal] = hcode(n) } list = list[0 : len(list)-int(bits)] } + + // Code values are assigned in literal order (not frequency order) + // within each code length, starting from the first code of each length. + var nextCode [maxBitsLimit]uint16 + code := uint16(0) + for n := 1; n < len(bitCount); n++ { + code = (code + uint16(bitCount[n-1])) << 1 + nextCode[n] = code + } + for i, c := range codes { + if c == 0 { + continue + } + // n is at most maxBitsLimit-1; the mask only elides bounds checks. + n := uint8(c) + codes[i] = newhcode(reverseBits(nextCode[n&15], n), n) + nextCode[n&15]++ + } +} + +// sortByFreq sorts list by increasing frequency. +// The sort is stable, so nodes with equal frequencies keep their order. +func (h *huffmanEncoder) sortByFreq(list []literalNode) { + if len(list) <= 32 { + // Insertion sort is faster for small lists. + for i := 1; i < len(list); i++ { + n := list[i] + j := i + for ; j > 0 && list[j-1].freq > n.freq; j-- { + list[j] = list[j-1] + } + list[j] = n + } + return + } + + // Counting sort on the low byte and then on the high byte + // of the frequency. Both passes are stable. + tmp := h.sortcache[:len(list)] + var count [256]uint16 + var maxFreq uint16 + for _, n := range list { + count[n.freq&0xff]++ + maxFreq |= n.freq + } + var pos uint16 + for i, c := range count { + count[i] = pos + pos += c + } + for _, n := range list { + tmp[count[n.freq&0xff]] = n + count[n.freq&0xff]++ + } + if maxFreq < 256 { + copy(list, tmp) + return + } + count = [256]uint16{} + for _, n := range tmp { + count[n.freq>>8]++ + } + pos = 0 + for i, c := range count { + count[i] = pos + pos += c + } + for _, n := range tmp { + list[count[n.freq>>8]] = n + count[n.freq>>8]++ + } } // Update this Huffman Code object to be the minimum code for the specified frequency count. @@ -362,12 +423,14 @@ func (h *huffmanEncoder) generate(freq []uint16, maxBits int32) { } return } - sortByFreq(list) + // list is in order of increasing literal value, so a stable sort + // by frequency orders it by (frequency, literal). + h.sortByFreq(list) // Get the number of literals for each bit count bitCount := h.bitCounts(list, maxBits) // And do the assignment - h.assignEncodingAndSize(bitCount, list) + h.assignEncodingAndSize(bitCount, list, codes) } // atLeastOne clamps the result between 1 and 15. @@ -394,24 +457,27 @@ func histogram(b []byte, h []uint16) { } func histogramSplit(b []byte, h []uint16) { - // Tested, and slightly faster than 2-way. - // Writing to separate arrays and combining is also slightly slower. - h = h[:256] + // Walk four quarters in parallel, each into its own table. + // Tested to be faster than walking halves. Using separate tables + // avoids the load/store dependencies that arise when two of the + // streams hit the same byte value, which is common for text. + var h0, h1, h2, h3 [256]uint16 + // Make size divisible by 4 for len(b)&3 != 0 { - h[b[0]]++ + h0[b[0]]++ b = b[1:] } n := len(b) / 4 x, y, z, w := b[:n], b[n:], b[n+n:], b[n+n+n:] y, z, w = y[:len(x)], z[:len(x)], w[:len(x)] for i, t := range x { - v0 := &h[t] - v1 := &h[y[i]] - v2 := &h[z[i]] - v3 := &h[w[i]] - *v0++ - *v1++ - *v2++ - *v3++ + h0[t]++ + h1[y[i]]++ + h2[z[i]]++ + h3[w[i]]++ + } + h = h[:256] + for i := range h { + h[i] += h0[i] + h1[i] + h2[i] + h3[i] } } diff --git a/vendor/github.com/klauspost/compress/flate/huffman_sortByFreq.go b/vendor/github.com/klauspost/compress/flate/huffman_sortByFreq.go deleted file mode 100644 index 6c05ba8c1c..0000000000 --- a/vendor/github.com/klauspost/compress/flate/huffman_sortByFreq.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2009 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 flate - -// Sort sorts data. -// It makes one call to data.Len to determine n, and O(n*log(n)) calls to -// data.Less and data.Swap. The sort is not guaranteed to be stable. -func sortByFreq(data []literalNode) { - n := len(data) - quickSortByFreq(data, 0, n, maxDepth(n)) -} - -func quickSortByFreq(data []literalNode, a, b, maxDepth int) { - for b-a > 12 { // Use ShellSort for slices <= 12 elements - if maxDepth == 0 { - heapSort(data, a, b) - return - } - maxDepth-- - mlo, mhi := doPivotByFreq(data, a, b) - // Avoiding recursion on the larger subproblem guarantees - // a stack depth of at most lg(b-a). - if mlo-a < b-mhi { - quickSortByFreq(data, a, mlo, maxDepth) - a = mhi // i.e., quickSortByFreq(data, mhi, b) - } else { - quickSortByFreq(data, mhi, b, maxDepth) - b = mlo // i.e., quickSortByFreq(data, a, mlo) - } - } - if b-a > 1 { - // Do ShellSort pass with gap 6 - // It could be written in this simplified form cause b-a <= 12 - for i := a + 6; i < b; i++ { - if data[i].freq == data[i-6].freq && data[i].literal < data[i-6].literal || data[i].freq < data[i-6].freq { - data[i], data[i-6] = data[i-6], data[i] - } - } - insertionSortByFreq(data, a, b) - } -} - -func doPivotByFreq(data []literalNode, lo, hi int) (midlo, midhi int) { - m := int(uint(lo+hi) >> 1) // Written like this to avoid integer overflow. - if hi-lo > 40 { - // Tukey's ``Ninther,'' median of three medians of three. - s := (hi - lo) / 8 - medianOfThreeSortByFreq(data, lo, lo+s, lo+2*s) - medianOfThreeSortByFreq(data, m, m-s, m+s) - medianOfThreeSortByFreq(data, hi-1, hi-1-s, hi-1-2*s) - } - medianOfThreeSortByFreq(data, lo, m, hi-1) - - // Invariants are: - // data[lo] = pivot (set up by ChoosePivot) - // data[lo < i < a] < pivot - // data[a <= i < b] <= pivot - // data[b <= i < c] unexamined - // data[c <= i < hi-1] > pivot - // data[hi-1] >= pivot - pivot := lo - a, c := lo+1, hi-1 - - for ; a < c && (data[a].freq == data[pivot].freq && data[a].literal < data[pivot].literal || data[a].freq < data[pivot].freq); a++ { - } - b := a - for { - for ; b < c && (data[pivot].freq == data[b].freq && data[pivot].literal > data[b].literal || data[pivot].freq > data[b].freq); b++ { // data[b] <= pivot - } - for ; b < c && (data[pivot].freq == data[c-1].freq && data[pivot].literal < data[c-1].literal || data[pivot].freq < data[c-1].freq); c-- { // data[c-1] > pivot - } - if b >= c { - break - } - // data[b] > pivot; data[c-1] <= pivot - data[b], data[c-1] = data[c-1], data[b] - b++ - c-- - } - // If hi-c<3 then there are duplicates (by property of median of nine). - // Let's be a bit more conservative, and set border to 5. - protect := hi-c < 5 - if !protect && hi-c < (hi-lo)/4 { - // Lets test some points for equality to pivot - dups := 0 - if data[pivot].freq == data[hi-1].freq && data[pivot].literal > data[hi-1].literal || data[pivot].freq > data[hi-1].freq { // data[hi-1] = pivot - data[c], data[hi-1] = data[hi-1], data[c] - c++ - dups++ - } - if data[b-1].freq == data[pivot].freq && data[b-1].literal > data[pivot].literal || data[b-1].freq > data[pivot].freq { // data[b-1] = pivot - b-- - dups++ - } - // m-lo = (hi-lo)/2 > 6 - // b-lo > (hi-lo)*3/4-1 > 8 - // ==> m < b ==> data[m] <= pivot - if data[m].freq == data[pivot].freq && data[m].literal > data[pivot].literal || data[m].freq > data[pivot].freq { // data[m] = pivot - data[m], data[b-1] = data[b-1], data[m] - b-- - dups++ - } - // if at least 2 points are equal to pivot, assume skewed distribution - protect = dups > 1 - } - if protect { - // Protect against a lot of duplicates - // Add invariant: - // data[a <= i < b] unexamined - // data[b <= i < c] = pivot - for { - for ; a < b && (data[b-1].freq == data[pivot].freq && data[b-1].literal > data[pivot].literal || data[b-1].freq > data[pivot].freq); b-- { // data[b] == pivot - } - for ; a < b && (data[a].freq == data[pivot].freq && data[a].literal < data[pivot].literal || data[a].freq < data[pivot].freq); a++ { // data[a] < pivot - } - if a >= b { - break - } - // data[a] == pivot; data[b-1] < pivot - data[a], data[b-1] = data[b-1], data[a] - a++ - b-- - } - } - // Swap pivot into middle - data[pivot], data[b-1] = data[b-1], data[pivot] - return b - 1, c -} - -// Insertion sort -func insertionSortByFreq(data []literalNode, a, b int) { - for i := a + 1; i < b; i++ { - for j := i; j > a && (data[j].freq == data[j-1].freq && data[j].literal < data[j-1].literal || data[j].freq < data[j-1].freq); j-- { - data[j], data[j-1] = data[j-1], data[j] - } - } -} - -// quickSortByFreq, loosely following Bentley and McIlroy, -// ``Engineering a Sort Function,'' SP&E November 1993. - -// medianOfThreeSortByFreq moves the median of the three values data[m0], data[m1], data[m2] into data[m1]. -func medianOfThreeSortByFreq(data []literalNode, m1, m0, m2 int) { - // sort 3 elements - if data[m1].freq == data[m0].freq && data[m1].literal < data[m0].literal || data[m1].freq < data[m0].freq { - data[m1], data[m0] = data[m0], data[m1] - } - // data[m0] <= data[m1] - if data[m2].freq == data[m1].freq && data[m2].literal < data[m1].literal || data[m2].freq < data[m1].freq { - data[m2], data[m1] = data[m1], data[m2] - // data[m0] <= data[m2] && data[m1] < data[m2] - if data[m1].freq == data[m0].freq && data[m1].literal < data[m0].literal || data[m1].freq < data[m0].freq { - data[m1], data[m0] = data[m0], data[m1] - } - } - // now data[m0] <= data[m1] <= data[m2] -} diff --git a/vendor/github.com/klauspost/compress/flate/huffman_sortByLiteral.go b/vendor/github.com/klauspost/compress/flate/huffman_sortByLiteral.go deleted file mode 100644 index 93f1aea109..0000000000 --- a/vendor/github.com/klauspost/compress/flate/huffman_sortByLiteral.go +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright 2009 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 flate - -// Sort sorts data. -// It makes one call to data.Len to determine n, and O(n*log(n)) calls to -// data.Less and data.Swap. The sort is not guaranteed to be stable. -func sortByLiteral(data []literalNode) { - n := len(data) - quickSort(data, 0, n, maxDepth(n)) -} - -func quickSort(data []literalNode, a, b, maxDepth int) { - for b-a > 12 { // Use ShellSort for slices <= 12 elements - if maxDepth == 0 { - heapSort(data, a, b) - return - } - maxDepth-- - mlo, mhi := doPivot(data, a, b) - // Avoiding recursion on the larger subproblem guarantees - // a stack depth of at most lg(b-a). - if mlo-a < b-mhi { - quickSort(data, a, mlo, maxDepth) - a = mhi // i.e., quickSort(data, mhi, b) - } else { - quickSort(data, mhi, b, maxDepth) - b = mlo // i.e., quickSort(data, a, mlo) - } - } - if b-a > 1 { - // Do ShellSort pass with gap 6 - // It could be written in this simplified form cause b-a <= 12 - for i := a + 6; i < b; i++ { - if data[i].literal < data[i-6].literal { - data[i], data[i-6] = data[i-6], data[i] - } - } - insertionSort(data, a, b) - } -} -func heapSort(data []literalNode, a, b int) { - first := a - lo := 0 - hi := b - a - - // Build heap with greatest element at top. - for i := (hi - 1) / 2; i >= 0; i-- { - siftDown(data, i, hi, first) - } - - // Pop elements, largest first, into end of data. - for i := hi - 1; i >= 0; i-- { - data[first], data[first+i] = data[first+i], data[first] - siftDown(data, lo, i, first) - } -} - -// siftDown implements the heap property on data[lo, hi). -// first is an offset into the array where the root of the heap lies. -func siftDown(data []literalNode, lo, hi, first int) { - root := lo - for { - child := 2*root + 1 - if child >= hi { - break - } - if child+1 < hi && data[first+child].literal < data[first+child+1].literal { - child++ - } - if data[first+root].literal > data[first+child].literal { - return - } - data[first+root], data[first+child] = data[first+child], data[first+root] - root = child - } -} -func doPivot(data []literalNode, lo, hi int) (midlo, midhi int) { - m := int(uint(lo+hi) >> 1) // Written like this to avoid integer overflow. - if hi-lo > 40 { - // Tukey's ``Ninther,'' median of three medians of three. - s := (hi - lo) / 8 - medianOfThree(data, lo, lo+s, lo+2*s) - medianOfThree(data, m, m-s, m+s) - medianOfThree(data, hi-1, hi-1-s, hi-1-2*s) - } - medianOfThree(data, lo, m, hi-1) - - // Invariants are: - // data[lo] = pivot (set up by ChoosePivot) - // data[lo < i < a] < pivot - // data[a <= i < b] <= pivot - // data[b <= i < c] unexamined - // data[c <= i < hi-1] > pivot - // data[hi-1] >= pivot - pivot := lo - a, c := lo+1, hi-1 - - for ; a < c && data[a].literal < data[pivot].literal; a++ { - } - b := a - for { - for ; b < c && data[pivot].literal > data[b].literal; b++ { // data[b] <= pivot - } - for ; b < c && data[pivot].literal < data[c-1].literal; c-- { // data[c-1] > pivot - } - if b >= c { - break - } - // data[b] > pivot; data[c-1] <= pivot - data[b], data[c-1] = data[c-1], data[b] - b++ - c-- - } - // If hi-c<3 then there are duplicates (by property of median of nine). - // Let's be a bit more conservative, and set border to 5. - protect := hi-c < 5 - if !protect && hi-c < (hi-lo)/4 { - // Lets test some points for equality to pivot - dups := 0 - if data[pivot].literal > data[hi-1].literal { // data[hi-1] = pivot - data[c], data[hi-1] = data[hi-1], data[c] - c++ - dups++ - } - if data[b-1].literal > data[pivot].literal { // data[b-1] = pivot - b-- - dups++ - } - // m-lo = (hi-lo)/2 > 6 - // b-lo > (hi-lo)*3/4-1 > 8 - // ==> m < b ==> data[m] <= pivot - if data[m].literal > data[pivot].literal { // data[m] = pivot - data[m], data[b-1] = data[b-1], data[m] - b-- - dups++ - } - // if at least 2 points are equal to pivot, assume skewed distribution - protect = dups > 1 - } - if protect { - // Protect against a lot of duplicates - // Add invariant: - // data[a <= i < b] unexamined - // data[b <= i < c] = pivot - for { - for ; a < b && data[b-1].literal > data[pivot].literal; b-- { // data[b] == pivot - } - for ; a < b && data[a].literal < data[pivot].literal; a++ { // data[a] < pivot - } - if a >= b { - break - } - // data[a] == pivot; data[b-1] < pivot - data[a], data[b-1] = data[b-1], data[a] - a++ - b-- - } - } - // Swap pivot into middle - data[pivot], data[b-1] = data[b-1], data[pivot] - return b - 1, c -} - -// Insertion sort -func insertionSort(data []literalNode, a, b int) { - for i := a + 1; i < b; i++ { - for j := i; j > a && data[j].literal < data[j-1].literal; j-- { - data[j], data[j-1] = data[j-1], data[j] - } - } -} - -// maxDepth returns a threshold at which quicksort should switch -// to heapsort. It returns 2*ceil(lg(n+1)). -func maxDepth(n int) int { - var depth int - for i := n; i > 0; i >>= 1 { - depth++ - } - return depth * 2 -} - -// medianOfThree moves the median of the three values data[m0], data[m1], data[m2] into data[m1]. -func medianOfThree(data []literalNode, m1, m0, m2 int) { - // sort 3 elements - if data[m1].literal < data[m0].literal { - data[m1], data[m0] = data[m0], data[m1] - } - // data[m0] <= data[m1] - if data[m2].literal < data[m1].literal { - data[m2], data[m1] = data[m1], data[m2] - // data[m0] <= data[m2] && data[m1] < data[m2] - if data[m1].literal < data[m0].literal { - data[m1], data[m0] = data[m0], data[m1] - } - } - // now data[m0] <= data[m1] <= data[m2] -} diff --git a/vendor/github.com/klauspost/compress/flate/inflate.go b/vendor/github.com/klauspost/compress/flate/inflate.go index 39dd683b2d..ad0ad3e22b 100644 --- a/vendor/github.com/klauspost/compress/flate/inflate.go +++ b/vendor/github.com/klauspost/compress/flate/inflate.go @@ -14,6 +14,8 @@ import ( "io" "math/bits" "sync" + + "github.com/klauspost/compress/internal/regmask" ) const ( @@ -557,8 +559,8 @@ func (f *decompressor) readHuffman() error { return err } } - rep += int(f.b & uint32(1<<(nb®SizeMaskUint32)-1)) - f.b >>= nb & regSizeMaskUint32 + rep += int(f.b & uint32(1<<(nb®mask.Shift32ByUint)-1)) + f.b >>= nb & regmask.Shift32ByUint f.nb -= nb if i+rep > n { if debugDecode { @@ -731,7 +733,7 @@ func (f *decompressor) moreBits() error { return noEOF(err) } f.roffset++ - f.b |= uint32(c) << (f.nb & regSizeMaskUint32) + f.b |= uint32(c) << (f.nb & regmask.Shift32ByUint) f.nb += 8 return nil } @@ -756,7 +758,7 @@ func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) { return 0, noEOF(err) } f.roffset++ - b |= uint32(c) << (nb & regSizeMaskUint32) + b |= uint32(c) << (nb & regmask.Shift32ByUint) nb += 8 } chunk := h.chunks[b&(huffmanNumChunks-1)] @@ -775,7 +777,7 @@ func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) { f.err = CorruptInputError(f.roffset) return 0, f.err } - f.b = b >> (n & regSizeMaskUint32) + f.b = b >> (n & regmask.Shift32ByUint) f.nb = nb - n return int(chunk >> huffmanValueShift), nil } diff --git a/vendor/github.com/klauspost/compress/flate/inflate_gen.go b/vendor/github.com/klauspost/compress/flate/inflate_gen.go index e80f196560..55539156a7 100644 --- a/vendor/github.com/klauspost/compress/flate/inflate_gen.go +++ b/vendor/github.com/klauspost/compress/flate/inflate_gen.go @@ -8,6 +8,8 @@ import ( "fmt" "math/bits" "strings" + + "github.com/klauspost/compress/internal/regmask" ) func peekBufio(fr *bufio.Reader) ([]byte, error) { @@ -62,7 +64,7 @@ readLiteral: return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] @@ -80,7 +82,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n v = int(chunk >> huffmanValueShift) break @@ -118,15 +120,15 @@ readLiteral: if debugDecode { fmt.Println("morebits n>0:", err) } - f.err = err + f.err = noEOF(err) return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 + fb >>= n & regmask.Shift32ByUint fnb -= n default: if debugDecode { @@ -146,11 +148,11 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb<5:", err) } - f.err = err + f.err = noEOF(err) return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) @@ -174,7 +176,7 @@ readLiteral: return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] @@ -192,7 +194,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n dist = uint32(chunk >> huffmanValueShift) break @@ -206,7 +208,7 @@ readLiteral: case dist < maxNumDist: nb := uint(dist-2) >> 1 // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) + extra := (dist & 1) << (nb & regmask.Shift32ByUint) for fnb < nb { c, err := fr.ReadByte() if err != nil { @@ -214,17 +216,17 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 + fb >>= nb & regmask.Shift32ByUint fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra + dist = 1<<((nb+1)®mask.Shift32ByUint) + 1 + extra // slower: dist = bitMask32[nb+1] + 2 + extra default: f.b, f.nb = fb, fnb @@ -313,7 +315,7 @@ readLiteral: return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] @@ -331,7 +333,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n v = int(chunk >> huffmanValueShift) break @@ -369,15 +371,15 @@ readLiteral: if debugDecode { fmt.Println("morebits n>0:", err) } - f.err = err + f.err = noEOF(err) return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 + fb >>= n & regmask.Shift32ByUint fnb -= n default: if debugDecode { @@ -397,11 +399,11 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb<5:", err) } - f.err = err + f.err = noEOF(err) return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) @@ -425,7 +427,7 @@ readLiteral: return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] @@ -443,7 +445,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n dist = uint32(chunk >> huffmanValueShift) break @@ -457,7 +459,7 @@ readLiteral: case dist < maxNumDist: nb := uint(dist-2) >> 1 // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) + extra := (dist & 1) << (nb & regmask.Shift32ByUint) for fnb < nb { c, err := fr.ReadByte() if err != nil { @@ -465,17 +467,17 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 + fb >>= nb & regmask.Shift32ByUint fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra + dist = 1<<((nb+1)®mask.Shift32ByUint) + 1 + extra // slower: dist = bitMask32[nb+1] + 2 + extra default: f.b, f.nb = fb, fnb @@ -573,7 +575,7 @@ readLiteral: c := pbuf[pos] pos++ f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] @@ -592,7 +594,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n v = int(chunk >> huffmanValueShift) break @@ -636,18 +638,18 @@ readLiteral: if debugDecode { fmt.Println("morebits n>0:", err) } - f.err = err + f.err = noEOF(err) return } } c := pbuf[pos] pos++ f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 + fb >>= n & regmask.Shift32ByUint fnb -= n default: fr.Discard(pos) @@ -672,14 +674,14 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb<5:", err) } - f.err = err + f.err = noEOF(err) return } } c := pbuf[pos] pos++ f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) @@ -710,7 +712,7 @@ readLiteral: c := pbuf[pos] pos++ f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] @@ -729,7 +731,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n dist = uint32(chunk >> huffmanValueShift) break @@ -743,7 +745,7 @@ readLiteral: case dist < maxNumDist: nb := uint(dist-2) >> 1 // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) + extra := (dist & 1) << (nb & regmask.Shift32ByUint) for fnb < nb { if pos >= len(pbuf) { fr.Discard(pos) @@ -755,20 +757,20 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 + fb >>= nb & regmask.Shift32ByUint fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra + dist = 1<<((nb+1)®mask.Shift32ByUint) + 1 + extra // slower: dist = bitMask32[nb+1] + 2 + extra default: fr.Discard(pos) @@ -860,7 +862,7 @@ readLiteral: return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] @@ -878,7 +880,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n v = int(chunk >> huffmanValueShift) break @@ -916,15 +918,15 @@ readLiteral: if debugDecode { fmt.Println("morebits n>0:", err) } - f.err = err + f.err = noEOF(err) return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 + fb >>= n & regmask.Shift32ByUint fnb -= n default: if debugDecode { @@ -944,11 +946,11 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb<5:", err) } - f.err = err + f.err = noEOF(err) return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) @@ -972,7 +974,7 @@ readLiteral: return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] @@ -990,7 +992,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n dist = uint32(chunk >> huffmanValueShift) break @@ -1004,7 +1006,7 @@ readLiteral: case dist < maxNumDist: nb := uint(dist-2) >> 1 // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) + extra := (dist & 1) << (nb & regmask.Shift32ByUint) for fnb < nb { c, err := fr.ReadByte() if err != nil { @@ -1012,17 +1014,17 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 + fb >>= nb & regmask.Shift32ByUint fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra + dist = 1<<((nb+1)®mask.Shift32ByUint) + 1 + extra // slower: dist = bitMask32[nb+1] + 2 + extra default: f.b, f.nb = fb, fnb @@ -1111,7 +1113,7 @@ readLiteral: return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] @@ -1129,7 +1131,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n v = int(chunk >> huffmanValueShift) break @@ -1167,15 +1169,15 @@ readLiteral: if debugDecode { fmt.Println("morebits n>0:", err) } - f.err = err + f.err = noEOF(err) return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 + fb >>= n & regmask.Shift32ByUint fnb -= n default: if debugDecode { @@ -1195,11 +1197,11 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb<5:", err) } - f.err = err + f.err = noEOF(err) return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) @@ -1223,7 +1225,7 @@ readLiteral: return } f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) + fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] @@ -1241,7 +1243,7 @@ readLiteral: f.err = CorruptInputError(f.roffset) return } - fb = fb >> (n & regSizeMaskUint32) + fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n dist = uint32(chunk >> huffmanValueShift) break @@ -1255,7 +1257,7 @@ readLiteral: case dist < maxNumDist: nb := uint(dist-2) >> 1 // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) + extra := (dist & 1) << (nb & regmask.Shift32ByUint) for fnb < nb { c, err := fr.ReadByte() if err != nil { @@ -1263,17 +1265,17 @@ readLiteral: if debugDecode { fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 + fb >>= nb & regmask.Shift32ByUint fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra + dist = 1<<((nb+1)®mask.Shift32ByUint) + 1 + extra // slower: dist = bitMask32[nb+1] + 2 + extra default: f.b, f.nb = fb, fnb diff --git a/vendor/github.com/klauspost/compress/flate/matchlen_generic.go b/vendor/github.com/klauspost/compress/flate/matchlen_generic.go index 6149384aaf..b897261a13 100644 --- a/vendor/github.com/klauspost/compress/flate/matchlen_generic.go +++ b/vendor/github.com/klauspost/compress/flate/matchlen_generic.go @@ -12,18 +12,17 @@ import ( // matchLen returns the maximum common prefix length of a and b. // a must be the shortest of the two. func matchLen(a, b []byte) (n int) { - left := len(a) - for left >= 8 { - diff := le.Load64(a, n) ^ le.Load64(b, n) + // Keeping a and b the same length and reslicing them as we go + // lets the compiler prove that no bounds checks are needed. + b = b[:len(a)] + for len(a) >= 8 { + diff := le.Load64(a, 0) ^ le.Load64(b, 0) if diff != 0 { return n + bits.TrailingZeros64(diff)>>3 } + a, b = a[8:], b[8:] n += 8 - left -= 8 } - - a = a[n:] - b = b[n:] for i := range a { if a[i] != b[i] { break diff --git a/vendor/github.com/klauspost/compress/flate/regmask_amd64.go b/vendor/github.com/klauspost/compress/flate/regmask_amd64.go deleted file mode 100644 index 6ed28061b2..0000000000 --- a/vendor/github.com/klauspost/compress/flate/regmask_amd64.go +++ /dev/null @@ -1,37 +0,0 @@ -package flate - -const ( - // Masks for shifts with register sizes of the shift value. - // This can be used to work around the x86 design of shifting by mod register size. - // It can be used when a variable shift is always smaller than the register size. - - // reg8SizeMaskX - shift value is 8 bits, shifted is X - reg8SizeMask8 = 7 - reg8SizeMask16 = 15 - reg8SizeMask32 = 31 - reg8SizeMask64 = 63 - - // reg16SizeMaskX - shift value is 16 bits, shifted is X - reg16SizeMask8 = reg8SizeMask8 - reg16SizeMask16 = reg8SizeMask16 - reg16SizeMask32 = reg8SizeMask32 - reg16SizeMask64 = reg8SizeMask64 - - // reg32SizeMaskX - shift value is 32 bits, shifted is X - reg32SizeMask8 = reg8SizeMask8 - reg32SizeMask16 = reg8SizeMask16 - reg32SizeMask32 = reg8SizeMask32 - reg32SizeMask64 = reg8SizeMask64 - - // reg64SizeMaskX - shift value is 64 bits, shifted is X - reg64SizeMask8 = reg8SizeMask8 - reg64SizeMask16 = reg8SizeMask16 - reg64SizeMask32 = reg8SizeMask32 - reg64SizeMask64 = reg8SizeMask64 - - // regSizeMaskUintX - shift value is uint, shifted is X - regSizeMaskUint8 = reg8SizeMask8 - regSizeMaskUint16 = reg8SizeMask16 - regSizeMaskUint32 = reg8SizeMask32 - regSizeMaskUint64 = reg8SizeMask64 -) diff --git a/vendor/github.com/klauspost/compress/flate/regmask_other.go b/vendor/github.com/klauspost/compress/flate/regmask_other.go deleted file mode 100644 index e62caf711e..0000000000 --- a/vendor/github.com/klauspost/compress/flate/regmask_other.go +++ /dev/null @@ -1,39 +0,0 @@ -//go:build !amd64 - -package flate - -const ( - // Masks for shifts with register sizes of the shift value. - // This can be used to work around the x86 design of shifting by mod register size. - // It can be used when a variable shift is always smaller than the register size. - - // reg8SizeMaskX - shift value is 8 bits, shifted is X - reg8SizeMask8 = 0xff - reg8SizeMask16 = 0xff - reg8SizeMask32 = 0xff - reg8SizeMask64 = 0xff - - // reg16SizeMaskX - shift value is 16 bits, shifted is X - reg16SizeMask8 = 0xffff - reg16SizeMask16 = 0xffff - reg16SizeMask32 = 0xffff - reg16SizeMask64 = 0xffff - - // reg32SizeMaskX - shift value is 32 bits, shifted is X - reg32SizeMask8 = 0xffffffff - reg32SizeMask16 = 0xffffffff - reg32SizeMask32 = 0xffffffff - reg32SizeMask64 = 0xffffffff - - // reg64SizeMaskX - shift value is 64 bits, shifted is X - reg64SizeMask8 = 0xffffffffffffffff - reg64SizeMask16 = 0xffffffffffffffff - reg64SizeMask32 = 0xffffffffffffffff - reg64SizeMask64 = 0xffffffffffffffff - - // regSizeMaskUintX - shift value is uint, shifted is X - regSizeMaskUint8 = ^uint(0) - regSizeMaskUint16 = ^uint(0) - regSizeMaskUint32 = ^uint(0) - regSizeMaskUint64 = ^uint(0) -) diff --git a/vendor/github.com/klauspost/compress/flate/token.go b/vendor/github.com/klauspost/compress/flate/token.go index d818790c13..d31f6ccb6d 100644 --- a/vendor/github.com/klauspost/compress/flate/token.go +++ b/vendor/github.com/klauspost/compress/flate/token.go @@ -215,7 +215,11 @@ func mFastLog2(val float32) float32 { ux &= -0x7f800001 ux += 127 << 23 uval := math.Float32frombits(uint32(ux)) - log2 += ((-0.34484843)*uval+2.02466578)*uval - 0.67487759 + + p := float32(-0.34484843*uval) + 2.02466578 + q := float32(p*uval) - 0.67487759 + log2 += q + return log2 } @@ -232,7 +236,8 @@ func (t *tokens) EstimatedBits() int { for _, v := range t.litHist[:] { if v > 0 { n := float32(v) - shannon += atLeastOne(-mFastLog2(n*invTotal)) * n + w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n) + shannon += w } } // Just add 15 for EOB @@ -240,7 +245,8 @@ func (t *tokens) EstimatedBits() int { for i, v := range t.extraHist[1 : literalCount-256] { if v > 0 { n := float32(v) - shannon += atLeastOne(-mFastLog2(n*invTotal)) * n + w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n) + shannon += w bits += int(lengthExtraBits[i&31]) * int(v) nMatches += int(v) } @@ -251,7 +257,8 @@ func (t *tokens) EstimatedBits() int { for i, v := range t.offHist[:offsetCodeCount] { if v > 0 { n := float32(v) - shannon += atLeastOne(-mFastLog2(n*invTotal)) * n + w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n) + shannon += w bits += int(offsetExtraBits[i&31]) * int(v) } } @@ -358,9 +365,6 @@ func (t token) offset() uint32 { return uint32(t) & offsetMask } func (t token) length() uint8 { return uint8(t >> lengthShift) } -// Convert length to code. -func lengthCode(len uint8) uint8 { return lengthCodes[len] } - // Returns the offset code corresponding to a specific offset func offsetCode(off uint32) uint32 { if false { diff --git a/vendor/github.com/klauspost/compress/huff0/bitreader.go b/vendor/github.com/klauspost/compress/huff0/bitreader.go index bfc7a523de..faaa418a75 100644 --- a/vendor/github.com/klauspost/compress/huff0/bitreader.go +++ b/vendor/github.com/klauspost/compress/huff0/bitreader.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "io" + "math/bits" "github.com/klauspost/compress/internal/le" ) @@ -210,6 +211,68 @@ func (b *bitReaderShifted) remaining() uint { return b.off*8 + uint(64-b.bitsRead) } +// canUseAsm reports whether the reader has a full 8-byte window ahead of +// its read pointer, which the Decompress4X asm loops need to take over. +func (b *bitReaderShifted) canUseAsm() bool { + return b.off >= 8 +} + +// prepareForAsm establishes the invariant the Decompress4X asm loops rely +// on: value == load64(in[off:off+8]) << bitsRead with bitsRead <= 7, so +// that a full group of symbols can never shift their sentinel bit out of +// the container. init leaves bitsRead == 8 when the final byte of the +// stream is exactly 0x01; that whole byte is consumed, so the same position +// is the window one byte lower with nothing consumed. Requires canUseAsm. +func (b *bitReaderShifted) prepareForAsm() { + if b.bitsRead >= 8 { + b.off-- + b.value = le.Load64(b.in, b.off) + b.bitsRead -= 8 + } +} + +// restoreFromAsm converts the state left behind by the Decompress4X asm +// loops back to the invariant the Go code relies on: value holds the 8 +// bytes at in[off:off+8] shifted left by bitsRead, with the low bitsRead +// bits zero. +// +// The asm keeps a sentinel bit in value just below the unread bits, so its +// trailing zero count is the number of consumed bits. The sentinel is ORed +// over the lowest bit of the window, which the loop never consumes before +// re-reading memory, so the window is re-read here too rather than taken +// from value. The asm reports off as the signed distance from the start of +// the stream, and it can be negative: a reload always reads a whole 8-byte +// window, so a stream that is nearly drained ends with up to 7 bytes of the +// previous stream (or the jump table) below its start inside the window. +// Those bytes sit below the stream's own bits and count as consumed. +// Anything further below, or more bits consumed than the stream holds, is +// corruption. +func (b *bitReaderShifted) restoreFromAsm() error { + off := int(b.off) + consumed := uint(bits.TrailingZeros64(b.value)) + if off < 0 { + if off < -7 { + return errors.New("corruption detected: stream underrun") + } + consumed += uint(-off) * 8 + if consumed > 64 { + return errors.New("corruption detected: stream underrun") + } + off = 0 + } + if off+8 > len(b.in) { + return errors.New("corruption detected: stream overrun") + } + b.off = uint(off) + b.bitsRead = uint8(consumed) + if consumed >= 64 { + b.value = 0 + } else { + b.value = le.Load64(b.in, b.off) << consumed + } + return nil +} + // close the bitstream and returns an error if out-of-buffer reads occurred. func (b *bitReaderShifted) close() error { // Release reference. diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go index 2d6ef64be1..e651f30ecb 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go +++ b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go @@ -1,222 +1,128 @@ //go:build amd64 && !appengine && !noasm && gc -// This file contains the specialisation of Decoder.Decompress4X -// and Decoder.Decompress1X that use an asm implementation of thir main loops. +// amd64 stubs and dispatch for the asm loops used by decompress_asm.go. package huff0 import ( - "errors" - "fmt" - "github.com/klauspost/compress/internal/cpuinfo" ) -// decompress4x_main_loop_x86 is an x86 assembler implementation -// of Decompress4X when tablelog > 8. +// decompress4x_main_loop_amd64 is an x86 assembler implementation +// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per +// stream between bit container reloads. // //go:noescape func decompress4x_main_loop_amd64(ctx *decompress4xContext) -// decompress4x_8b_loop_x86 is an x86 assembler implementation -// of Decompress4X when tablelog <= 8 which decodes 4 entries -// per loop. +// decompress4x_8b_main_loop_amd64 is an x86 assembler implementation +// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols +// per stream between bit container reloads. // //go:noescape func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) -// fallback8BitSize is the size where using Go version is faster. -const fallback8BitSize = 800 - -type decompress4xContext struct { - pbr *[4]bitReaderShifted - peekBits uint8 - out *byte - dstEvery int - tbl *dEntrySingle - decoded int - limit *byte -} +// decompress4x_4b_main_loop_amd64 is an x86 assembler implementation +// of Decompress4X when tablelog <= 4, decoding fast4bSymbols symbols +// per stream between bit container reloads. +// +//go:noescape +func decompress4x_4b_main_loop_amd64(ctx *decompress4xContext) -// Decompress4X will decompress a 4X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// The *capacity* of the dst slice must match the destination size of -// the uncompressed data exactly. -func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") - } - if len(src) < 6+(4*1) { - return nil, errors.New("input too small") - } +// decompress4x_4b_main_loop_bmi2 is the BMI2 twin of decompress4x_4b_main_loop_amd64. +// +//go:noescape +func decompress4x_4b_main_loop_bmi2(ctx *decompress4xContext) - use8BitTables := d.actualTableLog <= 8 - if cap(dst) < fallback8BitSize && use8BitTables { - return d.decompress4X8bit(dst, src) - } +// decompress4x_main_loop_bmi2 is the BMI2 twin of decompress4x_main_loop_amd64. +// +//go:noescape +func decompress4x_main_loop_bmi2(ctx *decompress4xContext) - var br [4]bitReaderShifted - // Decode "jump table" - start := 6 - for i := range 3 { - length := int(src[i*2]) | (int(src[i*2+1]) << 8) - if start+length >= len(src) { - return nil, errors.New("truncated input (or invalid offset)") - } - err := br[i].init(src[start : start+length]) - if err != nil { - return nil, err - } - start += length - } - err := br[3].init(src[start:]) - if err != nil { - return nil, err - } +// decompress4x_8b_main_loop_bmi2 is the BMI2 twin of decompress4x_8b_main_loop_amd64. +// +//go:noescape +func decompress4x_8b_main_loop_bmi2(ctx *decompress4xContext) - // destination, offset to match first output - dstSize := cap(dst) - dst = dst[:dstSize] - out := dst - dstEvery := (dstSize + 3) / 4 - - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - single := d.dt.single[:tlSize] - - var decoded int - - if len(out) > 4*4 && !(br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4) { - ctx := decompress4xContext{ - pbr: &br, - peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() - out: &out[0], - dstEvery: dstEvery, - tbl: &single[0], - limit: &out[dstEvery-4], // Always stop decoding when first buffer gets here to avoid writing OOB on last. - } - if use8BitTables { - decompress4x_8b_main_loop_amd64(&ctx) - } else { - decompress4x_main_loop_amd64(&ctx) - } - - decoded = ctx.decoded - out = out[decoded/4:] - } +// decompress1x_main_loop_amd64 is an x86 assembler implementation +// of Decompress1X when tablelog > 8, decoding fastSymbols symbols +// between bit container reloads. +// +//go:noescape +func decompress1x_main_loop_amd64(ctx *decompress1xContext) - // Decode remaining. - remainBytes := dstEvery - (decoded / 4) - for i := range br { - offset := dstEvery * i - endsAt := min(offset+remainBytes, len(out)) - br := &br[i] - bitsLeft := br.remaining() - for bitsLeft > 0 { - br.fill() - if offset >= endsAt { - return nil, errors.New("corruption detected: stream overrun 4") - } - - // Read value and increment offset. - val := br.peekBitsFast(d.actualTableLog) - v := single[val&tlMask].entry - nBits := uint8(v) - br.advance(nBits) - bitsLeft -= uint(nBits) - out[offset] = uint8(v >> 8) - offset++ - } - if offset != endsAt { - return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) - } - decoded += offset - dstEvery*i - err = br.close() - if err != nil { - return nil, err - } - } - if dstSize != decoded { - return nil, errors.New("corruption detected: short output block") - } - return dst, nil -} +// decompress1x_8b_main_loop_amd64 is an x86 assembler implementation +// of Decompress1X when tablelog <= 8, decoding fast8bSymbols symbols +// between bit container reloads. +// +//go:noescape +func decompress1x_8b_main_loop_amd64(ctx *decompress1xContext) -// decompress4x_main_loop_x86 is an x86 assembler implementation -// of Decompress1X when tablelog > 8. +// decompress1x_4b_main_loop_amd64 is an x86 assembler implementation +// of Decompress1X when tablelog <= 4, decoding fast4bSymbols symbols +// between bit container reloads. // //go:noescape -func decompress1x_main_loop_amd64(ctx *decompress1xContext) +func decompress1x_4b_main_loop_amd64(ctx *decompress1xContext) -// decompress4x_main_loop_x86 is an x86 with BMI2 assembler implementation -// of Decompress1X when tablelog > 8. +// decompress1x_main_loop_bmi2 is the BMI2 twin of decompress1x_main_loop_amd64. // //go:noescape func decompress1x_main_loop_bmi2(ctx *decompress1xContext) -type decompress1xContext struct { - pbr *bitReaderShifted - peekBits uint8 - out *byte - outCap int - tbl *dEntrySingle - decoded int +// decompress1x_8b_main_loop_bmi2 is the BMI2 twin of decompress1x_8b_main_loop_amd64. +// +//go:noescape +func decompress1x_8b_main_loop_bmi2(ctx *decompress1xContext) + +// decompress1x_4b_main_loop_bmi2 is the BMI2 twin of decompress1x_4b_main_loop_amd64. +// +//go:noescape +func decompress1x_4b_main_loop_bmi2(ctx *decompress1xContext) + +func decompress4x_main_loop_asm(ctx *decompress4xContext) { + if cpuinfo.HasBMI2() { + decompress4x_main_loop_bmi2(ctx) + } else { + decompress4x_main_loop_amd64(ctx) + } } -// Error reported by asm implementations -const error_max_decoded_size_exeeded = -1 +func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) { + if cpuinfo.HasBMI2() { + decompress4x_8b_main_loop_bmi2(ctx) + } else { + decompress4x_8b_main_loop_amd64(ctx) + } +} -// Decompress1X will decompress a 1X encoded stream. -// The cap of the output buffer will be the maximum decompressed size. -// The length of the supplied input must match the end of a block exactly. -func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") +func decompress4x_4b_main_loop_asm(ctx *decompress4xContext) { + if cpuinfo.HasBMI2() { + decompress4x_4b_main_loop_bmi2(ctx) + } else { + decompress4x_4b_main_loop_amd64(ctx) } - var br bitReaderShifted - err := br.init(src) - if err != nil { - return dst, err +} + +func decompress1x_main_loop_asm(ctx *decompress1xContext) { + if cpuinfo.HasBMI2() { + decompress1x_main_loop_bmi2(ctx) + } else { + decompress1x_main_loop_amd64(ctx) } - maxDecodedSize := cap(dst) - dst = dst[:maxDecodedSize] - - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - - if maxDecodedSize >= 4 { - ctx := decompress1xContext{ - pbr: &br, - out: &dst[0], - outCap: maxDecodedSize, - peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() - tbl: &d.dt.single[0], - } - - if cpuinfo.HasBMI2() { - decompress1x_main_loop_bmi2(&ctx) - } else { - decompress1x_main_loop_amd64(&ctx) - } - if ctx.decoded == error_max_decoded_size_exeeded { - return nil, ErrMaxDecodedSizeExceeded - } - - dst = dst[:ctx.decoded] +} + +func decompress1x_8b_main_loop_asm(ctx *decompress1xContext) { + if cpuinfo.HasBMI2() { + decompress1x_8b_main_loop_bmi2(ctx) + } else { + decompress1x_8b_main_loop_amd64(ctx) } +} - // br < 8, so uint8 is fine - bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead - for bitsLeft > 0 { - br.fill() - if len(dst) >= maxDecodedSize { - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] - nBits := uint8(v.entry) - br.advance(nBits) - bitsLeft -= nBits - dst = append(dst, uint8(v.entry>>8)) +func decompress1x_4b_main_loop_asm(ctx *decompress1xContext) { + if cpuinfo.HasBMI2() { + decompress1x_4b_main_loop_bmi2(ctx) + } else { + decompress1x_4b_main_loop_amd64(ctx) } - return dst, br.close() } diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s index c4c7ab2d1f..f072c18f04 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s +++ b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s @@ -1,830 +1,3386 @@ -// Code generated by command: go run gen.go -out ../decompress_amd64.s -pkg=huff0. DO NOT EDIT. +// Code generated by command: go run gen.go -out ../decompress.s -arch amd64,arm64 -pkg=huff0. DO NOT EDIT. -//go:build amd64 && !appengine && !noasm && gc +//go:build !appengine && !noasm && gc // func decompress4x_main_loop_amd64(ctx *decompress4xContext) +// Requires: BMI, CMOV TEXT ·decompress4x_main_loop_amd64(SB), $0-8 - // Preload values - MOVQ ctx+0(FP), AX - MOVBQZX 8(AX), DI - MOVQ 16(AX), BX - MOVQ 48(AX), SI - MOVQ 24(AX), R8 - MOVQ 32(AX), R9 - MOVQ (AX), R10 - - // Main loop -main_loop: - XORL DX, DX - CMPQ BX, SI - SETGE DL - - // br0.fillFast32() - MOVQ 32(R10), R11 - MOVBQZX 40(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill0 - MOVQ 24(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ (R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 24(R10) - ORQ R13, R11 - - // exhausted += (br0.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill0: - // val0 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br0.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX) - - // update the bitreader structure - MOVQ R11, 32(R10) - MOVB R12, 40(R10) - - // br1.fillFast32() - MOVQ 80(R10), R11 - MOVBQZX 88(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill1 - MOVQ 72(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 48(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 72(R10) - ORQ R13, R11 - - // exhausted += (br1.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br1.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX)(R8*1) - - // update the bitreader structure - MOVQ R11, 80(R10) - MOVB R12, 88(R10) - - // br2.fillFast32() - MOVQ 128(R10), R11 - MOVBQZX 136(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill2 - MOVQ 120(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 96(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 120(R10) - ORQ R13, R11 - - // exhausted += (br2.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br2.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX)(R8*2) - - // update the bitreader structure - MOVQ R11, 128(R10) - MOVB R12, 136(R10) - - // br3.fillFast32() - MOVQ 176(R10), R11 - MOVBQZX 184(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill3 - MOVQ 168(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 144(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 168(R10) - ORQ R13, R11 - - // exhausted += (br3.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 + MOVQ ctx+0(FP), AX - // val1 := br3.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - LEAQ (R8)(R8*2), CX - MOVW AX, (BX)(CX*1) - - // update the bitreader structure - MOVQ R11, 176(R10) - MOVB R12, 184(R10) - ADDQ $0x02, BX - TESTB DL, DL - JZ main_loop - MOVQ ctx+0(FP), AX - SUBQ 16(AX), BX - SHLQ $0x02, BX - MOVQ BX, 40(AX) + // Preload values + MOVBQZX 8(AX), DX + MOVQ 32(AX), BX + MOVQ 16(AX), SI + MOVQ 24(AX), CX + LEAQ (SI)(CX*1), R8 + LEAQ (SI)(CX*2), R10 + LEAQ (CX)(CX*2), R12 + ADDQ SI, R12 + + // Convert each bit reader to sentinel form: bits = value | 1<> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX) - - // update the bitreader structure - MOVQ R11, 32(R10) - MOVB R12, 40(R10) - - // br1.fillFast32() - MOVQ 80(R10), R11 - MOVBQZX 88(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill1 - MOVQ 72(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 48(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 72(R10) - ORQ R14, R11 + TZCNTQ R13, R14 + MOVQ R14, CX + ANDQ $0x07, CX + SHRQ $0x03, R14 + MOVQ 88(AX), R13 + SUBQ R14, R13 + MOVQ R13, 88(AX) + MOVQ (R13), R13 + ORQ $0x01, R13 + SHLQ CL, R13 + ADDQ $0x0e, SI + ADDQ $0x0e, R8 + ADDQ $0x0e, R10 + ADDQ $0x0e, R12 + CMPQ SI, 96(AX) + JB inner_loop + JMP outer_loop + +done: + // Hand the state back: off = ip - in (negative when the window reached below the stream start), + // value = the sentinel-form container. bitReaderShifted.restoreFromAsm normalizes both. + MOVQ (AX), CX + MOVQ 64(AX), DX + SUBQ (CX), DX + MOVQ DX, 24(CX) + MOVQ DI, 32(CX) + MOVQ 72(AX), DX + SUBQ 48(CX), DX + MOVQ DX, 72(CX) + MOVQ R9, 80(CX) + MOVQ 80(AX), DX + SUBQ 96(CX), DX + MOVQ DX, 120(CX) + MOVQ R11, 128(CX) + MOVQ 88(AX), DX + SUBQ 144(CX), DX + MOVQ DX, 168(CX) + MOVQ R13, 176(CX) + SUBQ 16(AX), SI + SHLQ $0x02, SI + MOVQ SI, 40(AX) + RET - // exhausted += (br1.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL +// func decompress4x_main_loop_bmi2(ctx *decompress4xContext) +// Requires: BMI, BMI2, CMOV +TEXT ·decompress4x_main_loop_bmi2(SB), $0-8 + MOVQ ctx+0(FP), AX -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 + // Preload values + MOVBQZX 8(AX), CX + MOVQ 32(AX), DX + MOVQ 16(AX), BX + MOVQ 24(AX), SI + LEAQ (BX)(SI*1), DI + LEAQ (BX)(SI*2), R9 + LEAQ (SI)(SI*2), R11 + ADDQ BX, R11 + + // Convert each bit reader to sentinel form: bits = value | 1<> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX)(R8*1) - - // update the bitreader structure - MOVQ R11, 80(R10) - MOVB R12, 88(R10) - - // br2.fillFast32() - MOVQ 128(R10), R11 - MOVBQZX 136(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill2 - MOVQ 120(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 96(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX + ANDQ $0x38, R13 + MOVQ -8(R8), R14 + SHRQ $0x01, R14 + ANDQ $0x07, R11 + MOVQ R13, CX + XORQ $0x3f, CX + SHRQ CL, R14 + MOVQ R11, CX SHLQ CL, R14 - MOVQ R13, 120(R10) - ORQ R14, R11 - - // exhausted += (br2.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX + ORQ R14, R10 + SHRQ $0x03, R13 + SUBQ R13, R8 + ADDQ $0x05, SI + CMPQ SI, R12 + JB inner_loop + JMP outer_loop + +done: + // Hand the state back in the Go bit reader's own form: off = ip - in, value, bitsRead. + MOVQ (AX), CX + SUBQ (CX), R8 + MOVQ R8, 24(CX) + MOVQ R10, 32(CX) + MOVB R11, 40(CX) + SUBQ 16(AX), SI + MOVQ SI, 40(AX) + RET - // br2.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX +// func decompress1x_8b_main_loop_amd64(ctx *decompress1xContext) +// Requires: CMOV +TEXT ·decompress1x_8b_main_loop_amd64(SB), $0-8 + MOVQ ctx+0(FP), AX - // val2 := br2.peekTopBits(peekBits) - MOVQ R11, R13 + // Preload values + MOVBQZX 8(AX), DX + MOVQ 32(AX), BX + MOVQ 16(AX), SI + MOVQ 24(AX), DI + ADDQ SI, DI + MOVQ 56(AX), R8 + MOVQ 48(AX), R9 + MOVQ (AX), CX + MOVQ 32(CX), R10 + MOVBQZX 40(CX), R11 + +outer_loop: + // Iterations allowed by the output: (limit - op) / 8 MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 + SUBQ SI, CX + JLE done + SHRQ $0x03, CX + + // Iterations allowed by the input: a refill reads the 8 bytes below the window and + // moves it down by at most 7, so every read stays inside the stream while ip stays + // at least 8 above ilowest. + MOVQ R8, R12 + SUBQ R9, R12 + SHRQ $0x03, R12 + CMPQ R12, CX + CMOVQCS R12, CX + TESTQ CX, CX + JZ done + IMUL3Q $0x07, CX, R12 + ADDQ SI, R12 + +inner_loop: + // symbol 0 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, (SI) + + // symbol 1 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 1(SI) + + // symbol 2 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 2(SI) + + // symbol 3 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 3(SI) + + // symbol 4 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 4(SI) + + // symbol 5 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 5(SI) + + // symbol 6 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 6(SI) - // val3 := br2.peekTopBits(peekBits) + // Refill the whole bytes consumed from below the window MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX)(R8*2) - - // update the bitreader structure - MOVQ R11, 128(R10) - MOVB R12, 136(R10) - - // br3.fillFast32() - MOVQ 176(R10), R11 - MOVBQZX 184(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill3 - MOVQ 168(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 144(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX + ANDQ $0x38, R13 + MOVQ -8(R8), R14 + SHRQ $0x01, R14 + ANDQ $0x07, R11 + MOVQ R13, CX + XORQ $0x3f, CX + SHRQ CL, R14 + MOVQ R11, CX SHLQ CL, R14 - MOVQ R13, 168(R10) - ORQ R14, R11 - - // exhausted += (br3.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX + ORQ R14, R10 + SHRQ $0x03, R13 + SUBQ R13, R8 + ADDQ $0x07, SI + CMPQ SI, R12 + JB inner_loop + JMP outer_loop + +done: + // Hand the state back in the Go bit reader's own form: off = ip - in, value, bitsRead. + MOVQ (AX), CX + SUBQ (CX), R8 + MOVQ R8, 24(CX) + MOVQ R10, 32(CX) + MOVB R11, 40(CX) + SUBQ 16(AX), SI + MOVQ SI, 40(AX) + RET - // br3.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 +// func decompress1x_4b_main_loop_amd64(ctx *decompress1xContext) +// Requires: CMOV +TEXT ·decompress1x_4b_main_loop_amd64(SB), $0-8 + MOVQ ctx+0(FP), AX - // val3 := br3.peekTopBits(peekBits) - MOVQ R11, R13 + // Preload values + MOVBQZX 8(AX), DX + MOVQ 32(AX), BX + MOVQ 16(AX), SI + MOVQ 24(AX), DI + ADDQ SI, DI + MOVQ 56(AX), R8 + MOVQ 48(AX), R9 + MOVQ (AX), CX + MOVQ 32(CX), R10 + MOVBQZX 40(CX), R11 + +outer_loop: + // Iterations allowed by the output: (limit - op) / 16 MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - LEAQ (R8)(R8*2), CX - MOVL AX, (BX)(CX*1) - - // update the bitreader structure - MOVQ R11, 176(R10) - MOVB R12, 184(R10) - ADDQ $0x04, BX - TESTB DL, DL - JZ main_loop - MOVQ ctx+0(FP), AX - SUBQ 16(AX), BX - SHLQ $0x02, BX - MOVQ BX, 40(AX) - RET - -// func decompress1x_main_loop_amd64(ctx *decompress1xContext) -TEXT ·decompress1x_main_loop_amd64(SB), $0-8 - MOVQ ctx+0(FP), CX - MOVQ 16(CX), DX - MOVQ 24(CX), BX - CMPQ BX, $0x04 - JB error_max_decoded_size_exceeded - LEAQ (DX)(BX*1), BX - MOVQ (CX), SI - MOVQ (SI), R8 - MOVQ 24(SI), R9 - MOVQ 32(SI), R10 - MOVBQZX 40(SI), R11 - MOVQ 32(CX), SI - MOVBQZX 8(CX), DI - JMP loop_condition - -main_loop: - // Check if we have room for 4 bytes in the output buffer - LEAQ 4(DX), CX - CMPQ CX, BX - JGE error_max_decoded_size_exceeded - - // Decode 4 values - CMPQ R11, $0x20 - JL bitReader_fillFast_1_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), R12 - MOVQ R11, CX - SHLQ CL, R12 - ORQ R12, R10 - -bitReader_fillFast_1_end: - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AL - MOVBQZX CL, CX + SUBQ SI, CX + JLE done + SHRQ $0x04, CX + + // Iterations allowed by the input: a refill reads the 8 bytes below the window and + // moves it down by at most 7, so every read stays inside the stream while ip stays + // at least 8 above ilowest. + MOVQ R8, R12 + SUBQ R9, R12 + SHRQ $0x03, R12 + CMPQ R12, CX + CMOVQCS R12, CX + TESTQ CX, CX + JZ done + IMUL3Q $0x0e, CX, R12 + ADDQ SI, R12 + +inner_loop: + // symbol 0 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, (SI) + + // symbol 1 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX SHLQ CL, R10 - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AH - MOVBQZX CL, CX ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 1(SI) + + // symbol 2 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX SHLQ CL, R10 - BSWAPL AX - CMPQ R11, $0x20 - JL bitReader_fillFast_2_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), R12 - MOVQ R11, CX - SHLQ CL, R12 - ORQ R12, R10 - -bitReader_fillFast_2_end: - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AH - MOVBQZX CL, CX ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 2(SI) + + // symbol 3 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX SHLQ CL, R10 - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AL - MOVBQZX CL, CX ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 3(SI) + + // symbol 4 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 4(SI) + + // symbol 5 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 5(SI) + + // symbol 6 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 6(SI) + + // symbol 7 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 7(SI) + + // symbol 8 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 8(SI) + + // symbol 9 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX SHLQ CL, R10 - BSWAPL AX - - // Store the decoded values - MOVL AX, (DX) - ADDQ $0x04, DX - -loop_condition: - CMPQ R9, $0x08 - JGE main_loop - - // Update ctx structure - MOVQ ctx+0(FP), AX - SUBQ 16(AX), DX - MOVQ DX, 40(AX) - MOVQ (AX), AX - MOVQ R9, 24(AX) - MOVQ R10, 32(AX) - MOVB R11, 40(AX) - RET - - // Report error -error_max_decoded_size_exceeded: - MOVQ ctx+0(FP), AX - MOVQ $-1, CX - MOVQ CX, 40(AX) - RET - -// func decompress1x_main_loop_bmi2(ctx *decompress1xContext) -// Requires: BMI2 -TEXT ·decompress1x_main_loop_bmi2(SB), $0-8 - MOVQ ctx+0(FP), CX - MOVQ 16(CX), DX - MOVQ 24(CX), BX - CMPQ BX, $0x04 - JB error_max_decoded_size_exceeded - LEAQ (DX)(BX*1), BX - MOVQ (CX), SI - MOVQ (SI), R8 - MOVQ 24(SI), R9 - MOVQ 32(SI), R10 - MOVBQZX 40(SI), R11 - MOVQ 32(CX), SI - MOVBQZX 8(CX), DI - JMP loop_condition - -main_loop: - // Check if we have room for 4 bytes in the output buffer - LEAQ 4(DX), CX - CMPQ CX, BX - JGE error_max_decoded_size_exceeded - - // Decode 4 values - CMPQ R11, $0x20 - JL bitReader_fillFast_1_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), CX - SHLXQ R11, CX, CX - ORQ CX, R10 - -bitReader_fillFast_1_end: - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AL - MOVBQZX CL, CX ADDQ CX, R11 - SHLXQ CX, R10, R10 - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AH - MOVBQZX CL, CX + SHRQ $0x08, CX + MOVB CL, 9(SI) + + // symbol 10 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 ADDQ CX, R11 - SHLXQ CX, R10, R10 - BSWAPL AX - CMPQ R11, $0x20 - JL bitReader_fillFast_2_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), CX - SHLXQ R11, CX, CX - ORQ CX, R10 - -bitReader_fillFast_2_end: - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AH - MOVBQZX CL, CX + SHRQ $0x08, CX + MOVB CL, 10(SI) + + // symbol 11 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 ADDQ CX, R11 - SHLXQ CX, R10, R10 - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AL - MOVBQZX CL, CX + SHRQ $0x08, CX + MOVB CL, 11(SI) + + // symbol 12 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 ADDQ CX, R11 - SHLXQ CX, R10, R10 - BSWAPL AX + SHRQ $0x08, CX + MOVB CL, 12(SI) + + // symbol 13 + MOVQ DX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (BX)(R13*2), CX + SHLQ CL, R10 + ADDQ CX, R11 + SHRQ $0x08, CX + MOVB CL, 13(SI) - // Store the decoded values - MOVL AX, (DX) - ADDQ $0x04, DX + // Refill the whole bytes consumed from below the window + MOVQ R11, R13 + ANDQ $0x38, R13 + MOVQ -8(R8), R14 + SHRQ $0x01, R14 + ANDQ $0x07, R11 + MOVQ R13, CX + XORQ $0x3f, CX + SHRQ CL, R14 + MOVQ R11, CX + SHLQ CL, R14 + ORQ R14, R10 + SHRQ $0x03, R13 + SUBQ R13, R8 + ADDQ $0x0e, SI + CMPQ SI, R12 + JB inner_loop + JMP outer_loop + +done: + // Hand the state back in the Go bit reader's own form: off = ip - in, value, bitsRead. + MOVQ (AX), CX + SUBQ (CX), R8 + MOVQ R8, 24(CX) + MOVQ R10, 32(CX) + MOVB R11, 40(CX) + SUBQ 16(AX), SI + MOVQ SI, 40(AX) + RET + +// func decompress1x_main_loop_bmi2(ctx *decompress1xContext) +// Requires: BMI2, CMOV +TEXT ·decompress1x_main_loop_bmi2(SB), $0-8 + MOVQ ctx+0(FP), AX -loop_condition: - CMPQ R9, $0x08 - JGE main_loop + // Preload values + MOVBQZX 8(AX), CX + MOVQ 32(AX), DX + MOVQ 16(AX), BX + MOVQ 24(AX), SI + ADDQ BX, SI + MOVQ 56(AX), DI + MOVQ 48(AX), R8 + MOVQ (AX), R10 + MOVQ 32(R10), R9 + MOVBQZX 40(R10), R10 + +outer_loop: + // Iterations allowed by the output: (limit - op) / 8 + MOVQ SI, R11 + SUBQ BX, R11 + JLE done + SHRQ $0x03, R11 + + // Iterations allowed by the input: a refill reads the 8 bytes below the window and + // moves it down by at most 7, so every read stays inside the stream while ip stays + // at least 8 above ilowest. + MOVQ DI, R12 + SUBQ R8, R12 + SHRQ $0x03, R12 + CMPQ R12, R11 + CMOVQCS R12, R11 + TESTQ R11, R11 + JZ done + IMUL3Q $0x05, R11, R11 + ADDQ BX, R11 + +inner_loop: + // symbol 0 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, (BX) + + // symbol 1 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 1(BX) + + // symbol 2 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 2(BX) + + // symbol 3 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 3(BX) + + // symbol 4 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 4(BX) + + // Refill the whole bytes consumed from below the window + MOVQ R10, R12 + ANDQ $0x38, R12 + MOVQ -8(DI), R13 + SHRQ $0x01, R13 + ANDQ $0x07, R10 + MOVQ R12, R14 + XORQ $0x3f, R14 + SHRXQ R14, R13, R13 + SHLXQ R10, R13, R13 + ORQ R13, R9 + SHRQ $0x03, R12 + SUBQ R12, DI + ADDQ $0x05, BX + CMPQ BX, R11 + JB inner_loop + JMP outer_loop + +done: + // Hand the state back in the Go bit reader's own form: off = ip - in, value, bitsRead. + MOVQ (AX), CX + SUBQ (CX), DI + MOVQ DI, 24(CX) + MOVQ R9, 32(CX) + MOVB R10, 40(CX) + SUBQ 16(AX), BX + MOVQ BX, 40(AX) + RET - // Update ctx structure +// func decompress1x_8b_main_loop_bmi2(ctx *decompress1xContext) +// Requires: BMI2, CMOV +TEXT ·decompress1x_8b_main_loop_bmi2(SB), $0-8 MOVQ ctx+0(FP), AX - SUBQ 16(AX), DX - MOVQ DX, 40(AX) - MOVQ (AX), AX - MOVQ R9, 24(AX) - MOVQ R10, 32(AX) - MOVB R11, 40(AX) + + // Preload values + MOVBQZX 8(AX), CX + MOVQ 32(AX), DX + MOVQ 16(AX), BX + MOVQ 24(AX), SI + ADDQ BX, SI + MOVQ 56(AX), DI + MOVQ 48(AX), R8 + MOVQ (AX), R10 + MOVQ 32(R10), R9 + MOVBQZX 40(R10), R10 + +outer_loop: + // Iterations allowed by the output: (limit - op) / 8 + MOVQ SI, R11 + SUBQ BX, R11 + JLE done + SHRQ $0x03, R11 + + // Iterations allowed by the input: a refill reads the 8 bytes below the window and + // moves it down by at most 7, so every read stays inside the stream while ip stays + // at least 8 above ilowest. + MOVQ DI, R12 + SUBQ R8, R12 + SHRQ $0x03, R12 + CMPQ R12, R11 + CMOVQCS R12, R11 + TESTQ R11, R11 + JZ done + IMUL3Q $0x07, R11, R11 + ADDQ BX, R11 + +inner_loop: + // symbol 0 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, (BX) + + // symbol 1 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 1(BX) + + // symbol 2 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 2(BX) + + // symbol 3 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 3(BX) + + // symbol 4 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 4(BX) + + // symbol 5 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 5(BX) + + // symbol 6 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 6(BX) + + // Refill the whole bytes consumed from below the window + MOVQ R10, R12 + ANDQ $0x38, R12 + MOVQ -8(DI), R13 + SHRQ $0x01, R13 + ANDQ $0x07, R10 + MOVQ R12, R14 + XORQ $0x3f, R14 + SHRXQ R14, R13, R13 + SHLXQ R10, R13, R13 + ORQ R13, R9 + SHRQ $0x03, R12 + SUBQ R12, DI + ADDQ $0x07, BX + CMPQ BX, R11 + JB inner_loop + JMP outer_loop + +done: + // Hand the state back in the Go bit reader's own form: off = ip - in, value, bitsRead. + MOVQ (AX), CX + SUBQ (CX), DI + MOVQ DI, 24(CX) + MOVQ R9, 32(CX) + MOVB R10, 40(CX) + SUBQ 16(AX), BX + MOVQ BX, 40(AX) RET - // Report error -error_max_decoded_size_exceeded: +// func decompress1x_4b_main_loop_bmi2(ctx *decompress1xContext) +// Requires: BMI2, CMOV +TEXT ·decompress1x_4b_main_loop_bmi2(SB), $0-8 MOVQ ctx+0(FP), AX - MOVQ $-1, CX - MOVQ CX, 40(AX) + + // Preload values + MOVBQZX 8(AX), CX + MOVQ 32(AX), DX + MOVQ 16(AX), BX + MOVQ 24(AX), SI + ADDQ BX, SI + MOVQ 56(AX), DI + MOVQ 48(AX), R8 + MOVQ (AX), R10 + MOVQ 32(R10), R9 + MOVBQZX 40(R10), R10 + +outer_loop: + // Iterations allowed by the output: (limit - op) / 16 + MOVQ SI, R11 + SUBQ BX, R11 + JLE done + SHRQ $0x04, R11 + + // Iterations allowed by the input: a refill reads the 8 bytes below the window and + // moves it down by at most 7, so every read stays inside the stream while ip stays + // at least 8 above ilowest. + MOVQ DI, R12 + SUBQ R8, R12 + SHRQ $0x03, R12 + CMPQ R12, R11 + CMOVQCS R12, R11 + TESTQ R11, R11 + JZ done + IMUL3Q $0x0e, R11, R11 + ADDQ BX, R11 + +inner_loop: + // symbol 0 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, (BX) + + // symbol 1 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 1(BX) + + // symbol 2 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 2(BX) + + // symbol 3 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 3(BX) + + // symbol 4 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 4(BX) + + // symbol 5 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 5(BX) + + // symbol 6 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 6(BX) + + // symbol 7 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 7(BX) + + // symbol 8 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 8(BX) + + // symbol 9 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 9(BX) + + // symbol 10 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 10(BX) + + // symbol 11 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 11(BX) + + // symbol 12 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 12(BX) + + // symbol 13 + SHRXQ CX, R9, R12 + MOVWQZX (DX)(R12*2), R12 + SHLXQ R12, R9, R9 + ADDQ R12, R10 + SHRQ $0x08, R12 + MOVB R12, 13(BX) + + // Refill the whole bytes consumed from below the window + MOVQ R10, R12 + ANDQ $0x38, R12 + MOVQ -8(DI), R13 + SHRQ $0x01, R13 + ANDQ $0x07, R10 + MOVQ R12, R14 + XORQ $0x3f, R14 + SHRXQ R14, R13, R13 + SHLXQ R10, R13, R13 + ORQ R13, R9 + SHRQ $0x03, R12 + SUBQ R12, DI + ADDQ $0x0e, BX + CMPQ BX, R11 + JB inner_loop + JMP outer_loop + +done: + // Hand the state back in the Go bit reader's own form: off = ip - in, value, bitsRead. + MOVQ (AX), CX + SUBQ (CX), DI + MOVQ DI, 24(CX) + MOVQ R9, 32(CX) + MOVB R10, 40(CX) + SUBQ 16(AX), BX + MOVQ BX, 40(AX) RET diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_arm64.go b/vendor/github.com/klauspost/compress/huff0/decompress_arm64.go new file mode 100644 index 0000000000..d1988ad54d --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/decompress_arm64.go @@ -0,0 +1,72 @@ +//go:build arm64 && !appengine && !noasm && gc + +// arm64 stubs and dispatch for the asm loops used by decompress_asm.go. +// The asm (decompress_arm64.s) is generated by the avo arm64 lowering +// printer from the same source as the amd64 asm; see _generate/gen.go. +package huff0 + +// decompress4x_main_loop_arm64 is an arm64 assembler implementation +// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per +// stream between bit container reloads. +// +//go:noescape +func decompress4x_main_loop_arm64(ctx *decompress4xContext) + +// decompress4x_8b_main_loop_arm64 is an arm64 assembler implementation +// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols +// per stream between bit container reloads. +// +//go:noescape +func decompress4x_8b_main_loop_arm64(ctx *decompress4xContext) + +// decompress4x_4b_main_loop_arm64 is an arm64 assembler implementation +// of Decompress4X when tablelog <= 4, decoding fast4bSymbols symbols +// per stream between bit container reloads. +// +//go:noescape +func decompress4x_4b_main_loop_arm64(ctx *decompress4xContext) + +// decompress1x_main_loop_arm64 is an arm64 assembler implementation +// of Decompress1X when tablelog > 8, decoding fastSymbols symbols +// between bit container reloads. +// +//go:noescape +func decompress1x_main_loop_arm64(ctx *decompress1xContext) + +// decompress1x_8b_main_loop_arm64 is an arm64 assembler implementation +// of Decompress1X when tablelog <= 8, decoding fast8bSymbols symbols +// between bit container reloads. +// +//go:noescape +func decompress1x_8b_main_loop_arm64(ctx *decompress1xContext) + +// decompress1x_4b_main_loop_arm64 is an arm64 assembler implementation +// of Decompress1X when tablelog <= 4, decoding fast4bSymbols symbols +// between bit container reloads. +// +//go:noescape +func decompress1x_4b_main_loop_arm64(ctx *decompress1xContext) + +func decompress4x_main_loop_asm(ctx *decompress4xContext) { + decompress4x_main_loop_arm64(ctx) +} + +func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) { + decompress4x_8b_main_loop_arm64(ctx) +} + +func decompress4x_4b_main_loop_asm(ctx *decompress4xContext) { + decompress4x_4b_main_loop_arm64(ctx) +} + +func decompress1x_main_loop_asm(ctx *decompress1xContext) { + decompress1x_main_loop_arm64(ctx) +} + +func decompress1x_8b_main_loop_asm(ctx *decompress1xContext) { + decompress1x_8b_main_loop_arm64(ctx) +} + +func decompress1x_4b_main_loop_asm(ctx *decompress1xContext) { + decompress1x_4b_main_loop_arm64(ctx) +} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_arm64.s b/vendor/github.com/klauspost/compress/huff0/decompress_arm64.s new file mode 100644 index 0000000000..971b8eb8bd --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/decompress_arm64.s @@ -0,0 +1,1657 @@ +// Code generated by command: go run gen.go -out ../decompress.s -arch amd64,arm64 -pkg=huff0. DO NOT EDIT. +// EXPERIMENTAL arm64 output lowered from an amd64 avo program. + +//go:build arm64 && (!appengine && !noasm && gc) + +// func decompress4x_main_loop_amd64(ctx *decompress4xContext) +// Requires: BMI, CMOV +TEXT ·decompress4x_main_loop_arm64(SB), $0-8 + MOVD ctx+0(FP), R0 + + // Preload values + MOVBU 8(R0), R2 + MOVD 32(R0), R3 + MOVD 16(R0), R5 + MOVD 24(R0), R1 + ADD R1, R5, R7 + ADD R1<<1, R5, R9 + ADD R1<<1, R1, R11 + ADD R5, R11, R11 + + // Convert each bit reader to sentinel form: bits = value | 1<= len(src) { + return nil, errors.New("truncated input (or invalid offset)") + } + err := br[i].init(src[start : start+length]) + if err != nil { + return nil, err + } + start += length + } + err := br[3].init(src[start:]) + if err != nil { + return nil, err + } + + // destination, offset to match first output + dstSize := cap(dst) + dst = dst[:dstSize] + out := dst + dstEvery := (dstSize + 3) / 4 + + const tlSize = 1 << tableLogMax + const tlMask = tlSize - 1 + single := d.dt.single[:tlSize] + + var decoded int + + nSyms := fastSymbols + if d.actualTableLog <= 4 { + nSyms = fast4bSymbols + } else if use8BitTables { + nSyms = fast8bSymbols + } + // The asm writes nSyms bytes per stream per iteration and only re-checks + // its bounds between batches of iterations (the batch size is derived + // from limit in _generate/gen.go), so stream 0 must stop early enough + // that stream 3 (which may be up to 3 bytes shorter than dstEvery) + // never writes past the end of out. Every stream needs a full 8-byte + // window ahead of its read pointer to enter the loop. + if limit := dstEvery - nSyms - 2; limit > 0 && br[0].canUseAsm() && br[1].canUseAsm() && br[2].canUseAsm() && br[3].canUseAsm() { + for i := range br { + br[i].prepareForAsm() + } + ctx := decompress4xContext{ + pbr: &br, + peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() + out: &out[0], + dstEvery: dstEvery, + tbl: &single[0], + limit: &out[limit], + // The 6-byte jump table sits below stream 0 inside src, so the + // lowest window may reach into it; restoreFromAsm accounts for + // bytes below a stream's start. Bounding by src rather than by + // stream 0 keeps the asm running about six bytes longer, which + // matters for streams with very short codes. + ilowest: &src[0], + } + for i := range br { + ctx.ip[i] = &br[i].in[br[i].off] + } + switch nSyms { + case fast4bSymbols: + decompress4x_4b_main_loop_asm(&ctx) + case fast8bSymbols: + decompress4x_8b_main_loop_asm(&ctx) + default: + decompress4x_main_loop_asm(&ctx) + } + + decoded = ctx.decoded + out = out[decoded/4:] + for i := range br { + if err := br[i].restoreFromAsm(); err != nil { + return nil, err + } + } + } + + // Decode remaining. + remainBytes := dstEvery - (decoded / 4) + for i := range br { + offset := dstEvery * i + endsAt := min(offset+remainBytes, len(out)) + br := &br[i] + bitsLeft := br.remaining() + for bitsLeft > 0 { + br.fill() + if offset >= endsAt { + return nil, errors.New("corruption detected: stream overrun 4") + } + + // Read value and increment offset. + val := br.peekBitsFast(d.actualTableLog) + v := single[val&tlMask].entry + nBits := uint8(v) + br.advance(nBits) + bitsLeft -= uint(nBits) + out[offset] = uint8(v >> 8) + offset++ + } + if offset != endsAt { + return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) + } + decoded += offset - dstEvery*i + err = br.close() + if err != nil { + return nil, err + } + } + if dstSize != decoded { + return nil, errors.New("corruption detected: short output block") + } + return dst, nil +} + +// decompress1xContext is the argument block of the Decompress1X asm loops. +// Go fills every field but decoded; the asm advances ip, and on return +// leaves the bit reader in the form bitReaderShifted.restoreFromAsm expects. +type decompress1xContext struct { + pbr *bitReaderShifted + peekBits uint8 + out *byte + outCap int // no write reaches out[outCap] + tbl *dEntrySingle + decoded int + ilowest *byte // start of the stream; no read goes below it + ip *byte // the 8-byte input window, advanced by the asm +} + +// Decompress1X will decompress a 1X encoded stream. +// The cap of the output buffer will be the maximum decompressed size. +// The length of the supplied input must match the end of a block exactly. +func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { + if len(d.dt.single) == 0 { + return nil, errors.New("no table loaded") + } + var br bitReaderShifted + err := br.init(src) + if err != nil { + return dst, err + } + maxDecodedSize := cap(dst) + dst = dst[:maxDecodedSize] + + const tlSize = 1 << tableLogMax + const tlMask = tlSize - 1 + + // The asm decodes whole batches of symbols and only re-checks its + // bounds between them, so it needs at least one batch of room (the + // output bound rounds nSyms up to 16, see _generate/gen.go) and a full + // 8-byte window ahead of the read pointer to enter the loop. It also + // needs at most 7 bits consumed on entry so that a batch cannot run + // the container dry, which prepareForAsm establishes. + decoded := 0 + if maxDecodedSize >= 16 && br.canUseAsm() { + br.prepareForAsm() + ctx := decompress1xContext{ + pbr: &br, + out: &dst[0], + outCap: maxDecodedSize, + peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() + tbl: &d.dt.single[0], + ilowest: &src[0], + ip: &br.in[br.off], + } + if d.actualTableLog <= 4 { + decompress1x_4b_main_loop_asm(&ctx) + } else if d.actualTableLog <= 8 { + decompress1x_8b_main_loop_asm(&ctx) + } else { + decompress1x_main_loop_asm(&ctx) + } + decoded = ctx.decoded + } + dst = dst[:decoded] + + bitsLeft := br.remaining() + for bitsLeft > 0 { + br.fill() + if len(dst) >= maxDecodedSize { + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] + nBits := uint8(v.entry) + br.advance(nBits) + bitsLeft -= uint(nBits) + dst = append(dst, uint8(v.entry>>8)) + } + return dst, br.close() +} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_generic.go b/vendor/github.com/klauspost/compress/huff0/decompress_generic.go index 6103923222..e1bca5c686 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress_generic.go +++ b/vendor/github.com/klauspost/compress/huff0/decompress_generic.go @@ -1,4 +1,4 @@ -//go:build !amd64 || appengine || !gc || noasm +//go:build (!amd64 && !arm64) || appengine || !gc || noasm // This file contains a generic implementation of Decoder.Decompress4X. package huff0 diff --git a/vendor/github.com/klauspost/compress/internal/regmask/regmask.go b/vendor/github.com/klauspost/compress/internal/regmask/regmask.go new file mode 100644 index 0000000000..3da49d1544 --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/regmask/regmask.go @@ -0,0 +1,50 @@ +//go:build !386 + +// Package regmask provides masks for variable shift counts. +// +// Go defines a shift by more than the width of the shifted value as producing +// zero, so the compiler has to guard every variable shift against that: on +// amd64 with a CMP and an SBB, on arm64 with a CMP and a CSEL, and so on. When +// the count is known to be smaller than the width anyway, masking it with the +// width minus one lets the compiler drop the guard. The mask itself costs +// nothing on the architectures whose shift instructions already use only the +// low bits of the count, which the compiler knows about. +// +// Each constant is named for the width of the value being shifted and the type +// of the shift count, and may only be used where the count is always smaller +// than that width: +// +// x := y >> (n & regmask.Shift64ByUint) // y is 64 bits, n is a uint below 64 +package regmask + +const ( + // ShiftNByUint8 - shifting an N bit value by a uint8 + Shift8ByUint8 = 7 + Shift16ByUint8 = 15 + Shift32ByUint8 = 31 + Shift64ByUint8 = 63 + + // ShiftNByUint16 - shifting an N bit value by a uint16 + Shift8ByUint16 = Shift8ByUint8 + Shift16ByUint16 = Shift16ByUint8 + Shift32ByUint16 = Shift32ByUint8 + Shift64ByUint16 = Shift64ByUint8 + + // ShiftNByUint32 - shifting an N bit value by a uint32 + Shift8ByUint32 = Shift8ByUint8 + Shift16ByUint32 = Shift16ByUint8 + Shift32ByUint32 = Shift32ByUint8 + Shift64ByUint32 = Shift64ByUint8 + + // ShiftNByUint64 - shifting an N bit value by a uint64 + Shift8ByUint64 = Shift8ByUint8 + Shift16ByUint64 = Shift16ByUint8 + Shift32ByUint64 = Shift32ByUint8 + Shift64ByUint64 = Shift64ByUint8 + + // ShiftNByUint - shifting an N bit value by a uint + Shift8ByUint = Shift8ByUint8 + Shift16ByUint = Shift16ByUint8 + Shift32ByUint = Shift32ByUint8 + Shift64ByUint = Shift64ByUint8 +) diff --git a/vendor/github.com/klauspost/compress/internal/regmask/regmask_386.go b/vendor/github.com/klauspost/compress/internal/regmask/regmask_386.go new file mode 100644 index 0000000000..ff15f7c1af --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/regmask/regmask_386.go @@ -0,0 +1,39 @@ +//go:build 386 + +package regmask + +// A 64 bit shift on 386 is synthesized from 32 bit instructions, and masking its +// count makes the compiler emit more code rather than less, so those masks are +// no-ops here: each is the largest value its count type can hold, which the +// compiler folds away. Shifts of narrower values behave as elsewhere. +const ( + // ShiftNByUint8 - shifting an N bit value by a uint8 + Shift8ByUint8 = 7 + Shift16ByUint8 = 15 + Shift32ByUint8 = 31 + Shift64ByUint8 = 0xff + + // ShiftNByUint16 - shifting an N bit value by a uint16 + Shift8ByUint16 = Shift8ByUint8 + Shift16ByUint16 = Shift16ByUint8 + Shift32ByUint16 = Shift32ByUint8 + Shift64ByUint16 = 0xffff + + // ShiftNByUint32 - shifting an N bit value by a uint32 + Shift8ByUint32 = Shift8ByUint8 + Shift16ByUint32 = Shift16ByUint8 + Shift32ByUint32 = Shift32ByUint8 + Shift64ByUint32 = 0xffffffff + + // ShiftNByUint64 - shifting an N bit value by a uint64 + Shift8ByUint64 = Shift8ByUint8 + Shift16ByUint64 = Shift16ByUint8 + Shift32ByUint64 = Shift32ByUint8 + Shift64ByUint64 = 0xffffffffffffffff + + // ShiftNByUint - shifting an N bit value by a uint + Shift8ByUint = Shift8ByUint8 + Shift16ByUint = Shift16ByUint8 + Shift32ByUint = Shift32ByUint8 + Shift64ByUint = ^uint(0) +) diff --git a/vendor/github.com/klauspost/compress/zstd/blockdec.go b/vendor/github.com/klauspost/compress/zstd/blockdec.go index 2329e996f8..89b20d6a84 100644 --- a/vendor/github.com/klauspost/compress/zstd/blockdec.go +++ b/vendor/github.com/klauspost/compress/zstd/blockdec.go @@ -240,9 +240,11 @@ func (b *blockDec) decodeBuf(hist *history) error { b.dst[i] = v } hist.appendKeep(b.dst) + hist.decoders.consumeSyncLen(len(b.dst)) return nil case blockTypeRaw: hist.appendKeep(b.data) + hist.decoders.consumeSyncLen(len(b.data)) return nil case blockTypeCompressed: saved := b.dst @@ -400,8 +402,9 @@ func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err } } var err error - // Use our out buffer. - huff.MaxDecodedSize = litRegenSize + // Decoder.Decompress* uses cap(dst) for the size limit. Do not write + // MaxDecodedSize on hist.huffTree: with a trained dictionary that + // pointer aliases the shared dict.litEnc and concurrent DecodeAll races. if fourStreams { literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals) } else { @@ -486,6 +489,7 @@ func (b *blockDec) decodeCompressed(hist *history) error { } if hist.decoders.nSeqs == 0 { b.dst = append(b.dst, hist.decoders.literals...) + hist.decoders.consumeSyncLen(len(hist.decoders.literals)) return nil } before := len(hist.decoders.out) @@ -673,10 +677,6 @@ func (b *blockDec) executeSequences(hist *history) error { hbytes := hist.b if len(hbytes) > hist.windowSize { hbytes = hbytes[len(hbytes)-hist.windowSize:] - // We do not need history anymore. - if hist.dict != nil { - hist.dict.content = nil - } } hist.decoders.windowSize = hist.windowSize hist.decoders.out = b.dst[:0] diff --git a/vendor/github.com/klauspost/compress/zstd/decoder.go b/vendor/github.com/klauspost/compress/zstd/decoder.go index c7e500f02a..90ef3bb03f 100644 --- a/vendor/github.com/klauspost/compress/zstd/decoder.go +++ b/vendor/github.com/klauspost/compress/zstd/decoder.go @@ -7,8 +7,11 @@ package zstd import ( "context" "encoding/binary" + "errors" "io" + "maps" "sync" + "sync/atomic" "github.com/klauspost/compress/zstd/internal/xxhash" ) @@ -20,7 +23,8 @@ import ( // A decoder can safely be re-used even if the previous stream failed. // To release the resources, you must call the Close() function on a decoder. type Decoder struct { - o decoderOptions + // publishedOptions contains the current immutable decoder options. + publishedOptions atomic.Pointer[decoderOptions] // Unreferenced decoders, ready for use. decoders chan *blockDec @@ -84,9 +88,10 @@ var ( func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) { initPredefined() var d Decoder - d.o.setDefault() - for _, o := range opts { - err := o(&d.o) + var o decoderOptions + o.setDefault() + for _, opt := range opts { + err := opt(&o) if err != nil { return nil, err } @@ -99,17 +104,19 @@ func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) { } // Initialize dict map if needed. - if d.o.dicts == nil { - d.o.dicts = make(map[uint32]*dict) + if o.dicts == nil { + o.dicts = make(map[uint32]*dict) } // Create decoders - d.decoders = make(chan *blockDec, d.o.concurrent) - for i := 0; i < d.o.concurrent; i++ { - dec := newBlockDec(d.o.lowMem) - dec.localFrame = newFrameDec(d.o) + d.decoders = make(chan *blockDec, o.concurrent) + for i := 0; i < o.concurrent; i++ { + dec := newBlockDec(o.lowMem) + dec.localFrame = newFrameDec(o) + dec.localFrame.o.dicts = nil d.decoders <- dec } + d.publishedOptions.Store(&o) if r == nil { return &d, nil @@ -171,6 +178,9 @@ func (d *Decoder) Reset(r io.Reader) error { d.drainOutput() d.syncStream.br.r = nil + if d.frame != nil { + d.frame.o.dicts = nil + } if r == nil { d.current.err = ErrDecoderNilInput if len(d.current.b) > 0 { @@ -180,8 +190,10 @@ func (d *Decoder) Reset(r io.Reader) error { return nil } + o := *d.publishedOptions.Load() + // If bytes buffer and < 5MB, do sync decoding anyway. - if bb, ok := r.(byter); ok && bb.Len() < d.o.decodeBufsBelow && !d.o.limitToCap { + if bb, ok := r.(byter); ok && bb.Len() < o.decodeBufsBelow && !o.limitToCap { bb2 := bb if debugDecoder { println("*bytes.Buffer detected, doing sync decode, len:", bb.Len()) @@ -193,18 +205,30 @@ func (d *Decoder) Reset(r io.Reader) error { } dst, err := d.DecodeAll(b, dst) - if err == nil { - err = io.EOF + if !errors.Is(err, ErrDecoderSizeExceeded) { + if err == nil { + err = io.EOF + } + // Save output buffer + d.syncStream.dstBuf = dst + d.current.b = dst + d.current.err = err + d.current.flushed = true + if debugDecoder { + println("sync decode to", len(dst), "bytes, err:", err) + } + return nil } - // Save output buffer - d.syncStream.dstBuf = dst - d.current.b = dst - d.current.err = err - d.current.flushed = true + // The output does not fit WithDecoderMaxMemory, which caps the total + // decoded size when decoding in memory. A Reader follows the + // streaming contract, where the option caps the window instead, so + // decode this input as a stream after all; the shortcut has not + // consumed the reader. Drop the oversized buffer rather than keep it + // for reuse. if debugDecoder { - println("sync decode to", len(dst), "bytes, err:", err) + println("sync decode exceeded max memory after", len(dst), "bytes; streaming instead") } - return nil + d.syncStream.dstBuf = nil } // Remove current block. d.stashDecoder() @@ -217,14 +241,16 @@ func (d *Decoder) Reset(r io.Reader) error { // Ensure no-one else is still running... d.streamWg.Wait() if d.frame == nil { - d.frame = newFrameDec(d.o) + d.frame = newFrameDec(o) + } else { + d.frame.setOptions(o) } - if d.o.concurrent == 1 { + if o.concurrent == 1 { return d.startSyncDecoder(r) } - d.current.output = make(chan decodeOutput, d.o.concurrent) + d.current.output = make(chan decodeOutput, o.concurrent) ctx, cancel := context.WithCancel(context.Background()) d.current.cancel = cancel d.streamWg.Add(1) @@ -238,13 +264,21 @@ func (d *Decoder) Reset(r io.Reader) error { // Options are applied on top of the existing options. // Some options cannot be changed on reset and will return an error. func (d *Decoder) ResetWithOptions(r io.Reader, opts ...DOption) error { - d.o.resetOpt = true - defer func() { d.o.resetOpt = false }() + if d.current.err == ErrDecoderClosed { + return d.current.err + } + next := *d.publishedOptions.Load() + next.dicts = maps.Clone(next.dicts) + next.resetOpt = true for _, o := range opts { - if err := o(&d.o); err != nil { + if err := o(&next); err != nil { + next.resetOpt = false + d.publishedOptions.Store(&next) return err } } + next.resetOpt = false + d.publishedOptions.Store(&next) return d.Reset(r) } @@ -324,6 +358,8 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { // Grab a block decoder and frame decoder. block := <-d.decoders frame := block.localFrame + o := *d.publishedOptions.Load() + frame.setOptions(o) initialSize := len(dst) defer func() { if debugDecoder { @@ -335,6 +371,7 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { frame.history.decoders.br.in = nil frame.history.decoders.br.cursor = 0 } + frame.o.dicts = nil d.decoders <- block }() frame.bBuf = input @@ -354,20 +391,20 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { if err = d.setDict(frame); err != nil { return nil, err } - if frame.WindowSize > d.o.maxWindowSize { + if frame.WindowSize > frame.o.maxWindowSize { if debugDecoder { - println("window size exceeded:", frame.WindowSize, ">", d.o.maxWindowSize) + println("window size exceeded:", frame.WindowSize, ">", frame.o.maxWindowSize) } return dst, ErrWindowSizeExceeded } if frame.FrameContentSize != fcsUnknown { - if frame.FrameContentSize > d.o.maxDecodedSize-uint64(len(dst)-initialSize) { + if frame.FrameContentSize > frame.o.maxDecodedSize-uint64(len(dst)-initialSize) { if debugDecoder { - println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", d.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst)) + println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", frame.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst)) } return dst, ErrDecoderSizeExceeded } - if d.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) { + if frame.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) { if debugDecoder { println("decoder size exceeded; fcs:", frame.FrameContentSize, "> (cap-len)", cap(dst)-len(dst)) } @@ -380,14 +417,14 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { } } - if cap(dst) == 0 && !d.o.limitToCap { + if cap(dst) == 0 && !frame.o.limitToCap { // Allocate len(input) * 2 by default if nothing is provided // and we didn't get frame content size. size := min( // Cap to 1 MB. len(input)*2, 1<<20) - if uint64(size) > d.o.maxDecodedSize { - size = int(d.o.maxDecodedSize) + if uint64(size) > frame.o.maxDecodedSize { + size = int(frame.o.maxDecodedSize) } dst = make([]byte, 0, size) } @@ -396,7 +433,7 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { if err != nil { return dst, err } - if uint64(len(dst)-initialSize) > d.o.maxDecodedSize { + if uint64(len(dst)-initialSize) > frame.o.maxDecodedSize { return dst, ErrDecoderSizeExceeded } if len(frame.bBuf) == 0 { @@ -459,7 +496,7 @@ func (d *Decoder) nextBlock(blocking bool) (ok bool) { println("got", len(d.current.b), "bytes, error:", d.current.err, "data crc:", tmp) } - if d.o.ignoreChecksum { + if d.frame.o.ignoreChecksum { return true } @@ -497,7 +534,7 @@ func (d *Decoder) nextBlockSync() (ok bool) { if d.current.err != nil { return false } - if d.frame.WindowSize > d.o.maxDecodedSize || d.frame.WindowSize > d.o.maxWindowSize { + if d.frame.WindowSize > d.frame.o.maxDecodedSize || d.frame.WindowSize > d.frame.o.maxWindowSize { d.current.err = ErrDecoderSizeExceeded return false } @@ -546,11 +583,11 @@ func (d *Decoder) nextBlockSync() (ok bool) { // Update/Check CRC if d.frame.HasCheckSum { - if !d.o.ignoreChecksum { + if !d.frame.o.ignoreChecksum { d.frame.crc.Write(d.current.b) } if d.current.d.Last { - if !d.o.ignoreChecksum { + if !d.frame.o.ignoreChecksum { d.current.err = d.frame.checkCRC() } else { d.current.err = d.frame.consumeCRC() @@ -656,8 +693,8 @@ func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output ch defer d.streamWg.Done() br := readerWrapper{r: r} - var seqDecode = make(chan *blockDec, d.o.concurrent) - var seqExecute = make(chan *blockDec, d.o.concurrent) + var seqDecode = make(chan *blockDec, d.frame.o.concurrent) + var seqExecute = make(chan *blockDec, d.frame.o.concurrent) // Async 1: Decode sequences... go func() { @@ -858,9 +895,9 @@ decodeStream: if err == nil { err = d.setDict(frame) } - if err == nil && d.frame.WindowSize > d.o.maxWindowSize { + if err == nil && d.frame.WindowSize > d.frame.o.maxWindowSize { if debugDecoder { - println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.o.maxWindowSize) + println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.frame.o.maxWindowSize) } err = ErrDecoderSizeExceeded @@ -940,7 +977,7 @@ decodeStream: } func (d *Decoder) setDict(frame *frameDec) (err error) { - dict, ok := d.o.dicts[frame.DictionaryID] + dict, ok := frame.o.dicts[frame.DictionaryID] if ok { if debugDecoder { println("setting dict", frame.DictionaryID) diff --git a/vendor/github.com/klauspost/compress/zstd/dict.go b/vendor/github.com/klauspost/compress/zstd/dict.go index 4f1c4938cd..67f40e7914 100644 --- a/vendor/github.com/klauspost/compress/zstd/dict.go +++ b/vendor/github.com/klauspost/compress/zstd/dict.go @@ -296,40 +296,81 @@ func BuildDict(o BuildDictOptions) ([]byte, error) { if offset > 3 { newOffsets[offset-3]++ } else { - newOffsets[uint32(o.Offsets[offset-1])]++ + // Repeat codes reference the training Offsets. Skip unset + // (zero) entries so they are not ranked as real offsets. + prev := o.Offsets[offset-1] + if prev > 0 { + newOffsets[uint32(prev)]++ + } } } } // Find most used offsets. var sortedOffsets []uint32 for k := range newOffsets { + if k == 0 { + continue + } sortedOffsets = append(sortedOffsets, k) } sort.Slice(sortedOffsets, func(i, j int) bool { a, b := sortedOffsets[i], sortedOffsets[j] - if a == b { + ca, cb := newOffsets[a], newOffsets[b] + if ca == cb { // Prefer the longer offset - return sortedOffsets[i] > sortedOffsets[j] + return a > b } - return newOffsets[sortedOffsets[i]] > newOffsets[sortedOffsets[j]] + return ca > cb }) - if len(sortedOffsets) > 3 { - if debug { - print("Offsets:") - for i, v := range sortedOffsets { - if i > 20 { - break - } - printf("[%d: %d],", v, newOffsets[v]) + if debug { + print("Offsets:") + for i, v := range sortedOffsets { + if i > 20 { + break } - println("") + printf("[%d: %d],", v, newOffsets[v]) + } + println("") + } + // Dictionary recent-offsets must be three positive values within the + // history. Ranked matches may be fewer (or empty when only unset + // repeat codes were seen), so fill remaining slots with defaults. + used := make(map[int]bool, 3) + var finalOffsets [3]int + nOff := 0 + for _, v := range sortedOffsets { + iv := int(v) + if iv <= 0 || iv > len(hist) || used[iv] { + continue + } + finalOffsets[nOff] = iv + used[iv] = true + nOff++ + if nOff == 3 { + break } - - sortedOffsets = sortedOffsets[:3] } - for i, v := range sortedOffsets { - o.Offsets[i] = int(v) + for _, def := range []int{1, 4, 8} { + if nOff == 3 { + break + } + if def <= len(hist) && !used[def] { + finalOffsets[nOff] = def + used[def] = true + nOff++ + } + } + for def := 1; nOff < 3 && def <= len(hist); def++ { + if !used[def] { + finalOffsets[nOff] = def + used[def] = true + nOff++ + } + } + if nOff < 3 { + return nil, fmt.Errorf("could not determine 3 valid dictionary offsets (history size %d)", len(hist)) } + o.Offsets = finalOffsets if debug { println("New repeat offsets", o.Offsets) } @@ -337,6 +378,9 @@ func BuildDict(o BuildDictOptions) ([]byte, error) { if nUsed == 0 || seqs == 0 { return nil, fmt.Errorf("%d blocks, %d sequences found", nUsed, seqs) } + if litTotal == 0 { + return nil, errors.New("0 literals found") + } if debug { println("Sequences:", seqs, "Blocks:", nUsed, "Literals:", litTotal) } @@ -517,11 +561,10 @@ func BuildDict(o BuildDictOptions) ([]byte, error) { out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[1]))) out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[2]))) out.Write(hist) + if _, err := loadDict(out.Bytes()); err != nil { + return nil, fmt.Errorf("built dictionary failed validation: %w", err) + } if debug { - _, err := loadDict(out.Bytes()) - if err != nil { - panic(err) - } i, err := InspectDictionary(out.Bytes()) if err != nil { panic(err) diff --git a/vendor/github.com/klauspost/compress/zstd/framedec.go b/vendor/github.com/klauspost/compress/zstd/framedec.go index d88f067e5c..81d8b9c922 100644 --- a/vendor/github.com/klauspost/compress/zstd/framedec.go +++ b/vendor/github.com/klauspost/compress/zstd/framedec.go @@ -49,13 +49,16 @@ const ( ) func newFrameDec(o decoderOptions) *frameDec { + d := frameDec{} + d.setOptions(o) + return &d +} + +func (d *frameDec) setOptions(o decoderOptions) { if o.maxWindowSize > o.maxDecodedSize { o.maxWindowSize = o.maxDecodedSize } - d := frameDec{ - o: o, - } - return &d + d.o = o } // reset will read the frame header and prepare for block decoding. diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s b/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s index 77ee3913f0..8ca913eaec 100644 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s @@ -1,7 +1,7 @@ // Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT. // EXPERIMENTAL arm64 output lowered from an amd64 avo program. -//go:build arm64 && !appengine && !noasm && gc && !noasm +//go:build arm64 && (!appengine && !noasm && gc && !noasm) // func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int TEXT ·buildDtable_asm(SB), $0-24 @@ -26,11 +26,10 @@ TEXT ·buildDtable_asm(SB), $0-24 JMP init_main_loop_condition init_main_loop: - ADD R8<<1, R1, R15 - MOVH (R15), R9 - AND $0xffff, R9, R15 + MOVH (R1)(R8<<1), R9 MOVD $-1, R16 AND $0xffff, R16, R16 + AND $0xffff, R9, R15 CMP R16, R15 BNE do_not_update_high_threshold ADD R7<<3, R5, R15 @@ -39,8 +38,7 @@ init_main_loop: MOVD $0x0000000000000001, R9 do_not_update_high_threshold: - ADD R8<<1, R3, R15 - MOVH R9, (R15) + MOVH R9, (R3)(R8<<1) ADD $1, R8, R8 init_main_loop_condition: @@ -49,12 +47,10 @@ init_main_loop_condition: // Spread symbols // Calculate table step - MOVD R0, R8 - LSR $0x01, R8, R8 - MOVD R0, R9 - LSR $0x03, R9, R9 - ADD R9, R8, R8 - ADD $3, R8, R8 + LSR $0x01, R0, R8 + LSR $0x03, R0, R9 + ADD R9, R8, R8 + ADD $3, R8, R8 // Fill add bits values SUB $1, R0, R9 @@ -64,8 +60,7 @@ init_main_loop_condition: spread_main_loop: MOVD $0, R12 - ADD R11<<1, R1, R15 - MOVH (R15), R13 + MOVH (R1)(R11<<1), R13 JMP spread_inner_loop_condition spread_inner_loop: @@ -102,11 +97,9 @@ spread_check_ok: build_table_main_table: ADD R6<<3, R5, R15 MOVBU 1(R15), R1 - ADD R1<<1, R3, R15 - MOVHU (R15), R7 + MOVHU (R3)(R1<<1), R7 ADD $1, R7, R8 - ADD R1<<1, R3, R15 - MOVH R8, (R15) + MOVH R8, (R3)(R1<<1) MOVD R7, R8 CLZ R8, R16 MOVD $63, R8 @@ -129,12 +122,10 @@ build_table_main_table: RET build_table_check1_ok: - AND $0xff, R1, R15 - AND $0xff, R1, R16 - TST R16, R15 + TST $0xff, R1 BNE build_table_check2_ok - AND $0xffff, R7, R15 AND $0xffff, R6, R16 + AND $0xffff, R7, R15 CMP R16, R15 BNE build_table_check2_ok MOVD ctx+8(FP), R0 diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go index fc40c82001..9c0cbc1681 100644 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go @@ -52,6 +52,11 @@ func (d *Digest) Reset() { d.n = 0 } +// maxAsmSize bounds the input handed to a single writeBlocks call. Assembly is +// never preemptible, so an unbounded call holds every P in stop-the-world for +// its duration. Whole 32-byte blocks, so Write can feed it in pieces. +const maxAsmSize = 128 << 10 // 4096 whole 32-byte blocks + // Size always returns 8 bytes. func (d *Digest) Size() int { return 8 } @@ -83,6 +88,13 @@ func (d *Digest) Write(b []byte) (n int, err error) { d.n = 0 } + for len(b) >= maxAsmSize { + // Assembly is not preemptible, so hashing a large buffer in one call + // blocks every stop-the-world for the whole call. Feed it in chunks. + writeBlocks(d, b[:maxAsmSize]) + b = b[maxAsmSize:] + } + if len(b) >= 32 { // One or more full blocks left. nw := writeBlocks(d, b) diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s index ddb63aa91b..e4c688efd3 100644 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s @@ -175,7 +175,11 @@ finalize: RET // func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 +// +// Deliberately not NOSPLIT: the stack check is the preemption point that lets a +// stop-the-world proceed between chunks. The frame must be >= abi.StackSmall +// (128), or the assembler marks this leaf NOSPLIT anyway and drops that check. +TEXT ·writeBlocks(SB), $128-40 // Load fixed primes needed for round. MOVQ ·primes+0(SB), prime1 MOVQ ·primes+8(SB), prime2 diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s index ae7d4d3295..e88cc2fc91 100644 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s @@ -163,7 +163,11 @@ finalize: RET // func writeBlocks(s *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 +// +// Deliberately not NOSPLIT: the stack check is the preemption point that lets a +// stop-the-world proceed between chunks. The frame must be >= abi.StackSmall +// (128), or the assembler marks this leaf NOSPLIT anyway and drops that check. +TEXT ·writeBlocks(SB), $128-40 LDP ·primes+0(SB), (prime1, prime2) // Load state. Assume v[1-4] are stored contiguously. diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec.go b/vendor/github.com/klauspost/compress/zstd/seqdec.go index 0bfb0e43c7..d1a7732fcc 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec.go @@ -99,6 +99,29 @@ func (s *sequenceDecs) initialize(br *bitReader, hist *history, out []byte) erro return nil } +// consumeSyncLen accounts for n bytes of frame output produced outside +// decodeSync. maxSyncLen bounds how much the frame may still produce and +// decodeSyncSimple compares it with the output buffer's slack to decide +// whether the extended 16-byte copies are safe. Blocks with sequences +// subtracted their output; raw blocks, RLE blocks and compressed blocks +// holding only literals did not, so a frame that opened with a raw block +// overstated its remaining size for every block after it and ran the +// bounds-exact copies for the rest of the frame. +// +// Zero means "no bound" and selects the conservative paths, so a block that +// meets or exceeds the bound lands there; the frame-size checks in +// runDecoder reject the excess afterwards. +func (s *sequenceDecs) consumeSyncLen(n int) { + if s.maxSyncLen == 0 { + return + } + if uint64(n) >= s.maxSyncLen { + s.maxSyncLen = 0 + return + } + s.maxSyncLen -= uint64(n) +} + func (s *sequenceDecs) freeDecoders() { if f := s.litLengths.fse; f != nil && !f.preDefined { fseDecoderPool.Put(f) diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s index 3fc381c7a7..798d940231 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s @@ -4,7 +4,7 @@ // func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV -TEXT ·sequenceDecs_decode_amd64(SB), $8-32 +TEXT ·sequenceDecs_decode_amd64(SB), $40-32 MOVQ br+8(FP), CX MOVQ 24(CX), DX MOVBQZX 40(CX), BX @@ -16,6 +16,14 @@ TEXT ·sequenceDecs_decode_amd64(SB), $8-32 MOVQ 72(AX), DI MOVQ 80(AX), R8 MOVQ 88(AX), R9 + MOVQ (AX), CX + MOVQ CX, 8(SP) + MOVQ 24(AX), CX + MOVQ CX, 16(SP) + MOVQ 48(AX), CX + MOVQ CX, 24(SP) + MOVQ 96(AX), CX + MOVQ CX, 32(SP) MOVQ 104(AX), R10 MOVQ s+0(FP), AX MOVQ 144(AX), R11 @@ -55,46 +63,32 @@ sequenceDecs_decode_amd64_fill_check_overread: sequenceDecs_decode_amd64_fill_end: // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_of_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_of_update_zero: - MOVQ AX, 16(R10) + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, 16(R10) // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_ml_update_zero: - MOVQ AX, 8(R10) + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, 8(R10) // Fill bitreader to have enough for the remaining CMPQ SI, $0x08 @@ -126,90 +120,76 @@ sequenceDecs_decode_amd64_fill_2_check_overread: sequenceDecs_decode_amd64_fill_2_end: // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_ll_update_zero: - MOVQ AX, (R10) + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, (R10) // Fill bitreader for state updates MOVQ R14, (SP) MOVQ R9, AX SHRQ $0x08, AX MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decode_amd64_skip_update // Update Literal Length State MOVBQZX DI, R14 SHRL $0x10, DI - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, DI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(DI*8), DI // Update Match Length State MOVBQZX R8, R14 SHRL $0x10, R8 - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, R8 // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(R8*8), R8 // Update Offset State MOVBQZX R9, R14 SHRL $0x10, R9 - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, R9 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R9*8), R9 sequenceDecs_decode_amd64_skip_update: @@ -290,8 +270,7 @@ sequenceDecs_decode_amd64_after_adjust: sequenceDecs_decode_amd64_match_len_ofs_ok: ADDQ $0x18, R10 - MOVQ ctx+16(FP), AX - DECQ 96(AX) + DECQ 32(SP) JNS sequenceDecs_decode_amd64_main_loop MOVQ s+0(FP), AX MOVQ R11, 144(AX) @@ -303,36 +282,54 @@ sequenceDecs_decode_amd64_match_len_ofs_ok: MOVQ SI, 32(AX) // Return success + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000000, ret+24(FP) RET // Return with match length error sequenceDecs_decode_amd64_error_match_len_ofs_mismatch: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000001, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_amd64_error_match_len_too_big: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000002, ret+24(FP) RET // Return with match offset too long error + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000003, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000004, ret+24(FP) RET // Return with overread error error_overread: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000006, ret+24(FP) RET // func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV -TEXT ·sequenceDecs_decode_56_amd64(SB), $8-32 +TEXT ·sequenceDecs_decode_56_amd64(SB), $40-32 MOVQ br+8(FP), CX MOVQ 24(CX), DX MOVBQZX 40(CX), BX @@ -344,6 +341,14 @@ TEXT ·sequenceDecs_decode_56_amd64(SB), $8-32 MOVQ 72(AX), DI MOVQ 80(AX), R8 MOVQ 88(AX), R9 + MOVQ (AX), CX + MOVQ CX, 8(SP) + MOVQ 24(AX), CX + MOVQ CX, 16(SP) + MOVQ 48(AX), CX + MOVQ CX, 24(SP) + MOVQ 96(AX), CX + MOVQ CX, 32(SP) MOVQ 104(AX), R10 MOVQ s+0(FP), AX MOVQ 144(AX), R11 @@ -383,132 +388,104 @@ sequenceDecs_decode_56_amd64_fill_check_overread: sequenceDecs_decode_56_amd64_fill_end: // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_of_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_of_update_zero: - MOVQ AX, 16(R10) + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, 16(R10) // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_ml_update_zero: - MOVQ AX, 8(R10) + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, 8(R10) // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_ll_update_zero: - MOVQ AX, (R10) + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, (R10) // Fill bitreader for state updates MOVQ R14, (SP) MOVQ R9, AX SHRQ $0x08, AX MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decode_56_amd64_skip_update // Update Literal Length State MOVBQZX DI, R14 SHRL $0x10, DI - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, DI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(DI*8), DI // Update Match Length State MOVBQZX R8, R14 SHRL $0x10, R8 - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, R8 // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(R8*8), R8 // Update Offset State MOVBQZX R9, R14 SHRL $0x10, R9 - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, R9 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R9*8), R9 sequenceDecs_decode_56_amd64_skip_update: @@ -589,8 +566,7 @@ sequenceDecs_decode_56_amd64_after_adjust: sequenceDecs_decode_56_amd64_match_len_ofs_ok: ADDQ $0x18, R10 - MOVQ ctx+16(FP), AX - DECQ 96(AX) + DECQ 32(SP) JNS sequenceDecs_decode_56_amd64_main_loop MOVQ s+0(FP), AX MOVQ R11, 144(AX) @@ -602,36 +578,54 @@ sequenceDecs_decode_56_amd64_match_len_ofs_ok: MOVQ SI, 32(AX) // Return success + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000000, ret+24(FP) RET // Return with match length error sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000001, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_56_amd64_error_match_len_too_big: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000002, ret+24(FP) RET // Return with match offset too long error + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000003, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000004, ret+24(FP) RET // Return with overread error error_overread: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000006, ret+24(FP) RET // func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: BMI, BMI2, CMOV -TEXT ·sequenceDecs_decode_bmi2(SB), $8-32 +TEXT ·sequenceDecs_decode_bmi2(SB), $40-32 MOVQ br+8(FP), BX MOVQ 24(BX), AX MOVBQZX 40(BX), DX @@ -643,6 +637,14 @@ TEXT ·sequenceDecs_decode_bmi2(SB), $8-32 MOVQ 72(CX), SI MOVQ 80(CX), DI MOVQ 88(CX), R8 + MOVQ (CX), R9 + MOVQ R9, 8(SP) + MOVQ 24(CX), R9 + MOVQ R9, 16(SP) + MOVQ 48(CX), R9 + MOVQ R9, 24(SP) + MOVQ 96(CX), R9 + MOVQ R9, 32(SP) MOVQ 104(CX), R9 MOVQ s+0(FP), CX MOVQ 144(CX), R10 @@ -753,8 +755,7 @@ sequenceDecs_decode_bmi2_fill_2_end: MOVQ R13, (SP) MOVQ $0x00000808, CX BEXTRQ CX, R8, R13 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decode_bmi2_skip_update LEAQ (SI)(DI*1), R14 ADDQ R8, R14 @@ -772,8 +773,7 @@ sequenceDecs_decode_bmi2_fill_2_end: ADDQ CX, R8 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R8*8), R8 // Update Match Length State @@ -783,8 +783,7 @@ sequenceDecs_decode_bmi2_fill_2_end: ADDQ CX, DI // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(DI*8), DI // Update Literal Length State @@ -793,8 +792,7 @@ sequenceDecs_decode_bmi2_fill_2_end: ADDQ CX, SI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(SI*8), SI sequenceDecs_decode_bmi2_skip_update: @@ -875,8 +873,7 @@ sequenceDecs_decode_bmi2_after_adjust: sequenceDecs_decode_bmi2_match_len_ofs_ok: ADDQ $0x18, R9 - MOVQ ctx+16(FP), CX - DECQ 96(CX) + DECQ 32(SP) JNS sequenceDecs_decode_bmi2_main_loop MOVQ s+0(FP), CX MOVQ R10, 144(CX) @@ -888,36 +885,54 @@ sequenceDecs_decode_bmi2_match_len_ofs_ok: MOVQ BX, 32(CX) // Return success + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000000, ret+24(FP) RET // Return with match length error sequenceDecs_decode_bmi2_error_match_len_ofs_mismatch: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000001, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_bmi2_error_match_len_too_big: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000002, ret+24(FP) RET // Return with match offset too long error + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000003, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000004, ret+24(FP) RET // Return with overread error error_overread: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000006, ret+24(FP) RET // func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: BMI, BMI2, CMOV -TEXT ·sequenceDecs_decode_56_bmi2(SB), $8-32 +TEXT ·sequenceDecs_decode_56_bmi2(SB), $40-32 MOVQ br+8(FP), BX MOVQ 24(BX), AX MOVBQZX 40(BX), DX @@ -929,6 +944,14 @@ TEXT ·sequenceDecs_decode_56_bmi2(SB), $8-32 MOVQ 72(CX), SI MOVQ 80(CX), DI MOVQ 88(CX), R8 + MOVQ (CX), R9 + MOVQ R9, 8(SP) + MOVQ 24(CX), R9 + MOVQ R9, 16(SP) + MOVQ 48(CX), R9 + MOVQ R9, 24(SP) + MOVQ 96(CX), R9 + MOVQ R9, 32(SP) MOVQ 104(CX), R9 MOVQ s+0(FP), CX MOVQ 144(CX), R10 @@ -1010,8 +1033,7 @@ sequenceDecs_decode_56_bmi2_fill_end: MOVQ R13, (SP) MOVQ $0x00000808, CX BEXTRQ CX, R8, R13 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decode_56_bmi2_skip_update LEAQ (SI)(DI*1), R14 ADDQ R8, R14 @@ -1029,8 +1051,7 @@ sequenceDecs_decode_56_bmi2_fill_end: ADDQ CX, R8 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R8*8), R8 // Update Match Length State @@ -1040,8 +1061,7 @@ sequenceDecs_decode_56_bmi2_fill_end: ADDQ CX, DI // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(DI*8), DI // Update Literal Length State @@ -1050,8 +1070,7 @@ sequenceDecs_decode_56_bmi2_fill_end: ADDQ CX, SI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(SI*8), SI sequenceDecs_decode_56_bmi2_skip_update: @@ -1132,8 +1151,7 @@ sequenceDecs_decode_56_bmi2_after_adjust: sequenceDecs_decode_56_bmi2_match_len_ofs_ok: ADDQ $0x18, R9 - MOVQ ctx+16(FP), CX - DECQ 96(CX) + DECQ 32(SP) JNS sequenceDecs_decode_56_bmi2_main_loop MOVQ s+0(FP), CX MOVQ R10, 144(CX) @@ -1145,30 +1163,48 @@ sequenceDecs_decode_56_bmi2_match_len_ofs_ok: MOVQ BX, 32(CX) // Return success + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000000, ret+24(FP) RET // Return with match length error sequenceDecs_decode_56_bmi2_error_match_len_ofs_mismatch: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000001, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_56_bmi2_error_match_len_too_big: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000002, ret+24(FP) RET // Return with match offset too long error + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000003, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000004, ret+24(FP) RET // Return with overread error error_overread: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000006, ret+24(FP) RET @@ -1203,9 +1239,11 @@ main_loop: MOVQ 8(AX), R13 // Copy literals - TESTQ R11, R11 - JZ check_offset - XORQ R14, R14 + MOVUPS (SI), X0 + MOVUPS X0, (BX) + CMPQ R11, $0x10 + JBE copy_1_end + MOVQ $0x00000010, R14 copy_1: MOVUPS (SI)(R14*1), X0 @@ -1213,12 +1251,13 @@ copy_1: ADDQ $0x10, R14 CMPQ R14, R11 JB copy_1 - ADDQ R11, SI - ADDQ R11, BX - ADDQ R11, DI + +copy_1_end: + ADDQ R11, SI + ADDQ R11, BX + ADDQ R11, DI // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: LEAQ (DI)(R10*1), R11 CMPQ R12, R11 JG error_match_off_too_big @@ -1258,13 +1297,13 @@ copy_4_small: JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), R11 - MOVB 2(R14), R12 - MOVW R11, (BX) - MOVB R12, 2(BX) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end + MOVWQZX (R14), R11 + MOVB 2(R14), R12 + MOVW R11, (BX) + MOVB R12, 2(BX) + ADDQ R13, R14 + ADDQ R13, BX + JMP copy_4_end copy_4_move_4through7: MOVL (R14), R11 @@ -1327,13 +1366,13 @@ copy_5_move_1or2: JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (BX) - MOVB BP, 2(BX) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (BX) + MOVB BP, 2(BX) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 @@ -1366,9 +1405,19 @@ copy_match: JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, DI - MOVQ BX, R12 + ADDQ R13, DI + MOVUPS (R11), X0 + MOVUPS X0, (BX) + CMPQ R13, $0x10 + JA copy_2_long + ADDQ R13, BX + JMP handle_loop + +copy_2_long: + LEAQ 16(BX), R12 ADDQ R13, BX + ADDQ $0x10, R11 + SUBQ $0x10, R13 copy_2: MOVUPS (R11), X0 @@ -1384,12 +1433,12 @@ copy_overlapping_match: ADDQ R13, DI copy_slow_3: - MOVB (R11), R12 - MOVB R12, (BX) - INCQ R11 - INCQ BX - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (R11), R12 + MOVB R12, (BX) + INCQ R11 + INCQ BX + DECQ R13 + JNZ copy_slow_3 handle_loop: ADDQ $0x18, AX @@ -1494,13 +1543,13 @@ copy_1_move_1or2: JMP copy_1_end copy_1_move_3: - MOVW (SI), R14 - MOVB 2(SI), R15 - MOVW R14, (BX) - MOVB R15, 2(BX) - ADDQ R11, SI - ADDQ R11, BX - JMP copy_1_end + MOVWQZX (SI), R14 + MOVB 2(SI), R15 + MOVW R14, (BX) + MOVB R15, 2(BX) + ADDQ R11, SI + ADDQ R11, BX + JMP copy_1_end copy_1_move_4through7: MOVL (SI), R14 @@ -1563,13 +1612,13 @@ copy_4_small: JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), R11 - MOVB 2(R14), R12 - MOVW R11, (BX) - MOVB R12, 2(BX) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end + MOVWQZX (R14), R11 + MOVB 2(R14), R12 + MOVW R11, (BX) + MOVB R12, 2(BX) + ADDQ R13, R14 + ADDQ R13, BX + JMP copy_4_end copy_4_move_4through7: MOVL (R14), R11 @@ -1632,13 +1681,13 @@ copy_5_move_1or2: JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (BX) - MOVB BP, 2(BX) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (BX) + MOVB BP, 2(BX) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 @@ -1707,13 +1756,13 @@ copy_2_move_1or2: JMP copy_2_end copy_2_move_3: - MOVW (R11), R12 - MOVB 2(R11), R14 - MOVW R12, (BX) - MOVB R14, 2(BX) - ADDQ R13, R11 - ADDQ R13, BX - JMP copy_2_end + MOVWQZX (R11), R12 + MOVB 2(R11), R14 + MOVW R12, (BX) + MOVB R14, 2(BX) + ADDQ R13, R11 + ADDQ R13, BX + JMP copy_2_end copy_2_move_4through7: MOVL (R11), R12 @@ -1740,12 +1789,12 @@ copy_overlapping_match: ADDQ R13, DI copy_slow_3: - MOVB (R11), R12 - MOVB R12, (BX) - INCQ R11 - INCQ BX - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (R11), R12 + MOVB R12, (BX) + INCQ R11 + INCQ BX + DECQ R13 + JNZ copy_slow_3 handle_loop: ADDQ $0x18, AX @@ -1784,7 +1833,7 @@ empty_seqs: // func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_amd64(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_amd64(SB), $96-32 MOVQ br+8(FP), CX MOVQ 24(CX), DX MOVBQZX 40(CX), BX @@ -1796,26 +1845,34 @@ TEXT ·sequenceDecs_decodeSync_amd64(SB), $64-32 MOVQ 72(AX), DI MOVQ 80(AX), R8 MOVQ 88(AX), R9 - XORQ CX, CX + MOVQ (AX), CX MOVQ CX, 8(SP) + MOVQ 24(AX), CX MOVQ CX, 16(SP) + MOVQ 48(AX), CX MOVQ CX, 24(SP) + MOVQ 96(AX), CX + MOVQ CX, 32(SP) + XORQ CX, CX + MOVQ CX, 40(SP) + MOVQ CX, 48(SP) + MOVQ CX, 56(SP) MOVQ 112(AX), R10 MOVQ 128(AX), CX - MOVQ CX, 32(SP) + MOVQ CX, 64(SP) MOVQ 144(AX), R11 MOVQ 136(AX), R12 MOVQ 200(AX), CX - MOVQ CX, 56(SP) + MOVQ CX, 88(SP) MOVQ 176(AX), CX - MOVQ CX, 48(SP) + MOVQ CX, 80(SP) MOVQ 184(AX), AX - MOVQ AX, 40(SP) - MOVQ 40(SP), AX - ADDQ AX, 48(SP) + MOVQ AX, 72(SP) + MOVQ 72(SP), AX + ADDQ AX, 80(SP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - ADDQ R10, 32(SP) + ADDQ R10, 64(SP) // outBase += outPosition ADDQ R12, R10 @@ -1853,46 +1910,32 @@ sequenceDecs_decodeSync_amd64_fill_check_overread: sequenceDecs_decodeSync_amd64_fill_end: // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_of_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_of_update_zero: - MOVQ AX, 8(SP) + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 40(SP) // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_ml_update_zero: - MOVQ AX, 16(SP) + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 48(SP) // Fill bitreader to have enough for the remaining CMPQ SI, $0x08 @@ -1924,96 +1967,82 @@ sequenceDecs_decodeSync_amd64_fill_2_check_overread: sequenceDecs_decodeSync_amd64_fill_2_end: // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_ll_update_zero: - MOVQ AX, 24(SP) + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 56(SP) // Fill bitreader for state updates MOVQ R13, (SP) MOVQ R9, AX SHRQ $0x08, AX MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decodeSync_amd64_skip_update // Update Literal Length State MOVBQZX DI, R13 SHRL $0x10, DI - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, DI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(DI*8), DI // Update Match Length State MOVBQZX R8, R13 SHRL $0x10, R8 - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, R8 // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(R8*8), R8 // Update Offset State MOVBQZX R9, R13 SHRL $0x10, R9 - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, R9 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R9*8), R9 sequenceDecs_decodeSync_amd64_skip_update: // Adjust offset MOVQ s+0(FP), CX - MOVQ 8(SP), R13 + MOVQ 40(SP), R13 CMPQ AX, $0x01 JBE sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0 MOVUPS 144(CX), X0 @@ -2022,7 +2051,7 @@ sequenceDecs_decodeSync_amd64_skip_update: JMP sequenceDecs_decodeSync_amd64_after_adjust sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 + CMPQ 56(SP), $0x00000000 JNE sequenceDecs_decodeSync_amd64_adjust_offset_maybezero INCQ R13 JMP sequenceDecs_decodeSync_amd64_adjust_offset_nonzero @@ -2057,14 +2086,11 @@ sequenceDecs_decodeSync_amd64_adjust_skip: MOVQ R14, R13 sequenceDecs_decodeSync_amd64_after_adjust: - MOVQ R13, 8(SP) + MOVQ R13, 40(SP) // Check values - MOVQ 16(SP), AX - MOVQ 24(SP), CX - LEAQ (AX)(CX*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) + MOVQ 48(SP), AX + MOVQ 56(SP), CX MOVQ ctx+16(FP), R14 SUBQ CX, 104(R14) JS error_not_enough_literals @@ -2076,50 +2102,49 @@ sequenceDecs_decodeSync_amd64_after_adjust: JNZ sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch sequenceDecs_decodeSync_amd64_match_len_ofs_ok: - MOVQ 24(SP), AX - MOVQ 8(SP), CX - MOVQ 16(SP), R13 - // Check if we have enough space in s.out - LEAQ (AX)(R13*1), R14 + LEAQ 16(CX)(AX*1), R14 ADDQ R10, R14 - CMPQ R14, 32(SP) + CMPQ R14, 64(SP) JA error_not_enough_space // Copy literals - TESTQ AX, AX - JZ check_offset - XORQ R14, R14 + MOVUPS (R11), X0 + MOVUPS X0, (R10) + CMPQ CX, $0x10 + JBE copy_1_end + MOVQ $0x00000010, R14 copy_1: MOVUPS (R11)(R14*1), X0 MOVUPS X0, (R10)(R14*1) ADDQ $0x10, R14 - CMPQ R14, AX + CMPQ R14, CX JB copy_1 - ADDQ AX, R11 - ADDQ AX, R10 - ADDQ AX, R12 + +copy_1_end: + ADDQ CX, R11 + ADDQ CX, R10 + ADDQ CX, R12 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R12, AX - ADDQ 40(SP), AX - CMPQ CX, AX + MOVQ R12, CX + ADDQ 72(SP), CX + CMPQ R13, CX JG error_match_off_too_big - CMPQ CX, 56(SP) + CMPQ R13, 88(SP) JG error_match_off_too_big // Copy match from history - MOVQ CX, AX - SUBQ R12, AX + MOVQ R13, CX + SUBQ R12, CX JLS copy_match - MOVQ 48(SP), R14 - SUBQ AX, R14 - CMPQ R13, AX + MOVQ 80(SP), R14 + SUBQ CX, R14 + CMPQ AX, CX JG copy_all_from_history - MOVQ R13, AX - SUBQ $0x10, AX + MOVQ AX, CX + SUBQ $0x10, CX JB copy_4_small copy_4_loop: @@ -2127,54 +2152,54 @@ copy_4_loop: MOVUPS X0, (R10) ADDQ $0x10, R14 ADDQ $0x10, R10 - SUBQ $0x10, AX + SUBQ $0x10, CX JAE copy_4_loop - LEAQ 16(R14)(AX*1), R14 - LEAQ 16(R10)(AX*1), R10 + LEAQ 16(R14)(CX*1), R14 + LEAQ 16(R10)(CX*1), R10 MOVUPS -16(R14), X0 MOVUPS X0, -16(R10) JMP copy_4_end copy_4_small: - CMPQ R13, $0x03 + CMPQ AX, $0x03 JE copy_4_move_3 - CMPQ R13, $0x08 + CMPQ AX, $0x08 JB copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), AX - MOVB 2(R14), CL - MOVW AX, (R10) - MOVB CL, 2(R10) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end + MOVWQZX (R14), CX + MOVB 2(R14), R13 + MOVW CX, (R10) + MOVB R13, 2(R10) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_4_end copy_4_move_4through7: - MOVL (R14), AX - MOVL -4(R14)(R13*1), CX - MOVL AX, (R10) - MOVL CX, -4(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 + MOVL (R14), CX + MOVL -4(R14)(AX*1), R13 + MOVL CX, (R10) + MOVL R13, -4(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 JMP copy_4_end copy_4_move_8through16: - MOVQ (R14), AX - MOVQ -8(R14)(R13*1), CX - MOVQ AX, (R10) - MOVQ CX, -8(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 + MOVQ (R14), CX + MOVQ -8(R14)(AX*1), R13 + MOVQ CX, (R10) + MOVQ R13, -8(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 copy_4_end: - ADDQ R13, R12 + ADDQ AX, R12 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVQ AX, R15 + MOVQ CX, R15 SUBQ $0x10, R15 JB copy_5_small @@ -2192,90 +2217,99 @@ copy_5_loop: JMP copy_5_end copy_5_small: - CMPQ AX, $0x03 + CMPQ CX, $0x03 JE copy_5_move_3 JB copy_5_move_1or2 - CMPQ AX, $0x08 + CMPQ CX, $0x08 JB copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVB (R14), R15 - MOVB -1(R14)(AX*1), BP + MOVB -1(R14)(CX*1), BP MOVB R15, (R10) - MOVB BP, -1(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVB BP, -1(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R10) - MOVB BP, 2(R10) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R10) + MOVB BP, 2(R10) + ADDQ CX, R14 + ADDQ CX, R10 + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 - MOVL -4(R14)(AX*1), BP + MOVL -4(R14)(CX*1), BP MOVL R15, (R10) - MOVL BP, -4(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVL BP, -4(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 JMP copy_5_end copy_5_move_8through16: MOVQ (R14), R15 - MOVQ -8(R14)(AX*1), BP + MOVQ -8(R14)(CX*1), BP MOVQ R15, (R10) - MOVQ BP, -8(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVQ BP, -8(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 copy_5_end: - ADDQ AX, R12 - SUBQ AX, R13 + ADDQ CX, R12 + SUBQ CX, AX // Copy match from the current buffer copy_match: - MOVQ R10, AX - SUBQ CX, AX + MOVQ R10, CX + SUBQ R13, CX // ml <= mo - CMPQ R13, CX + CMPQ AX, R13 JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, R12 - MOVQ R10, CX - ADDQ R13, R10 + ADDQ AX, R12 + MOVUPS (CX), X0 + MOVUPS X0, (R10) + CMPQ AX, $0x10 + JA copy_2_long + ADDQ AX, R10 + JMP handle_loop + +copy_2_long: + LEAQ 16(R10), R13 + ADDQ AX, R10 + ADDQ $0x10, CX + SUBQ $0x10, AX copy_2: - MOVUPS (AX), X0 - MOVUPS X0, (CX) - ADDQ $0x10, AX + MOVUPS (CX), X0 + MOVUPS X0, (R13) ADDQ $0x10, CX - SUBQ $0x10, R13 + ADDQ $0x10, R13 + SUBQ $0x10, AX JHI copy_2 JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADDQ R13, R12 + ADDQ AX, R12 copy_slow_3: - MOVB (AX), CL - MOVB CL, (R10) - INCQ AX - INCQ R10 - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (CX), R13 + MOVB R13, (R10) + INCQ CX + INCQ R10 + DECQ AX + JNZ copy_slow_3 handle_loop: - MOVQ ctx+16(FP), AX - DECQ 96(AX) + DECQ 32(SP) JNS sequenceDecs_decodeSync_amd64_main_loop loop_finished: @@ -2284,6 +2318,13 @@ loop_finished: MOVB BL, 40(AX) MOVQ SI, 32(AX) + // s.seqSize += outPosition - ctx.outPosition + MOVQ ctx+16(FP), AX + MOVQ s+0(FP), CX + MOVQ R12, DX + SUBQ 136(AX), DX + ADDQ DX, 256(CX) + // Update the context MOVQ ctx+16(FP), AX MOVQ R12, 136(AX) @@ -2297,7 +2338,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX + MOVQ 48(SP), AX MOVQ ctx+16(FP), CX MOVQ AX, 216(CX) MOVQ $0x00000001, ret+24(FP) @@ -2306,7 +2347,7 @@ sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_amd64_error_match_len_too_big: MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ $0x00000002, ret+24(FP) RET @@ -2314,7 +2355,7 @@ sequenceDecs_decodeSync_amd64_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX + MOVQ 40(SP), CX MOVQ CX, 224(AX) MOVQ R12, 136(AX) MOVQ $0x00000003, ret+24(FP) @@ -2323,7 +2364,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) MOVQ $0x00000004, ret+24(FP) RET @@ -2336,9 +2377,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ R12, 136(AX) MOVQ $0x00000005, ret+24(FP) @@ -2346,7 +2387,7 @@ error_not_enough_space: // func sequenceDecs_decodeSync_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: BMI, BMI2, CMOV, SSE -TEXT ·sequenceDecs_decodeSync_bmi2(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_bmi2(SB), $96-32 MOVQ br+8(FP), BX MOVQ 24(BX), AX MOVBQZX 40(BX), DX @@ -2358,26 +2399,34 @@ TEXT ·sequenceDecs_decodeSync_bmi2(SB), $64-32 MOVQ 72(CX), SI MOVQ 80(CX), DI MOVQ 88(CX), R8 - XORQ R9, R9 + MOVQ (CX), R9 MOVQ R9, 8(SP) + MOVQ 24(CX), R9 MOVQ R9, 16(SP) + MOVQ 48(CX), R9 MOVQ R9, 24(SP) + MOVQ 96(CX), R9 + MOVQ R9, 32(SP) + XORQ R9, R9 + MOVQ R9, 40(SP) + MOVQ R9, 48(SP) + MOVQ R9, 56(SP) MOVQ 112(CX), R9 MOVQ 128(CX), R10 - MOVQ R10, 32(SP) + MOVQ R10, 64(SP) MOVQ 144(CX), R10 MOVQ 136(CX), R11 MOVQ 200(CX), R12 - MOVQ R12, 56(SP) + MOVQ R12, 88(SP) MOVQ 176(CX), R12 - MOVQ R12, 48(SP) + MOVQ R12, 80(SP) MOVQ 184(CX), CX - MOVQ CX, 40(SP) - MOVQ 40(SP), CX - ADDQ CX, 48(SP) + MOVQ CX, 72(SP) + MOVQ 72(SP), CX + ADDQ CX, 80(SP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - ADDQ R9, 32(SP) + ADDQ R9, 64(SP) // outBase += outPosition ADDQ R11, R9 @@ -2425,7 +2474,7 @@ sequenceDecs_decodeSync_bmi2_fill_end: MOVQ R8, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 8(SP) + MOVQ CX, 40(SP) // Update match length MOVQ $0x00000808, CX @@ -2438,7 +2487,7 @@ sequenceDecs_decodeSync_bmi2_fill_end: MOVQ DI, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 16(SP) + MOVQ CX, 48(SP) // Fill bitreader to have enough for the remaining CMPQ BX, $0x08 @@ -2480,14 +2529,13 @@ sequenceDecs_decodeSync_bmi2_fill_2_end: MOVQ SI, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 24(SP) + MOVQ CX, 56(SP) // Fill bitreader for state updates MOVQ R12, (SP) MOVQ $0x00000808, CX BEXTRQ CX, R8, R12 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decodeSync_bmi2_skip_update LEAQ (SI)(DI*1), R13 ADDQ R8, R13 @@ -2505,8 +2553,7 @@ sequenceDecs_decodeSync_bmi2_fill_2_end: ADDQ CX, R8 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R8*8), R8 // Update Match Length State @@ -2516,8 +2563,7 @@ sequenceDecs_decodeSync_bmi2_fill_2_end: ADDQ CX, DI // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(DI*8), DI // Update Literal Length State @@ -2526,14 +2572,13 @@ sequenceDecs_decodeSync_bmi2_fill_2_end: ADDQ CX, SI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(SI*8), SI sequenceDecs_decodeSync_bmi2_skip_update: // Adjust offset MOVQ s+0(FP), CX - MOVQ 8(SP), R13 + MOVQ 40(SP), R13 CMPQ R12, $0x01 JBE sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0 MOVUPS 144(CX), X0 @@ -2542,7 +2587,7 @@ sequenceDecs_decodeSync_bmi2_skip_update: JMP sequenceDecs_decodeSync_bmi2_after_adjust sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 + CMPQ 56(SP), $0x00000000 JNE sequenceDecs_decodeSync_bmi2_adjust_offset_maybezero INCQ R13 JMP sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero @@ -2577,14 +2622,11 @@ sequenceDecs_decodeSync_bmi2_adjust_skip: MOVQ R14, R13 sequenceDecs_decodeSync_bmi2_after_adjust: - MOVQ R13, 8(SP) + MOVQ R13, 40(SP) // Check values - MOVQ 16(SP), CX - MOVQ 24(SP), R12 - LEAQ (CX)(R12*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) + MOVQ 48(SP), CX + MOVQ 56(SP), R12 MOVQ ctx+16(FP), R14 SUBQ R12, 104(R14) JS error_not_enough_literals @@ -2596,50 +2638,49 @@ sequenceDecs_decodeSync_bmi2_after_adjust: JNZ sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch sequenceDecs_decodeSync_bmi2_match_len_ofs_ok: - MOVQ 24(SP), CX - MOVQ 8(SP), R12 - MOVQ 16(SP), R13 - // Check if we have enough space in s.out - LEAQ (CX)(R13*1), R14 + LEAQ 16(R12)(CX*1), R14 ADDQ R9, R14 - CMPQ R14, 32(SP) + CMPQ R14, 64(SP) JA error_not_enough_space // Copy literals - TESTQ CX, CX - JZ check_offset - XORQ R14, R14 + MOVUPS (R10), X0 + MOVUPS X0, (R9) + CMPQ R12, $0x10 + JBE copy_1_end + MOVQ $0x00000010, R14 copy_1: MOVUPS (R10)(R14*1), X0 MOVUPS X0, (R9)(R14*1) ADDQ $0x10, R14 - CMPQ R14, CX + CMPQ R14, R12 JB copy_1 - ADDQ CX, R10 - ADDQ CX, R9 - ADDQ CX, R11 + +copy_1_end: + ADDQ R12, R10 + ADDQ R12, R9 + ADDQ R12, R11 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R11, CX - ADDQ 40(SP), CX - CMPQ R12, CX + MOVQ R11, R12 + ADDQ 72(SP), R12 + CMPQ R13, R12 JG error_match_off_too_big - CMPQ R12, 56(SP) + CMPQ R13, 88(SP) JG error_match_off_too_big // Copy match from history - MOVQ R12, CX - SUBQ R11, CX + MOVQ R13, R12 + SUBQ R11, R12 JLS copy_match - MOVQ 48(SP), R14 - SUBQ CX, R14 - CMPQ R13, CX + MOVQ 80(SP), R14 + SUBQ R12, R14 + CMPQ CX, R12 JG copy_all_from_history - MOVQ R13, CX - SUBQ $0x10, CX + MOVQ CX, R12 + SUBQ $0x10, R12 JB copy_4_small copy_4_loop: @@ -2647,54 +2688,54 @@ copy_4_loop: MOVUPS X0, (R9) ADDQ $0x10, R14 ADDQ $0x10, R9 - SUBQ $0x10, CX + SUBQ $0x10, R12 JAE copy_4_loop - LEAQ 16(R14)(CX*1), R14 - LEAQ 16(R9)(CX*1), R9 + LEAQ 16(R14)(R12*1), R14 + LEAQ 16(R9)(R12*1), R9 MOVUPS -16(R14), X0 MOVUPS X0, -16(R9) JMP copy_4_end copy_4_small: - CMPQ R13, $0x03 + CMPQ CX, $0x03 JE copy_4_move_3 - CMPQ R13, $0x08 + CMPQ CX, $0x08 JB copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), CX - MOVB 2(R14), R12 - MOVW CX, (R9) - MOVB R12, 2(R9) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end + MOVWQZX (R14), R12 + MOVB 2(R14), R13 + MOVW R12, (R9) + MOVB R13, 2(R9) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_4_end copy_4_move_4through7: - MOVL (R14), CX - MOVL -4(R14)(R13*1), R12 - MOVL CX, (R9) - MOVL R12, -4(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 + MOVL (R14), R12 + MOVL -4(R14)(CX*1), R13 + MOVL R12, (R9) + MOVL R13, -4(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 JMP copy_4_end copy_4_move_8through16: - MOVQ (R14), CX - MOVQ -8(R14)(R13*1), R12 - MOVQ CX, (R9) - MOVQ R12, -8(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 + MOVQ (R14), R12 + MOVQ -8(R14)(CX*1), R13 + MOVQ R12, (R9) + MOVQ R13, -8(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 copy_4_end: - ADDQ R13, R11 + ADDQ CX, R11 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVQ CX, R15 + MOVQ R12, R15 SUBQ $0x10, R15 JB copy_5_small @@ -2712,90 +2753,99 @@ copy_5_loop: JMP copy_5_end copy_5_small: - CMPQ CX, $0x03 + CMPQ R12, $0x03 JE copy_5_move_3 JB copy_5_move_1or2 - CMPQ CX, $0x08 + CMPQ R12, $0x08 JB copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVB (R14), R15 - MOVB -1(R14)(CX*1), BP + MOVB -1(R14)(R12*1), BP MOVB R15, (R9) - MOVB BP, -1(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVB BP, -1(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R9) - MOVB BP, 2(R9) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R9) + MOVB BP, 2(R9) + ADDQ R12, R14 + ADDQ R12, R9 + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 - MOVL -4(R14)(CX*1), BP + MOVL -4(R14)(R12*1), BP MOVL R15, (R9) - MOVL BP, -4(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVL BP, -4(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 JMP copy_5_end copy_5_move_8through16: MOVQ (R14), R15 - MOVQ -8(R14)(CX*1), BP + MOVQ -8(R14)(R12*1), BP MOVQ R15, (R9) - MOVQ BP, -8(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVQ BP, -8(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 copy_5_end: - ADDQ CX, R11 - SUBQ CX, R13 + ADDQ R12, R11 + SUBQ R12, CX // Copy match from the current buffer copy_match: - MOVQ R9, CX - SUBQ R12, CX + MOVQ R9, R12 + SUBQ R13, R12 // ml <= mo - CMPQ R13, R12 + CMPQ CX, R13 JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, R11 - MOVQ R9, R12 - ADDQ R13, R9 + ADDQ CX, R11 + MOVUPS (R12), X0 + MOVUPS X0, (R9) + CMPQ CX, $0x10 + JA copy_2_long + ADDQ CX, R9 + JMP handle_loop + +copy_2_long: + LEAQ 16(R9), R13 + ADDQ CX, R9 + ADDQ $0x10, R12 + SUBQ $0x10, CX copy_2: - MOVUPS (CX), X0 - MOVUPS X0, (R12) - ADDQ $0x10, CX + MOVUPS (R12), X0 + MOVUPS X0, (R13) ADDQ $0x10, R12 - SUBQ $0x10, R13 + ADDQ $0x10, R13 + SUBQ $0x10, CX JHI copy_2 JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADDQ R13, R11 + ADDQ CX, R11 copy_slow_3: - MOVB (CX), R12 - MOVB R12, (R9) - INCQ CX - INCQ R9 - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (R12), R13 + MOVB R13, (R9) + INCQ R12 + INCQ R9 + DECQ CX + JNZ copy_slow_3 handle_loop: - MOVQ ctx+16(FP), CX - DECQ 96(CX) + DECQ 32(SP) JNS sequenceDecs_decodeSync_bmi2_main_loop loop_finished: @@ -2804,6 +2854,13 @@ loop_finished: MOVB DL, 40(CX) MOVQ BX, 32(CX) + // s.seqSize += outPosition - ctx.outPosition + MOVQ ctx+16(FP), AX + MOVQ s+0(FP), CX + MOVQ R11, DX + SUBQ 136(AX), DX + ADDQ DX, 256(CX) + // Update the context MOVQ ctx+16(FP), AX MOVQ R11, 136(AX) @@ -2817,7 +2874,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX + MOVQ 48(SP), AX MOVQ ctx+16(FP), CX MOVQ AX, 216(CX) MOVQ $0x00000001, ret+24(FP) @@ -2826,7 +2883,7 @@ sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_bmi2_error_match_len_too_big: MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ $0x00000002, ret+24(FP) RET @@ -2834,7 +2891,7 @@ sequenceDecs_decodeSync_bmi2_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX + MOVQ 40(SP), CX MOVQ CX, 224(AX) MOVQ R11, 136(AX) MOVQ $0x00000003, ret+24(FP) @@ -2843,7 +2900,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) MOVQ $0x00000004, ret+24(FP) RET @@ -2856,9 +2913,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ R11, 136(AX) MOVQ $0x00000005, ret+24(FP) @@ -2866,7 +2923,7 @@ error_not_enough_space: // func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $96-32 MOVQ br+8(FP), CX MOVQ 24(CX), DX MOVBQZX 40(CX), BX @@ -2878,26 +2935,34 @@ TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $64-32 MOVQ 72(AX), DI MOVQ 80(AX), R8 MOVQ 88(AX), R9 - XORQ CX, CX + MOVQ (AX), CX MOVQ CX, 8(SP) + MOVQ 24(AX), CX MOVQ CX, 16(SP) + MOVQ 48(AX), CX MOVQ CX, 24(SP) + MOVQ 96(AX), CX + MOVQ CX, 32(SP) + XORQ CX, CX + MOVQ CX, 40(SP) + MOVQ CX, 48(SP) + MOVQ CX, 56(SP) MOVQ 112(AX), R10 MOVQ 128(AX), CX - MOVQ CX, 32(SP) + MOVQ CX, 64(SP) MOVQ 144(AX), R11 MOVQ 136(AX), R12 MOVQ 200(AX), CX - MOVQ CX, 56(SP) + MOVQ CX, 88(SP) MOVQ 176(AX), CX - MOVQ CX, 48(SP) + MOVQ CX, 80(SP) MOVQ 184(AX), AX - MOVQ AX, 40(SP) - MOVQ 40(SP), AX - ADDQ AX, 48(SP) + MOVQ AX, 72(SP) + MOVQ 72(SP), AX + ADDQ AX, 80(SP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - ADDQ R10, 32(SP) + ADDQ R10, 64(SP) // outBase += outPosition ADDQ R12, R10 @@ -2935,46 +3000,32 @@ sequenceDecs_decodeSync_safe_amd64_fill_check_overread: sequenceDecs_decodeSync_safe_amd64_fill_end: // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_of_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_of_update_zero: - MOVQ AX, 8(SP) + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 40(SP) // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_ml_update_zero: - MOVQ AX, 16(SP) + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 48(SP) // Fill bitreader to have enough for the remaining CMPQ SI, $0x08 @@ -3006,96 +3057,82 @@ sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread: sequenceDecs_decodeSync_safe_amd64_fill_2_end: // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_ll_update_zero: - MOVQ AX, 24(SP) + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 56(SP) // Fill bitreader for state updates MOVQ R13, (SP) MOVQ R9, AX SHRQ $0x08, AX MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decodeSync_safe_amd64_skip_update // Update Literal Length State MOVBQZX DI, R13 SHRL $0x10, DI - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, DI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(DI*8), DI // Update Match Length State MOVBQZX R8, R13 SHRL $0x10, R8 - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, R8 // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(R8*8), R8 // Update Offset State MOVBQZX R9, R13 SHRL $0x10, R9 - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, R9 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R9*8), R9 sequenceDecs_decodeSync_safe_amd64_skip_update: // Adjust offset MOVQ s+0(FP), CX - MOVQ 8(SP), R13 + MOVQ 40(SP), R13 CMPQ AX, $0x01 JBE sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0 MOVUPS 144(CX), X0 @@ -3104,7 +3141,7 @@ sequenceDecs_decodeSync_safe_amd64_skip_update: JMP sequenceDecs_decodeSync_safe_amd64_after_adjust sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 + CMPQ 56(SP), $0x00000000 JNE sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero INCQ R13 JMP sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero @@ -3139,14 +3176,11 @@ sequenceDecs_decodeSync_safe_amd64_adjust_skip: MOVQ R14, R13 sequenceDecs_decodeSync_safe_amd64_after_adjust: - MOVQ R13, 8(SP) + MOVQ R13, 40(SP) // Check values - MOVQ 16(SP), AX - MOVQ 24(SP), CX - LEAQ (AX)(CX*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) + MOVQ 48(SP), AX + MOVQ 56(SP), CX MOVQ ctx+16(FP), R14 SUBQ CX, 104(R14) JS error_not_enough_literals @@ -3158,20 +3192,16 @@ sequenceDecs_decodeSync_safe_amd64_after_adjust: JNZ sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok: - MOVQ 24(SP), AX - MOVQ 8(SP), CX - MOVQ 16(SP), R13 - // Check if we have enough space in s.out - LEAQ (AX)(R13*1), R14 + LEAQ (CX)(AX*1), R14 ADDQ R10, R14 - CMPQ R14, 32(SP) + CMPQ R14, 64(SP) JA error_not_enough_space // Copy literals - TESTQ AX, AX + TESTQ CX, CX JZ check_offset - MOVQ AX, R14 + MOVQ CX, R14 SUBQ $0x10, R14 JB copy_1_small @@ -3189,70 +3219,70 @@ copy_1_loop: JMP copy_1_end copy_1_small: - CMPQ AX, $0x03 + CMPQ CX, $0x03 JE copy_1_move_3 JB copy_1_move_1or2 - CMPQ AX, $0x08 + CMPQ CX, $0x08 JB copy_1_move_4through7 JMP copy_1_move_8through16 copy_1_move_1or2: MOVB (R11), R14 - MOVB -1(R11)(AX*1), R15 + MOVB -1(R11)(CX*1), R15 MOVB R14, (R10) - MOVB R15, -1(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 + MOVB R15, -1(R10)(CX*1) + ADDQ CX, R11 + ADDQ CX, R10 JMP copy_1_end copy_1_move_3: - MOVW (R11), R14 - MOVB 2(R11), R15 - MOVW R14, (R10) - MOVB R15, 2(R10) - ADDQ AX, R11 - ADDQ AX, R10 - JMP copy_1_end + MOVWQZX (R11), R14 + MOVB 2(R11), R15 + MOVW R14, (R10) + MOVB R15, 2(R10) + ADDQ CX, R11 + ADDQ CX, R10 + JMP copy_1_end copy_1_move_4through7: MOVL (R11), R14 - MOVL -4(R11)(AX*1), R15 + MOVL -4(R11)(CX*1), R15 MOVL R14, (R10) - MOVL R15, -4(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 + MOVL R15, -4(R10)(CX*1) + ADDQ CX, R11 + ADDQ CX, R10 JMP copy_1_end copy_1_move_8through16: MOVQ (R11), R14 - MOVQ -8(R11)(AX*1), R15 + MOVQ -8(R11)(CX*1), R15 MOVQ R14, (R10) - MOVQ R15, -8(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 + MOVQ R15, -8(R10)(CX*1) + ADDQ CX, R11 + ADDQ CX, R10 copy_1_end: - ADDQ AX, R12 + ADDQ CX, R12 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) check_offset: - MOVQ R12, AX - ADDQ 40(SP), AX - CMPQ CX, AX + MOVQ R12, CX + ADDQ 72(SP), CX + CMPQ R13, CX JG error_match_off_too_big - CMPQ CX, 56(SP) + CMPQ R13, 88(SP) JG error_match_off_too_big // Copy match from history - MOVQ CX, AX - SUBQ R12, AX + MOVQ R13, CX + SUBQ R12, CX JLS copy_match - MOVQ 48(SP), R14 - SUBQ AX, R14 - CMPQ R13, AX + MOVQ 80(SP), R14 + SUBQ CX, R14 + CMPQ AX, CX JG copy_all_from_history - MOVQ R13, AX - SUBQ $0x10, AX + MOVQ AX, CX + SUBQ $0x10, CX JB copy_4_small copy_4_loop: @@ -3260,54 +3290,54 @@ copy_4_loop: MOVUPS X0, (R10) ADDQ $0x10, R14 ADDQ $0x10, R10 - SUBQ $0x10, AX + SUBQ $0x10, CX JAE copy_4_loop - LEAQ 16(R14)(AX*1), R14 - LEAQ 16(R10)(AX*1), R10 + LEAQ 16(R14)(CX*1), R14 + LEAQ 16(R10)(CX*1), R10 MOVUPS -16(R14), X0 MOVUPS X0, -16(R10) JMP copy_4_end copy_4_small: - CMPQ R13, $0x03 + CMPQ AX, $0x03 JE copy_4_move_3 - CMPQ R13, $0x08 + CMPQ AX, $0x08 JB copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), AX - MOVB 2(R14), CL - MOVW AX, (R10) - MOVB CL, 2(R10) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end + MOVWQZX (R14), CX + MOVB 2(R14), R13 + MOVW CX, (R10) + MOVB R13, 2(R10) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_4_end copy_4_move_4through7: - MOVL (R14), AX - MOVL -4(R14)(R13*1), CX - MOVL AX, (R10) - MOVL CX, -4(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 + MOVL (R14), CX + MOVL -4(R14)(AX*1), R13 + MOVL CX, (R10) + MOVL R13, -4(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 JMP copy_4_end copy_4_move_8through16: - MOVQ (R14), AX - MOVQ -8(R14)(R13*1), CX - MOVQ AX, (R10) - MOVQ CX, -8(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 + MOVQ (R14), CX + MOVQ -8(R14)(AX*1), R13 + MOVQ CX, (R10) + MOVQ R13, -8(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 copy_4_end: - ADDQ R13, R12 + ADDQ AX, R12 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVQ AX, R15 + MOVQ CX, R15 SUBQ $0x10, R15 JB copy_5_small @@ -3325,141 +3355,140 @@ copy_5_loop: JMP copy_5_end copy_5_small: - CMPQ AX, $0x03 + CMPQ CX, $0x03 JE copy_5_move_3 JB copy_5_move_1or2 - CMPQ AX, $0x08 + CMPQ CX, $0x08 JB copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVB (R14), R15 - MOVB -1(R14)(AX*1), BP + MOVB -1(R14)(CX*1), BP MOVB R15, (R10) - MOVB BP, -1(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVB BP, -1(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R10) - MOVB BP, 2(R10) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R10) + MOVB BP, 2(R10) + ADDQ CX, R14 + ADDQ CX, R10 + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 - MOVL -4(R14)(AX*1), BP + MOVL -4(R14)(CX*1), BP MOVL R15, (R10) - MOVL BP, -4(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVL BP, -4(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 JMP copy_5_end copy_5_move_8through16: MOVQ (R14), R15 - MOVQ -8(R14)(AX*1), BP + MOVQ -8(R14)(CX*1), BP MOVQ R15, (R10) - MOVQ BP, -8(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVQ BP, -8(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 copy_5_end: - ADDQ AX, R12 - SUBQ AX, R13 + ADDQ CX, R12 + SUBQ CX, AX // Copy match from the current buffer copy_match: - MOVQ R10, AX - SUBQ CX, AX + MOVQ R10, CX + SUBQ R13, CX // ml <= mo - CMPQ R13, CX + CMPQ AX, R13 JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, R12 - MOVQ R13, CX - SUBQ $0x10, CX + ADDQ AX, R12 + MOVQ AX, R13 + SUBQ $0x10, R13 JB copy_2_small copy_2_loop: - MOVUPS (AX), X0 + MOVUPS (CX), X0 MOVUPS X0, (R10) - ADDQ $0x10, AX + ADDQ $0x10, CX ADDQ $0x10, R10 - SUBQ $0x10, CX + SUBQ $0x10, R13 JAE copy_2_loop - LEAQ 16(AX)(CX*1), AX - LEAQ 16(R10)(CX*1), R10 - MOVUPS -16(AX), X0 + LEAQ 16(CX)(R13*1), CX + LEAQ 16(R10)(R13*1), R10 + MOVUPS -16(CX), X0 MOVUPS X0, -16(R10) JMP copy_2_end copy_2_small: - CMPQ R13, $0x03 + CMPQ AX, $0x03 JE copy_2_move_3 JB copy_2_move_1or2 - CMPQ R13, $0x08 + CMPQ AX, $0x08 JB copy_2_move_4through7 JMP copy_2_move_8through16 copy_2_move_1or2: - MOVB (AX), CL - MOVB -1(AX)(R13*1), R14 - MOVB CL, (R10) - MOVB R14, -1(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 + MOVB (CX), R13 + MOVB -1(CX)(AX*1), R14 + MOVB R13, (R10) + MOVB R14, -1(R10)(AX*1) + ADDQ AX, CX + ADDQ AX, R10 JMP copy_2_end copy_2_move_3: - MOVW (AX), CX - MOVB 2(AX), R14 - MOVW CX, (R10) - MOVB R14, 2(R10) - ADDQ R13, AX - ADDQ R13, R10 - JMP copy_2_end + MOVWQZX (CX), R13 + MOVB 2(CX), R14 + MOVW R13, (R10) + MOVB R14, 2(R10) + ADDQ AX, CX + ADDQ AX, R10 + JMP copy_2_end copy_2_move_4through7: - MOVL (AX), CX - MOVL -4(AX)(R13*1), R14 - MOVL CX, (R10) - MOVL R14, -4(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 + MOVL (CX), R13 + MOVL -4(CX)(AX*1), R14 + MOVL R13, (R10) + MOVL R14, -4(R10)(AX*1) + ADDQ AX, CX + ADDQ AX, R10 JMP copy_2_end copy_2_move_8through16: - MOVQ (AX), CX - MOVQ -8(AX)(R13*1), R14 - MOVQ CX, (R10) - MOVQ R14, -8(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 + MOVQ (CX), R13 + MOVQ -8(CX)(AX*1), R14 + MOVQ R13, (R10) + MOVQ R14, -8(R10)(AX*1) + ADDQ AX, CX + ADDQ AX, R10 copy_2_end: JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADDQ R13, R12 + ADDQ AX, R12 copy_slow_3: - MOVB (AX), CL - MOVB CL, (R10) - INCQ AX - INCQ R10 - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (CX), R13 + MOVB R13, (R10) + INCQ CX + INCQ R10 + DECQ AX + JNZ copy_slow_3 handle_loop: - MOVQ ctx+16(FP), AX - DECQ 96(AX) + DECQ 32(SP) JNS sequenceDecs_decodeSync_safe_amd64_main_loop loop_finished: @@ -3468,6 +3497,13 @@ loop_finished: MOVB BL, 40(AX) MOVQ SI, 32(AX) + // s.seqSize += outPosition - ctx.outPosition + MOVQ ctx+16(FP), AX + MOVQ s+0(FP), CX + MOVQ R12, DX + SUBQ 136(AX), DX + ADDQ DX, 256(CX) + // Update the context MOVQ ctx+16(FP), AX MOVQ R12, 136(AX) @@ -3481,7 +3517,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX + MOVQ 48(SP), AX MOVQ ctx+16(FP), CX MOVQ AX, 216(CX) MOVQ $0x00000001, ret+24(FP) @@ -3490,7 +3526,7 @@ sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ $0x00000002, ret+24(FP) RET @@ -3498,7 +3534,7 @@ sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX + MOVQ 40(SP), CX MOVQ CX, 224(AX) MOVQ R12, 136(AX) MOVQ $0x00000003, ret+24(FP) @@ -3507,7 +3543,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) MOVQ $0x00000004, ret+24(FP) RET @@ -3520,9 +3556,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ R12, 136(AX) MOVQ $0x00000005, ret+24(FP) @@ -3530,7 +3566,7 @@ error_not_enough_space: // func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: BMI, BMI2, CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $96-32 MOVQ br+8(FP), BX MOVQ 24(BX), AX MOVBQZX 40(BX), DX @@ -3542,26 +3578,34 @@ TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $64-32 MOVQ 72(CX), SI MOVQ 80(CX), DI MOVQ 88(CX), R8 - XORQ R9, R9 + MOVQ (CX), R9 MOVQ R9, 8(SP) + MOVQ 24(CX), R9 MOVQ R9, 16(SP) + MOVQ 48(CX), R9 MOVQ R9, 24(SP) + MOVQ 96(CX), R9 + MOVQ R9, 32(SP) + XORQ R9, R9 + MOVQ R9, 40(SP) + MOVQ R9, 48(SP) + MOVQ R9, 56(SP) MOVQ 112(CX), R9 MOVQ 128(CX), R10 - MOVQ R10, 32(SP) + MOVQ R10, 64(SP) MOVQ 144(CX), R10 MOVQ 136(CX), R11 MOVQ 200(CX), R12 - MOVQ R12, 56(SP) + MOVQ R12, 88(SP) MOVQ 176(CX), R12 - MOVQ R12, 48(SP) + MOVQ R12, 80(SP) MOVQ 184(CX), CX - MOVQ CX, 40(SP) - MOVQ 40(SP), CX - ADDQ CX, 48(SP) + MOVQ CX, 72(SP) + MOVQ 72(SP), CX + ADDQ CX, 80(SP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - ADDQ R9, 32(SP) + ADDQ R9, 64(SP) // outBase += outPosition ADDQ R11, R9 @@ -3609,7 +3653,7 @@ sequenceDecs_decodeSync_safe_bmi2_fill_end: MOVQ R8, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 8(SP) + MOVQ CX, 40(SP) // Update match length MOVQ $0x00000808, CX @@ -3622,7 +3666,7 @@ sequenceDecs_decodeSync_safe_bmi2_fill_end: MOVQ DI, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 16(SP) + MOVQ CX, 48(SP) // Fill bitreader to have enough for the remaining CMPQ BX, $0x08 @@ -3664,14 +3708,13 @@ sequenceDecs_decodeSync_safe_bmi2_fill_2_end: MOVQ SI, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 24(SP) + MOVQ CX, 56(SP) // Fill bitreader for state updates MOVQ R12, (SP) MOVQ $0x00000808, CX BEXTRQ CX, R8, R12 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decodeSync_safe_bmi2_skip_update LEAQ (SI)(DI*1), R13 ADDQ R8, R13 @@ -3689,8 +3732,7 @@ sequenceDecs_decodeSync_safe_bmi2_fill_2_end: ADDQ CX, R8 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R8*8), R8 // Update Match Length State @@ -3700,8 +3742,7 @@ sequenceDecs_decodeSync_safe_bmi2_fill_2_end: ADDQ CX, DI // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(DI*8), DI // Update Literal Length State @@ -3710,14 +3751,13 @@ sequenceDecs_decodeSync_safe_bmi2_fill_2_end: ADDQ CX, SI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(SI*8), SI sequenceDecs_decodeSync_safe_bmi2_skip_update: // Adjust offset MOVQ s+0(FP), CX - MOVQ 8(SP), R13 + MOVQ 40(SP), R13 CMPQ R12, $0x01 JBE sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0 MOVUPS 144(CX), X0 @@ -3726,7 +3766,7 @@ sequenceDecs_decodeSync_safe_bmi2_skip_update: JMP sequenceDecs_decodeSync_safe_bmi2_after_adjust sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 + CMPQ 56(SP), $0x00000000 JNE sequenceDecs_decodeSync_safe_bmi2_adjust_offset_maybezero INCQ R13 JMP sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero @@ -3761,14 +3801,11 @@ sequenceDecs_decodeSync_safe_bmi2_adjust_skip: MOVQ R14, R13 sequenceDecs_decodeSync_safe_bmi2_after_adjust: - MOVQ R13, 8(SP) + MOVQ R13, 40(SP) // Check values - MOVQ 16(SP), CX - MOVQ 24(SP), R12 - LEAQ (CX)(R12*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) + MOVQ 48(SP), CX + MOVQ 56(SP), R12 MOVQ ctx+16(FP), R14 SUBQ R12, 104(R14) JS error_not_enough_literals @@ -3780,20 +3817,16 @@ sequenceDecs_decodeSync_safe_bmi2_after_adjust: JNZ sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch sequenceDecs_decodeSync_safe_bmi2_match_len_ofs_ok: - MOVQ 24(SP), CX - MOVQ 8(SP), R12 - MOVQ 16(SP), R13 - // Check if we have enough space in s.out - LEAQ (CX)(R13*1), R14 + LEAQ (R12)(CX*1), R14 ADDQ R9, R14 - CMPQ R14, 32(SP) + CMPQ R14, 64(SP) JA error_not_enough_space // Copy literals - TESTQ CX, CX + TESTQ R12, R12 JZ check_offset - MOVQ CX, R14 + MOVQ R12, R14 SUBQ $0x10, R14 JB copy_1_small @@ -3811,70 +3844,70 @@ copy_1_loop: JMP copy_1_end copy_1_small: - CMPQ CX, $0x03 + CMPQ R12, $0x03 JE copy_1_move_3 JB copy_1_move_1or2 - CMPQ CX, $0x08 + CMPQ R12, $0x08 JB copy_1_move_4through7 JMP copy_1_move_8through16 copy_1_move_1or2: MOVB (R10), R14 - MOVB -1(R10)(CX*1), R15 + MOVB -1(R10)(R12*1), R15 MOVB R14, (R9) - MOVB R15, -1(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 + MOVB R15, -1(R9)(R12*1) + ADDQ R12, R10 + ADDQ R12, R9 JMP copy_1_end copy_1_move_3: - MOVW (R10), R14 - MOVB 2(R10), R15 - MOVW R14, (R9) - MOVB R15, 2(R9) - ADDQ CX, R10 - ADDQ CX, R9 - JMP copy_1_end + MOVWQZX (R10), R14 + MOVB 2(R10), R15 + MOVW R14, (R9) + MOVB R15, 2(R9) + ADDQ R12, R10 + ADDQ R12, R9 + JMP copy_1_end copy_1_move_4through7: MOVL (R10), R14 - MOVL -4(R10)(CX*1), R15 + MOVL -4(R10)(R12*1), R15 MOVL R14, (R9) - MOVL R15, -4(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 + MOVL R15, -4(R9)(R12*1) + ADDQ R12, R10 + ADDQ R12, R9 JMP copy_1_end copy_1_move_8through16: MOVQ (R10), R14 - MOVQ -8(R10)(CX*1), R15 + MOVQ -8(R10)(R12*1), R15 MOVQ R14, (R9) - MOVQ R15, -8(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 + MOVQ R15, -8(R9)(R12*1) + ADDQ R12, R10 + ADDQ R12, R9 copy_1_end: - ADDQ CX, R11 + ADDQ R12, R11 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) check_offset: - MOVQ R11, CX - ADDQ 40(SP), CX - CMPQ R12, CX + MOVQ R11, R12 + ADDQ 72(SP), R12 + CMPQ R13, R12 JG error_match_off_too_big - CMPQ R12, 56(SP) + CMPQ R13, 88(SP) JG error_match_off_too_big // Copy match from history - MOVQ R12, CX - SUBQ R11, CX + MOVQ R13, R12 + SUBQ R11, R12 JLS copy_match - MOVQ 48(SP), R14 - SUBQ CX, R14 - CMPQ R13, CX + MOVQ 80(SP), R14 + SUBQ R12, R14 + CMPQ CX, R12 JG copy_all_from_history - MOVQ R13, CX - SUBQ $0x10, CX + MOVQ CX, R12 + SUBQ $0x10, R12 JB copy_4_small copy_4_loop: @@ -3882,54 +3915,54 @@ copy_4_loop: MOVUPS X0, (R9) ADDQ $0x10, R14 ADDQ $0x10, R9 - SUBQ $0x10, CX + SUBQ $0x10, R12 JAE copy_4_loop - LEAQ 16(R14)(CX*1), R14 - LEAQ 16(R9)(CX*1), R9 + LEAQ 16(R14)(R12*1), R14 + LEAQ 16(R9)(R12*1), R9 MOVUPS -16(R14), X0 MOVUPS X0, -16(R9) JMP copy_4_end copy_4_small: - CMPQ R13, $0x03 + CMPQ CX, $0x03 JE copy_4_move_3 - CMPQ R13, $0x08 + CMPQ CX, $0x08 JB copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), CX - MOVB 2(R14), R12 - MOVW CX, (R9) - MOVB R12, 2(R9) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end + MOVWQZX (R14), R12 + MOVB 2(R14), R13 + MOVW R12, (R9) + MOVB R13, 2(R9) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_4_end copy_4_move_4through7: - MOVL (R14), CX - MOVL -4(R14)(R13*1), R12 - MOVL CX, (R9) - MOVL R12, -4(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 + MOVL (R14), R12 + MOVL -4(R14)(CX*1), R13 + MOVL R12, (R9) + MOVL R13, -4(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 JMP copy_4_end copy_4_move_8through16: - MOVQ (R14), CX - MOVQ -8(R14)(R13*1), R12 - MOVQ CX, (R9) - MOVQ R12, -8(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 + MOVQ (R14), R12 + MOVQ -8(R14)(CX*1), R13 + MOVQ R12, (R9) + MOVQ R13, -8(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 copy_4_end: - ADDQ R13, R11 + ADDQ CX, R11 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVQ CX, R15 + MOVQ R12, R15 SUBQ $0x10, R15 JB copy_5_small @@ -3947,141 +3980,140 @@ copy_5_loop: JMP copy_5_end copy_5_small: - CMPQ CX, $0x03 + CMPQ R12, $0x03 JE copy_5_move_3 JB copy_5_move_1or2 - CMPQ CX, $0x08 + CMPQ R12, $0x08 JB copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVB (R14), R15 - MOVB -1(R14)(CX*1), BP + MOVB -1(R14)(R12*1), BP MOVB R15, (R9) - MOVB BP, -1(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVB BP, -1(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R9) - MOVB BP, 2(R9) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R9) + MOVB BP, 2(R9) + ADDQ R12, R14 + ADDQ R12, R9 + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 - MOVL -4(R14)(CX*1), BP + MOVL -4(R14)(R12*1), BP MOVL R15, (R9) - MOVL BP, -4(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVL BP, -4(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 JMP copy_5_end copy_5_move_8through16: MOVQ (R14), R15 - MOVQ -8(R14)(CX*1), BP + MOVQ -8(R14)(R12*1), BP MOVQ R15, (R9) - MOVQ BP, -8(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVQ BP, -8(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 copy_5_end: - ADDQ CX, R11 - SUBQ CX, R13 + ADDQ R12, R11 + SUBQ R12, CX // Copy match from the current buffer copy_match: - MOVQ R9, CX - SUBQ R12, CX + MOVQ R9, R12 + SUBQ R13, R12 // ml <= mo - CMPQ R13, R12 + CMPQ CX, R13 JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, R11 - MOVQ R13, R12 - SUBQ $0x10, R12 + ADDQ CX, R11 + MOVQ CX, R13 + SUBQ $0x10, R13 JB copy_2_small copy_2_loop: - MOVUPS (CX), X0 + MOVUPS (R12), X0 MOVUPS X0, (R9) - ADDQ $0x10, CX + ADDQ $0x10, R12 ADDQ $0x10, R9 - SUBQ $0x10, R12 + SUBQ $0x10, R13 JAE copy_2_loop - LEAQ 16(CX)(R12*1), CX - LEAQ 16(R9)(R12*1), R9 - MOVUPS -16(CX), X0 + LEAQ 16(R12)(R13*1), R12 + LEAQ 16(R9)(R13*1), R9 + MOVUPS -16(R12), X0 MOVUPS X0, -16(R9) JMP copy_2_end copy_2_small: - CMPQ R13, $0x03 + CMPQ CX, $0x03 JE copy_2_move_3 JB copy_2_move_1or2 - CMPQ R13, $0x08 + CMPQ CX, $0x08 JB copy_2_move_4through7 JMP copy_2_move_8through16 copy_2_move_1or2: - MOVB (CX), R12 - MOVB -1(CX)(R13*1), R14 - MOVB R12, (R9) - MOVB R14, -1(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 + MOVB (R12), R13 + MOVB -1(R12)(CX*1), R14 + MOVB R13, (R9) + MOVB R14, -1(R9)(CX*1) + ADDQ CX, R12 + ADDQ CX, R9 JMP copy_2_end copy_2_move_3: - MOVW (CX), R12 - MOVB 2(CX), R14 - MOVW R12, (R9) - MOVB R14, 2(R9) - ADDQ R13, CX - ADDQ R13, R9 - JMP copy_2_end + MOVWQZX (R12), R13 + MOVB 2(R12), R14 + MOVW R13, (R9) + MOVB R14, 2(R9) + ADDQ CX, R12 + ADDQ CX, R9 + JMP copy_2_end copy_2_move_4through7: - MOVL (CX), R12 - MOVL -4(CX)(R13*1), R14 - MOVL R12, (R9) - MOVL R14, -4(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 + MOVL (R12), R13 + MOVL -4(R12)(CX*1), R14 + MOVL R13, (R9) + MOVL R14, -4(R9)(CX*1) + ADDQ CX, R12 + ADDQ CX, R9 JMP copy_2_end copy_2_move_8through16: - MOVQ (CX), R12 - MOVQ -8(CX)(R13*1), R14 - MOVQ R12, (R9) - MOVQ R14, -8(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 + MOVQ (R12), R13 + MOVQ -8(R12)(CX*1), R14 + MOVQ R13, (R9) + MOVQ R14, -8(R9)(CX*1) + ADDQ CX, R12 + ADDQ CX, R9 copy_2_end: JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADDQ R13, R11 + ADDQ CX, R11 copy_slow_3: - MOVB (CX), R12 - MOVB R12, (R9) - INCQ CX - INCQ R9 - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (R12), R13 + MOVB R13, (R9) + INCQ R12 + INCQ R9 + DECQ CX + JNZ copy_slow_3 handle_loop: - MOVQ ctx+16(FP), CX - DECQ 96(CX) + DECQ 32(SP) JNS sequenceDecs_decodeSync_safe_bmi2_main_loop loop_finished: @@ -4090,6 +4122,13 @@ loop_finished: MOVB DL, 40(CX) MOVQ BX, 32(CX) + // s.seqSize += outPosition - ctx.outPosition + MOVQ ctx+16(FP), AX + MOVQ s+0(FP), CX + MOVQ R11, DX + SUBQ 136(AX), DX + ADDQ DX, 256(CX) + // Update the context MOVQ ctx+16(FP), AX MOVQ R11, 136(AX) @@ -4103,7 +4142,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX + MOVQ 48(SP), AX MOVQ ctx+16(FP), CX MOVQ AX, 216(CX) MOVQ $0x00000001, ret+24(FP) @@ -4112,7 +4151,7 @@ sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big: MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ $0x00000002, ret+24(FP) RET @@ -4120,7 +4159,7 @@ sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX + MOVQ 40(SP), CX MOVQ CX, 224(AX) MOVQ R11, 136(AX) MOVQ $0x00000003, ret+24(FP) @@ -4129,7 +4168,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) MOVQ $0x00000004, ret+24(FP) RET @@ -4142,9 +4181,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ R11, 136(AX) MOVQ $0x00000005, ret+24(FP) diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s b/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s index a468e5fc2c..56391bfc18 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s @@ -1,22 +1,30 @@ // Code generated by command: go run gen.go -out ../seqdec.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT. // EXPERIMENTAL arm64 output lowered from an amd64 avo program. -//go:build arm64 && !appengine && !noasm && gc && !noasm +//go:build arm64 && (!appengine && !noasm && gc && !noasm) // func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV -TEXT ·sequenceDecs_decode_arm64(SB), $8-32 +TEXT ·sequenceDecs_decode_arm64(SB), $40-32 MOVD br+8(FP), R1 MOVD 24(R1), R2 MOVBU 40(R1), R3 MOVD (R1), R0 MOVD 32(R1), R5 ADD R5, R0, R0 - MOVD R0, (RSP) + MOVD R0, 8(RSP) MOVD ctx+16(FP), R0 MOVD 72(R0), R6 MOVD 80(R0), R7 MOVD 88(R0), R8 + MOVD (R0), R1 + MOVD R1, 16(RSP) + MOVD 24(R0), R1 + MOVD R1, 24(RSP) + MOVD 48(R0), R1 + MOVD R1, 32(RSP) + MOVD 96(R0), R1 + MOVD R1, 40(RSP) MOVD 104(R0), R9 MOVD s+0(FP), R0 MOVD 144(R0), R10 @@ -24,13 +32,12 @@ TEXT ·sequenceDecs_decode_arm64(SB), $8-32 MOVD 160(R0), R12 sequenceDecs_decode_amd64_main_loop: - MOVD (RSP), R13 + MOVD 8(RSP), R13 // Fill bitreader to have enough for the offset and match length. CMP $0x08, R5 BLT sequenceDecs_decode_amd64_fill_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 + LSR $0x03, R3, R0 SUB R0, R13, R13 MOVD (R13), R2 SUB R0, R5, R5 @@ -57,51 +64,32 @@ sequenceDecs_decode_amd64_fill_check_overread: sequenceDecs_decode_amd64_fill_end: // Update offset MOVD R8, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_amd64_of_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_amd64_of_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_amd64_of_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_amd64_of_update_zero: MOVD R0, 16(R9) // Update match length MOVD R7, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_amd64_ml_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_amd64_ml_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_amd64_ml_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_amd64_ml_update_zero: MOVD R0, 8(R9) // Fill bitreader to have enough for the remaining CMP $0x08, R5 BLT sequenceDecs_decode_amd64_fill_2_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 + LSR $0x03, R3, R0 SUB R0, R13, R13 MOVD (R13), R2 SUB R0, R5, R5 @@ -128,97 +116,64 @@ sequenceDecs_decode_amd64_fill_2_check_overread: sequenceDecs_decode_amd64_fill_2_end: // Update literal length MOVD R6, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_amd64_ll_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_amd64_ll_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_amd64_ll_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_amd64_ll_update_zero: MOVD R0, (R9) // Fill bitreader for state updates - MOVD R13, (RSP) - MOVD R8, R0 - LSR $0x08, R0, R0 - MOVBU R0, R0 - MOVD ctx+16(FP), R1 - MOVD 96(R1), R16 - CMP $0x00, R16 - BEQ sequenceDecs_decode_amd64_skip_update + MOVD R13, 8(RSP) + UBFX $8, R8, $8, R0 + MOVD 40(RSP), R16 + CMP $0x00, R16 + BEQ sequenceDecs_decode_amd64_skip_update // Update Literal Length State MOVBU R6, R13 LSRW $0x10, R6, R6 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - MOVB R13, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R6, R6 // Load ctx.llTable - MOVD ctx+16(FP), R1 - MOVD (R1), R1 - ADD R6<<3, R1, R15 - MOVD (R15), R6 + MOVD 16(RSP), R1 + MOVD (R1)(R6<<3), R6 // Update Match Length State MOVBU R7, R13 LSRW $0x10, R7, R7 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - MOVB R13, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R7, R7 // Load ctx.mlTable - MOVD ctx+16(FP), R1 - MOVD 24(R1), R1 - ADD R7<<3, R1, R15 - MOVD (R15), R7 + MOVD 24(RSP), R1 + MOVD (R1)(R7<<3), R7 // Update Offset State MOVBU R8, R13 LSRW $0x10, R8, R8 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - MOVB R13, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R8, R8 // Load ctx.ofTable - MOVD ctx+16(FP), R1 - MOVD 48(R1), R1 - ADD R8<<3, R1, R15 - MOVD (R15), R8 + MOVD 32(RSP), R1 + MOVD (R1)(R8<<3), R8 sequenceDecs_decode_amd64_skip_update: // Adjust offset @@ -303,10 +258,9 @@ sequenceDecs_decode_amd64_after_adjust: sequenceDecs_decode_amd64_match_len_ofs_ok: ADD $0x18, R9, R9 - MOVD ctx+16(FP), R0 - MOVD 96(R0), R16 + MOVD 40(RSP), R16 SUBS $1, R16, R16 - MOVD R16, 96(R0) + MOVD R16, 40(RSP) BPL sequenceDecs_decode_amd64_main_loop MOVD s+0(FP), R0 MOVD R10, 144(R0) @@ -318,53 +272,79 @@ sequenceDecs_decode_amd64_match_len_ofs_ok: MOVD R5, 32(R0) // Return success + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000000, R16 MOVD R16, ret+24(FP) RET // Return with match length error sequenceDecs_decode_amd64_error_match_len_ofs_mismatch: + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000001, R16 MOVD R16, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_amd64_error_match_len_too_big: + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000002, R16 MOVD R16, ret+24(FP) RET // Return with match offset too long error + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000003, R16 MOVD R16, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000004, R16 MOVD R16, ret+24(FP) RET // Return with overread error error_overread: + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000006, R16 MOVD R16, ret+24(FP) RET // func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV -TEXT ·sequenceDecs_decode_56_arm64(SB), $8-32 +TEXT ·sequenceDecs_decode_56_arm64(SB), $40-32 MOVD br+8(FP), R1 MOVD 24(R1), R2 MOVBU 40(R1), R3 MOVD (R1), R0 MOVD 32(R1), R5 ADD R5, R0, R0 - MOVD R0, (RSP) + MOVD R0, 8(RSP) MOVD ctx+16(FP), R0 MOVD 72(R0), R6 MOVD 80(R0), R7 MOVD 88(R0), R8 + MOVD (R0), R1 + MOVD R1, 16(RSP) + MOVD 24(R0), R1 + MOVD R1, 24(RSP) + MOVD 48(R0), R1 + MOVD R1, 32(RSP) + MOVD 96(R0), R1 + MOVD R1, 40(RSP) MOVD 104(R0), R9 MOVD s+0(FP), R0 MOVD 144(R0), R10 @@ -372,13 +352,12 @@ TEXT ·sequenceDecs_decode_56_arm64(SB), $8-32 MOVD 160(R0), R12 sequenceDecs_decode_56_amd64_main_loop: - MOVD (RSP), R13 + MOVD 8(RSP), R13 // Fill bitreader to have enough for the offset and match length. CMP $0x08, R5 BLT sequenceDecs_decode_56_amd64_fill_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 + LSR $0x03, R3, R0 SUB R0, R13, R13 MOVD (R13), R2 SUB R0, R5, R5 @@ -405,139 +384,88 @@ sequenceDecs_decode_56_amd64_fill_check_overread: sequenceDecs_decode_56_amd64_fill_end: // Update offset MOVD R8, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_56_amd64_of_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_56_amd64_of_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_56_amd64_of_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_56_amd64_of_update_zero: MOVD R0, 16(R9) // Update match length MOVD R7, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_56_amd64_ml_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_56_amd64_ml_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_56_amd64_ml_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_56_amd64_ml_update_zero: MOVD R0, 8(R9) // Update literal length MOVD R6, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_56_amd64_ll_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_56_amd64_ll_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_56_amd64_ll_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_56_amd64_ll_update_zero: MOVD R0, (R9) // Fill bitreader for state updates - MOVD R13, (RSP) - MOVD R8, R0 - LSR $0x08, R0, R0 - MOVBU R0, R0 - MOVD ctx+16(FP), R1 - MOVD 96(R1), R16 - CMP $0x00, R16 - BEQ sequenceDecs_decode_56_amd64_skip_update + MOVD R13, 8(RSP) + UBFX $8, R8, $8, R0 + MOVD 40(RSP), R16 + CMP $0x00, R16 + BEQ sequenceDecs_decode_56_amd64_skip_update // Update Literal Length State MOVBU R6, R13 LSRW $0x10, R6, R6 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - MOVB R13, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R6, R6 // Load ctx.llTable - MOVD ctx+16(FP), R1 - MOVD (R1), R1 - ADD R6<<3, R1, R15 - MOVD (R15), R6 + MOVD 16(RSP), R1 + MOVD (R1)(R6<<3), R6 // Update Match Length State MOVBU R7, R13 LSRW $0x10, R7, R7 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - MOVB R13, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R7, R7 // Load ctx.mlTable - MOVD ctx+16(FP), R1 - MOVD 24(R1), R1 - ADD R7<<3, R1, R15 - MOVD (R15), R7 + MOVD 24(RSP), R1 + MOVD (R1)(R7<<3), R7 // Update Offset State MOVBU R8, R13 LSRW $0x10, R8, R8 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - MOVB R13, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R8, R8 // Load ctx.ofTable - MOVD ctx+16(FP), R1 - MOVD 48(R1), R1 - ADD R8<<3, R1, R15 - MOVD (R15), R8 + MOVD 32(RSP), R1 + MOVD (R1)(R8<<3), R8 sequenceDecs_decode_56_amd64_skip_update: // Adjust offset @@ -622,10 +550,9 @@ sequenceDecs_decode_56_amd64_after_adjust: sequenceDecs_decode_56_amd64_match_len_ofs_ok: ADD $0x18, R9, R9 - MOVD ctx+16(FP), R0 - MOVD 96(R0), R16 + MOVD 40(RSP), R16 SUBS $1, R16, R16 - MOVD R16, 96(R0) + MOVD R16, 40(RSP) BPL sequenceDecs_decode_56_amd64_main_loop MOVD s+0(FP), R0 MOVD R10, 144(R0) @@ -637,35 +564,53 @@ sequenceDecs_decode_56_amd64_match_len_ofs_ok: MOVD R5, 32(R0) // Return success + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000000, R16 MOVD R16, ret+24(FP) RET // Return with match length error sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch: + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000001, R16 MOVD R16, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_56_amd64_error_match_len_too_big: + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000002, R16 MOVD R16, ret+24(FP) RET // Return with match offset too long error + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000003, R16 MOVD R16, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000004, R16 MOVD R16, ret+24(FP) RET // Return with overread error error_overread: + MOVD 40(RSP), R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000006, R16 MOVD R16, ret+24(FP) RET @@ -705,24 +650,27 @@ main_loop: MOVD 8(R0), R12 // Copy literals - TST R10, R10 - BEQ check_offset - MOVD $0, R13 + FMOVQ (R5), F0 + FMOVQ F0, (R3) + CMP $0x10, R10 + BLS copy_1_end + MOVD $0x00000010, R13 copy_1: - ADD R13, R5, R15 - VLD1 (R15), [V0.B16] - ADD R13, R3, R15 - VST1 [V0.B16], (R15) - ADD $0x10, R13, R13 - CMP R10, R13 - BLO copy_1 - ADD R10, R5, R5 - ADD R10, R3, R3 - ADD R10, R6, R6 + ADD R13, R5, R15 + FMOVQ (R15), F0 + ADD R13, R3, R15 + FMOVQ F0, (R15) + ADD $0x10, R13, R13 + CMP R10, R13 + BLO copy_1 + +copy_1_end: + ADD R10, R5, R5 + ADD R10, R3, R3 + ADD R10, R6, R6 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: ADD R9, R6, R10 CMP R10, R11 BGT error_match_off_too_big @@ -742,21 +690,19 @@ check_offset: BLO copy_4_small copy_4_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R13, R13 - ADD $0x10, R3, R3 - SUBS $0x10, R10, R10 - BHS copy_4_loop - ADD R10, R13, R13 - ADD $16, R13, R13 - ADD R10, R3, R3 - ADD $16, R3, R3 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_4_end + FMOVQ (R13), F0 + FMOVQ F0, (R3) + ADD $0x10, R13, R13 + ADD $0x10, R3, R3 + SUBS $0x10, R10, R10 + BHS copy_4_loop + ADD R10, R13, R13 + ADD $16, R13, R13 + ADD R10, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R3) + JMP copy_4_end copy_4_small: CMP $0x03, R12 @@ -766,13 +712,14 @@ copy_4_small: JMP copy_4_move_8through16 copy_4_move_3: - MOVH (R13), R10 - MOVB 2(R13), R11 - MOVH R10, (R3) - MOVB R11, 2(R3) - ADD R12, R13, R13 - ADD R12, R3, R3 - JMP copy_4_end + MOVHU (R13), R10 + MOVBU 2(R13), R16 + BFI $0, R16, $8, R11 + MOVH R10, (R3) + MOVB R11, 2(R3) + ADD R12, R13, R13 + ADD R12, R3, R3 + JMP copy_4_end copy_4_move_4through7: MOVWU (R13), R10 @@ -809,21 +756,19 @@ copy_all_from_history: BLO copy_5_small copy_5_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R13, R13 - ADD $0x10, R3, R3 - SUBS $0x10, R14, R14 - BHS copy_5_loop - ADD R14, R13, R13 - ADD $16, R13, R13 - ADD R14, R3, R3 - ADD $16, R3, R3 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_5_end + FMOVQ (R13), F0 + FMOVQ F0, (R3) + ADD $0x10, R13, R13 + ADD $0x10, R3, R3 + SUBS $0x10, R14, R14 + BHS copy_5_loop + ADD R14, R13, R13 + ADD $16, R13, R13 + ADD R14, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R3) + JMP copy_5_end copy_5_small: CMP $0x03, R10 @@ -834,24 +779,27 @@ copy_5_small: JMP copy_5_move_8through16 copy_5_move_1or2: - MOVB (R13), R14 - ADD R10, R13, R15 - MOVB -1(R15), R4 - MOVB R14, (R3) - ADD R10, R3, R15 - MOVB R4, -1(R15) - ADD R10, R13, R13 - ADD R10, R3, R3 - JMP copy_5_end + MOVBU (R13), R16 + BFI $0, R16, $8, R14 + ADD R10, R13, R15 + MOVBU -1(R15), R16 + BFI $0, R16, $8, R4 + MOVB R14, (R3) + ADD R10, R3, R15 + MOVB R4, -1(R15) + ADD R10, R13, R13 + ADD R10, R3, R3 + JMP copy_5_end copy_5_move_3: - MOVH (R13), R14 - MOVB 2(R13), R4 - MOVH R14, (R3) - MOVB R4, 2(R3) - ADD R10, R13, R13 - ADD R10, R3, R3 - JMP copy_5_end + MOVHU (R13), R14 + MOVBU 2(R13), R16 + BFI $0, R16, $8, R4 + MOVH R14, (R3) + MOVB R4, 2(R3) + ADD R10, R13, R13 + ADD R10, R3, R3 + JMP copy_5_end copy_5_move_4through7: MOVWU (R13), R14 @@ -888,30 +836,40 @@ copy_match: BHI copy_overlapping_match // Copy non-overlapping match - ADD R12, R6, R6 - MOVD R3, R11 - ADD R12, R3, R3 + ADD R12, R6, R6 + FMOVQ (R10), F0 + FMOVQ F0, (R3) + CMP $0x10, R12 + BHI copy_2_long + ADD R12, R3, R3 + JMP handle_loop + +copy_2_long: + ADD $16, R3, R11 + ADD R12, R3, R3 + ADD $0x10, R10, R10 + SUB $0x10, R12, R12 copy_2: - VLD1 (R10), [V0.B16] - VST1 [V0.B16], (R11) - ADD $0x10, R10, R10 - ADD $0x10, R11, R11 - SUBS $0x10, R12, R12 - BHI copy_2 - JMP handle_loop + FMOVQ (R10), F0 + FMOVQ F0, (R11) + ADD $0x10, R10, R10 + ADD $0x10, R11, R11 + SUBS $0x10, R12, R12 + BHI copy_2 + JMP handle_loop // Copy overlapping match copy_overlapping_match: ADD R12, R6, R6 copy_slow_3: - MOVB (R10), R11 - MOVB R11, (R3) - ADD $1, R10, R10 - ADD $1, R3, R3 - SUBS $1, R12, R12 - BNE copy_slow_3 + MOVBU (R10), R11 + MOVB R11, (R3) + ADD $1, R10, R10 + ADD $1, R3, R3 + SUBS $1, R12, R12 + BNE copy_slow_3 handle_loop: ADD $0x18, R0, R0 @@ -991,21 +949,19 @@ main_loop: BLO copy_1_small copy_1_loop: - VLD1 (R5), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R5, R5 - ADD $0x10, R3, R3 - SUBS $0x10, R13, R13 - BHS copy_1_loop - ADD R13, R5, R5 - ADD $16, R5, R5 - ADD R13, R3, R3 - ADD $16, R3, R3 - ADD $-16, R5, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_1_end + FMOVQ (R5), F0 + FMOVQ F0, (R3) + ADD $0x10, R5, R5 + ADD $0x10, R3, R3 + SUBS $0x10, R13, R13 + BHS copy_1_loop + ADD R13, R5, R5 + ADD $16, R5, R5 + ADD R13, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R5), F0 + FMOVQ F0, -16(R3) + JMP copy_1_end copy_1_small: CMP $0x03, R10 @@ -1016,24 +972,27 @@ copy_1_small: JMP copy_1_move_8through16 copy_1_move_1or2: - MOVB (R5), R13 - ADD R10, R5, R15 - MOVB -1(R15), R14 - MOVB R13, (R3) - ADD R10, R3, R15 - MOVB R14, -1(R15) - ADD R10, R5, R5 - ADD R10, R3, R3 - JMP copy_1_end + MOVBU (R5), R16 + BFI $0, R16, $8, R13 + ADD R10, R5, R15 + MOVBU -1(R15), R16 + BFI $0, R16, $8, R14 + MOVB R13, (R3) + ADD R10, R3, R15 + MOVB R14, -1(R15) + ADD R10, R5, R5 + ADD R10, R3, R3 + JMP copy_1_end copy_1_move_3: - MOVH (R5), R13 - MOVB 2(R5), R14 - MOVH R13, (R3) - MOVB R14, 2(R3) - ADD R10, R5, R5 - ADD R10, R3, R3 - JMP copy_1_end + MOVHU (R5), R13 + MOVBU 2(R5), R16 + BFI $0, R16, $8, R14 + MOVH R13, (R3) + MOVB R14, 2(R3) + ADD R10, R5, R5 + ADD R10, R3, R3 + JMP copy_1_end copy_1_move_4through7: MOVWU (R5), R13 @@ -1080,21 +1039,19 @@ check_offset: BLO copy_4_small copy_4_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R13, R13 - ADD $0x10, R3, R3 - SUBS $0x10, R10, R10 - BHS copy_4_loop - ADD R10, R13, R13 - ADD $16, R13, R13 - ADD R10, R3, R3 - ADD $16, R3, R3 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_4_end + FMOVQ (R13), F0 + FMOVQ F0, (R3) + ADD $0x10, R13, R13 + ADD $0x10, R3, R3 + SUBS $0x10, R10, R10 + BHS copy_4_loop + ADD R10, R13, R13 + ADD $16, R13, R13 + ADD R10, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R3) + JMP copy_4_end copy_4_small: CMP $0x03, R12 @@ -1104,13 +1061,14 @@ copy_4_small: JMP copy_4_move_8through16 copy_4_move_3: - MOVH (R13), R10 - MOVB 2(R13), R11 - MOVH R10, (R3) - MOVB R11, 2(R3) - ADD R12, R13, R13 - ADD R12, R3, R3 - JMP copy_4_end + MOVHU (R13), R10 + MOVBU 2(R13), R16 + BFI $0, R16, $8, R11 + MOVH R10, (R3) + MOVB R11, 2(R3) + ADD R12, R13, R13 + ADD R12, R3, R3 + JMP copy_4_end copy_4_move_4through7: MOVWU (R13), R10 @@ -1147,21 +1105,19 @@ copy_all_from_history: BLO copy_5_small copy_5_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R13, R13 - ADD $0x10, R3, R3 - SUBS $0x10, R14, R14 - BHS copy_5_loop - ADD R14, R13, R13 - ADD $16, R13, R13 - ADD R14, R3, R3 - ADD $16, R3, R3 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_5_end + FMOVQ (R13), F0 + FMOVQ F0, (R3) + ADD $0x10, R13, R13 + ADD $0x10, R3, R3 + SUBS $0x10, R14, R14 + BHS copy_5_loop + ADD R14, R13, R13 + ADD $16, R13, R13 + ADD R14, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R3) + JMP copy_5_end copy_5_small: CMP $0x03, R10 @@ -1172,24 +1128,27 @@ copy_5_small: JMP copy_5_move_8through16 copy_5_move_1or2: - MOVB (R13), R14 - ADD R10, R13, R15 - MOVB -1(R15), R4 - MOVB R14, (R3) - ADD R10, R3, R15 - MOVB R4, -1(R15) - ADD R10, R13, R13 - ADD R10, R3, R3 - JMP copy_5_end + MOVBU (R13), R16 + BFI $0, R16, $8, R14 + ADD R10, R13, R15 + MOVBU -1(R15), R16 + BFI $0, R16, $8, R4 + MOVB R14, (R3) + ADD R10, R3, R15 + MOVB R4, -1(R15) + ADD R10, R13, R13 + ADD R10, R3, R3 + JMP copy_5_end copy_5_move_3: - MOVH (R13), R14 - MOVB 2(R13), R4 - MOVH R14, (R3) - MOVB R4, 2(R3) - ADD R10, R13, R13 - ADD R10, R3, R3 - JMP copy_5_end + MOVHU (R13), R14 + MOVBU 2(R13), R16 + BFI $0, R16, $8, R4 + MOVH R14, (R3) + MOVB R4, 2(R3) + ADD R10, R13, R13 + ADD R10, R3, R3 + JMP copy_5_end copy_5_move_4through7: MOVWU (R13), R14 @@ -1232,21 +1191,19 @@ copy_match: BLO copy_2_small copy_2_loop: - VLD1 (R10), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R10, R10 - ADD $0x10, R3, R3 - SUBS $0x10, R11, R11 - BHS copy_2_loop - ADD R11, R10, R10 - ADD $16, R10, R10 - ADD R11, R3, R3 - ADD $16, R3, R3 - ADD $-16, R10, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_2_end + FMOVQ (R10), F0 + FMOVQ F0, (R3) + ADD $0x10, R10, R10 + ADD $0x10, R3, R3 + SUBS $0x10, R11, R11 + BHS copy_2_loop + ADD R11, R10, R10 + ADD $16, R10, R10 + ADD R11, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R10), F0 + FMOVQ F0, -16(R3) + JMP copy_2_end copy_2_small: CMP $0x03, R12 @@ -1257,24 +1214,27 @@ copy_2_small: JMP copy_2_move_8through16 copy_2_move_1or2: - MOVB (R10), R11 - ADD R12, R10, R15 - MOVB -1(R15), R13 - MOVB R11, (R3) - ADD R12, R3, R15 - MOVB R13, -1(R15) - ADD R12, R10, R10 - ADD R12, R3, R3 - JMP copy_2_end + MOVBU (R10), R16 + BFI $0, R16, $8, R11 + ADD R12, R10, R15 + MOVBU -1(R15), R16 + BFI $0, R16, $8, R13 + MOVB R11, (R3) + ADD R12, R3, R15 + MOVB R13, -1(R15) + ADD R12, R10, R10 + ADD R12, R3, R3 + JMP copy_2_end copy_2_move_3: - MOVH (R10), R11 - MOVB 2(R10), R13 - MOVH R11, (R3) - MOVB R13, 2(R3) - ADD R12, R10, R10 - ADD R12, R3, R3 - JMP copy_2_end + MOVHU (R10), R11 + MOVBU 2(R10), R16 + BFI $0, R16, $8, R13 + MOVH R11, (R3) + MOVB R13, 2(R3) + ADD R12, R10, R10 + ADD R12, R3, R3 + JMP copy_2_end copy_2_move_4through7: MOVWU (R10), R11 @@ -1305,12 +1265,12 @@ copy_overlapping_match: ADD R12, R6, R6 copy_slow_3: - MOVB (R10), R11 - MOVB R11, (R3) - ADD $1, R10, R10 - ADD $1, R3, R3 - SUBS $1, R12, R12 - BNE copy_slow_3 + MOVBU (R10), R11 + MOVB R11, (R3) + ADD $1, R10, R10 + ADD $1, R3, R3 + SUBS $1, R12, R12 + BNE copy_slow_3 handle_loop: ADD $0x18, R0, R0 @@ -1354,54 +1314,61 @@ empty_seqs: // func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_arm64(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_arm64(SB), $96-32 MOVD br+8(FP), R1 MOVD 24(R1), R2 MOVBU 40(R1), R3 MOVD (R1), R0 MOVD 32(R1), R5 ADD R5, R0, R0 - MOVD R0, (RSP) + MOVD R0, 8(RSP) MOVD ctx+16(FP), R0 MOVD 72(R0), R6 MOVD 80(R0), R7 MOVD 88(R0), R8 - MOVD $0, R1 - MOVD R1, 8(RSP) + MOVD (R0), R1 MOVD R1, 16(RSP) + MOVD 24(R0), R1 MOVD R1, 24(RSP) + MOVD 48(R0), R1 + MOVD R1, 32(RSP) + MOVD 96(R0), R1 + MOVD R1, 40(RSP) + MOVD $0, R1 + MOVD R1, 48(RSP) + MOVD R1, 56(RSP) + MOVD R1, 64(RSP) MOVD 112(R0), R9 MOVD 128(R0), R1 - MOVD R1, 32(RSP) + MOVD R1, 72(RSP) MOVD 144(R0), R10 MOVD 136(R0), R11 MOVD 200(R0), R1 - MOVD R1, 56(RSP) + MOVD R1, 96(RSP) MOVD 176(R0), R1 - MOVD R1, 48(RSP) + MOVD R1, 88(RSP) MOVD 184(R0), R0 - MOVD R0, 40(RSP) - MOVD 40(RSP), R0 - MOVD 48(RSP), R16 + MOVD R0, 80(RSP) + MOVD 80(RSP), R0 + MOVD 88(RSP), R16 ADD R0, R16, R16 - MOVD R16, 48(RSP) + MOVD R16, 88(RSP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - MOVD 32(RSP), R16 + MOVD 72(RSP), R16 ADD R9, R16, R16 - MOVD R16, 32(RSP) + MOVD R16, 72(RSP) // outBase += outPosition ADD R11, R9, R9 sequenceDecs_decodeSync_amd64_main_loop: - MOVD (RSP), R12 + MOVD 8(RSP), R12 // Fill bitreader to have enough for the offset and match length. CMP $0x08, R5 BLT sequenceDecs_decodeSync_amd64_fill_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 + LSR $0x03, R3, R0 SUB R0, R12, R12 MOVD (R12), R2 SUB R0, R5, R5 @@ -1428,51 +1395,32 @@ sequenceDecs_decodeSync_amd64_fill_check_overread: sequenceDecs_decodeSync_amd64_fill_end: // Update offset MOVD R8, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_amd64_of_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_amd64_of_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_amd64_of_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_amd64_of_update_zero: - MOVD R0, 8(RSP) + MOVD R0, 48(RSP) // Update match length MOVD R7, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_amd64_ml_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_amd64_ml_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_amd64_ml_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_amd64_ml_update_zero: - MOVD R0, 16(RSP) + MOVD R0, 56(RSP) // Fill bitreader to have enough for the remaining CMP $0x08, R5 BLT sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 + LSR $0x03, R3, R0 SUB R0, R12, R12 MOVD (R12), R2 SUB R0, R5, R5 @@ -1499,113 +1447,78 @@ sequenceDecs_decodeSync_amd64_fill_2_check_overread: sequenceDecs_decodeSync_amd64_fill_2_end: // Update literal length MOVD R6, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_amd64_ll_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_amd64_ll_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_amd64_ll_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_amd64_ll_update_zero: - MOVD R0, 24(RSP) + MOVD R0, 64(RSP) // Fill bitreader for state updates - MOVD R12, (RSP) - MOVD R8, R0 - LSR $0x08, R0, R0 - MOVBU R0, R0 - MOVD ctx+16(FP), R1 - MOVD 96(R1), R16 - CMP $0x00, R16 - BEQ sequenceDecs_decodeSync_amd64_skip_update + MOVD R12, 8(RSP) + UBFX $8, R8, $8, R0 + MOVD 40(RSP), R16 + CMP $0x00, R16 + BEQ sequenceDecs_decodeSync_amd64_skip_update // Update Literal Length State MOVBU R6, R12 LSRW $0x10, R6, R6 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - MOVB R12, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R6, R6 // Load ctx.llTable - MOVD ctx+16(FP), R1 - MOVD (R1), R1 - ADD R6<<3, R1, R15 - MOVD (R15), R6 + MOVD 16(RSP), R1 + MOVD (R1)(R6<<3), R6 // Update Match Length State MOVBU R7, R12 LSRW $0x10, R7, R7 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - MOVB R12, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R7, R7 // Load ctx.mlTable - MOVD ctx+16(FP), R1 - MOVD 24(R1), R1 - ADD R7<<3, R1, R15 - MOVD (R15), R7 + MOVD 24(RSP), R1 + MOVD (R1)(R7<<3), R7 // Update Offset State MOVBU R8, R12 LSRW $0x10, R8, R8 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - MOVB R12, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R8, R8 // Load ctx.ofTable - MOVD ctx+16(FP), R1 - MOVD 48(R1), R1 - ADD R8<<3, R1, R15 - MOVD (R15), R8 + MOVD 32(RSP), R1 + MOVD (R1)(R8<<3), R8 sequenceDecs_decodeSync_amd64_skip_update: // Adjust offset - MOVD s+0(FP), R1 - MOVD 8(RSP), R12 - CMP $0x01, R0 - BLS sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0 - ADD $144, R1, R15 - VLD1 (R15), [V0.B16] - MOVD R12, 144(R1) - ADD $152, R1, R15 - VST1 [V0.B16], (R15) - JMP sequenceDecs_decodeSync_amd64_after_adjust + MOVD s+0(FP), R1 + MOVD 48(RSP), R12 + CMP $0x01, R0 + BLS sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0 + FMOVQ 144(R1), F0 + MOVD R12, 144(R1) + FMOVQ F0, 152(R1) + JMP sequenceDecs_decodeSync_amd64_after_adjust sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0: - MOVD 24(RSP), R16 + MOVD 64(RSP), R16 CMP $0x00000000, R16 BNE sequenceDecs_decodeSync_amd64_adjust_offset_maybezero ADD $1, R12, R12 @@ -1643,16 +1556,11 @@ sequenceDecs_decodeSync_amd64_adjust_skip: MOVD R13, R12 sequenceDecs_decodeSync_amd64_after_adjust: - MOVD R12, 8(RSP) + MOVD R12, 48(RSP) // Check values - MOVD 16(RSP), R0 - MOVD 24(RSP), R1 - ADD R1, R0, R13 - MOVD s+0(FP), R14 - MOVD 256(R14), R16 - ADD R13, R16, R16 - MOVD R16, 256(R14) + MOVD 56(RSP), R0 + MOVD 64(RSP), R1 MOVD ctx+16(FP), R13 MOVD 104(R13), R16 SUBS R1, R16, R16 @@ -1666,231 +1574,240 @@ sequenceDecs_decodeSync_amd64_after_adjust: BNE sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch sequenceDecs_decodeSync_amd64_match_len_ofs_ok: - MOVD 24(RSP), R0 - MOVD 8(RSP), R1 - MOVD 16(RSP), R12 - // Check if we have enough space in s.out - ADD R12, R0, R13 + ADD R0, R1, R13 + ADD $16, R13, R13 ADD R9, R13, R13 - MOVD 32(RSP), R16 + MOVD 72(RSP), R16 CMP R16, R13 BHI error_not_enough_space // Copy literals - TST R0, R0 - BEQ check_offset - MOVD $0, R13 + FMOVQ (R10), F0 + FMOVQ F0, (R9) + CMP $0x10, R1 + BLS copy_1_end + MOVD $0x00000010, R13 copy_1: - ADD R13, R10, R15 - VLD1 (R15), [V0.B16] - ADD R13, R9, R15 - VST1 [V0.B16], (R15) - ADD $0x10, R13, R13 - CMP R0, R13 - BLO copy_1 - ADD R0, R10, R10 - ADD R0, R9, R9 - ADD R0, R11, R11 + ADD R13, R10, R15 + FMOVQ (R15), F0 + ADD R13, R9, R15 + FMOVQ F0, (R15) + ADD $0x10, R13, R13 + CMP R1, R13 + BLO copy_1 + +copy_1_end: + ADD R1, R10, R10 + ADD R1, R9, R9 + ADD R1, R11, R11 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVD R11, R0 - MOVD 40(RSP), R16 - ADD R16, R0, R0 - CMP R0, R1 + MOVD R11, R1 + MOVD 80(RSP), R16 + ADD R16, R1, R1 + CMP R1, R12 BGT error_match_off_too_big - MOVD 56(RSP), R16 - CMP R16, R1 + MOVD 96(RSP), R16 + CMP R16, R12 BGT error_match_off_too_big // Copy match from history - MOVD R1, R0 - SUBS R11, R0, R0 + MOVD R12, R1 + SUBS R11, R1, R1 BLS copy_match - MOVD 48(RSP), R13 - SUB R0, R13, R13 - CMP R0, R12 + MOVD 88(RSP), R13 + SUB R1, R13, R13 + CMP R1, R0 BGT copy_all_from_history - MOVD R12, R0 - SUBS $0x10, R0, R0 + MOVD R0, R1 + SUBS $0x10, R1, R1 BLO copy_4_small copy_4_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R13, R13 - ADD $0x10, R9, R9 - SUBS $0x10, R0, R0 - BHS copy_4_loop - ADD R0, R13, R13 - ADD $16, R13, R13 - ADD R0, R9, R9 - ADD $16, R9, R9 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_4_end + FMOVQ (R13), F0 + FMOVQ F0, (R9) + ADD $0x10, R13, R13 + ADD $0x10, R9, R9 + SUBS $0x10, R1, R1 + BHS copy_4_loop + ADD R1, R13, R13 + ADD $16, R13, R13 + ADD R1, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R9) + JMP copy_4_end copy_4_small: - CMP $0x03, R12 + CMP $0x03, R0 BEQ copy_4_move_3 - CMP $0x08, R12 + CMP $0x08, R0 BLO copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVH (R13), R0 - MOVB 2(R13), R1 - MOVH R0, (R9) - MOVB R1, 2(R9) - ADD R12, R13, R13 - ADD R12, R9, R9 - JMP copy_4_end + MOVHU (R13), R1 + MOVBU 2(R13), R16 + BFI $0, R16, $8, R12 + MOVH R1, (R9) + MOVB R12, 2(R9) + ADD R0, R13, R13 + ADD R0, R9, R9 + JMP copy_4_end copy_4_move_4through7: - MOVWU (R13), R0 - ADD R12, R13, R15 - MOVWU -4(R15), R1 - MOVW R0, (R9) - ADD R12, R9, R15 - MOVW R1, -4(R15) - ADD R12, R13, R13 - ADD R12, R9, R9 + MOVWU (R13), R1 + ADD R0, R13, R15 + MOVWU -4(R15), R12 + MOVW R1, (R9) + ADD R0, R9, R15 + MOVW R12, -4(R15) + ADD R0, R13, R13 + ADD R0, R9, R9 JMP copy_4_end copy_4_move_8through16: - MOVD (R13), R0 - ADD R12, R13, R15 - MOVD -8(R15), R1 - MOVD R0, (R9) - ADD R12, R9, R15 - MOVD R1, -8(R15) - ADD R12, R13, R13 - ADD R12, R9, R9 + MOVD (R13), R1 + ADD R0, R13, R15 + MOVD -8(R15), R12 + MOVD R1, (R9) + ADD R0, R9, R15 + MOVD R12, -8(R15) + ADD R0, R13, R13 + ADD R0, R9, R9 copy_4_end: - ADD R12, R11, R11 + ADD R0, R11, R11 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVD R0, R14 + MOVD R1, R14 SUBS $0x10, R14, R14 BLO copy_5_small copy_5_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R13, R13 - ADD $0x10, R9, R9 - SUBS $0x10, R14, R14 - BHS copy_5_loop - ADD R14, R13, R13 - ADD $16, R13, R13 - ADD R14, R9, R9 - ADD $16, R9, R9 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_5_end + FMOVQ (R13), F0 + FMOVQ F0, (R9) + ADD $0x10, R13, R13 + ADD $0x10, R9, R9 + SUBS $0x10, R14, R14 + BHS copy_5_loop + ADD R14, R13, R13 + ADD $16, R13, R13 + ADD R14, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R9) + JMP copy_5_end copy_5_small: - CMP $0x03, R0 + CMP $0x03, R1 BEQ copy_5_move_3 BLO copy_5_move_1or2 - CMP $0x08, R0 + CMP $0x08, R1 BLO copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: - MOVB (R13), R14 - ADD R0, R13, R15 - MOVB -1(R15), R4 - MOVB R14, (R9) - ADD R0, R9, R15 - MOVB R4, -1(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 - JMP copy_5_end + MOVBU (R13), R16 + BFI $0, R16, $8, R14 + ADD R1, R13, R15 + MOVBU -1(R15), R16 + BFI $0, R16, $8, R4 + MOVB R14, (R9) + ADD R1, R9, R15 + MOVB R4, -1(R15) + ADD R1, R13, R13 + ADD R1, R9, R9 + JMP copy_5_end copy_5_move_3: - MOVH (R13), R14 - MOVB 2(R13), R4 - MOVH R14, (R9) - MOVB R4, 2(R9) - ADD R0, R13, R13 - ADD R0, R9, R9 - JMP copy_5_end + MOVHU (R13), R14 + MOVBU 2(R13), R16 + BFI $0, R16, $8, R4 + MOVH R14, (R9) + MOVB R4, 2(R9) + ADD R1, R13, R13 + ADD R1, R9, R9 + JMP copy_5_end copy_5_move_4through7: MOVWU (R13), R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVWU -4(R15), R4 MOVW R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVW R4, -4(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 JMP copy_5_end copy_5_move_8through16: MOVD (R13), R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVD -8(R15), R4 MOVD R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVD R4, -8(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 copy_5_end: - ADD R0, R11, R11 - SUB R0, R12, R12 + ADD R1, R11, R11 + SUB R1, R0, R0 // Copy match from the current buffer copy_match: - MOVD R9, R0 - SUB R1, R0, R0 + MOVD R9, R1 + SUB R12, R1, R1 // ml <= mo - CMP R1, R12 + CMP R12, R0 BHI copy_overlapping_match // Copy non-overlapping match - ADD R12, R11, R11 - MOVD R9, R1 - ADD R12, R9, R9 + ADD R0, R11, R11 + FMOVQ (R1), F0 + FMOVQ F0, (R9) + CMP $0x10, R0 + BHI copy_2_long + ADD R0, R9, R9 + JMP handle_loop + +copy_2_long: + ADD $16, R9, R12 + ADD R0, R9, R9 + ADD $0x10, R1, R1 + SUB $0x10, R0, R0 copy_2: - VLD1 (R0), [V0.B16] - VST1 [V0.B16], (R1) - ADD $0x10, R0, R0 - ADD $0x10, R1, R1 - SUBS $0x10, R12, R12 - BHI copy_2 - JMP handle_loop + FMOVQ (R1), F0 + FMOVQ F0, (R12) + ADD $0x10, R1, R1 + ADD $0x10, R12, R12 + SUBS $0x10, R0, R0 + BHI copy_2 + JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADD R12, R11, R11 + ADD R0, R11, R11 copy_slow_3: - MOVB (R0), R1 - MOVB R1, (R9) - ADD $1, R0, R0 - ADD $1, R9, R9 - SUBS $1, R12, R12 - BNE copy_slow_3 + MOVBU (R1), R12 + MOVB R12, (R9) + ADD $1, R1, R1 + ADD $1, R9, R9 + SUBS $1, R0, R0 + BNE copy_slow_3 handle_loop: - MOVD ctx+16(FP), R0 - MOVD 96(R0), R16 + MOVD 40(RSP), R16 SUBS $1, R16, R16 - MOVD R16, 96(R0) + MOVD R16, 40(RSP) BPL sequenceDecs_decodeSync_amd64_main_loop loop_finished: @@ -1899,6 +1816,16 @@ loop_finished: MOVB R3, 40(R0) MOVD R5, 32(R0) + // s.seqSize += outPosition - ctx.outPosition + MOVD ctx+16(FP), R0 + MOVD s+0(FP), R1 + MOVD R11, R2 + MOVD 136(R0), R16 + SUB R16, R2, R2 + MOVD 256(R1), R16 + ADD R2, R16, R16 + MOVD R16, 256(R1) + // Update the context MOVD ctx+16(FP), R0 MOVD R11, 136(R0) @@ -1913,7 +1840,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: - MOVD 16(RSP), R0 + MOVD 56(RSP), R0 MOVD ctx+16(FP), R1 MOVD R0, 216(R1) MOVD $0x00000001, R16 @@ -1923,7 +1850,7 @@ sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_amd64_error_match_len_too_big: MOVD ctx+16(FP), R0 - MOVD 16(RSP), R1 + MOVD 56(RSP), R1 MOVD R1, 216(R0) MOVD $0x00000002, R16 MOVD R16, ret+24(FP) @@ -1932,7 +1859,7 @@ sequenceDecs_decodeSync_amd64_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVD ctx+16(FP), R0 - MOVD 8(RSP), R1 + MOVD 48(RSP), R1 MOVD R1, 224(R0) MOVD R11, 136(R0) MOVD $0x00000003, R16 @@ -1942,7 +1869,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVD ctx+16(FP), R0 - MOVD 24(RSP), R1 + MOVD 64(RSP), R1 MOVD R1, 208(R0) MOVD $0x00000004, R16 MOVD R16, ret+24(FP) @@ -1957,9 +1884,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVD ctx+16(FP), R0 - MOVD 24(RSP), R1 + MOVD 64(RSP), R1 MOVD R1, 208(R0) - MOVD 16(RSP), R1 + MOVD 56(RSP), R1 MOVD R1, 216(R0) MOVD R11, 136(R0) MOVD $0x00000005, R16 @@ -1970,54 +1897,61 @@ error_not_enough_space: // func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_arm64(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_safe_arm64(SB), $96-32 MOVD br+8(FP), R1 MOVD 24(R1), R2 MOVBU 40(R1), R3 MOVD (R1), R0 MOVD 32(R1), R5 ADD R5, R0, R0 - MOVD R0, (RSP) + MOVD R0, 8(RSP) MOVD ctx+16(FP), R0 MOVD 72(R0), R6 MOVD 80(R0), R7 MOVD 88(R0), R8 - MOVD $0, R1 - MOVD R1, 8(RSP) + MOVD (R0), R1 MOVD R1, 16(RSP) + MOVD 24(R0), R1 MOVD R1, 24(RSP) + MOVD 48(R0), R1 + MOVD R1, 32(RSP) + MOVD 96(R0), R1 + MOVD R1, 40(RSP) + MOVD $0, R1 + MOVD R1, 48(RSP) + MOVD R1, 56(RSP) + MOVD R1, 64(RSP) MOVD 112(R0), R9 MOVD 128(R0), R1 - MOVD R1, 32(RSP) + MOVD R1, 72(RSP) MOVD 144(R0), R10 MOVD 136(R0), R11 MOVD 200(R0), R1 - MOVD R1, 56(RSP) + MOVD R1, 96(RSP) MOVD 176(R0), R1 - MOVD R1, 48(RSP) + MOVD R1, 88(RSP) MOVD 184(R0), R0 - MOVD R0, 40(RSP) - MOVD 40(RSP), R0 - MOVD 48(RSP), R16 + MOVD R0, 80(RSP) + MOVD 80(RSP), R0 + MOVD 88(RSP), R16 ADD R0, R16, R16 - MOVD R16, 48(RSP) + MOVD R16, 88(RSP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - MOVD 32(RSP), R16 + MOVD 72(RSP), R16 ADD R9, R16, R16 - MOVD R16, 32(RSP) + MOVD R16, 72(RSP) // outBase += outPosition ADD R11, R9, R9 sequenceDecs_decodeSync_safe_amd64_main_loop: - MOVD (RSP), R12 + MOVD 8(RSP), R12 // Fill bitreader to have enough for the offset and match length. CMP $0x08, R5 BLT sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 + LSR $0x03, R3, R0 SUB R0, R12, R12 MOVD (R12), R2 SUB R0, R5, R5 @@ -2044,51 +1978,32 @@ sequenceDecs_decodeSync_safe_amd64_fill_check_overread: sequenceDecs_decodeSync_safe_amd64_fill_end: // Update offset MOVD R8, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_safe_amd64_of_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_safe_amd64_of_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_safe_amd64_of_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_safe_amd64_of_update_zero: - MOVD R0, 8(RSP) + MOVD R0, 48(RSP) // Update match length MOVD R7, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_safe_amd64_ml_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_safe_amd64_ml_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_safe_amd64_ml_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_safe_amd64_ml_update_zero: - MOVD R0, 16(RSP) + MOVD R0, 56(RSP) // Fill bitreader to have enough for the remaining CMP $0x08, R5 BLT sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 + LSR $0x03, R3, R0 SUB R0, R12, R12 MOVD (R12), R2 SUB R0, R5, R5 @@ -2115,113 +2030,78 @@ sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread: sequenceDecs_decodeSync_safe_amd64_fill_2_end: // Update literal length MOVD R6, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_safe_amd64_ll_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_safe_amd64_ll_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_safe_amd64_ll_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_safe_amd64_ll_update_zero: - MOVD R0, 24(RSP) + MOVD R0, 64(RSP) // Fill bitreader for state updates - MOVD R12, (RSP) - MOVD R8, R0 - LSR $0x08, R0, R0 - MOVBU R0, R0 - MOVD ctx+16(FP), R1 - MOVD 96(R1), R16 - CMP $0x00, R16 - BEQ sequenceDecs_decodeSync_safe_amd64_skip_update + MOVD R12, 8(RSP) + UBFX $8, R8, $8, R0 + MOVD 40(RSP), R16 + CMP $0x00, R16 + BEQ sequenceDecs_decodeSync_safe_amd64_skip_update // Update Literal Length State MOVBU R6, R12 LSRW $0x10, R6, R6 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - MOVB R12, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R6, R6 // Load ctx.llTable - MOVD ctx+16(FP), R1 - MOVD (R1), R1 - ADD R6<<3, R1, R15 - MOVD (R15), R6 + MOVD 16(RSP), R1 + MOVD (R1)(R6<<3), R6 // Update Match Length State MOVBU R7, R12 LSRW $0x10, R7, R7 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - MOVB R12, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R7, R7 // Load ctx.mlTable - MOVD ctx+16(FP), R1 - MOVD 24(R1), R1 - ADD R7<<3, R1, R15 - MOVD (R15), R7 + MOVD 24(RSP), R1 + MOVD (R1)(R7<<3), R7 // Update Offset State MOVBU R8, R12 LSRW $0x10, R8, R8 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - MOVB R12, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R8, R8 // Load ctx.ofTable - MOVD ctx+16(FP), R1 - MOVD 48(R1), R1 - ADD R8<<3, R1, R15 - MOVD (R15), R8 + MOVD 32(RSP), R1 + MOVD (R1)(R8<<3), R8 sequenceDecs_decodeSync_safe_amd64_skip_update: // Adjust offset - MOVD s+0(FP), R1 - MOVD 8(RSP), R12 - CMP $0x01, R0 - BLS sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0 - ADD $144, R1, R15 - VLD1 (R15), [V0.B16] - MOVD R12, 144(R1) - ADD $152, R1, R15 - VST1 [V0.B16], (R15) - JMP sequenceDecs_decodeSync_safe_amd64_after_adjust + MOVD s+0(FP), R1 + MOVD 48(RSP), R12 + CMP $0x01, R0 + BLS sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0 + FMOVQ 144(R1), F0 + MOVD R12, 144(R1) + FMOVQ F0, 152(R1) + JMP sequenceDecs_decodeSync_safe_amd64_after_adjust sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0: - MOVD 24(RSP), R16 + MOVD 64(RSP), R16 CMP $0x00000000, R16 BNE sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero ADD $1, R12, R12 @@ -2259,16 +2139,11 @@ sequenceDecs_decodeSync_safe_amd64_adjust_skip: MOVD R13, R12 sequenceDecs_decodeSync_safe_amd64_after_adjust: - MOVD R12, 8(RSP) + MOVD R12, 48(RSP) // Check values - MOVD 16(RSP), R0 - MOVD 24(RSP), R1 - ADD R1, R0, R13 - MOVD s+0(FP), R14 - MOVD 256(R14), R16 - ADD R13, R16, R16 - MOVD R16, 256(R14) + MOVD 56(RSP), R0 + MOVD 64(RSP), R1 MOVD ctx+16(FP), R13 MOVD 104(R13), R16 SUBS R1, R16, R16 @@ -2282,351 +2157,348 @@ sequenceDecs_decodeSync_safe_amd64_after_adjust: BNE sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok: - MOVD 24(RSP), R0 - MOVD 8(RSP), R1 - MOVD 16(RSP), R12 - // Check if we have enough space in s.out - ADD R12, R0, R13 + ADD R0, R1, R13 ADD R9, R13, R13 - MOVD 32(RSP), R16 + MOVD 72(RSP), R16 CMP R16, R13 BHI error_not_enough_space // Copy literals - TST R0, R0 + TST R1, R1 BEQ check_offset - MOVD R0, R13 + MOVD R1, R13 SUBS $0x10, R13, R13 BLO copy_1_small copy_1_loop: - VLD1 (R10), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R10, R10 - ADD $0x10, R9, R9 - SUBS $0x10, R13, R13 - BHS copy_1_loop - ADD R13, R10, R10 - ADD $16, R10, R10 - ADD R13, R9, R9 - ADD $16, R9, R9 - ADD $-16, R10, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_1_end + FMOVQ (R10), F0 + FMOVQ F0, (R9) + ADD $0x10, R10, R10 + ADD $0x10, R9, R9 + SUBS $0x10, R13, R13 + BHS copy_1_loop + ADD R13, R10, R10 + ADD $16, R10, R10 + ADD R13, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R10), F0 + FMOVQ F0, -16(R9) + JMP copy_1_end copy_1_small: - CMP $0x03, R0 + CMP $0x03, R1 BEQ copy_1_move_3 BLO copy_1_move_1or2 - CMP $0x08, R0 + CMP $0x08, R1 BLO copy_1_move_4through7 JMP copy_1_move_8through16 copy_1_move_1or2: - MOVB (R10), R13 - ADD R0, R10, R15 - MOVB -1(R15), R14 - MOVB R13, (R9) - ADD R0, R9, R15 - MOVB R14, -1(R15) - ADD R0, R10, R10 - ADD R0, R9, R9 - JMP copy_1_end + MOVBU (R10), R16 + BFI $0, R16, $8, R13 + ADD R1, R10, R15 + MOVBU -1(R15), R16 + BFI $0, R16, $8, R14 + MOVB R13, (R9) + ADD R1, R9, R15 + MOVB R14, -1(R15) + ADD R1, R10, R10 + ADD R1, R9, R9 + JMP copy_1_end copy_1_move_3: - MOVH (R10), R13 - MOVB 2(R10), R14 - MOVH R13, (R9) - MOVB R14, 2(R9) - ADD R0, R10, R10 - ADD R0, R9, R9 - JMP copy_1_end + MOVHU (R10), R13 + MOVBU 2(R10), R16 + BFI $0, R16, $8, R14 + MOVH R13, (R9) + MOVB R14, 2(R9) + ADD R1, R10, R10 + ADD R1, R9, R9 + JMP copy_1_end copy_1_move_4through7: MOVWU (R10), R13 - ADD R0, R10, R15 + ADD R1, R10, R15 MOVWU -4(R15), R14 MOVW R13, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVW R14, -4(R15) - ADD R0, R10, R10 - ADD R0, R9, R9 + ADD R1, R10, R10 + ADD R1, R9, R9 JMP copy_1_end copy_1_move_8through16: MOVD (R10), R13 - ADD R0, R10, R15 + ADD R1, R10, R15 MOVD -8(R15), R14 MOVD R13, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVD R14, -8(R15) - ADD R0, R10, R10 - ADD R0, R9, R9 + ADD R1, R10, R10 + ADD R1, R9, R9 copy_1_end: - ADD R0, R11, R11 + ADD R1, R11, R11 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) check_offset: - MOVD R11, R0 - MOVD 40(RSP), R16 - ADD R16, R0, R0 - CMP R0, R1 + MOVD R11, R1 + MOVD 80(RSP), R16 + ADD R16, R1, R1 + CMP R1, R12 BGT error_match_off_too_big - MOVD 56(RSP), R16 - CMP R16, R1 + MOVD 96(RSP), R16 + CMP R16, R12 BGT error_match_off_too_big // Copy match from history - MOVD R1, R0 - SUBS R11, R0, R0 + MOVD R12, R1 + SUBS R11, R1, R1 BLS copy_match - MOVD 48(RSP), R13 - SUB R0, R13, R13 - CMP R0, R12 + MOVD 88(RSP), R13 + SUB R1, R13, R13 + CMP R1, R0 BGT copy_all_from_history - MOVD R12, R0 - SUBS $0x10, R0, R0 + MOVD R0, R1 + SUBS $0x10, R1, R1 BLO copy_4_small copy_4_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R13, R13 - ADD $0x10, R9, R9 - SUBS $0x10, R0, R0 - BHS copy_4_loop - ADD R0, R13, R13 - ADD $16, R13, R13 - ADD R0, R9, R9 - ADD $16, R9, R9 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_4_end + FMOVQ (R13), F0 + FMOVQ F0, (R9) + ADD $0x10, R13, R13 + ADD $0x10, R9, R9 + SUBS $0x10, R1, R1 + BHS copy_4_loop + ADD R1, R13, R13 + ADD $16, R13, R13 + ADD R1, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R9) + JMP copy_4_end copy_4_small: - CMP $0x03, R12 + CMP $0x03, R0 BEQ copy_4_move_3 - CMP $0x08, R12 + CMP $0x08, R0 BLO copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVH (R13), R0 - MOVB 2(R13), R1 - MOVH R0, (R9) - MOVB R1, 2(R9) - ADD R12, R13, R13 - ADD R12, R9, R9 - JMP copy_4_end + MOVHU (R13), R1 + MOVBU 2(R13), R16 + BFI $0, R16, $8, R12 + MOVH R1, (R9) + MOVB R12, 2(R9) + ADD R0, R13, R13 + ADD R0, R9, R9 + JMP copy_4_end copy_4_move_4through7: - MOVWU (R13), R0 - ADD R12, R13, R15 - MOVWU -4(R15), R1 - MOVW R0, (R9) - ADD R12, R9, R15 - MOVW R1, -4(R15) - ADD R12, R13, R13 - ADD R12, R9, R9 + MOVWU (R13), R1 + ADD R0, R13, R15 + MOVWU -4(R15), R12 + MOVW R1, (R9) + ADD R0, R9, R15 + MOVW R12, -4(R15) + ADD R0, R13, R13 + ADD R0, R9, R9 JMP copy_4_end copy_4_move_8through16: - MOVD (R13), R0 - ADD R12, R13, R15 - MOVD -8(R15), R1 - MOVD R0, (R9) - ADD R12, R9, R15 - MOVD R1, -8(R15) - ADD R12, R13, R13 - ADD R12, R9, R9 + MOVD (R13), R1 + ADD R0, R13, R15 + MOVD -8(R15), R12 + MOVD R1, (R9) + ADD R0, R9, R15 + MOVD R12, -8(R15) + ADD R0, R13, R13 + ADD R0, R9, R9 copy_4_end: - ADD R12, R11, R11 + ADD R0, R11, R11 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVD R0, R14 + MOVD R1, R14 SUBS $0x10, R14, R14 BLO copy_5_small copy_5_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R13, R13 - ADD $0x10, R9, R9 - SUBS $0x10, R14, R14 - BHS copy_5_loop - ADD R14, R13, R13 - ADD $16, R13, R13 - ADD R14, R9, R9 - ADD $16, R9, R9 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_5_end + FMOVQ (R13), F0 + FMOVQ F0, (R9) + ADD $0x10, R13, R13 + ADD $0x10, R9, R9 + SUBS $0x10, R14, R14 + BHS copy_5_loop + ADD R14, R13, R13 + ADD $16, R13, R13 + ADD R14, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R9) + JMP copy_5_end copy_5_small: - CMP $0x03, R0 + CMP $0x03, R1 BEQ copy_5_move_3 BLO copy_5_move_1or2 - CMP $0x08, R0 + CMP $0x08, R1 BLO copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: - MOVB (R13), R14 - ADD R0, R13, R15 - MOVB -1(R15), R4 - MOVB R14, (R9) - ADD R0, R9, R15 - MOVB R4, -1(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 - JMP copy_5_end + MOVBU (R13), R16 + BFI $0, R16, $8, R14 + ADD R1, R13, R15 + MOVBU -1(R15), R16 + BFI $0, R16, $8, R4 + MOVB R14, (R9) + ADD R1, R9, R15 + MOVB R4, -1(R15) + ADD R1, R13, R13 + ADD R1, R9, R9 + JMP copy_5_end copy_5_move_3: - MOVH (R13), R14 - MOVB 2(R13), R4 - MOVH R14, (R9) - MOVB R4, 2(R9) - ADD R0, R13, R13 - ADD R0, R9, R9 - JMP copy_5_end + MOVHU (R13), R14 + MOVBU 2(R13), R16 + BFI $0, R16, $8, R4 + MOVH R14, (R9) + MOVB R4, 2(R9) + ADD R1, R13, R13 + ADD R1, R9, R9 + JMP copy_5_end copy_5_move_4through7: MOVWU (R13), R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVWU -4(R15), R4 MOVW R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVW R4, -4(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 JMP copy_5_end copy_5_move_8through16: MOVD (R13), R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVD -8(R15), R4 MOVD R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVD R4, -8(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 copy_5_end: - ADD R0, R11, R11 - SUB R0, R12, R12 + ADD R1, R11, R11 + SUB R1, R0, R0 // Copy match from the current buffer copy_match: - MOVD R9, R0 - SUB R1, R0, R0 + MOVD R9, R1 + SUB R12, R1, R1 // ml <= mo - CMP R1, R12 + CMP R12, R0 BHI copy_overlapping_match // Copy non-overlapping match - ADD R12, R11, R11 - MOVD R12, R1 - SUBS $0x10, R1, R1 + ADD R0, R11, R11 + MOVD R0, R12 + SUBS $0x10, R12, R12 BLO copy_2_small copy_2_loop: - VLD1 (R0), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R0, R0 - ADD $0x10, R9, R9 - SUBS $0x10, R1, R1 - BHS copy_2_loop - ADD R1, R0, R0 - ADD $16, R0, R0 - ADD R1, R9, R9 - ADD $16, R9, R9 - ADD $-16, R0, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_2_end + FMOVQ (R1), F0 + FMOVQ F0, (R9) + ADD $0x10, R1, R1 + ADD $0x10, R9, R9 + SUBS $0x10, R12, R12 + BHS copy_2_loop + ADD R12, R1, R1 + ADD $16, R1, R1 + ADD R12, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R1), F0 + FMOVQ F0, -16(R9) + JMP copy_2_end copy_2_small: - CMP $0x03, R12 + CMP $0x03, R0 BEQ copy_2_move_3 BLO copy_2_move_1or2 - CMP $0x08, R12 + CMP $0x08, R0 BLO copy_2_move_4through7 JMP copy_2_move_8through16 copy_2_move_1or2: - MOVB (R0), R1 - ADD R12, R0, R15 - MOVB -1(R15), R13 - MOVB R1, (R9) - ADD R12, R9, R15 - MOVB R13, -1(R15) - ADD R12, R0, R0 - ADD R12, R9, R9 - JMP copy_2_end + MOVBU (R1), R16 + BFI $0, R16, $8, R12 + ADD R0, R1, R15 + MOVBU -1(R15), R16 + BFI $0, R16, $8, R13 + MOVB R12, (R9) + ADD R0, R9, R15 + MOVB R13, -1(R15) + ADD R0, R1, R1 + ADD R0, R9, R9 + JMP copy_2_end copy_2_move_3: - MOVH (R0), R1 - MOVB 2(R0), R13 - MOVH R1, (R9) - MOVB R13, 2(R9) - ADD R12, R0, R0 - ADD R12, R9, R9 - JMP copy_2_end + MOVHU (R1), R12 + MOVBU 2(R1), R16 + BFI $0, R16, $8, R13 + MOVH R12, (R9) + MOVB R13, 2(R9) + ADD R0, R1, R1 + ADD R0, R9, R9 + JMP copy_2_end copy_2_move_4through7: - MOVWU (R0), R1 - ADD R12, R0, R15 + MOVWU (R1), R12 + ADD R0, R1, R15 MOVWU -4(R15), R13 - MOVW R1, (R9) - ADD R12, R9, R15 + MOVW R12, (R9) + ADD R0, R9, R15 MOVW R13, -4(R15) - ADD R12, R0, R0 - ADD R12, R9, R9 + ADD R0, R1, R1 + ADD R0, R9, R9 JMP copy_2_end copy_2_move_8through16: - MOVD (R0), R1 - ADD R12, R0, R15 + MOVD (R1), R12 + ADD R0, R1, R15 MOVD -8(R15), R13 - MOVD R1, (R9) - ADD R12, R9, R15 + MOVD R12, (R9) + ADD R0, R9, R15 MOVD R13, -8(R15) - ADD R12, R0, R0 - ADD R12, R9, R9 + ADD R0, R1, R1 + ADD R0, R9, R9 copy_2_end: JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADD R12, R11, R11 + ADD R0, R11, R11 copy_slow_3: - MOVB (R0), R1 - MOVB R1, (R9) - ADD $1, R0, R0 - ADD $1, R9, R9 - SUBS $1, R12, R12 - BNE copy_slow_3 + MOVBU (R1), R12 + MOVB R12, (R9) + ADD $1, R1, R1 + ADD $1, R9, R9 + SUBS $1, R0, R0 + BNE copy_slow_3 handle_loop: - MOVD ctx+16(FP), R0 - MOVD 96(R0), R16 + MOVD 40(RSP), R16 SUBS $1, R16, R16 - MOVD R16, 96(R0) + MOVD R16, 40(RSP) BPL sequenceDecs_decodeSync_safe_amd64_main_loop loop_finished: @@ -2635,6 +2507,16 @@ loop_finished: MOVB R3, 40(R0) MOVD R5, 32(R0) + // s.seqSize += outPosition - ctx.outPosition + MOVD ctx+16(FP), R0 + MOVD s+0(FP), R1 + MOVD R11, R2 + MOVD 136(R0), R16 + SUB R16, R2, R2 + MOVD 256(R1), R16 + ADD R2, R16, R16 + MOVD R16, 256(R1) + // Update the context MOVD ctx+16(FP), R0 MOVD R11, 136(R0) @@ -2649,7 +2531,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: - MOVD 16(RSP), R0 + MOVD 56(RSP), R0 MOVD ctx+16(FP), R1 MOVD R0, 216(R1) MOVD $0x00000001, R16 @@ -2659,7 +2541,7 @@ sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: MOVD ctx+16(FP), R0 - MOVD 16(RSP), R1 + MOVD 56(RSP), R1 MOVD R1, 216(R0) MOVD $0x00000002, R16 MOVD R16, ret+24(FP) @@ -2668,7 +2550,7 @@ sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVD ctx+16(FP), R0 - MOVD 8(RSP), R1 + MOVD 48(RSP), R1 MOVD R1, 224(R0) MOVD R11, 136(R0) MOVD $0x00000003, R16 @@ -2678,7 +2560,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVD ctx+16(FP), R0 - MOVD 24(RSP), R1 + MOVD 64(RSP), R1 MOVD R1, 208(R0) MOVD $0x00000004, R16 MOVD R16, ret+24(FP) @@ -2693,9 +2575,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVD ctx+16(FP), R0 - MOVD 24(RSP), R1 + MOVD 64(RSP), R1 MOVD R1, 208(R0) - MOVD 16(RSP), R1 + MOVD 56(RSP), R1 MOVD R1, 216(R0) MOVD R11, 136(R0) MOVD $0x00000005, R16 diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_asm.go b/vendor/github.com/klauspost/compress/zstd/seqdec_asm.go index 55405f3914..94559c459a 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_asm.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_asm.go @@ -77,6 +77,36 @@ const errorNotEnoughSpace = 5 // error reported when bits are overread. const errorOverread = 6 +// useSafeDecodeSync reports whether decodeSyncSimple must use the bounds-exact +// ("safe") copy variants for the current buffer geometry. +// +// When the output and literal buffers have compressedBlockOverAlloc (16) +// bytes of slack past their logical use, the assembly may use extended +// memory copies that read and write in 16-byte blocks, overrunning the end +// of a literal run or match by up to 15 bytes; an empty literal run still +// copies one block, reading and writing the full 16 bytes of slack past +// its position. Otherwise it must use the bounds-exact ("safe") copies. +// This mirrors the analogous, always-dynamic selection in executeSimple below. +// +// The unsafe copies were disabled in #644 (2022) as a mitigation for a +// crash, but that crash's root cause — an unguarded bitReader overread that +// produced out-of-range match offsets/lengths — was fixed three days later +// in #645, which also added the fuzz corpus that has guarded this path since. +// See #1168. An asan-instrumented fuzz job (see .github/workflows/go.yml) +// covers the extended-copy path, which -race and plain fuzzing cannot. +func (s *sequenceDecs) useSafeDecodeSync() bool { + if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSizeAlloc { + return true + } + if s.maxSyncLen > 0 && cap(s.out)-len(s.out)-compressedBlockOverAlloc < int(s.maxSyncLen) { + return true + } + if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc { + return true + } + return false +} + // decode sequences from the stream with the provided history but without a dictionary. func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { if len(s.dict) > 0 { @@ -86,9 +116,7 @@ func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { return false, nil } - // FIXME: Using unsafe memory copies leads to rare, random crashes - // with fuzz testing. It is therefore disabled for now. - const useSafe = true + useSafe := s.useSafeDecodeSync() br := s.br diff --git a/vendor/github.com/moby/moby/api/pkg/authconfig/authconfig.go b/vendor/github.com/moby/moby/api/pkg/authconfig/authconfig.go index d1b0105a68..9e9686878c 100644 --- a/vendor/github.com/moby/moby/api/pkg/authconfig/authconfig.go +++ b/vendor/github.com/moby/moby/api/pkg/authconfig/authconfig.go @@ -21,7 +21,7 @@ func Encode(authConfig registry.AuthConfig) (string, error) { // // FIXME(thaJeztah): find exactly what code-paths are impacted by this. // if authConfig == (AuthConfig{}) { return "", nil } - buf, err := json.Marshal(authConfig) + buf, err := json.Marshal(authConfig) // #nosec G117 -- intentionally marshaling auth. if err != nil { return "", errInvalidParameter{err} } diff --git a/vendor/github.com/moby/moby/api/types/build/disk_usage.go b/vendor/github.com/moby/moby/api/types/build/disk_usage.go index 3613797dba..bf178f81e6 100644 --- a/vendor/github.com/moby/moby/api/types/build/disk_usage.go +++ b/vendor/github.com/moby/moby/api/types/build/disk_usage.go @@ -2,9 +2,6 @@ package build -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // DiskUsage represents system data usage for build cache resources. // // swagger:model DiskUsage diff --git a/vendor/github.com/moby/moby/api/types/common/error_response.go b/vendor/github.com/moby/moby/api/types/common/error_response.go index b49d3eea0a..9c7f2fdc2d 100644 --- a/vendor/github.com/moby/moby/api/types/common/error_response.go +++ b/vendor/github.com/moby/moby/api/types/common/error_response.go @@ -2,9 +2,6 @@ package common -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // ErrorResponse Represents an error. // Example: {"message":"Something went wrong."} // diff --git a/vendor/github.com/moby/moby/api/types/common/id_response.go b/vendor/github.com/moby/moby/api/types/common/id_response.go index 7dfe4bf12b..546f5e8d1f 100644 --- a/vendor/github.com/moby/moby/api/types/common/id_response.go +++ b/vendor/github.com/moby/moby/api/types/common/id_response.go @@ -2,9 +2,6 @@ package common -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // IDResponse Response to an API call that returns just an Id // // swagger:model IDResponse diff --git a/vendor/github.com/moby/moby/api/types/container/change_type.go b/vendor/github.com/moby/moby/api/types/container/change_type.go index 52fc99235b..1f2ac105f7 100644 --- a/vendor/github.com/moby/moby/api/types/container/change_type.go +++ b/vendor/github.com/moby/moby/api/types/container/change_type.go @@ -2,9 +2,6 @@ package container -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // ChangeType Kind of change // // Can be one of: diff --git a/vendor/github.com/moby/moby/api/types/container/create_response.go b/vendor/github.com/moby/moby/api/types/container/create_response.go index 39d761aa96..9fc92fb6fe 100644 --- a/vendor/github.com/moby/moby/api/types/container/create_response.go +++ b/vendor/github.com/moby/moby/api/types/container/create_response.go @@ -2,9 +2,6 @@ package container -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // CreateResponse ContainerCreateResponse // // # OK response to ContainerCreate operation diff --git a/vendor/github.com/moby/moby/api/types/container/disk_usage.go b/vendor/github.com/moby/moby/api/types/container/disk_usage.go index c36721d3b0..0c0a772d62 100644 --- a/vendor/github.com/moby/moby/api/types/container/disk_usage.go +++ b/vendor/github.com/moby/moby/api/types/container/disk_usage.go @@ -2,9 +2,6 @@ package container -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // DiskUsage represents system data usage information for container resources. // // swagger:model DiskUsage diff --git a/vendor/github.com/moby/moby/api/types/container/filesystem_change.go b/vendor/github.com/moby/moby/api/types/container/filesystem_change.go index b9ec83e521..d895095259 100644 --- a/vendor/github.com/moby/moby/api/types/container/filesystem_change.go +++ b/vendor/github.com/moby/moby/api/types/container/filesystem_change.go @@ -2,9 +2,6 @@ package container -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // FilesystemChange Change in the container's filesystem. // // swagger:model FilesystemChange diff --git a/vendor/github.com/moby/moby/api/types/container/hostconfig.go b/vendor/github.com/moby/moby/api/types/container/hostconfig.go index 0f889c6512..297ebc35e5 100644 --- a/vendor/github.com/moby/moby/api/types/container/hostconfig.go +++ b/vendor/github.com/moby/moby/api/types/container/hostconfig.go @@ -454,6 +454,7 @@ type HostConfig struct { ShmSize int64 // Total shm memory usage Sysctls map[string]string `json:",omitempty"` // List of Namespaced sysctls used for the container Runtime string `json:",omitempty"` // Runtime to use with this container + Umask *uint32 `json:",omitempty"` // Initial process umask // Applicable to Windows Isolation Isolation // Isolation technology of the container (e.g. default, hyperv) diff --git a/vendor/github.com/moby/moby/api/types/container/port_summary.go b/vendor/github.com/moby/moby/api/types/container/port_summary.go index 68148eece4..0cb7455f36 100644 --- a/vendor/github.com/moby/moby/api/types/container/port_summary.go +++ b/vendor/github.com/moby/moby/api/types/container/port_summary.go @@ -2,9 +2,6 @@ package container -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - import ( "net/netip" ) diff --git a/vendor/github.com/moby/moby/api/types/container/top_response.go b/vendor/github.com/moby/moby/api/types/container/top_response.go index 966603617f..50124e8a76 100644 --- a/vendor/github.com/moby/moby/api/types/container/top_response.go +++ b/vendor/github.com/moby/moby/api/types/container/top_response.go @@ -2,9 +2,6 @@ package container -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // TopResponse ContainerTopResponse // // Container "top" response. diff --git a/vendor/github.com/moby/moby/api/types/container/update_response.go b/vendor/github.com/moby/moby/api/types/container/update_response.go index 2f7263b141..94e5eccb20 100644 --- a/vendor/github.com/moby/moby/api/types/container/update_response.go +++ b/vendor/github.com/moby/moby/api/types/container/update_response.go @@ -2,9 +2,6 @@ package container -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // UpdateResponse ContainerUpdateResponse // // Response for a successful container-update. diff --git a/vendor/github.com/moby/moby/api/types/container/wait_exit_error.go b/vendor/github.com/moby/moby/api/types/container/wait_exit_error.go index 96a7770c34..50f353f95e 100644 --- a/vendor/github.com/moby/moby/api/types/container/wait_exit_error.go +++ b/vendor/github.com/moby/moby/api/types/container/wait_exit_error.go @@ -2,9 +2,6 @@ package container -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // WaitExitError container waiting error, if any // // swagger:model WaitExitError diff --git a/vendor/github.com/moby/moby/api/types/container/wait_response.go b/vendor/github.com/moby/moby/api/types/container/wait_response.go index 68d3c38724..ff9281dd91 100644 --- a/vendor/github.com/moby/moby/api/types/container/wait_response.go +++ b/vendor/github.com/moby/moby/api/types/container/wait_response.go @@ -2,9 +2,6 @@ package container -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // WaitResponse ContainerWaitResponse // // # OK response to ContainerWait operation diff --git a/vendor/github.com/moby/moby/api/types/image/delete_response.go b/vendor/github.com/moby/moby/api/types/image/delete_response.go index b19119a381..c0a0a5af3d 100644 --- a/vendor/github.com/moby/moby/api/types/image/delete_response.go +++ b/vendor/github.com/moby/moby/api/types/image/delete_response.go @@ -2,9 +2,6 @@ package image -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // DeleteResponse delete response // // swagger:model DeleteResponse diff --git a/vendor/github.com/moby/moby/api/types/image/disk_usage.go b/vendor/github.com/moby/moby/api/types/image/disk_usage.go index 7297813c1d..bbe2d57672 100644 --- a/vendor/github.com/moby/moby/api/types/image/disk_usage.go +++ b/vendor/github.com/moby/moby/api/types/image/disk_usage.go @@ -2,9 +2,6 @@ package image -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // DiskUsage represents system data usage for image resources. // // swagger:model DiskUsage diff --git a/vendor/github.com/moby/moby/api/types/image/history_response_item.go b/vendor/github.com/moby/moby/api/types/image/history_response_item.go index 3de3181ab9..c7b1eddcd9 100644 --- a/vendor/github.com/moby/moby/api/types/image/history_response_item.go +++ b/vendor/github.com/moby/moby/api/types/image/history_response_item.go @@ -2,9 +2,6 @@ package image -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // HistoryResponseItem HistoryResponseItem // // individual image layer information in response to ImageHistory operation diff --git a/vendor/github.com/moby/moby/api/types/image/image_inspect.go b/vendor/github.com/moby/moby/api/types/image/image_inspect.go index df09c9511b..90ebfd894c 100644 --- a/vendor/github.com/moby/moby/api/types/image/image_inspect.go +++ b/vendor/github.com/moby/moby/api/types/image/image_inspect.go @@ -72,7 +72,11 @@ type InspectResponse struct { // run on (especially for Windows). OsVersion string `json:",omitempty"` - // Size is the total size of the image including all layers it is composed of. + // Size is the total size of the selected image variant, including all layers + // it is composed of. + // + // When using the containerd image store, this includes both the image content + // that's present locally and the unpacked snapshot data. Size int64 // GraphDriver holds information about the storage driver used to store the diff --git a/vendor/github.com/moby/moby/api/types/network/config_reference.go b/vendor/github.com/moby/moby/api/types/network/config_reference.go index 1158afe655..0c940a9e74 100644 --- a/vendor/github.com/moby/moby/api/types/network/config_reference.go +++ b/vendor/github.com/moby/moby/api/types/network/config_reference.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // ConfigReference The config-only network source to provide the configuration for // this network. // diff --git a/vendor/github.com/moby/moby/api/types/network/connect_request.go b/vendor/github.com/moby/moby/api/types/network/connect_request.go index 2ff14d3603..68fbf16844 100644 --- a/vendor/github.com/moby/moby/api/types/network/connect_request.go +++ b/vendor/github.com/moby/moby/api/types/network/connect_request.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // ConnectRequest NetworkConnectRequest represents the data to be used to connect a container to a network. // // swagger:model ConnectRequest diff --git a/vendor/github.com/moby/moby/api/types/network/create_response.go b/vendor/github.com/moby/moby/api/types/network/create_response.go index 1997059912..429b278e48 100644 --- a/vendor/github.com/moby/moby/api/types/network/create_response.go +++ b/vendor/github.com/moby/moby/api/types/network/create_response.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // CreateResponse NetworkCreateResponse // // # OK response to NetworkCreate operation diff --git a/vendor/github.com/moby/moby/api/types/network/disconnect_request.go b/vendor/github.com/moby/moby/api/types/network/disconnect_request.go index 7b1f521e77..aeebee70a9 100644 --- a/vendor/github.com/moby/moby/api/types/network/disconnect_request.go +++ b/vendor/github.com/moby/moby/api/types/network/disconnect_request.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // DisconnectRequest NetworkDisconnectRequest represents the data to be used to disconnect a container from a network. // // swagger:model DisconnectRequest diff --git a/vendor/github.com/moby/moby/api/types/network/endpoint_resource.go b/vendor/github.com/moby/moby/api/types/network/endpoint_resource.go index bf493ad5dd..a9ab27ae3c 100644 --- a/vendor/github.com/moby/moby/api/types/network/endpoint_resource.go +++ b/vendor/github.com/moby/moby/api/types/network/endpoint_resource.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - import ( "net/netip" ) diff --git a/vendor/github.com/moby/moby/api/types/network/inspect.go b/vendor/github.com/moby/moby/api/types/network/inspect.go index cded5e6081..c07026ac40 100644 --- a/vendor/github.com/moby/moby/api/types/network/inspect.go +++ b/vendor/github.com/moby/moby/api/types/network/inspect.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // Inspect The body of the "get network" http response message. // // swagger:model Inspect diff --git a/vendor/github.com/moby/moby/api/types/network/ipam_status.go b/vendor/github.com/moby/moby/api/types/network/ipam_status.go index 7eb4e8487e..50e410ff8f 100644 --- a/vendor/github.com/moby/moby/api/types/network/ipam_status.go +++ b/vendor/github.com/moby/moby/api/types/network/ipam_status.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // IPAMStatus IPAM status // // swagger:model IPAMStatus diff --git a/vendor/github.com/moby/moby/api/types/network/network.go b/vendor/github.com/moby/moby/api/types/network/network.go index a7d9c0f6ad..b2d4d43cd2 100644 --- a/vendor/github.com/moby/moby/api/types/network/network.go +++ b/vendor/github.com/moby/moby/api/types/network/network.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - import ( timeext "time" ) diff --git a/vendor/github.com/moby/moby/api/types/network/peer_info.go b/vendor/github.com/moby/moby/api/types/network/peer_info.go index dc88ec16fa..8638e61623 100644 --- a/vendor/github.com/moby/moby/api/types/network/peer_info.go +++ b/vendor/github.com/moby/moby/api/types/network/peer_info.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - import ( "net/netip" ) diff --git a/vendor/github.com/moby/moby/api/types/network/service_info.go b/vendor/github.com/moby/moby/api/types/network/service_info.go index fdd92f1611..abb3619533 100644 --- a/vendor/github.com/moby/moby/api/types/network/service_info.go +++ b/vendor/github.com/moby/moby/api/types/network/service_info.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - import ( "net/netip" ) diff --git a/vendor/github.com/moby/moby/api/types/network/status.go b/vendor/github.com/moby/moby/api/types/network/status.go index 94f4b4b2ec..b90f1bf1e8 100644 --- a/vendor/github.com/moby/moby/api/types/network/status.go +++ b/vendor/github.com/moby/moby/api/types/network/status.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // Status provides runtime information about the network such as the number of allocated IPs. // // swagger:model Status diff --git a/vendor/github.com/moby/moby/api/types/network/subnet_status.go b/vendor/github.com/moby/moby/api/types/network/subnet_status.go index dd62429f5f..de74c7a2e6 100644 --- a/vendor/github.com/moby/moby/api/types/network/subnet_status.go +++ b/vendor/github.com/moby/moby/api/types/network/subnet_status.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // SubnetStatus subnet status // // swagger:model SubnetStatus diff --git a/vendor/github.com/moby/moby/api/types/network/summary.go b/vendor/github.com/moby/moby/api/types/network/summary.go index 3f50ce2278..50c346ffa5 100644 --- a/vendor/github.com/moby/moby/api/types/network/summary.go +++ b/vendor/github.com/moby/moby/api/types/network/summary.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // Summary Network list response item // // swagger:model Summary diff --git a/vendor/github.com/moby/moby/api/types/network/task.go b/vendor/github.com/moby/moby/api/types/network/task.go index a547523a44..c0eac2322e 100644 --- a/vendor/github.com/moby/moby/api/types/network/task.go +++ b/vendor/github.com/moby/moby/api/types/network/task.go @@ -2,9 +2,6 @@ package network -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - import ( "net/netip" ) diff --git a/vendor/github.com/moby/moby/api/types/plugin/device.go b/vendor/github.com/moby/moby/api/types/plugin/device.go index ae96177047..2044e4b99a 100644 --- a/vendor/github.com/moby/moby/api/types/plugin/device.go +++ b/vendor/github.com/moby/moby/api/types/plugin/device.go @@ -2,9 +2,6 @@ package plugin -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // Device device // // swagger:model Device diff --git a/vendor/github.com/moby/moby/api/types/plugin/env.go b/vendor/github.com/moby/moby/api/types/plugin/env.go index dcbe0b762d..99ee46dabf 100644 --- a/vendor/github.com/moby/moby/api/types/plugin/env.go +++ b/vendor/github.com/moby/moby/api/types/plugin/env.go @@ -2,9 +2,6 @@ package plugin -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // Env env // // swagger:model Env diff --git a/vendor/github.com/moby/moby/api/types/plugin/mount.go b/vendor/github.com/moby/moby/api/types/plugin/mount.go index 7970306cc8..9426a94c57 100644 --- a/vendor/github.com/moby/moby/api/types/plugin/mount.go +++ b/vendor/github.com/moby/moby/api/types/plugin/mount.go @@ -2,9 +2,6 @@ package plugin -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // Mount mount // // swagger:model Mount diff --git a/vendor/github.com/moby/moby/api/types/plugin/plugin.go b/vendor/github.com/moby/moby/api/types/plugin/plugin.go index 3305170d5e..2dcf83be25 100644 --- a/vendor/github.com/moby/moby/api/types/plugin/plugin.go +++ b/vendor/github.com/moby/moby/api/types/plugin/plugin.go @@ -2,9 +2,6 @@ package plugin -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // Plugin A plugin for the Engine API // // swagger:model Plugin diff --git a/vendor/github.com/moby/moby/api/types/plugin/plugin_responses.go b/vendor/github.com/moby/moby/api/types/plugin/plugin_responses.go index 91b327eb47..f4b224307c 100644 --- a/vendor/github.com/moby/moby/api/types/plugin/plugin_responses.go +++ b/vendor/github.com/moby/moby/api/types/plugin/plugin_responses.go @@ -1,9 +1,5 @@ package plugin -import ( - "sort" -) - // ListResponse contains the response for the Engine API type ListResponse []Plugin @@ -15,19 +11,26 @@ type Privilege struct { Value []string } -// Privileges is a list of Privilege +// Privileges is a list of Privilege. type Privileges []Privilege +// Len implements [sort.Interface]. +// +// Deprecated: use [slices.SortFunc] to sort privileges instead. func (s Privileges) Len() int { return len(s) } +// Less implements [sort.Interface]. +// +// Deprecated: use [slices.SortFunc] to sort privileges instead. func (s Privileges) Less(i, j int) bool { return s[i].Name < s[j].Name } +// Swap implements [sort.Interface]. +// +// Deprecated: use [slices.SortFunc] to sort privileges instead. func (s Privileges) Swap(i, j int) { - sort.Strings(s[i].Value) - sort.Strings(s[j].Value) s[i], s[j] = s[j], s[i] } diff --git a/vendor/github.com/moby/moby/api/types/registry/auth_response.go b/vendor/github.com/moby/moby/api/types/registry/auth_response.go index 94c2e1bb36..c7057d8606 100644 --- a/vendor/github.com/moby/moby/api/types/registry/auth_response.go +++ b/vendor/github.com/moby/moby/api/types/registry/auth_response.go @@ -2,9 +2,6 @@ package registry -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // AuthResponse An identity token was generated successfully. // // swagger:model AuthResponse diff --git a/vendor/github.com/moby/moby/api/types/storage/driver_data.go b/vendor/github.com/moby/moby/api/types/storage/driver_data.go index 65d5b4c20e..5e6cb22ab5 100644 --- a/vendor/github.com/moby/moby/api/types/storage/driver_data.go +++ b/vendor/github.com/moby/moby/api/types/storage/driver_data.go @@ -2,9 +2,6 @@ package storage -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // DriverData Information about the storage driver used to store the container's and // image's filesystem. // diff --git a/vendor/github.com/moby/moby/api/types/storage/root_f_s_storage.go b/vendor/github.com/moby/moby/api/types/storage/root_f_s_storage.go index d82f2b6bcb..ecf63ea0cc 100644 --- a/vendor/github.com/moby/moby/api/types/storage/root_f_s_storage.go +++ b/vendor/github.com/moby/moby/api/types/storage/root_f_s_storage.go @@ -2,9 +2,6 @@ package storage -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // RootFSStorage Information about the storage used for the container's root filesystem. // // swagger:model RootFSStorage diff --git a/vendor/github.com/moby/moby/api/types/storage/root_f_s_storage_snapshot.go b/vendor/github.com/moby/moby/api/types/storage/root_f_s_storage_snapshot.go index dd2b82d245..c040636da8 100644 --- a/vendor/github.com/moby/moby/api/types/storage/root_f_s_storage_snapshot.go +++ b/vendor/github.com/moby/moby/api/types/storage/root_f_s_storage_snapshot.go @@ -2,9 +2,6 @@ package storage -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // RootFSStorageSnapshot Information about a snapshot backend of the container's root filesystem. // // swagger:model RootFSStorageSnapshot diff --git a/vendor/github.com/moby/moby/api/types/storage/storage.go b/vendor/github.com/moby/moby/api/types/storage/storage.go index 77843db970..4cf31c54b5 100644 --- a/vendor/github.com/moby/moby/api/types/storage/storage.go +++ b/vendor/github.com/moby/moby/api/types/storage/storage.go @@ -2,9 +2,6 @@ package storage -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // Storage Information about the storage used by the container. // // swagger:model Storage diff --git a/vendor/github.com/moby/moby/api/types/swarm/service_create_response.go b/vendor/github.com/moby/moby/api/types/swarm/service_create_response.go index ebbc097d90..2dcc49c903 100644 --- a/vendor/github.com/moby/moby/api/types/swarm/service_create_response.go +++ b/vendor/github.com/moby/moby/api/types/swarm/service_create_response.go @@ -2,9 +2,6 @@ package swarm -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // ServiceCreateResponse contains the information returned to a client on the // creation of a new service. // diff --git a/vendor/github.com/moby/moby/api/types/swarm/service_update_response.go b/vendor/github.com/moby/moby/api/types/swarm/service_update_response.go index b7649096a0..be5d44c4cf 100644 --- a/vendor/github.com/moby/moby/api/types/swarm/service_update_response.go +++ b/vendor/github.com/moby/moby/api/types/swarm/service_update_response.go @@ -2,9 +2,6 @@ package swarm -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // ServiceUpdateResponse service update response // Example: {"Warnings":["unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found"]} // diff --git a/vendor/github.com/moby/moby/api/types/volume/create_request.go b/vendor/github.com/moby/moby/api/types/volume/create_request.go index 3217df8270..17c5f86784 100644 --- a/vendor/github.com/moby/moby/api/types/volume/create_request.go +++ b/vendor/github.com/moby/moby/api/types/volume/create_request.go @@ -2,9 +2,6 @@ package volume -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // CreateRequest VolumeConfig // // # Volume configuration diff --git a/vendor/github.com/moby/moby/api/types/volume/disk_usage.go b/vendor/github.com/moby/moby/api/types/volume/disk_usage.go index e2afbac659..cbf740e33c 100644 --- a/vendor/github.com/moby/moby/api/types/volume/disk_usage.go +++ b/vendor/github.com/moby/moby/api/types/volume/disk_usage.go @@ -2,9 +2,6 @@ package volume -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // DiskUsage represents system data usage for volume resources. // // swagger:model DiskUsage diff --git a/vendor/github.com/moby/moby/api/types/volume/list_response.go b/vendor/github.com/moby/moby/api/types/volume/list_response.go index f257762f09..02dc415a5f 100644 --- a/vendor/github.com/moby/moby/api/types/volume/list_response.go +++ b/vendor/github.com/moby/moby/api/types/volume/list_response.go @@ -2,9 +2,6 @@ package volume -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // ListResponse VolumeListResponse // // # Volume list response diff --git a/vendor/github.com/moby/moby/api/types/volume/volume.go b/vendor/github.com/moby/moby/api/types/volume/volume.go index 524ebfb8ac..a3d6d82864 100644 --- a/vendor/github.com/moby/moby/api/types/volume/volume.go +++ b/vendor/github.com/moby/moby/api/types/volume/volume.go @@ -2,9 +2,6 @@ package volume -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - // Volume volume // // swagger:model Volume diff --git a/vendor/github.com/moby/moby/client/checkpoint_create.go b/vendor/github.com/moby/moby/client/checkpoint_create.go index b3ba5459d0..46867643f2 100644 --- a/vendor/github.com/moby/moby/client/checkpoint_create.go +++ b/vendor/github.com/moby/moby/client/checkpoint_create.go @@ -24,13 +24,11 @@ func (cli *Client) CheckpointCreate(ctx context.Context, containerID string, opt if err != nil { return CheckpointCreateResult{}, err } - requestBody := checkpoint.CreateRequest{ + resp, err := cli.post(ctx, "/containers/"+containerID+"/checkpoints", nil, nil, checkpoint.CreateRequest{ CheckpointID: options.CheckpointID, CheckpointDir: options.CheckpointDir, Exit: options.Exit, - } - - resp, err := cli.post(ctx, "/containers/"+containerID+"/checkpoints", nil, requestBody, nil) + }) defer ensureReaderClosed(resp) return CheckpointCreateResult{}, err } diff --git a/vendor/github.com/moby/moby/client/client.go b/vendor/github.com/moby/moby/client/client.go index 4b4ef976a3..f407505e01 100644 --- a/vendor/github.com/moby/moby/client/client.go +++ b/vendor/github.com/moby/moby/client/client.go @@ -60,7 +60,6 @@ import ( "net/url" "path" "runtime" - "slices" "strings" "sync" "sync/atomic" @@ -109,7 +108,7 @@ const DummyHost = "api.moby.localhost" // overriding the version and disable API-version negotiation. // // This version may be lower than the version of the api library module used. -const MaxAPIVersion = "1.55" +const MaxAPIVersion = "1.56" // MinAPIVersion is the minimum API version supported by the client. API versions // below this version are not considered when performing API-version negotiation. @@ -250,10 +249,11 @@ func New(ops ...Opt) (*Client, error) { c.client.Transport = otelhttp.NewTransport(c.client.Transport, c.traceOpts...) - if len(cfg.responseHooks) > 0 { - c.client.Transport = &responseHookTransport{ - base: c.client.Transport, - hooks: slices.Clone(cfg.responseHooks), + if len(cfg.requestHooks) > 0 || len(cfg.responseHooks) > 0 { + c.client.Transport = &hookTransport{ + base: c.client.Transport, + reqHooks: cfg.requestHooks, + respHooks: cfg.responseHooks, } } diff --git a/vendor/github.com/moby/moby/client/client_hook.go b/vendor/github.com/moby/moby/client/client_hook.go new file mode 100644 index 0000000000..c9afa34ddd --- /dev/null +++ b/vendor/github.com/moby/moby/client/client_hook.go @@ -0,0 +1,70 @@ +package client + +import ( + "errors" + "io" + "net/http" +) + +type hookTransport struct { + base http.RoundTripper + reqHooks []RequestHook + respHooks []ResponseHook +} + +func (t *hookTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if len(t.reqHooks) > 0 { + hookReq := req.Clone(req.Context()) + + if hookReq.Body != nil { + hookReq.Body = hookBody{} + } + if hookReq.GetBody != nil { + hookReq.GetBody = func() (io.ReadCloser, error) { + return hookBody{}, nil + } + } + + for _, h := range t.reqHooks { + if err := h(hookReq); err != nil { + // The base transport never takes ownership, so close the original + // request body before returning the hook error. + if req.Body != nil { + _ = req.Body.Close() + } + return nil, err + } + } + // Restore the actual request body after the hooks have run. The + // modified request metadata is preserved on hookReq. + hookReq.Body = req.Body + hookReq.GetBody = req.GetBody + req = hookReq + } + + resp, err := t.base.RoundTrip(req) + if err != nil { + return resp, err + } + + if len(t.respHooks) > 0 { + hookResp := *resp + if hookResp.Body != nil { + hookResp.Body = hookBody{} + } + + for _, h := range t.respHooks { + h(&hookResp) + } + } + + return resp, nil +} + +type hookBody struct{} + +func (hookBody) Read([]byte) (int, error) { + return 0, errors.New("hooks must not read HTTP message body") +} + +func (hookBody) Close() error { return nil } diff --git a/vendor/github.com/moby/moby/client/client_options.go b/vendor/github.com/moby/moby/client/client_options.go index 3992557230..3499172c4d 100644 --- a/vendor/github.com/moby/moby/client/client_options.go +++ b/vendor/github.com/moby/moby/client/client_options.go @@ -58,13 +58,23 @@ type clientConfig struct { // takes precedence. Either field disables API-version negotiation. envAPIVersion string - // responseHooks is a list of custom response hooks to call on responses. + // requestHooks contains hooks to call before requests are made. + requestHooks []RequestHook + // responseHooks contains hooks to call on responses. responseHooks []ResponseHook // traceOpts is a list of options to configure the tracing span. traceOpts []otelhttp.Option } +// RequestHook is called for each HTTP request made by the client. +// Hooks are invoked in the order they were added. +// +// Hooks may inspect the request and modify request metadata, such as headers, +// before the request is sent. The request body cannot be read or closed by +// the hook. +type RequestHook func(*http.Request) error + // ResponseHook is called for each HTTP response returned by the daemon. // Hooks are invoked in the order they were added. // @@ -411,12 +421,25 @@ func WithTraceOptions(opts ...otelhttp.Option) Opt { } } -// WithResponseHook adds a ResponseHook to the client. ResponseHooks are called +// WithHTTPRequestHook adds a [RequestHook] to the client. RequestHooks are called +// before an HTTP request is made to the daemon. Hooks are invoked in the order +// they were added. +func WithHTTPRequestHook(h RequestHook) Opt { + return func(c *clientConfig) error { + if h == nil { + return errors.New("invalid request hook: hook is nil") + } + c.requestHooks = append(c.requestHooks, h) + return nil + } +} + +// WithHTTPResponseHook adds a [ResponseHook] to the client. ResponseHooks are called // for each HTTP response returned by the daemon. Hooks are invoked in the order // they were added. // // Hooks must not read or close resp.Body. -func WithResponseHook(h ResponseHook) Opt { +func WithHTTPResponseHook(h ResponseHook) Opt { return func(c *clientConfig) error { if h == nil { return errors.New("invalid response hook: hook is nil") @@ -425,3 +448,12 @@ func WithResponseHook(h ResponseHook) Opt { return nil } } + +// WithResponseHook is equivalent to [WithHTTPResponseHook]. +// +// Deprecated: use [WithHTTPResponseHook] instead. +// +//go:fix inline +func WithResponseHook(h ResponseHook) Opt { + return WithHTTPResponseHook(h) +} diff --git a/vendor/github.com/moby/moby/client/client_responsehook.go b/vendor/github.com/moby/moby/client/client_responsehook.go deleted file mode 100644 index 7c93f111c7..0000000000 --- a/vendor/github.com/moby/moby/client/client_responsehook.go +++ /dev/null @@ -1,23 +0,0 @@ -package client - -import ( - "net/http" -) - -type responseHookTransport struct { - base http.RoundTripper - hooks []ResponseHook -} - -func (t *responseHookTransport) RoundTrip(req *http.Request) (*http.Response, error) { - resp, err := t.base.RoundTrip(req) - if err != nil { - return resp, err - } - - for _, h := range t.hooks { - h(resp) - } - - return resp, nil -} diff --git a/vendor/github.com/moby/moby/client/config_create.go b/vendor/github.com/moby/moby/client/config_create.go index 874e2c947c..3c37ea9e50 100644 --- a/vendor/github.com/moby/moby/client/config_create.go +++ b/vendor/github.com/moby/moby/client/config_create.go @@ -19,7 +19,7 @@ type ConfigCreateResult struct { // ConfigCreate creates a new config. func (cli *Client) ConfigCreate(ctx context.Context, options ConfigCreateOptions) (ConfigCreateResult, error) { - resp, err := cli.post(ctx, "/configs/create", nil, options.Spec, nil) + resp, err := cli.post(ctx, "/configs/create", nil, nil, options.Spec) defer ensureReaderClosed(resp) if err != nil { return ConfigCreateResult{}, err diff --git a/vendor/github.com/moby/moby/client/config_update.go b/vendor/github.com/moby/moby/client/config_update.go index 31bdd79569..bfbac46dec 100644 --- a/vendor/github.com/moby/moby/client/config_update.go +++ b/vendor/github.com/moby/moby/client/config_update.go @@ -24,7 +24,7 @@ func (cli *Client) ConfigUpdate(ctx context.Context, id string, options ConfigUp } query := url.Values{} query.Set("version", options.Version.String()) - resp, err := cli.post(ctx, "/configs/"+id+"/update", query, options.Spec, nil) + resp, err := cli.post(ctx, "/configs/"+id+"/update", query, nil, options.Spec) defer ensureReaderClosed(resp) if err != nil { return ConfigUpdateResult{}, err diff --git a/vendor/github.com/moby/moby/client/container_attach.go b/vendor/github.com/moby/moby/client/container_attach.go index ce84122d32..9619e812b2 100644 --- a/vendor/github.com/moby/moby/client/container_attach.go +++ b/vendor/github.com/moby/moby/client/container_attach.go @@ -75,9 +75,8 @@ func (cli *Client) ContainerAttach(ctx context.Context, containerID string, opti query.Set("logs", "1") } - hijacked, err := cli.postHijacked(ctx, "/containers/"+containerID+"/attach", query, nil, http.Header{ - "Content-Type": {"text/plain"}, - }) + headers := http.Header{"Content-Type": {"text/plain"}} + hijacked, err := cli.postHijacked(ctx, "/containers/"+containerID+"/attach", query, headers, nil) if err != nil { return ContainerAttachResult{}, err } diff --git a/vendor/github.com/moby/moby/client/container_commit.go b/vendor/github.com/moby/moby/client/container_commit.go index f73cd22f51..47981bec72 100644 --- a/vendor/github.com/moby/moby/client/container_commit.go +++ b/vendor/github.com/moby/moby/client/container_commit.go @@ -65,7 +65,7 @@ func (cli *Client) ContainerCommit(ctx context.Context, containerID string, opti } var response container.CommitResponse - resp, err := cli.post(ctx, "/commit", query, options.Config, nil) + resp, err := cli.post(ctx, "/commit", query, nil, options.Config) defer ensureReaderClosed(resp) if err != nil { return ContainerCommitResult{}, err diff --git a/vendor/github.com/moby/moby/client/container_copy.go b/vendor/github.com/moby/moby/client/container_copy.go index b37d1765f4..b91babd3bd 100644 --- a/vendor/github.com/moby/moby/client/container_copy.go +++ b/vendor/github.com/moby/moby/client/container_copy.go @@ -77,7 +77,7 @@ func (cli *Client) CopyToContainer(ctx context.Context, containerID string, opti query.Set("copyUIDGID", "true") } - response, err := cli.putRaw(ctx, "/containers/"+containerID+"/archive", query, options.Content, nil) + response, err := cli.putRaw(ctx, "/containers/"+containerID+"/archive", query, nil, options.Content) defer ensureReaderClosed(response) if err != nil { return CopyToContainerResult{}, err diff --git a/vendor/github.com/moby/moby/client/container_create.go b/vendor/github.com/moby/moby/client/container_create.go index d941a37207..7e6b15a96e 100644 --- a/vendor/github.com/moby/moby/client/container_create.go +++ b/vendor/github.com/moby/moby/client/container_create.go @@ -5,7 +5,7 @@ import ( "encoding/json" "net/url" "path" - "sort" + "slices" "strings" cerrdefs "github.com/containerd/errdefs" @@ -35,13 +35,6 @@ func (cli *Client) ContainerCreate(ctx context.Context, options ContainerCreateO return ContainerCreateResult{}, cerrdefs.ErrInvalidArgument.WithMessage("config.Image or Image is required") } - var response container.CreateResponse - - if options.HostConfig != nil { - options.HostConfig.CapAdd = normalizeCapabilities(options.HostConfig.CapAdd) - options.HostConfig.CapDrop = normalizeCapabilities(options.HostConfig.CapDrop) - } - query := url.Values{} if options.Platform != nil { if p := formatPlatform(*options.Platform); p != "unknown" { @@ -53,18 +46,17 @@ func (cli *Client) ContainerCreate(ctx context.Context, options ContainerCreateO query.Set("name", options.Name) } - body := container.CreateRequest{ + resp, err := cli.post(ctx, "/containers/create", query, nil, container.CreateRequest{ Config: cfg, - HostConfig: options.HostConfig, + HostConfig: normalizeHostConfig(options.HostConfig), NetworkingConfig: options.NetworkingConfig, - } - - resp, err := cli.post(ctx, "/containers/create", query, body, nil) + }) defer ensureReaderClosed(resp) if err != nil { return ContainerCreateResult{}, err } + var response container.CreateResponse err = json.NewDecoder(resp.Body).Decode(&response) return ContainerCreateResult{ID: response.ID, Warnings: response.Warnings}, err } @@ -86,6 +78,17 @@ func formatPlatform(platform ocispec.Platform) string { // allCapabilities is a magic value for "all capabilities" const allCapabilities = "ALL" +// normalizeCap normalizes a capability to its canonical format by upper-casing +// and adding a "CAP_" prefix (if not yet present). It also accepts the "ALL" +// magic-value. +func normalizeCap(c string) string { + c = strings.ToUpper(c) + if c != allCapabilities && !strings.HasPrefix(c, "CAP_") { + c = "CAP_" + c + } + return c +} + // normalizeCapabilities normalizes capabilities to their canonical form, // removes duplicates, and sorts the results. // @@ -94,32 +97,22 @@ const allCapabilities = "ALL" // // [caps.NormalizeLegacyCapabilities]: https://github.com/moby/moby/blob/v28.3.2/oci/caps/utils.go#L56 func normalizeCapabilities(caps []string) []string { - var normalized []string - - unique := make(map[string]struct{}) - for _, c := range caps { - c = normalizeCap(c) - if _, ok := unique[c]; ok { - continue - } - unique[c] = struct{}{} - normalized = append(normalized, c) + normalized := slices.Clone(caps) + for i, c := range normalized { + normalized[i] = normalizeCap(c) } - - sort.Strings(normalized) - return normalized + slices.Sort(normalized) + return slices.Compact(normalized) } -// normalizeCap normalizes a capability to its canonical format by upper-casing -// and adding a "CAP_" prefix (if not yet present). It also accepts the "ALL" -// magic-value. -func normalizeCap(capability string) string { - capability = strings.ToUpper(capability) - if capability == allCapabilities { - return capability +// normalizeHostConfig returns a shallow copy of hostConfig with capabilities normalized. +func normalizeHostConfig(hostConfig *container.HostConfig) *container.HostConfig { + if hostConfig == nil { + return nil } - if !strings.HasPrefix(capability, "CAP_") { - capability = "CAP_" + capability - } - return capability + + normalized := *hostConfig + normalized.CapAdd = normalizeCapabilities(hostConfig.CapAdd) + normalized.CapDrop = normalizeCapabilities(hostConfig.CapDrop) + return &normalized } diff --git a/vendor/github.com/moby/moby/client/container_exec.go b/vendor/github.com/moby/moby/client/container_exec.go index 30ed00ea52..d831521842 100644 --- a/vendor/github.com/moby/moby/client/container_exec.go +++ b/vendor/github.com/moby/moby/client/container_exec.go @@ -42,7 +42,7 @@ func (cli *Client) ExecCreate(ctx context.Context, containerID string, options E return ExecCreateResult{}, err } - req := container.ExecCreateRequest{ + resp, err := cli.post(ctx, "/containers/"+containerID+"/exec", nil, nil, container.ExecCreateRequest{ User: options.User, Privileged: options.Privileged, Tty: options.TTY, @@ -54,9 +54,7 @@ func (cli *Client) ExecCreate(ctx context.Context, containerID string, options E Env: options.Env, WorkingDir: options.WorkingDir, Cmd: options.Cmd, - } - - resp, err := cli.post(ctx, "/containers/"+containerID+"/exec", nil, req, nil) + }) defer ensureReaderClosed(resp) if err != nil { return ExecCreateResult{}, err @@ -91,12 +89,11 @@ func (cli *Client) ExecStart(ctx context.Context, execID string, options ExecSta return ExecStartResult{}, err } - req := container.ExecStartRequest{ + resp, err := cli.post(ctx, "/exec/"+execID+"/start", nil, nil, container.ExecStartRequest{ Detach: options.Detach, Tty: options.TTY, ConsoleSize: consoleSize, - } - resp, err := cli.post(ctx, "/exec/"+execID+"/start", nil, req, nil) + }) defer ensureReaderClosed(resp) return ExecStartResult{}, err } @@ -137,13 +134,11 @@ func (cli *Client) ExecAttach(ctx context.Context, execID string, options ExecAt if err != nil { return ExecAttachResult{}, err } - req := container.ExecStartRequest{ + headers := http.Header{"Content-Type": {"application/json"}} + response, err := cli.postHijacked(ctx, "/exec/"+execID+"/start", nil, headers, container.ExecStartRequest{ Detach: false, Tty: options.TTY, ConsoleSize: consoleSize, - } - response, err := cli.postHijacked(ctx, "/exec/"+execID+"/start", nil, req, http.Header{ - "Content-Type": {"application/json"}, }) return ExecAttachResult{HijackedResponse: response}, err } diff --git a/vendor/github.com/moby/moby/client/container_update.go b/vendor/github.com/moby/moby/client/container_update.go index a1d4d249a9..197d8da432 100644 --- a/vendor/github.com/moby/moby/client/container_update.go +++ b/vendor/github.com/moby/moby/client/container_update.go @@ -26,15 +26,10 @@ func (cli *Client) ContainerUpdate(ctx context.Context, containerID string, opti return ContainerUpdateResult{}, err } - updateConfig := container.UpdateConfig{} - if options.Resources != nil { - updateConfig.Resources = *options.Resources - } - if options.RestartPolicy != nil { - updateConfig.RestartPolicy = *options.RestartPolicy - } - - resp, err := cli.post(ctx, "/containers/"+containerID+"/update", nil, updateConfig, nil) + resp, err := cli.post(ctx, "/containers/"+containerID+"/update", nil, nil, container.UpdateConfig{ + Resources: valueOrZero(options.Resources), + RestartPolicy: valueOrZero(options.RestartPolicy), + }) defer ensureReaderClosed(resp) if err != nil { return ContainerUpdateResult{}, err diff --git a/vendor/github.com/moby/moby/client/hijack.go b/vendor/github.com/moby/moby/client/hijack.go index 31c44e5988..fbb0402725 100644 --- a/vendor/github.com/moby/moby/client/hijack.go +++ b/vendor/github.com/moby/moby/client/hijack.go @@ -13,16 +13,16 @@ import ( ) // postHijacked sends a POST request and hijacks the connection. -func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body any, headers map[string][]string) (HijackedResponse, error) { +func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, headers map[string][]string, body any) (HijackedResponse, error) { jsonBody, err := jsonEncode(body) if err != nil { return HijackedResponse{}, err } - req, err := cli.buildRequest(ctx, http.MethodPost, cli.getAPIPath(ctx, path, query), jsonBody, headers) + req, err := cli.buildRequest(ctx, http.MethodPost, cli.getAPIPath(ctx, path, query), headers, jsonBody) if err != nil { return HijackedResponse{}, err } - conn, mediaType, err := setupHijackConn(cli.dialer(), req, "tcp") + conn, mediaType, err := cli.setupHijackConn(req, "tcp") if err != nil { return HijackedResponse{}, err } @@ -38,16 +38,17 @@ func (cli *Client) DialHijack(ctx context.Context, url, proto string, meta map[s } req = cli.addHeaders(req, meta) - conn, _, err := setupHijackConn(cli.Dialer(), req, proto) + conn, _, err := cli.setupHijackConn(req, proto) return conn, err } -func setupHijackConn(dialer func(context.Context) (net.Conn, error), req *http.Request, proto string) (_ net.Conn, _ string, retErr error) { +func (cli *Client) setupHijackConn(req *http.Request, proto string) (retConn net.Conn, mediaType string, retErr error) { ctx := req.Context() req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", proto) - conn, err := dialer(ctx) + dial := cli.dialer() + conn, err := dial(ctx) if err != nil { return nil, "", fmt.Errorf("cannot connect to the Docker daemon. Is 'docker daemon' running on this host?: %w", err) } @@ -69,8 +70,33 @@ func setupHijackConn(dialer func(context.Context) (net.Conn, error), req *http.R hc := &hijackedConn{conn, bufio.NewReader(conn)} + // Cancel the handshake without tying the returned connection to ctx. + cancelled := make(chan struct{}) + stop := context.AfterFunc(ctx, func() { + _ = hc.Conn.Close() + close(cancelled) + }) + defer func() { + if !stop() { + // Cancellation won the race; don't return a connection being closed. + <-cancelled + retConn, mediaType, retErr = nil, "", ctx.Err() + } + }() + + cfg := &cli.clientConfig + + var rt http.RoundTripper = otelhttp.NewTransport(hc, cli.traceOpts...) + if len(cfg.requestHooks) > 0 || len(cfg.responseHooks) > 0 { + rt = &hookTransport{ + base: rt, + reqHooks: cfg.requestHooks, + respHooks: cfg.responseHooks, + } + } + // Server hijacks the connection, error 'connection closed' expected - resp, err := otelhttp.NewTransport(hc).RoundTrip(req) + resp, err := rt.RoundTrip(req) if err != nil { return nil, "", err } diff --git a/vendor/github.com/moby/moby/client/image_build.go b/vendor/github.com/moby/moby/client/image_build.go index 67ac204aaf..82ddc8ee1a 100644 --- a/vendor/github.com/moby/moby/client/image_build.go +++ b/vendor/github.com/moby/moby/client/image_build.go @@ -32,7 +32,7 @@ func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, optio headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) headers.Set("Content-Type", "application/x-tar") - resp, err := cli.postRaw(ctx, "/build", query, buildContext, headers) + resp, err := cli.postRaw(ctx, "/build", query, headers, buildContext) if err != nil { return ImageBuildResult{}, err } diff --git a/vendor/github.com/moby/moby/client/image_import.go b/vendor/github.com/moby/moby/client/image_import.go index 6c9f22866f..66186f228d 100644 --- a/vendor/github.com/moby/moby/client/image_import.go +++ b/vendor/github.com/moby/moby/client/image_import.go @@ -46,7 +46,7 @@ func (cli *Client) ImageImport(ctx context.Context, source ImageImportSource, re query.Add("changes", change) } - resp, err := cli.postRaw(ctx, "/images/create", query, source.Source, nil) + resp, err := cli.postRaw(ctx, "/images/create", query, nil, source.Source) if err != nil { return nil, err } diff --git a/vendor/github.com/moby/moby/client/image_load.go b/vendor/github.com/moby/moby/client/image_load.go index ec5fcae6eb..3edd491d22 100644 --- a/vendor/github.com/moby/moby/client/image_load.go +++ b/vendor/github.com/moby/moby/client/image_load.go @@ -42,9 +42,8 @@ func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, loadOpts ...I query["platform"] = p } - resp, err := cli.postRaw(ctx, "/images/load", query, input, http.Header{ - "Content-Type": {"application/x-tar"}, - }) + headers := http.Header{"Content-Type": {"application/x-tar"}} + resp, err := cli.postRaw(ctx, "/images/load", query, headers, input) if err != nil { return nil, err } diff --git a/vendor/github.com/moby/moby/client/image_pull.go b/vendor/github.com/moby/moby/client/image_pull.go index 11c0afa418..04d9edf1bb 100644 --- a/vendor/github.com/moby/moby/client/image_pull.go +++ b/vendor/github.com/moby/moby/client/image_pull.go @@ -89,5 +89,5 @@ func (cli *Client) tryImageCreate(ctx context.Context, query url.Values, resolve hdr.Set(registry.AuthHeader, registryAuth) } } - return cli.post(ctx, "/images/create", query, nil, hdr) + return cli.post(ctx, "/images/create", query, hdr, nil) } diff --git a/vendor/github.com/moby/moby/client/image_push.go b/vendor/github.com/moby/moby/client/image_push.go index 5dd8bc1407..d7729841cc 100644 --- a/vendor/github.com/moby/moby/client/image_push.go +++ b/vendor/github.com/moby/moby/client/image_push.go @@ -94,5 +94,5 @@ func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.V // We use [http.NoBody], which gets marshaled to an empty JSON document. // // see: https://github.com/moby/moby/commit/ea29dffaa541289591aa44fa85d2a596ce860e16 - return cli.post(ctx, "/images/"+imageID+"/push", query, http.NoBody, hdr) + return cli.post(ctx, "/images/"+imageID+"/push", query, hdr, http.NoBody) } diff --git a/vendor/github.com/moby/moby/client/login.go b/vendor/github.com/moby/moby/client/login.go index b295080ab7..9d9e5fad3f 100644 --- a/vendor/github.com/moby/moby/client/login.go +++ b/vendor/github.com/moby/moby/client/login.go @@ -32,7 +32,7 @@ func (cli *Client) RegistryLogin(ctx context.Context, options RegistryLoginOptio RegistryToken: options.RegistryToken, } - resp, err := cli.post(ctx, "/auth", url.Values{}, auth, nil) + resp, err := cli.post(ctx, "/auth", url.Values{}, nil, auth) defer ensureReaderClosed(resp) if err != nil { diff --git a/vendor/github.com/moby/moby/client/network_connect.go b/vendor/github.com/moby/moby/client/network_connect.go index 40db955a90..1a5cd645a4 100644 --- a/vendor/github.com/moby/moby/client/network_connect.go +++ b/vendor/github.com/moby/moby/client/network_connect.go @@ -34,7 +34,7 @@ func (cli *Client) NetworkConnect(ctx context.Context, networkID string, options Container: containerID, EndpointConfig: options.EndpointConfig, } - resp, err := cli.post(ctx, "/networks/"+networkID+"/connect", nil, nc, nil) + resp, err := cli.post(ctx, "/networks/"+networkID+"/connect", nil, nil, nc) defer ensureReaderClosed(resp) return NetworkConnectResult{}, err } diff --git a/vendor/github.com/moby/moby/client/network_create.go b/vendor/github.com/moby/moby/client/network_create.go index 25ea32af45..b5dae82b28 100644 --- a/vendor/github.com/moby/moby/client/network_create.go +++ b/vendor/github.com/moby/moby/client/network_create.go @@ -51,7 +51,7 @@ func (cli *Client) NetworkCreate(ctx context.Context, name string, options Netwo req.ConfigFrom = &network.ConfigReference{Network: options.ConfigFrom} } - resp, err := cli.post(ctx, "/networks/create", nil, req, nil) + resp, err := cli.post(ctx, "/networks/create", nil, nil, req) defer ensureReaderClosed(resp) if err != nil { return NetworkCreateResult{}, err diff --git a/vendor/github.com/moby/moby/client/network_disconnect.go b/vendor/github.com/moby/moby/client/network_disconnect.go index 64a1796b8d..4b1a6f550b 100644 --- a/vendor/github.com/moby/moby/client/network_disconnect.go +++ b/vendor/github.com/moby/moby/client/network_disconnect.go @@ -30,11 +30,10 @@ func (cli *Client) NetworkDisconnect(ctx context.Context, networkID string, opti return NetworkDisconnectResult{}, err } - req := network.DisconnectRequest{ + resp, err := cli.post(ctx, "/networks/"+networkID+"/disconnect", nil, nil, network.DisconnectRequest{ Container: containerID, Force: options.Force, - } - resp, err := cli.post(ctx, "/networks/"+networkID+"/disconnect", nil, req, nil) + }) defer ensureReaderClosed(resp) return NetworkDisconnectResult{}, err } diff --git a/vendor/github.com/moby/moby/client/node_update.go b/vendor/github.com/moby/moby/client/node_update.go index 24f87a4df5..cdd80fba12 100644 --- a/vendor/github.com/moby/moby/client/node_update.go +++ b/vendor/github.com/moby/moby/client/node_update.go @@ -25,7 +25,7 @@ func (cli *Client) NodeUpdate(ctx context.Context, nodeID string, options NodeUp query := url.Values{} query.Set("version", options.Version.String()) - resp, err := cli.post(ctx, "/nodes/"+nodeID+"/update", query, options.Spec, nil) + resp, err := cli.post(ctx, "/nodes/"+nodeID+"/update", query, nil, options.Spec) defer ensureReaderClosed(resp) return NodeUpdateResult{}, err } diff --git a/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go b/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go index a955363d8a..7fae6dceaa 100644 --- a/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go +++ b/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go @@ -26,7 +26,8 @@ const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" type DisplayOpt func(*displayOpts) error type displayOpts struct { - auxCallback func(jsonstream.Message) + auxCallback func(jsonstream.Message) + messagePrinter func(jsonstream.Message, io.Writer) error } // WithAuxCallback registers a callback that is invoked for auxiliary @@ -39,6 +40,18 @@ func WithAuxCallback(fn func(jsonstream.Message)) DisplayOpt { } } +// WithMessagePrinter sets a custom printer for non-auxiliary messages. +// If set, [DisplayStream] and [DisplayMessages] pass each message to fn instead +// of using the default terminal-aware presentation. The caller is responsible +// for handling errors reported through [jsonstream.Message.Error] and any +// terminal handling, including progress rendering and terminal-width detection. +func WithMessagePrinter(fn func(jsonstream.Message, io.Writer) error) DisplayOpt { + return func(opts *displayOpts) error { + opts.messagePrinter = fn + return nil + } +} + func RenderTUIProgress(p jsonstream.Progress, width uint16) string { var ( pbBox string @@ -232,13 +245,19 @@ func displayJSONMessages(messages iter.Seq2[jsonstream.Message, error], out io.W } } auxCallback := cfg.auxCallback + messagePrinter := cfg.messagePrinter - ids := make(map[string]uint) - var width uint16 = 200 - if isTerminal { - ws, err := term.GetWinsize(terminalFd) - if err == nil { - width = ws.Width + var ( + ids map[string]uint + width uint16 = 200 + ) + if messagePrinter == nil { + ids = make(map[string]uint) + if isTerminal { + ws, err := term.GetWinsize(terminalFd) + if err == nil { + width = ws.Width + } } } @@ -255,6 +274,13 @@ func displayJSONMessages(messages iter.Seq2[jsonstream.Message, error], out io.W continue } + if messagePrinter != nil { + if err := messagePrinter(jm, out); err != nil { + return err + } + continue + } + if jm.ID != "" && jm.Progress != nil { line, ok := ids[jm.ID] if !ok { diff --git a/vendor/github.com/moby/moby/client/plugin_create.go b/vendor/github.com/moby/moby/client/plugin_create.go index c1a2dd5a6c..774b9e36b5 100644 --- a/vendor/github.com/moby/moby/client/plugin_create.go +++ b/vendor/github.com/moby/moby/client/plugin_create.go @@ -19,13 +19,11 @@ type PluginCreateResult struct { // PluginCreate creates a plugin func (cli *Client) PluginCreate(ctx context.Context, createContext io.Reader, createOptions PluginCreateOptions) (PluginCreateResult, error) { - headers := http.Header(make(map[string][]string)) - headers.Set("Content-Type", "application/x-tar") - query := url.Values{} query.Set("name", createOptions.RepoName) - resp, err := cli.postRaw(ctx, "/plugins/create", query, createContext, headers) + headers := http.Header{"Content-Type": {"application/x-tar"}} + resp, err := cli.postRaw(ctx, "/plugins/create", query, headers, createContext) defer ensureReaderClosed(resp) return PluginCreateResult{}, err } diff --git a/vendor/github.com/moby/moby/client/plugin_install.go b/vendor/github.com/moby/moby/client/plugin_install.go index a589b2e1fd..d26ee782c3 100644 --- a/vendor/github.com/moby/moby/client/plugin_install.go +++ b/vendor/github.com/moby/moby/client/plugin_install.go @@ -99,13 +99,12 @@ func (cli *Client) tryPluginPrivileges(ctx context.Context, query url.Values, re }) } -func (cli *Client) tryPluginPull(ctx context.Context, query url.Values, privileges plugin.Privileges, registryAuth string) (*http.Response, error) { - return cli.post(ctx, "/plugins/pull", query, privileges, http.Header{ - registry.AuthHeader: {registryAuth}, - }) +func (cli *Client) tryPluginPull(ctx context.Context, query url.Values, privileges []plugin.Privilege, registryAuth string) (*http.Response, error) { + headers := http.Header{registry.AuthHeader: {registryAuth}} + return cli.post(ctx, "/plugins/pull", query, headers, privileges) } -func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, options pluginOptions) (plugin.Privileges, error) { +func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, options pluginOptions) ([]plugin.Privilege, error) { resp, err := cli.tryPluginPrivileges(ctx, query, options.getRegistryAuth()) if cerrdefs.IsUnauthorized(err) && options.getPrivilegeFunc() != nil { // TODO: do inspect before to check existing name before checking privileges @@ -122,7 +121,7 @@ func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, return nil, err } - var privileges plugin.Privileges + var privileges []plugin.Privilege if err := json.NewDecoder(resp.Body).Decode(&privileges); err != nil { ensureReaderClosed(resp) return nil, err diff --git a/vendor/github.com/moby/moby/client/plugin_push.go b/vendor/github.com/moby/moby/client/plugin_push.go index 4ba25d1336..d206fd2603 100644 --- a/vendor/github.com/moby/moby/client/plugin_push.go +++ b/vendor/github.com/moby/moby/client/plugin_push.go @@ -24,9 +24,8 @@ func (cli *Client) PluginPush(ctx context.Context, name string, options PluginPu if err != nil { return PluginPushResult{}, err } - resp, err := cli.post(ctx, "/plugins/"+name+"/push", nil, nil, http.Header{ - registry.AuthHeader: {options.RegistryAuth}, - }) + headers := http.Header{registry.AuthHeader: {options.RegistryAuth}} + resp, err := cli.post(ctx, "/plugins/"+name+"/push", nil, headers, nil) if err != nil { return PluginPushResult{}, err } diff --git a/vendor/github.com/moby/moby/client/plugin_set.go b/vendor/github.com/moby/moby/client/plugin_set.go index c1f6bb5fac..309a30c029 100644 --- a/vendor/github.com/moby/moby/client/plugin_set.go +++ b/vendor/github.com/moby/moby/client/plugin_set.go @@ -21,7 +21,7 @@ func (cli *Client) PluginSet(ctx context.Context, name string, options PluginSet return PluginSetResult{}, err } - resp, err := cli.post(ctx, "/plugins/"+name+"/set", nil, options.Args, nil) + resp, err := cli.post(ctx, "/plugins/"+name+"/set", nil, nil, options.Args) defer ensureReaderClosed(resp) return PluginSetResult{}, err } diff --git a/vendor/github.com/moby/moby/client/plugin_upgrade.go b/vendor/github.com/moby/moby/client/plugin_upgrade.go index f9df6e5843..bcfb1eacfe 100644 --- a/vendor/github.com/moby/moby/client/plugin_upgrade.go +++ b/vendor/github.com/moby/moby/client/plugin_upgrade.go @@ -58,10 +58,9 @@ func (cli *Client) PluginUpgrade(ctx context.Context, name string, options Plugi return resp.Body, nil } -func (cli *Client) tryPluginUpgrade(ctx context.Context, query url.Values, privileges plugin.Privileges, name, registryAuth string) (*http.Response, error) { - return cli.post(ctx, "/plugins/"+name+"/upgrade", query, privileges, http.Header{ - registry.AuthHeader: {registryAuth}, - }) +func (cli *Client) tryPluginUpgrade(ctx context.Context, query url.Values, privileges []plugin.Privilege, name, registryAuth string) (*http.Response, error) { + headers := http.Header{registry.AuthHeader: {registryAuth}} + return cli.post(ctx, "/plugins/"+name+"/upgrade", query, headers, privileges) } func (o *PluginUpgradeOptions) getRegistryAuth() string { diff --git a/vendor/github.com/moby/moby/client/request.go b/vendor/github.com/moby/moby/client/request.go index 10ed36dc67..7d57b6b6ad 100644 --- a/vendor/github.com/moby/moby/client/request.go +++ b/vendor/github.com/moby/moby/client/request.go @@ -19,49 +19,49 @@ import ( // head sends an http request to the docker API using the method HEAD. func (cli *Client) head(ctx context.Context, path string, query url.Values, headers http.Header) (*http.Response, error) { - return cli.sendRequest(ctx, http.MethodHead, path, query, nil, headers) + return cli.sendRequest(ctx, http.MethodHead, path, query, headers, nil) } // get sends an http request to the docker API using the method GET with a specific Go context. func (cli *Client) get(ctx context.Context, path string, query url.Values, headers http.Header) (*http.Response, error) { - return cli.sendRequest(ctx, http.MethodGet, path, query, nil, headers) + return cli.sendRequest(ctx, http.MethodGet, path, query, headers, nil) } // post sends an http POST request to the API. -func (cli *Client) post(ctx context.Context, path string, query url.Values, body any, headers http.Header) (*http.Response, error) { +func (cli *Client) post(ctx context.Context, path string, query url.Values, headers http.Header, body any) (*http.Response, error) { jsonBody, headers, err := prepareJSONRequest(body, headers) if err != nil { return nil, err } - return cli.sendRequest(ctx, http.MethodPost, path, query, jsonBody, headers) + return cli.sendRequest(ctx, http.MethodPost, path, query, headers, jsonBody) } -func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers http.Header) (*http.Response, error) { - return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) +func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, headers http.Header, body io.Reader) (*http.Response, error) { + return cli.sendRequest(ctx, http.MethodPost, path, query, headers, body) } -func (cli *Client) put(ctx context.Context, path string, query url.Values, body any, headers http.Header) (*http.Response, error) { +func (cli *Client) put(ctx context.Context, path string, query url.Values, headers http.Header, body any) (*http.Response, error) { jsonBody, headers, err := prepareJSONRequest(body, headers) if err != nil { return nil, err } - return cli.putRaw(ctx, path, query, jsonBody, headers) + return cli.putRaw(ctx, path, query, headers, jsonBody) } // putRaw sends an http request to the docker API using the method PUT. -func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers http.Header) (*http.Response, error) { +func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, headers http.Header, body io.Reader) (*http.Response, error) { // PUT requests are expected to always have a body (apparently) // so explicitly pass an empty body to sendRequest to signal that // it should set the Content-Type header if not already present. if body == nil { body = http.NoBody } - return cli.sendRequest(ctx, http.MethodPut, path, query, body, headers) + return cli.sendRequest(ctx, http.MethodPut, path, query, headers, body) } // delete sends an http request to the docker API using the method DELETE. func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers http.Header) (*http.Response, error) { - return cli.sendRequest(ctx, http.MethodDelete, path, query, nil, headers) + return cli.sendRequest(ctx, http.MethodDelete, path, query, headers, nil) } // prepareJSONRequest encodes the given body to JSON and returns it as an [io.Reader], and sets the Content-Type @@ -87,7 +87,7 @@ func prepareJSONRequest(body any, headers http.Header) (io.Reader, http.Header, return jsonBody, hdr, nil } -func (cli *Client) buildRequest(ctx context.Context, method, path string, body io.Reader, headers http.Header) (*http.Request, error) { +func (cli *Client) buildRequest(ctx context.Context, method, path string, headers http.Header, body io.Reader) (*http.Request, error) { req, err := http.NewRequestWithContext(ctx, method, path, body) if err != nil { return nil, err @@ -104,8 +104,8 @@ func (cli *Client) buildRequest(ctx context.Context, method, path string, body i return req, nil } -func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers http.Header) (*http.Response, error) { - req, err := cli.buildRequest(ctx, method, cli.getAPIPath(ctx, path, query), body, headers) +func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, headers http.Header, body io.Reader) (*http.Response, error) { + req, err := cli.buildRequest(ctx, method, cli.getAPIPath(ctx, path, query), headers, body) if err != nil { return nil, err } diff --git a/vendor/github.com/moby/moby/client/secret_create.go b/vendor/github.com/moby/moby/client/secret_create.go index 8e59a42ce7..22d5362d7f 100644 --- a/vendor/github.com/moby/moby/client/secret_create.go +++ b/vendor/github.com/moby/moby/client/secret_create.go @@ -19,7 +19,7 @@ type SecretCreateResult struct { // SecretCreate creates a new secret. func (cli *Client) SecretCreate(ctx context.Context, options SecretCreateOptions) (SecretCreateResult, error) { - resp, err := cli.post(ctx, "/secrets/create", nil, options.Spec, nil) + resp, err := cli.post(ctx, "/secrets/create", nil, nil, options.Spec) defer ensureReaderClosed(resp) if err != nil { return SecretCreateResult{}, err diff --git a/vendor/github.com/moby/moby/client/secret_update.go b/vendor/github.com/moby/moby/client/secret_update.go index d50fba4d45..b9fe94c71a 100644 --- a/vendor/github.com/moby/moby/client/secret_update.go +++ b/vendor/github.com/moby/moby/client/secret_update.go @@ -24,7 +24,7 @@ func (cli *Client) SecretUpdate(ctx context.Context, id string, options SecretUp } query := url.Values{} query.Set("version", options.Version.String()) - resp, err := cli.post(ctx, "/secrets/"+id+"/update", query, options.Spec, nil) + resp, err := cli.post(ctx, "/secrets/"+id+"/update", query, nil, options.Spec) defer ensureReaderClosed(resp) if err != nil { return SecretUpdateResult{}, err diff --git a/vendor/github.com/moby/moby/client/service_create.go b/vendor/github.com/moby/moby/client/service_create.go index 8d5926bb9b..e911e5783d 100644 --- a/vendor/github.com/moby/moby/client/service_create.go +++ b/vendor/github.com/moby/moby/client/service_create.go @@ -78,7 +78,7 @@ func (cli *Client) ServiceCreate(ctx context.Context, options ServiceCreateOptio if options.EncodedRegistryAuth != "" { headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} } - resp, err := cli.post(ctx, "/services/create", nil, options.Spec, headers) + resp, err := cli.post(ctx, "/services/create", nil, headers, options.Spec) defer ensureReaderClosed(resp) if err != nil { return ServiceCreateResult{}, err diff --git a/vendor/github.com/moby/moby/client/service_update.go b/vendor/github.com/moby/moby/client/service_update.go index 2505fe4b8e..4f179f0a7d 100644 --- a/vendor/github.com/moby/moby/client/service_update.go +++ b/vendor/github.com/moby/moby/client/service_update.go @@ -101,7 +101,7 @@ func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, options if options.EncodedRegistryAuth != "" { headers.Set(registry.AuthHeader, options.EncodedRegistryAuth) } - resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, options.Spec, headers) + resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, headers, options.Spec) defer ensureReaderClosed(resp) if err != nil { return ServiceUpdateResult{}, err diff --git a/vendor/github.com/moby/moby/client/swarm_init.go b/vendor/github.com/moby/moby/client/swarm_init.go index caad560856..87be2ce10f 100644 --- a/vendor/github.com/moby/moby/client/swarm_init.go +++ b/vendor/github.com/moby/moby/client/swarm_init.go @@ -29,7 +29,7 @@ type SwarmInitResult struct { // SwarmInit initializes the swarm. func (cli *Client) SwarmInit(ctx context.Context, options SwarmInitOptions) (SwarmInitResult, error) { - req := swarm.InitRequest{ + resp, err := cli.post(ctx, "/swarm/init", nil, nil, swarm.InitRequest{ ListenAddr: options.ListenAddr, AdvertiseAddr: options.AdvertiseAddr, DataPathAddr: options.DataPathAddr, @@ -40,9 +40,7 @@ func (cli *Client) SwarmInit(ctx context.Context, options SwarmInitOptions) (Swa Availability: options.Availability, DefaultAddrPool: options.DefaultAddrPool, SubnetSize: options.SubnetSize, - } - - resp, err := cli.post(ctx, "/swarm/init", nil, req, nil) + }) defer ensureReaderClosed(resp) if err != nil { return SwarmInitResult{}, err diff --git a/vendor/github.com/moby/moby/client/swarm_join.go b/vendor/github.com/moby/moby/client/swarm_join.go index 66a7544821..9d33ef6e12 100644 --- a/vendor/github.com/moby/moby/client/swarm_join.go +++ b/vendor/github.com/moby/moby/client/swarm_join.go @@ -23,16 +23,14 @@ type SwarmJoinResult struct { // SwarmJoin joins the swarm. func (cli *Client) SwarmJoin(ctx context.Context, options SwarmJoinOptions) (SwarmJoinResult, error) { - req := swarm.JoinRequest{ + resp, err := cli.post(ctx, "/swarm/join", nil, nil, swarm.JoinRequest{ ListenAddr: options.ListenAddr, AdvertiseAddr: options.AdvertiseAddr, DataPathAddr: options.DataPathAddr, RemoteAddrs: options.RemoteAddrs, JoinToken: options.JoinToken, Availability: options.Availability, - } - - resp, err := cli.post(ctx, "/swarm/join", nil, req, nil) + }) defer ensureReaderClosed(resp) return SwarmJoinResult{}, err } diff --git a/vendor/github.com/moby/moby/client/swarm_unlock.go b/vendor/github.com/moby/moby/client/swarm_unlock.go index 92335afb54..a6aee22986 100644 --- a/vendor/github.com/moby/moby/client/swarm_unlock.go +++ b/vendor/github.com/moby/moby/client/swarm_unlock.go @@ -16,10 +16,9 @@ type SwarmUnlockResult struct{} // SwarmUnlock unlocks locked swarm. func (cli *Client) SwarmUnlock(ctx context.Context, options SwarmUnlockOptions) (SwarmUnlockResult, error) { - req := &swarm.UnlockRequest{ + resp, err := cli.post(ctx, "/swarm/unlock", nil, nil, swarm.UnlockRequest{ UnlockKey: options.Key, - } - resp, err := cli.post(ctx, "/swarm/unlock", nil, req, nil) + }) defer ensureReaderClosed(resp) return SwarmUnlockResult{}, err } diff --git a/vendor/github.com/moby/moby/client/swarm_update.go b/vendor/github.com/moby/moby/client/swarm_update.go index 81f62b2c02..0e6257ad46 100644 --- a/vendor/github.com/moby/moby/client/swarm_update.go +++ b/vendor/github.com/moby/moby/client/swarm_update.go @@ -27,7 +27,7 @@ func (cli *Client) SwarmUpdate(ctx context.Context, options SwarmUpdateOptions) query.Set("rotateWorkerToken", strconv.FormatBool(options.RotateWorkerToken)) query.Set("rotateManagerToken", strconv.FormatBool(options.RotateManagerToken)) query.Set("rotateManagerUnlockKey", strconv.FormatBool(options.RotateManagerUnlockKey)) - resp, err := cli.post(ctx, "/swarm/update", query, options.Spec, nil) + resp, err := cli.post(ctx, "/swarm/update", query, nil, options.Spec) defer ensureReaderClosed(resp) return SwarmUpdateResult{}, err } diff --git a/vendor/github.com/moby/moby/client/utils.go b/vendor/github.com/moby/moby/client/utils.go index 1c0d09dfa2..ceecafa55c 100644 --- a/vendor/github.com/moby/moby/client/utils.go +++ b/vendor/github.com/moby/moby/client/utils.go @@ -33,6 +33,14 @@ func trimID(objType, id string) (string, error) { return id, nil } +// valueOrZero returns the value pointed to by p, or the zero value of T if p is nil. +func valueOrZero[T any](p *T) (zero T) { + if p != nil { + return *p + } + return zero +} + // parseAPIVersion checks v to be a well-formed (".") // API version. It returns an error if the value is empty or does not // have the correct format, but does not validate if the API version is diff --git a/vendor/github.com/moby/moby/client/volume_create.go b/vendor/github.com/moby/moby/client/volume_create.go index 674e063357..5212f09a5f 100644 --- a/vendor/github.com/moby/moby/client/volume_create.go +++ b/vendor/github.com/moby/moby/client/volume_create.go @@ -23,14 +23,13 @@ type VolumeCreateResult struct { // VolumeCreate creates a volume in the docker host. func (cli *Client) VolumeCreate(ctx context.Context, options VolumeCreateOptions) (VolumeCreateResult, error) { - createRequest := volume.CreateRequest{ + resp, err := cli.post(ctx, "/volumes/create", nil, nil, volume.CreateRequest{ Name: options.Name, Driver: options.Driver, DriverOpts: options.DriverOpts, Labels: options.Labels, ClusterVolumeSpec: options.ClusterVolumeSpec, - } - resp, err := cli.post(ctx, "/volumes/create", nil, createRequest, nil) + }) defer ensureReaderClosed(resp) if err != nil { return VolumeCreateResult{}, err diff --git a/vendor/github.com/moby/moby/client/volume_update.go b/vendor/github.com/moby/moby/client/volume_update.go index 5aa2a0aa17..3810267ef5 100644 --- a/vendor/github.com/moby/moby/client/volume_update.go +++ b/vendor/github.com/moby/moby/client/volume_update.go @@ -31,7 +31,7 @@ func (cli *Client) VolumeUpdate(ctx context.Context, volumeID string, options Vo query := url.Values{} query.Set("version", options.Version.String()) - resp, err := cli.put(ctx, "/volumes/"+volumeID, query, options, nil) + resp, err := cli.put(ctx, "/volumes/"+volumeID, query, nil, options) defer ensureReaderClosed(resp) if err != nil { return VolumeUpdateResult{}, err diff --git a/vendor/github.com/openfga/language/pkg/go/gen/OpenFGALexer.interp b/vendor/github.com/openfga/language/pkg/go/gen/OpenFGALexer.interp index 79d5cbb7c8..bfaefca830 100644 --- a/vendor/github.com/openfga/language/pkg/go/gen/OpenFGALexer.interp +++ b/vendor/github.com/openfga/language/pkg/go/gen/OpenFGALexer.interp @@ -53,6 +53,7 @@ null null null null +'$expression' null null null @@ -113,6 +114,7 @@ NUM_INT NUM_UINT STRING BYTES +DOLLAR_EXPRESSION EXTENDED_IDENTIFIER NEWLINE CONDITION_PARAM_CONTAINER @@ -181,6 +183,7 @@ NUM_INT NUM_UINT STRING BYTES +DOLLAR_EXPRESSION IDENTIFIER EXTENDED_IDENTIFIER NEWLINE @@ -204,4 +207,4 @@ DEFAULT_MODE CONDITION_DEF atn: -[4, 0, 57, 717, 6, -1, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, 20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25, 2, 26, 7, 26, 2, 27, 7, 27, 2, 28, 7, 28, 2, 29, 7, 29, 2, 30, 7, 30, 2, 31, 7, 31, 2, 32, 7, 32, 2, 33, 7, 33, 2, 34, 7, 34, 2, 35, 7, 35, 2, 36, 7, 36, 2, 37, 7, 37, 2, 38, 7, 38, 2, 39, 7, 39, 2, 40, 7, 40, 2, 41, 7, 41, 2, 42, 7, 42, 2, 43, 7, 43, 2, 44, 7, 44, 2, 45, 7, 45, 2, 46, 7, 46, 2, 47, 7, 47, 2, 48, 7, 48, 2, 49, 7, 49, 2, 50, 7, 50, 2, 51, 7, 51, 2, 52, 7, 52, 2, 53, 7, 53, 2, 54, 7, 54, 2, 55, 7, 55, 2, 56, 7, 56, 2, 57, 7, 57, 2, 58, 7, 58, 2, 59, 7, 59, 2, 60, 7, 60, 2, 61, 7, 61, 2, 62, 7, 62, 2, 63, 7, 63, 2, 64, 7, 64, 2, 65, 7, 65, 2, 66, 7, 66, 2, 67, 7, 67, 2, 68, 7, 68, 2, 69, 7, 69, 2, 70, 7, 70, 2, 71, 7, 71, 2, 72, 7, 72, 2, 73, 7, 73, 2, 74, 7, 74, 1, 0, 1, 0, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 10, 4, 10, 200, 8, 10, 11, 10, 12, 10, 201, 1, 10, 1, 10, 4, 10, 206, 8, 10, 11, 10, 12, 10, 207, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 17, 1, 17, 1, 17, 1, 17, 1, 17, 1, 18, 1, 18, 1, 18, 1, 19, 1, 19, 1, 19, 1, 20, 1, 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, 22, 1, 23, 1, 23, 1, 23, 1, 24, 1, 24, 1, 25, 1, 25, 1, 25, 1, 26, 1, 26, 1, 26, 1, 27, 1, 27, 1, 28, 1, 28, 1, 29, 1, 29, 1, 30, 1, 30, 1, 31, 1, 31, 1, 32, 1, 32, 1, 33, 1, 33, 1, 34, 1, 34, 1, 35, 1, 35, 1, 36, 1, 36, 1, 37, 1, 37, 1, 38, 1, 38, 1, 39, 1, 39, 1, 40, 1, 40, 1, 41, 1, 41, 1, 41, 1, 41, 1, 41, 1, 42, 1, 42, 1, 42, 1, 42, 1, 42, 1, 42, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 1, 44, 1, 44, 1, 45, 1, 45, 1, 46, 1, 46, 1, 47, 1, 47, 3, 47, 342, 8, 47, 1, 47, 4, 47, 345, 8, 47, 11, 47, 12, 47, 346, 1, 48, 1, 48, 1, 49, 1, 49, 1, 50, 1, 50, 1, 50, 1, 50, 3, 50, 357, 8, 50, 1, 51, 1, 51, 1, 51, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 53, 1, 53, 1, 53, 1, 53, 1, 53, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 3, 54, 390, 8, 54, 1, 55, 4, 55, 393, 8, 55, 11, 55, 12, 55, 394, 1, 56, 1, 56, 1, 56, 1, 56, 5, 56, 401, 8, 56, 10, 56, 12, 56, 404, 9, 56, 1, 56, 1, 56, 1, 57, 4, 57, 409, 8, 57, 11, 57, 12, 57, 410, 1, 57, 1, 57, 4, 57, 415, 8, 57, 11, 57, 12, 57, 416, 1, 57, 3, 57, 420, 8, 57, 1, 57, 4, 57, 423, 8, 57, 11, 57, 12, 57, 424, 1, 57, 1, 57, 1, 57, 1, 57, 4, 57, 431, 8, 57, 11, 57, 12, 57, 432, 1, 57, 3, 57, 436, 8, 57, 3, 57, 438, 8, 57, 1, 58, 4, 58, 441, 8, 58, 11, 58, 12, 58, 442, 1, 58, 1, 58, 1, 58, 1, 58, 4, 58, 449, 8, 58, 11, 58, 12, 58, 450, 3, 58, 453, 8, 58, 1, 59, 4, 59, 456, 8, 59, 11, 59, 12, 59, 457, 1, 59, 1, 59, 1, 59, 1, 59, 1, 59, 1, 59, 4, 59, 466, 8, 59, 11, 59, 12, 59, 467, 1, 59, 1, 59, 3, 59, 472, 8, 59, 1, 60, 1, 60, 1, 60, 5, 60, 477, 8, 60, 10, 60, 12, 60, 480, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 486, 8, 60, 10, 60, 12, 60, 489, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 498, 8, 60, 10, 60, 12, 60, 501, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 512, 8, 60, 10, 60, 12, 60, 515, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 523, 8, 60, 10, 60, 12, 60, 526, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 533, 8, 60, 10, 60, 12, 60, 536, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 546, 8, 60, 10, 60, 12, 60, 549, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 561, 8, 60, 10, 60, 12, 60, 564, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 3, 60, 570, 8, 60, 1, 61, 1, 61, 1, 61, 1, 62, 1, 62, 3, 62, 577, 8, 62, 1, 62, 1, 62, 1, 62, 1, 62, 5, 62, 583, 8, 62, 10, 62, 12, 62, 586, 9, 62, 1, 63, 1, 63, 3, 63, 590, 8, 63, 1, 63, 1, 63, 1, 63, 3, 63, 595, 8, 63, 1, 63, 1, 63, 1, 63, 4, 63, 600, 8, 63, 11, 63, 12, 63, 601, 5, 63, 604, 8, 63, 10, 63, 12, 63, 607, 9, 63, 1, 64, 3, 64, 610, 8, 64, 1, 64, 3, 64, 613, 8, 64, 1, 64, 1, 64, 3, 64, 617, 8, 64, 1, 64, 3, 64, 620, 8, 64, 1, 64, 3, 64, 623, 8, 64, 1, 65, 1, 65, 1, 65, 1, 65, 1, 65, 1, 66, 1, 66, 1, 66, 1, 66, 1, 66, 1, 66, 1, 66, 3, 66, 637, 8, 66, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 3, 67, 688, 8, 67, 1, 68, 1, 68, 1, 68, 1, 68, 1, 69, 1, 69, 1, 69, 1, 69, 1, 70, 1, 70, 1, 70, 1, 70, 1, 71, 1, 71, 1, 71, 1, 71, 1, 72, 1, 72, 1, 72, 1, 72, 1, 73, 1, 73, 1, 73, 1, 73, 1, 74, 1, 74, 1, 74, 1, 74, 4, 499, 513, 547, 562, 0, 75, 2, 11, 4, 1, 6, 2, 8, 12, 10, 13, 12, 14, 14, 15, 16, 16, 18, 17, 20, 18, 22, 19, 24, 20, 26, 21, 28, 22, 30, 23, 32, 24, 34, 25, 36, 26, 38, 27, 40, 28, 42, 29, 44, 3, 46, 30, 48, 31, 50, 4, 52, 32, 54, 33, 56, 5, 58, 34, 60, 35, 62, 36, 64, 7, 66, 8, 68, 37, 70, 38, 72, 39, 74, 40, 76, 41, 78, 42, 80, 43, 82, 44, 84, 45, 86, 46, 88, 47, 90, 0, 92, 0, 94, 0, 96, 0, 98, 0, 100, 0, 102, 0, 104, 0, 106, 0, 108, 0, 110, 0, 112, 9, 114, 48, 116, 49, 118, 50, 120, 51, 122, 52, 124, 53, 126, 10, 128, 54, 130, 55, 132, 0, 134, 56, 136, 57, 138, 0, 140, 0, 142, 0, 144, 0, 146, 0, 148, 0, 150, 0, 2, 0, 1, 16, 2, 0, 65, 90, 97, 122, 2, 0, 69, 69, 101, 101, 2, 0, 43, 43, 45, 45, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 82, 82, 114, 114, 10, 0, 34, 34, 39, 39, 63, 63, 92, 92, 96, 98, 102, 102, 110, 110, 114, 114, 116, 116, 118, 118, 2, 0, 88, 88, 120, 120, 3, 0, 9, 9, 12, 12, 32, 32, 1, 0, 10, 10, 2, 0, 85, 85, 117, 117, 4, 0, 10, 10, 13, 13, 34, 34, 92, 92, 4, 0, 10, 10, 13, 13, 39, 39, 92, 92, 1, 0, 92, 92, 3, 0, 10, 10, 13, 13, 34, 34, 3, 0, 10, 10, 13, 13, 39, 39, 2, 0, 66, 66, 98, 98, 773, 0, 2, 1, 0, 0, 0, 0, 4, 1, 0, 0, 0, 0, 6, 1, 0, 0, 0, 0, 8, 1, 0, 0, 0, 0, 10, 1, 0, 0, 0, 0, 12, 1, 0, 0, 0, 0, 14, 1, 0, 0, 0, 0, 16, 1, 0, 0, 0, 0, 18, 1, 0, 0, 0, 0, 20, 1, 0, 0, 0, 0, 22, 1, 0, 0, 0, 0, 24, 1, 0, 0, 0, 0, 26, 1, 0, 0, 0, 0, 28, 1, 0, 0, 0, 0, 30, 1, 0, 0, 0, 0, 32, 1, 0, 0, 0, 0, 34, 1, 0, 0, 0, 0, 36, 1, 0, 0, 0, 0, 38, 1, 0, 0, 0, 0, 40, 1, 0, 0, 0, 0, 42, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 46, 1, 0, 0, 0, 0, 48, 1, 0, 0, 0, 0, 50, 1, 0, 0, 0, 0, 52, 1, 0, 0, 0, 0, 54, 1, 0, 0, 0, 0, 56, 1, 0, 0, 0, 0, 58, 1, 0, 0, 0, 0, 60, 1, 0, 0, 0, 0, 62, 1, 0, 0, 0, 0, 64, 1, 0, 0, 0, 0, 66, 1, 0, 0, 0, 0, 68, 1, 0, 0, 0, 0, 70, 1, 0, 0, 0, 0, 72, 1, 0, 0, 0, 0, 74, 1, 0, 0, 0, 0, 76, 1, 0, 0, 0, 0, 78, 1, 0, 0, 0, 0, 80, 1, 0, 0, 0, 0, 82, 1, 0, 0, 0, 0, 84, 1, 0, 0, 0, 0, 86, 1, 0, 0, 0, 0, 88, 1, 0, 0, 0, 0, 112, 1, 0, 0, 0, 0, 114, 1, 0, 0, 0, 0, 116, 1, 0, 0, 0, 0, 118, 1, 0, 0, 0, 0, 120, 1, 0, 0, 0, 0, 122, 1, 0, 0, 0, 0, 124, 1, 0, 0, 0, 0, 126, 1, 0, 0, 0, 0, 128, 1, 0, 0, 0, 0, 130, 1, 0, 0, 0, 1, 132, 1, 0, 0, 0, 1, 134, 1, 0, 0, 0, 1, 136, 1, 0, 0, 0, 1, 138, 1, 0, 0, 0, 1, 140, 1, 0, 0, 0, 1, 142, 1, 0, 0, 0, 1, 144, 1, 0, 0, 0, 1, 146, 1, 0, 0, 0, 1, 148, 1, 0, 0, 0, 1, 150, 1, 0, 0, 0, 2, 152, 1, 0, 0, 0, 4, 154, 1, 0, 0, 0, 6, 156, 1, 0, 0, 0, 8, 158, 1, 0, 0, 0, 10, 162, 1, 0, 0, 0, 12, 165, 1, 0, 0, 0, 14, 173, 1, 0, 0, 0, 16, 178, 1, 0, 0, 0, 18, 185, 1, 0, 0, 0, 20, 191, 1, 0, 0, 0, 22, 199, 1, 0, 0, 0, 24, 209, 1, 0, 0, 0, 26, 216, 1, 0, 0, 0, 28, 221, 1, 0, 0, 0, 30, 233, 1, 0, 0, 0, 32, 243, 1, 0, 0, 0, 34, 252, 1, 0, 0, 0, 36, 259, 1, 0, 0, 0, 38, 264, 1, 0, 0, 0, 40, 267, 1, 0, 0, 0, 42, 270, 1, 0, 0, 0, 44, 273, 1, 0, 0, 0, 46, 275, 1, 0, 0, 0, 48, 278, 1, 0, 0, 0, 50, 281, 1, 0, 0, 0, 52, 283, 1, 0, 0, 0, 54, 286, 1, 0, 0, 0, 56, 289, 1, 0, 0, 0, 58, 291, 1, 0, 0, 0, 60, 293, 1, 0, 0, 0, 62, 295, 1, 0, 0, 0, 64, 297, 1, 0, 0, 0, 66, 299, 1, 0, 0, 0, 68, 301, 1, 0, 0, 0, 70, 303, 1, 0, 0, 0, 72, 305, 1, 0, 0, 0, 74, 307, 1, 0, 0, 0, 76, 309, 1, 0, 0, 0, 78, 311, 1, 0, 0, 0, 80, 313, 1, 0, 0, 0, 82, 315, 1, 0, 0, 0, 84, 317, 1, 0, 0, 0, 86, 322, 1, 0, 0, 0, 88, 328, 1, 0, 0, 0, 90, 333, 1, 0, 0, 0, 92, 335, 1, 0, 0, 0, 94, 337, 1, 0, 0, 0, 96, 339, 1, 0, 0, 0, 98, 348, 1, 0, 0, 0, 100, 350, 1, 0, 0, 0, 102, 356, 1, 0, 0, 0, 104, 358, 1, 0, 0, 0, 106, 361, 1, 0, 0, 0, 108, 366, 1, 0, 0, 0, 110, 389, 1, 0, 0, 0, 112, 392, 1, 0, 0, 0, 114, 396, 1, 0, 0, 0, 116, 437, 1, 0, 0, 0, 118, 452, 1, 0, 0, 0, 120, 471, 1, 0, 0, 0, 122, 569, 1, 0, 0, 0, 124, 571, 1, 0, 0, 0, 126, 576, 1, 0, 0, 0, 128, 589, 1, 0, 0, 0, 130, 609, 1, 0, 0, 0, 132, 624, 1, 0, 0, 0, 134, 636, 1, 0, 0, 0, 136, 687, 1, 0, 0, 0, 138, 689, 1, 0, 0, 0, 140, 693, 1, 0, 0, 0, 142, 697, 1, 0, 0, 0, 144, 701, 1, 0, 0, 0, 146, 705, 1, 0, 0, 0, 148, 709, 1, 0, 0, 0, 150, 713, 1, 0, 0, 0, 152, 153, 5, 35, 0, 0, 153, 3, 1, 0, 0, 0, 154, 155, 5, 58, 0, 0, 155, 5, 1, 0, 0, 0, 156, 157, 5, 44, 0, 0, 157, 7, 1, 0, 0, 0, 158, 159, 5, 97, 0, 0, 159, 160, 5, 110, 0, 0, 160, 161, 5, 100, 0, 0, 161, 9, 1, 0, 0, 0, 162, 163, 5, 111, 0, 0, 163, 164, 5, 114, 0, 0, 164, 11, 1, 0, 0, 0, 165, 166, 5, 98, 0, 0, 166, 167, 5, 117, 0, 0, 167, 168, 5, 116, 0, 0, 168, 169, 5, 32, 0, 0, 169, 170, 5, 110, 0, 0, 170, 171, 5, 111, 0, 0, 171, 172, 5, 116, 0, 0, 172, 13, 1, 0, 0, 0, 173, 174, 5, 102, 0, 0, 174, 175, 5, 114, 0, 0, 175, 176, 5, 111, 0, 0, 176, 177, 5, 109, 0, 0, 177, 15, 1, 0, 0, 0, 178, 179, 5, 109, 0, 0, 179, 180, 5, 111, 0, 0, 180, 181, 5, 100, 0, 0, 181, 182, 5, 117, 0, 0, 182, 183, 5, 108, 0, 0, 183, 184, 5, 101, 0, 0, 184, 17, 1, 0, 0, 0, 185, 186, 5, 109, 0, 0, 186, 187, 5, 111, 0, 0, 187, 188, 5, 100, 0, 0, 188, 189, 5, 101, 0, 0, 189, 190, 5, 108, 0, 0, 190, 19, 1, 0, 0, 0, 191, 192, 5, 115, 0, 0, 192, 193, 5, 99, 0, 0, 193, 194, 5, 104, 0, 0, 194, 195, 5, 101, 0, 0, 195, 196, 5, 109, 0, 0, 196, 197, 5, 97, 0, 0, 197, 21, 1, 0, 0, 0, 198, 200, 3, 94, 46, 0, 199, 198, 1, 0, 0, 0, 200, 201, 1, 0, 0, 0, 201, 199, 1, 0, 0, 0, 201, 202, 1, 0, 0, 0, 202, 203, 1, 0, 0, 0, 203, 205, 5, 46, 0, 0, 204, 206, 3, 94, 46, 0, 205, 204, 1, 0, 0, 0, 206, 207, 1, 0, 0, 0, 207, 205, 1, 0, 0, 0, 207, 208, 1, 0, 0, 0, 208, 23, 1, 0, 0, 0, 209, 210, 5, 101, 0, 0, 210, 211, 5, 120, 0, 0, 211, 212, 5, 116, 0, 0, 212, 213, 5, 101, 0, 0, 213, 214, 5, 110, 0, 0, 214, 215, 5, 100, 0, 0, 215, 25, 1, 0, 0, 0, 216, 217, 5, 116, 0, 0, 217, 218, 5, 121, 0, 0, 218, 219, 5, 112, 0, 0, 219, 220, 5, 101, 0, 0, 220, 27, 1, 0, 0, 0, 221, 222, 5, 99, 0, 0, 222, 223, 5, 111, 0, 0, 223, 224, 5, 110, 0, 0, 224, 225, 5, 100, 0, 0, 225, 226, 5, 105, 0, 0, 226, 227, 5, 116, 0, 0, 227, 228, 5, 105, 0, 0, 228, 229, 5, 111, 0, 0, 229, 230, 5, 110, 0, 0, 230, 231, 1, 0, 0, 0, 231, 232, 6, 13, 0, 0, 232, 29, 1, 0, 0, 0, 233, 234, 5, 114, 0, 0, 234, 235, 5, 101, 0, 0, 235, 236, 5, 108, 0, 0, 236, 237, 5, 97, 0, 0, 237, 238, 5, 116, 0, 0, 238, 239, 5, 105, 0, 0, 239, 240, 5, 111, 0, 0, 240, 241, 5, 110, 0, 0, 241, 242, 5, 115, 0, 0, 242, 31, 1, 0, 0, 0, 243, 244, 5, 114, 0, 0, 244, 245, 5, 101, 0, 0, 245, 246, 5, 108, 0, 0, 246, 247, 5, 97, 0, 0, 247, 248, 5, 116, 0, 0, 248, 249, 5, 105, 0, 0, 249, 250, 5, 111, 0, 0, 250, 251, 5, 110, 0, 0, 251, 33, 1, 0, 0, 0, 252, 253, 5, 100, 0, 0, 253, 254, 5, 101, 0, 0, 254, 255, 5, 102, 0, 0, 255, 256, 5, 105, 0, 0, 256, 257, 5, 110, 0, 0, 257, 258, 5, 101, 0, 0, 258, 35, 1, 0, 0, 0, 259, 260, 5, 119, 0, 0, 260, 261, 5, 105, 0, 0, 261, 262, 5, 116, 0, 0, 262, 263, 5, 104, 0, 0, 263, 37, 1, 0, 0, 0, 264, 265, 5, 61, 0, 0, 265, 266, 5, 61, 0, 0, 266, 39, 1, 0, 0, 0, 267, 268, 5, 33, 0, 0, 268, 269, 5, 61, 0, 0, 269, 41, 1, 0, 0, 0, 270, 271, 5, 105, 0, 0, 271, 272, 5, 110, 0, 0, 272, 43, 1, 0, 0, 0, 273, 274, 5, 60, 0, 0, 274, 45, 1, 0, 0, 0, 275, 276, 5, 60, 0, 0, 276, 277, 5, 61, 0, 0, 277, 47, 1, 0, 0, 0, 278, 279, 5, 62, 0, 0, 279, 280, 5, 61, 0, 0, 280, 49, 1, 0, 0, 0, 281, 282, 5, 62, 0, 0, 282, 51, 1, 0, 0, 0, 283, 284, 5, 38, 0, 0, 284, 285, 5, 38, 0, 0, 285, 53, 1, 0, 0, 0, 286, 287, 5, 124, 0, 0, 287, 288, 5, 124, 0, 0, 288, 55, 1, 0, 0, 0, 289, 290, 5, 91, 0, 0, 290, 57, 1, 0, 0, 0, 291, 292, 5, 93, 0, 0, 292, 59, 1, 0, 0, 0, 293, 294, 5, 123, 0, 0, 294, 61, 1, 0, 0, 0, 295, 296, 5, 125, 0, 0, 296, 63, 1, 0, 0, 0, 297, 298, 5, 40, 0, 0, 298, 65, 1, 0, 0, 0, 299, 300, 5, 41, 0, 0, 300, 67, 1, 0, 0, 0, 301, 302, 5, 46, 0, 0, 302, 69, 1, 0, 0, 0, 303, 304, 5, 45, 0, 0, 304, 71, 1, 0, 0, 0, 305, 306, 5, 33, 0, 0, 306, 73, 1, 0, 0, 0, 307, 308, 5, 63, 0, 0, 308, 75, 1, 0, 0, 0, 309, 310, 5, 43, 0, 0, 310, 77, 1, 0, 0, 0, 311, 312, 5, 42, 0, 0, 312, 79, 1, 0, 0, 0, 313, 314, 5, 47, 0, 0, 314, 81, 1, 0, 0, 0, 315, 316, 5, 37, 0, 0, 316, 83, 1, 0, 0, 0, 317, 318, 5, 116, 0, 0, 318, 319, 5, 114, 0, 0, 319, 320, 5, 117, 0, 0, 320, 321, 5, 101, 0, 0, 321, 85, 1, 0, 0, 0, 322, 323, 5, 102, 0, 0, 323, 324, 5, 97, 0, 0, 324, 325, 5, 108, 0, 0, 325, 326, 5, 115, 0, 0, 326, 327, 5, 101, 0, 0, 327, 87, 1, 0, 0, 0, 328, 329, 5, 110, 0, 0, 329, 330, 5, 117, 0, 0, 330, 331, 5, 108, 0, 0, 331, 332, 5, 108, 0, 0, 332, 89, 1, 0, 0, 0, 333, 334, 5, 92, 0, 0, 334, 91, 1, 0, 0, 0, 335, 336, 7, 0, 0, 0, 336, 93, 1, 0, 0, 0, 337, 338, 2, 48, 57, 0, 338, 95, 1, 0, 0, 0, 339, 341, 7, 1, 0, 0, 340, 342, 7, 2, 0, 0, 341, 340, 1, 0, 0, 0, 341, 342, 1, 0, 0, 0, 342, 344, 1, 0, 0, 0, 343, 345, 3, 94, 46, 0, 344, 343, 1, 0, 0, 0, 345, 346, 1, 0, 0, 0, 346, 344, 1, 0, 0, 0, 346, 347, 1, 0, 0, 0, 347, 97, 1, 0, 0, 0, 348, 349, 7, 3, 0, 0, 349, 99, 1, 0, 0, 0, 350, 351, 7, 4, 0, 0, 351, 101, 1, 0, 0, 0, 352, 357, 3, 104, 51, 0, 353, 357, 3, 108, 53, 0, 354, 357, 3, 110, 54, 0, 355, 357, 3, 106, 52, 0, 356, 352, 1, 0, 0, 0, 356, 353, 1, 0, 0, 0, 356, 354, 1, 0, 0, 0, 356, 355, 1, 0, 0, 0, 357, 103, 1, 0, 0, 0, 358, 359, 3, 90, 44, 0, 359, 360, 7, 5, 0, 0, 360, 105, 1, 0, 0, 0, 361, 362, 3, 90, 44, 0, 362, 363, 2, 48, 51, 0, 363, 364, 2, 48, 55, 0, 364, 365, 2, 48, 55, 0, 365, 107, 1, 0, 0, 0, 366, 367, 3, 90, 44, 0, 367, 368, 7, 6, 0, 0, 368, 369, 3, 98, 48, 0, 369, 370, 3, 98, 48, 0, 370, 109, 1, 0, 0, 0, 371, 372, 3, 90, 44, 0, 372, 373, 5, 117, 0, 0, 373, 374, 3, 98, 48, 0, 374, 375, 3, 98, 48, 0, 375, 376, 3, 98, 48, 0, 376, 377, 3, 98, 48, 0, 377, 390, 1, 0, 0, 0, 378, 379, 3, 90, 44, 0, 379, 380, 5, 85, 0, 0, 380, 381, 3, 98, 48, 0, 381, 382, 3, 98, 48, 0, 382, 383, 3, 98, 48, 0, 383, 384, 3, 98, 48, 0, 384, 385, 3, 98, 48, 0, 385, 386, 3, 98, 48, 0, 386, 387, 3, 98, 48, 0, 387, 388, 3, 98, 48, 0, 388, 390, 1, 0, 0, 0, 389, 371, 1, 0, 0, 0, 389, 378, 1, 0, 0, 0, 390, 111, 1, 0, 0, 0, 391, 393, 7, 7, 0, 0, 392, 391, 1, 0, 0, 0, 393, 394, 1, 0, 0, 0, 394, 392, 1, 0, 0, 0, 394, 395, 1, 0, 0, 0, 395, 113, 1, 0, 0, 0, 396, 397, 5, 47, 0, 0, 397, 398, 5, 47, 0, 0, 398, 402, 1, 0, 0, 0, 399, 401, 8, 8, 0, 0, 400, 399, 1, 0, 0, 0, 401, 404, 1, 0, 0, 0, 402, 400, 1, 0, 0, 0, 402, 403, 1, 0, 0, 0, 403, 405, 1, 0, 0, 0, 404, 402, 1, 0, 0, 0, 405, 406, 6, 56, 1, 0, 406, 115, 1, 0, 0, 0, 407, 409, 3, 94, 46, 0, 408, 407, 1, 0, 0, 0, 409, 410, 1, 0, 0, 0, 410, 408, 1, 0, 0, 0, 410, 411, 1, 0, 0, 0, 411, 412, 1, 0, 0, 0, 412, 414, 5, 46, 0, 0, 413, 415, 3, 94, 46, 0, 414, 413, 1, 0, 0, 0, 415, 416, 1, 0, 0, 0, 416, 414, 1, 0, 0, 0, 416, 417, 1, 0, 0, 0, 417, 419, 1, 0, 0, 0, 418, 420, 3, 96, 47, 0, 419, 418, 1, 0, 0, 0, 419, 420, 1, 0, 0, 0, 420, 438, 1, 0, 0, 0, 421, 423, 3, 94, 46, 0, 422, 421, 1, 0, 0, 0, 423, 424, 1, 0, 0, 0, 424, 422, 1, 0, 0, 0, 424, 425, 1, 0, 0, 0, 425, 426, 1, 0, 0, 0, 426, 427, 3, 96, 47, 0, 427, 438, 1, 0, 0, 0, 428, 430, 5, 46, 0, 0, 429, 431, 3, 94, 46, 0, 430, 429, 1, 0, 0, 0, 431, 432, 1, 0, 0, 0, 432, 430, 1, 0, 0, 0, 432, 433, 1, 0, 0, 0, 433, 435, 1, 0, 0, 0, 434, 436, 3, 96, 47, 0, 435, 434, 1, 0, 0, 0, 435, 436, 1, 0, 0, 0, 436, 438, 1, 0, 0, 0, 437, 408, 1, 0, 0, 0, 437, 422, 1, 0, 0, 0, 437, 428, 1, 0, 0, 0, 438, 117, 1, 0, 0, 0, 439, 441, 3, 94, 46, 0, 440, 439, 1, 0, 0, 0, 441, 442, 1, 0, 0, 0, 442, 440, 1, 0, 0, 0, 442, 443, 1, 0, 0, 0, 443, 453, 1, 0, 0, 0, 444, 445, 5, 48, 0, 0, 445, 446, 5, 120, 0, 0, 446, 448, 1, 0, 0, 0, 447, 449, 3, 98, 48, 0, 448, 447, 1, 0, 0, 0, 449, 450, 1, 0, 0, 0, 450, 448, 1, 0, 0, 0, 450, 451, 1, 0, 0, 0, 451, 453, 1, 0, 0, 0, 452, 440, 1, 0, 0, 0, 452, 444, 1, 0, 0, 0, 453, 119, 1, 0, 0, 0, 454, 456, 3, 94, 46, 0, 455, 454, 1, 0, 0, 0, 456, 457, 1, 0, 0, 0, 457, 455, 1, 0, 0, 0, 457, 458, 1, 0, 0, 0, 458, 459, 1, 0, 0, 0, 459, 460, 7, 9, 0, 0, 460, 472, 1, 0, 0, 0, 461, 462, 5, 48, 0, 0, 462, 463, 5, 120, 0, 0, 463, 465, 1, 0, 0, 0, 464, 466, 3, 98, 48, 0, 465, 464, 1, 0, 0, 0, 466, 467, 1, 0, 0, 0, 467, 465, 1, 0, 0, 0, 467, 468, 1, 0, 0, 0, 468, 469, 1, 0, 0, 0, 469, 470, 7, 9, 0, 0, 470, 472, 1, 0, 0, 0, 471, 455, 1, 0, 0, 0, 471, 461, 1, 0, 0, 0, 472, 121, 1, 0, 0, 0, 473, 478, 5, 34, 0, 0, 474, 477, 3, 102, 50, 0, 475, 477, 8, 10, 0, 0, 476, 474, 1, 0, 0, 0, 476, 475, 1, 0, 0, 0, 477, 480, 1, 0, 0, 0, 478, 476, 1, 0, 0, 0, 478, 479, 1, 0, 0, 0, 479, 481, 1, 0, 0, 0, 480, 478, 1, 0, 0, 0, 481, 570, 5, 34, 0, 0, 482, 487, 5, 39, 0, 0, 483, 486, 3, 102, 50, 0, 484, 486, 8, 11, 0, 0, 485, 483, 1, 0, 0, 0, 485, 484, 1, 0, 0, 0, 486, 489, 1, 0, 0, 0, 487, 485, 1, 0, 0, 0, 487, 488, 1, 0, 0, 0, 488, 490, 1, 0, 0, 0, 489, 487, 1, 0, 0, 0, 490, 570, 5, 39, 0, 0, 491, 492, 5, 34, 0, 0, 492, 493, 5, 34, 0, 0, 493, 494, 5, 34, 0, 0, 494, 499, 1, 0, 0, 0, 495, 498, 3, 102, 50, 0, 496, 498, 8, 12, 0, 0, 497, 495, 1, 0, 0, 0, 497, 496, 1, 0, 0, 0, 498, 501, 1, 0, 0, 0, 499, 500, 1, 0, 0, 0, 499, 497, 1, 0, 0, 0, 500, 502, 1, 0, 0, 0, 501, 499, 1, 0, 0, 0, 502, 503, 5, 34, 0, 0, 503, 504, 5, 34, 0, 0, 504, 570, 5, 34, 0, 0, 505, 506, 5, 39, 0, 0, 506, 507, 5, 39, 0, 0, 507, 508, 5, 39, 0, 0, 508, 513, 1, 0, 0, 0, 509, 512, 3, 102, 50, 0, 510, 512, 8, 12, 0, 0, 511, 509, 1, 0, 0, 0, 511, 510, 1, 0, 0, 0, 512, 515, 1, 0, 0, 0, 513, 514, 1, 0, 0, 0, 513, 511, 1, 0, 0, 0, 514, 516, 1, 0, 0, 0, 515, 513, 1, 0, 0, 0, 516, 517, 5, 39, 0, 0, 517, 518, 5, 39, 0, 0, 518, 570, 5, 39, 0, 0, 519, 520, 3, 100, 49, 0, 520, 524, 5, 34, 0, 0, 521, 523, 8, 13, 0, 0, 522, 521, 1, 0, 0, 0, 523, 526, 1, 0, 0, 0, 524, 522, 1, 0, 0, 0, 524, 525, 1, 0, 0, 0, 525, 527, 1, 0, 0, 0, 526, 524, 1, 0, 0, 0, 527, 528, 5, 34, 0, 0, 528, 570, 1, 0, 0, 0, 529, 530, 3, 100, 49, 0, 530, 534, 5, 39, 0, 0, 531, 533, 8, 14, 0, 0, 532, 531, 1, 0, 0, 0, 533, 536, 1, 0, 0, 0, 534, 532, 1, 0, 0, 0, 534, 535, 1, 0, 0, 0, 535, 537, 1, 0, 0, 0, 536, 534, 1, 0, 0, 0, 537, 538, 5, 39, 0, 0, 538, 570, 1, 0, 0, 0, 539, 540, 3, 100, 49, 0, 540, 541, 5, 34, 0, 0, 541, 542, 5, 34, 0, 0, 542, 543, 5, 34, 0, 0, 543, 547, 1, 0, 0, 0, 544, 546, 9, 0, 0, 0, 545, 544, 1, 0, 0, 0, 546, 549, 1, 0, 0, 0, 547, 548, 1, 0, 0, 0, 547, 545, 1, 0, 0, 0, 548, 550, 1, 0, 0, 0, 549, 547, 1, 0, 0, 0, 550, 551, 5, 34, 0, 0, 551, 552, 5, 34, 0, 0, 552, 553, 5, 34, 0, 0, 553, 570, 1, 0, 0, 0, 554, 555, 3, 100, 49, 0, 555, 556, 5, 39, 0, 0, 556, 557, 5, 39, 0, 0, 557, 558, 5, 39, 0, 0, 558, 562, 1, 0, 0, 0, 559, 561, 9, 0, 0, 0, 560, 559, 1, 0, 0, 0, 561, 564, 1, 0, 0, 0, 562, 563, 1, 0, 0, 0, 562, 560, 1, 0, 0, 0, 563, 565, 1, 0, 0, 0, 564, 562, 1, 0, 0, 0, 565, 566, 5, 39, 0, 0, 566, 567, 5, 39, 0, 0, 567, 568, 5, 39, 0, 0, 568, 570, 1, 0, 0, 0, 569, 473, 1, 0, 0, 0, 569, 482, 1, 0, 0, 0, 569, 491, 1, 0, 0, 0, 569, 505, 1, 0, 0, 0, 569, 519, 1, 0, 0, 0, 569, 529, 1, 0, 0, 0, 569, 539, 1, 0, 0, 0, 569, 554, 1, 0, 0, 0, 570, 123, 1, 0, 0, 0, 571, 572, 7, 15, 0, 0, 572, 573, 3, 122, 60, 0, 573, 125, 1, 0, 0, 0, 574, 577, 3, 92, 45, 0, 575, 577, 5, 95, 0, 0, 576, 574, 1, 0, 0, 0, 576, 575, 1, 0, 0, 0, 577, 584, 1, 0, 0, 0, 578, 583, 3, 92, 45, 0, 579, 583, 3, 94, 46, 0, 580, 583, 5, 95, 0, 0, 581, 583, 3, 70, 34, 0, 582, 578, 1, 0, 0, 0, 582, 579, 1, 0, 0, 0, 582, 580, 1, 0, 0, 0, 582, 581, 1, 0, 0, 0, 583, 586, 1, 0, 0, 0, 584, 582, 1, 0, 0, 0, 584, 585, 1, 0, 0, 0, 585, 127, 1, 0, 0, 0, 586, 584, 1, 0, 0, 0, 587, 590, 3, 92, 45, 0, 588, 590, 5, 95, 0, 0, 589, 587, 1, 0, 0, 0, 589, 588, 1, 0, 0, 0, 590, 605, 1, 0, 0, 0, 591, 595, 3, 80, 39, 0, 592, 595, 3, 68, 33, 0, 593, 595, 3, 70, 34, 0, 594, 591, 1, 0, 0, 0, 594, 592, 1, 0, 0, 0, 594, 593, 1, 0, 0, 0, 594, 595, 1, 0, 0, 0, 595, 599, 1, 0, 0, 0, 596, 600, 3, 92, 45, 0, 597, 600, 3, 94, 46, 0, 598, 600, 5, 95, 0, 0, 599, 596, 1, 0, 0, 0, 599, 597, 1, 0, 0, 0, 599, 598, 1, 0, 0, 0, 600, 601, 1, 0, 0, 0, 601, 599, 1, 0, 0, 0, 601, 602, 1, 0, 0, 0, 602, 604, 1, 0, 0, 0, 603, 594, 1, 0, 0, 0, 604, 607, 1, 0, 0, 0, 605, 603, 1, 0, 0, 0, 605, 606, 1, 0, 0, 0, 606, 129, 1, 0, 0, 0, 607, 605, 1, 0, 0, 0, 608, 610, 3, 112, 55, 0, 609, 608, 1, 0, 0, 0, 609, 610, 1, 0, 0, 0, 610, 616, 1, 0, 0, 0, 611, 613, 5, 13, 0, 0, 612, 611, 1, 0, 0, 0, 612, 613, 1, 0, 0, 0, 613, 614, 1, 0, 0, 0, 614, 617, 5, 10, 0, 0, 615, 617, 2, 12, 13, 0, 616, 612, 1, 0, 0, 0, 616, 615, 1, 0, 0, 0, 617, 619, 1, 0, 0, 0, 618, 620, 3, 112, 55, 0, 619, 618, 1, 0, 0, 0, 619, 620, 1, 0, 0, 0, 620, 622, 1, 0, 0, 0, 621, 623, 3, 130, 64, 0, 622, 621, 1, 0, 0, 0, 622, 623, 1, 0, 0, 0, 623, 131, 1, 0, 0, 0, 624, 625, 3, 66, 32, 0, 625, 626, 1, 0, 0, 0, 626, 627, 6, 65, 2, 0, 627, 628, 6, 65, 3, 0, 628, 133, 1, 0, 0, 0, 629, 630, 5, 109, 0, 0, 630, 631, 5, 97, 0, 0, 631, 637, 5, 112, 0, 0, 632, 633, 5, 108, 0, 0, 633, 634, 5, 105, 0, 0, 634, 635, 5, 115, 0, 0, 635, 637, 5, 116, 0, 0, 636, 629, 1, 0, 0, 0, 636, 632, 1, 0, 0, 0, 637, 135, 1, 0, 0, 0, 638, 639, 5, 98, 0, 0, 639, 640, 5, 111, 0, 0, 640, 641, 5, 111, 0, 0, 641, 688, 5, 108, 0, 0, 642, 643, 5, 115, 0, 0, 643, 644, 5, 116, 0, 0, 644, 645, 5, 114, 0, 0, 645, 646, 5, 105, 0, 0, 646, 647, 5, 110, 0, 0, 647, 688, 5, 103, 0, 0, 648, 649, 5, 105, 0, 0, 649, 650, 5, 110, 0, 0, 650, 688, 5, 116, 0, 0, 651, 652, 5, 117, 0, 0, 652, 653, 5, 105, 0, 0, 653, 654, 5, 110, 0, 0, 654, 688, 5, 116, 0, 0, 655, 656, 5, 100, 0, 0, 656, 657, 5, 111, 0, 0, 657, 658, 5, 117, 0, 0, 658, 659, 5, 98, 0, 0, 659, 660, 5, 108, 0, 0, 660, 688, 5, 101, 0, 0, 661, 662, 5, 100, 0, 0, 662, 663, 5, 117, 0, 0, 663, 664, 5, 114, 0, 0, 664, 665, 5, 97, 0, 0, 665, 666, 5, 116, 0, 0, 666, 667, 5, 105, 0, 0, 667, 668, 5, 111, 0, 0, 668, 688, 5, 110, 0, 0, 669, 670, 5, 116, 0, 0, 670, 671, 5, 105, 0, 0, 671, 672, 5, 109, 0, 0, 672, 673, 5, 101, 0, 0, 673, 674, 5, 115, 0, 0, 674, 675, 5, 116, 0, 0, 675, 676, 5, 97, 0, 0, 676, 677, 5, 109, 0, 0, 677, 688, 5, 112, 0, 0, 678, 679, 5, 105, 0, 0, 679, 680, 5, 112, 0, 0, 680, 681, 5, 97, 0, 0, 681, 682, 5, 100, 0, 0, 682, 683, 5, 100, 0, 0, 683, 684, 5, 114, 0, 0, 684, 685, 5, 101, 0, 0, 685, 686, 5, 115, 0, 0, 686, 688, 5, 115, 0, 0, 687, 638, 1, 0, 0, 0, 687, 642, 1, 0, 0, 0, 687, 648, 1, 0, 0, 0, 687, 651, 1, 0, 0, 0, 687, 655, 1, 0, 0, 0, 687, 661, 1, 0, 0, 0, 687, 669, 1, 0, 0, 0, 687, 678, 1, 0, 0, 0, 688, 137, 1, 0, 0, 0, 689, 690, 3, 44, 21, 0, 690, 691, 1, 0, 0, 0, 691, 692, 6, 68, 4, 0, 692, 139, 1, 0, 0, 0, 693, 694, 3, 50, 24, 0, 694, 695, 1, 0, 0, 0, 695, 696, 6, 69, 5, 0, 696, 141, 1, 0, 0, 0, 697, 698, 3, 64, 31, 0, 698, 699, 1, 0, 0, 0, 699, 700, 6, 70, 6, 0, 700, 143, 1, 0, 0, 0, 701, 702, 3, 4, 1, 0, 702, 703, 1, 0, 0, 0, 703, 704, 6, 71, 7, 0, 704, 145, 1, 0, 0, 0, 705, 706, 3, 6, 2, 0, 706, 707, 1, 0, 0, 0, 707, 708, 6, 72, 8, 0, 708, 147, 1, 0, 0, 0, 709, 710, 3, 112, 55, 0, 710, 711, 1, 0, 0, 0, 711, 712, 6, 73, 9, 0, 712, 149, 1, 0, 0, 0, 713, 714, 3, 126, 62, 0, 714, 715, 1, 0, 0, 0, 715, 716, 6, 74, 10, 0, 716, 151, 1, 0, 0, 0, 51, 0, 1, 201, 207, 341, 346, 356, 389, 394, 402, 410, 416, 419, 424, 432, 435, 437, 442, 450, 452, 457, 467, 471, 476, 478, 485, 487, 497, 499, 511, 513, 524, 534, 547, 562, 569, 576, 582, 584, 589, 594, 599, 601, 605, 609, 612, 616, 619, 622, 636, 687, 11, 5, 1, 0, 0, 1, 0, 7, 8, 0, 4, 0, 0, 7, 3, 0, 7, 4, 0, 7, 7, 0, 7, 1, 0, 7, 2, 0, 7, 9, 0, 7, 10, 0] \ No newline at end of file +[4, 0, 58, 731, 6, -1, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, 20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25, 2, 26, 7, 26, 2, 27, 7, 27, 2, 28, 7, 28, 2, 29, 7, 29, 2, 30, 7, 30, 2, 31, 7, 31, 2, 32, 7, 32, 2, 33, 7, 33, 2, 34, 7, 34, 2, 35, 7, 35, 2, 36, 7, 36, 2, 37, 7, 37, 2, 38, 7, 38, 2, 39, 7, 39, 2, 40, 7, 40, 2, 41, 7, 41, 2, 42, 7, 42, 2, 43, 7, 43, 2, 44, 7, 44, 2, 45, 7, 45, 2, 46, 7, 46, 2, 47, 7, 47, 2, 48, 7, 48, 2, 49, 7, 49, 2, 50, 7, 50, 2, 51, 7, 51, 2, 52, 7, 52, 2, 53, 7, 53, 2, 54, 7, 54, 2, 55, 7, 55, 2, 56, 7, 56, 2, 57, 7, 57, 2, 58, 7, 58, 2, 59, 7, 59, 2, 60, 7, 60, 2, 61, 7, 61, 2, 62, 7, 62, 2, 63, 7, 63, 2, 64, 7, 64, 2, 65, 7, 65, 2, 66, 7, 66, 2, 67, 7, 67, 2, 68, 7, 68, 2, 69, 7, 69, 2, 70, 7, 70, 2, 71, 7, 71, 2, 72, 7, 72, 2, 73, 7, 73, 2, 74, 7, 74, 2, 75, 7, 75, 1, 0, 1, 0, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 10, 4, 10, 202, 8, 10, 11, 10, 12, 10, 203, 1, 10, 1, 10, 4, 10, 208, 8, 10, 11, 10, 12, 10, 209, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 17, 1, 17, 1, 17, 1, 17, 1, 17, 1, 18, 1, 18, 1, 18, 1, 19, 1, 19, 1, 19, 1, 20, 1, 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, 22, 1, 23, 1, 23, 1, 23, 1, 24, 1, 24, 1, 25, 1, 25, 1, 25, 1, 26, 1, 26, 1, 26, 1, 27, 1, 27, 1, 28, 1, 28, 1, 29, 1, 29, 1, 30, 1, 30, 1, 31, 1, 31, 1, 32, 1, 32, 1, 33, 1, 33, 1, 34, 1, 34, 1, 35, 1, 35, 1, 36, 1, 36, 1, 37, 1, 37, 1, 38, 1, 38, 1, 39, 1, 39, 1, 40, 1, 40, 1, 41, 1, 41, 1, 41, 1, 41, 1, 41, 1, 42, 1, 42, 1, 42, 1, 42, 1, 42, 1, 42, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 1, 44, 1, 44, 1, 45, 1, 45, 1, 46, 1, 46, 1, 47, 1, 47, 3, 47, 344, 8, 47, 1, 47, 4, 47, 347, 8, 47, 11, 47, 12, 47, 348, 1, 48, 1, 48, 1, 49, 1, 49, 1, 50, 1, 50, 1, 50, 1, 50, 3, 50, 359, 8, 50, 1, 51, 1, 51, 1, 51, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 53, 1, 53, 1, 53, 1, 53, 1, 53, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 3, 54, 392, 8, 54, 1, 55, 4, 55, 395, 8, 55, 11, 55, 12, 55, 396, 1, 56, 1, 56, 1, 56, 1, 56, 5, 56, 403, 8, 56, 10, 56, 12, 56, 406, 9, 56, 1, 56, 1, 56, 1, 57, 4, 57, 411, 8, 57, 11, 57, 12, 57, 412, 1, 57, 1, 57, 4, 57, 417, 8, 57, 11, 57, 12, 57, 418, 1, 57, 3, 57, 422, 8, 57, 1, 57, 4, 57, 425, 8, 57, 11, 57, 12, 57, 426, 1, 57, 1, 57, 1, 57, 1, 57, 4, 57, 433, 8, 57, 11, 57, 12, 57, 434, 1, 57, 3, 57, 438, 8, 57, 3, 57, 440, 8, 57, 1, 58, 4, 58, 443, 8, 58, 11, 58, 12, 58, 444, 1, 58, 1, 58, 1, 58, 1, 58, 4, 58, 451, 8, 58, 11, 58, 12, 58, 452, 3, 58, 455, 8, 58, 1, 59, 4, 59, 458, 8, 59, 11, 59, 12, 59, 459, 1, 59, 1, 59, 1, 59, 1, 59, 1, 59, 1, 59, 4, 59, 468, 8, 59, 11, 59, 12, 59, 469, 1, 59, 1, 59, 3, 59, 474, 8, 59, 1, 60, 1, 60, 1, 60, 5, 60, 479, 8, 60, 10, 60, 12, 60, 482, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 488, 8, 60, 10, 60, 12, 60, 491, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 500, 8, 60, 10, 60, 12, 60, 503, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 514, 8, 60, 10, 60, 12, 60, 517, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 525, 8, 60, 10, 60, 12, 60, 528, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 535, 8, 60, 10, 60, 12, 60, 538, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 548, 8, 60, 10, 60, 12, 60, 551, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 563, 8, 60, 10, 60, 12, 60, 566, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 3, 60, 572, 8, 60, 1, 61, 1, 61, 1, 61, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 63, 1, 63, 3, 63, 591, 8, 63, 1, 63, 1, 63, 1, 63, 1, 63, 5, 63, 597, 8, 63, 10, 63, 12, 63, 600, 9, 63, 1, 64, 1, 64, 3, 64, 604, 8, 64, 1, 64, 1, 64, 1, 64, 3, 64, 609, 8, 64, 1, 64, 1, 64, 1, 64, 4, 64, 614, 8, 64, 11, 64, 12, 64, 615, 5, 64, 618, 8, 64, 10, 64, 12, 64, 621, 9, 64, 1, 65, 3, 65, 624, 8, 65, 1, 65, 3, 65, 627, 8, 65, 1, 65, 1, 65, 3, 65, 631, 8, 65, 1, 65, 3, 65, 634, 8, 65, 1, 65, 3, 65, 637, 8, 65, 1, 66, 1, 66, 1, 66, 1, 66, 1, 66, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 3, 67, 651, 8, 67, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 3, 68, 702, 8, 68, 1, 69, 1, 69, 1, 69, 1, 69, 1, 70, 1, 70, 1, 70, 1, 70, 1, 71, 1, 71, 1, 71, 1, 71, 1, 72, 1, 72, 1, 72, 1, 72, 1, 73, 1, 73, 1, 73, 1, 73, 1, 74, 1, 74, 1, 74, 1, 74, 1, 75, 1, 75, 1, 75, 1, 75, 4, 501, 515, 549, 564, 0, 76, 2, 11, 4, 1, 6, 2, 8, 12, 10, 13, 12, 14, 14, 15, 16, 16, 18, 17, 20, 18, 22, 19, 24, 20, 26, 21, 28, 22, 30, 23, 32, 24, 34, 25, 36, 26, 38, 27, 40, 28, 42, 29, 44, 3, 46, 30, 48, 31, 50, 4, 52, 32, 54, 33, 56, 5, 58, 34, 60, 35, 62, 36, 64, 7, 66, 8, 68, 37, 70, 38, 72, 39, 74, 40, 76, 41, 78, 42, 80, 43, 82, 44, 84, 45, 86, 46, 88, 47, 90, 0, 92, 0, 94, 0, 96, 0, 98, 0, 100, 0, 102, 0, 104, 0, 106, 0, 108, 0, 110, 0, 112, 9, 114, 48, 116, 49, 118, 50, 120, 51, 122, 52, 124, 53, 126, 54, 128, 10, 130, 55, 132, 56, 134, 0, 136, 57, 138, 58, 140, 0, 142, 0, 144, 0, 146, 0, 148, 0, 150, 0, 152, 0, 2, 0, 1, 16, 2, 0, 65, 90, 97, 122, 2, 0, 69, 69, 101, 101, 2, 0, 43, 43, 45, 45, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 82, 82, 114, 114, 10, 0, 34, 34, 39, 39, 63, 63, 92, 92, 96, 98, 102, 102, 110, 110, 114, 114, 116, 116, 118, 118, 2, 0, 88, 88, 120, 120, 3, 0, 9, 9, 12, 12, 32, 32, 1, 0, 10, 10, 2, 0, 85, 85, 117, 117, 4, 0, 10, 10, 13, 13, 34, 34, 92, 92, 4, 0, 10, 10, 13, 13, 39, 39, 92, 92, 1, 0, 92, 92, 3, 0, 10, 10, 13, 13, 34, 34, 3, 0, 10, 10, 13, 13, 39, 39, 2, 0, 66, 66, 98, 98, 787, 0, 2, 1, 0, 0, 0, 0, 4, 1, 0, 0, 0, 0, 6, 1, 0, 0, 0, 0, 8, 1, 0, 0, 0, 0, 10, 1, 0, 0, 0, 0, 12, 1, 0, 0, 0, 0, 14, 1, 0, 0, 0, 0, 16, 1, 0, 0, 0, 0, 18, 1, 0, 0, 0, 0, 20, 1, 0, 0, 0, 0, 22, 1, 0, 0, 0, 0, 24, 1, 0, 0, 0, 0, 26, 1, 0, 0, 0, 0, 28, 1, 0, 0, 0, 0, 30, 1, 0, 0, 0, 0, 32, 1, 0, 0, 0, 0, 34, 1, 0, 0, 0, 0, 36, 1, 0, 0, 0, 0, 38, 1, 0, 0, 0, 0, 40, 1, 0, 0, 0, 0, 42, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 46, 1, 0, 0, 0, 0, 48, 1, 0, 0, 0, 0, 50, 1, 0, 0, 0, 0, 52, 1, 0, 0, 0, 0, 54, 1, 0, 0, 0, 0, 56, 1, 0, 0, 0, 0, 58, 1, 0, 0, 0, 0, 60, 1, 0, 0, 0, 0, 62, 1, 0, 0, 0, 0, 64, 1, 0, 0, 0, 0, 66, 1, 0, 0, 0, 0, 68, 1, 0, 0, 0, 0, 70, 1, 0, 0, 0, 0, 72, 1, 0, 0, 0, 0, 74, 1, 0, 0, 0, 0, 76, 1, 0, 0, 0, 0, 78, 1, 0, 0, 0, 0, 80, 1, 0, 0, 0, 0, 82, 1, 0, 0, 0, 0, 84, 1, 0, 0, 0, 0, 86, 1, 0, 0, 0, 0, 88, 1, 0, 0, 0, 0, 112, 1, 0, 0, 0, 0, 114, 1, 0, 0, 0, 0, 116, 1, 0, 0, 0, 0, 118, 1, 0, 0, 0, 0, 120, 1, 0, 0, 0, 0, 122, 1, 0, 0, 0, 0, 124, 1, 0, 0, 0, 0, 126, 1, 0, 0, 0, 0, 128, 1, 0, 0, 0, 0, 130, 1, 0, 0, 0, 0, 132, 1, 0, 0, 0, 1, 134, 1, 0, 0, 0, 1, 136, 1, 0, 0, 0, 1, 138, 1, 0, 0, 0, 1, 140, 1, 0, 0, 0, 1, 142, 1, 0, 0, 0, 1, 144, 1, 0, 0, 0, 1, 146, 1, 0, 0, 0, 1, 148, 1, 0, 0, 0, 1, 150, 1, 0, 0, 0, 1, 152, 1, 0, 0, 0, 2, 154, 1, 0, 0, 0, 4, 156, 1, 0, 0, 0, 6, 158, 1, 0, 0, 0, 8, 160, 1, 0, 0, 0, 10, 164, 1, 0, 0, 0, 12, 167, 1, 0, 0, 0, 14, 175, 1, 0, 0, 0, 16, 180, 1, 0, 0, 0, 18, 187, 1, 0, 0, 0, 20, 193, 1, 0, 0, 0, 22, 201, 1, 0, 0, 0, 24, 211, 1, 0, 0, 0, 26, 218, 1, 0, 0, 0, 28, 223, 1, 0, 0, 0, 30, 235, 1, 0, 0, 0, 32, 245, 1, 0, 0, 0, 34, 254, 1, 0, 0, 0, 36, 261, 1, 0, 0, 0, 38, 266, 1, 0, 0, 0, 40, 269, 1, 0, 0, 0, 42, 272, 1, 0, 0, 0, 44, 275, 1, 0, 0, 0, 46, 277, 1, 0, 0, 0, 48, 280, 1, 0, 0, 0, 50, 283, 1, 0, 0, 0, 52, 285, 1, 0, 0, 0, 54, 288, 1, 0, 0, 0, 56, 291, 1, 0, 0, 0, 58, 293, 1, 0, 0, 0, 60, 295, 1, 0, 0, 0, 62, 297, 1, 0, 0, 0, 64, 299, 1, 0, 0, 0, 66, 301, 1, 0, 0, 0, 68, 303, 1, 0, 0, 0, 70, 305, 1, 0, 0, 0, 72, 307, 1, 0, 0, 0, 74, 309, 1, 0, 0, 0, 76, 311, 1, 0, 0, 0, 78, 313, 1, 0, 0, 0, 80, 315, 1, 0, 0, 0, 82, 317, 1, 0, 0, 0, 84, 319, 1, 0, 0, 0, 86, 324, 1, 0, 0, 0, 88, 330, 1, 0, 0, 0, 90, 335, 1, 0, 0, 0, 92, 337, 1, 0, 0, 0, 94, 339, 1, 0, 0, 0, 96, 341, 1, 0, 0, 0, 98, 350, 1, 0, 0, 0, 100, 352, 1, 0, 0, 0, 102, 358, 1, 0, 0, 0, 104, 360, 1, 0, 0, 0, 106, 363, 1, 0, 0, 0, 108, 368, 1, 0, 0, 0, 110, 391, 1, 0, 0, 0, 112, 394, 1, 0, 0, 0, 114, 398, 1, 0, 0, 0, 116, 439, 1, 0, 0, 0, 118, 454, 1, 0, 0, 0, 120, 473, 1, 0, 0, 0, 122, 571, 1, 0, 0, 0, 124, 573, 1, 0, 0, 0, 126, 576, 1, 0, 0, 0, 128, 590, 1, 0, 0, 0, 130, 603, 1, 0, 0, 0, 132, 623, 1, 0, 0, 0, 134, 638, 1, 0, 0, 0, 136, 650, 1, 0, 0, 0, 138, 701, 1, 0, 0, 0, 140, 703, 1, 0, 0, 0, 142, 707, 1, 0, 0, 0, 144, 711, 1, 0, 0, 0, 146, 715, 1, 0, 0, 0, 148, 719, 1, 0, 0, 0, 150, 723, 1, 0, 0, 0, 152, 727, 1, 0, 0, 0, 154, 155, 5, 35, 0, 0, 155, 3, 1, 0, 0, 0, 156, 157, 5, 58, 0, 0, 157, 5, 1, 0, 0, 0, 158, 159, 5, 44, 0, 0, 159, 7, 1, 0, 0, 0, 160, 161, 5, 97, 0, 0, 161, 162, 5, 110, 0, 0, 162, 163, 5, 100, 0, 0, 163, 9, 1, 0, 0, 0, 164, 165, 5, 111, 0, 0, 165, 166, 5, 114, 0, 0, 166, 11, 1, 0, 0, 0, 167, 168, 5, 98, 0, 0, 168, 169, 5, 117, 0, 0, 169, 170, 5, 116, 0, 0, 170, 171, 5, 32, 0, 0, 171, 172, 5, 110, 0, 0, 172, 173, 5, 111, 0, 0, 173, 174, 5, 116, 0, 0, 174, 13, 1, 0, 0, 0, 175, 176, 5, 102, 0, 0, 176, 177, 5, 114, 0, 0, 177, 178, 5, 111, 0, 0, 178, 179, 5, 109, 0, 0, 179, 15, 1, 0, 0, 0, 180, 181, 5, 109, 0, 0, 181, 182, 5, 111, 0, 0, 182, 183, 5, 100, 0, 0, 183, 184, 5, 117, 0, 0, 184, 185, 5, 108, 0, 0, 185, 186, 5, 101, 0, 0, 186, 17, 1, 0, 0, 0, 187, 188, 5, 109, 0, 0, 188, 189, 5, 111, 0, 0, 189, 190, 5, 100, 0, 0, 190, 191, 5, 101, 0, 0, 191, 192, 5, 108, 0, 0, 192, 19, 1, 0, 0, 0, 193, 194, 5, 115, 0, 0, 194, 195, 5, 99, 0, 0, 195, 196, 5, 104, 0, 0, 196, 197, 5, 101, 0, 0, 197, 198, 5, 109, 0, 0, 198, 199, 5, 97, 0, 0, 199, 21, 1, 0, 0, 0, 200, 202, 3, 94, 46, 0, 201, 200, 1, 0, 0, 0, 202, 203, 1, 0, 0, 0, 203, 201, 1, 0, 0, 0, 203, 204, 1, 0, 0, 0, 204, 205, 1, 0, 0, 0, 205, 207, 5, 46, 0, 0, 206, 208, 3, 94, 46, 0, 207, 206, 1, 0, 0, 0, 208, 209, 1, 0, 0, 0, 209, 207, 1, 0, 0, 0, 209, 210, 1, 0, 0, 0, 210, 23, 1, 0, 0, 0, 211, 212, 5, 101, 0, 0, 212, 213, 5, 120, 0, 0, 213, 214, 5, 116, 0, 0, 214, 215, 5, 101, 0, 0, 215, 216, 5, 110, 0, 0, 216, 217, 5, 100, 0, 0, 217, 25, 1, 0, 0, 0, 218, 219, 5, 116, 0, 0, 219, 220, 5, 121, 0, 0, 220, 221, 5, 112, 0, 0, 221, 222, 5, 101, 0, 0, 222, 27, 1, 0, 0, 0, 223, 224, 5, 99, 0, 0, 224, 225, 5, 111, 0, 0, 225, 226, 5, 110, 0, 0, 226, 227, 5, 100, 0, 0, 227, 228, 5, 105, 0, 0, 228, 229, 5, 116, 0, 0, 229, 230, 5, 105, 0, 0, 230, 231, 5, 111, 0, 0, 231, 232, 5, 110, 0, 0, 232, 233, 1, 0, 0, 0, 233, 234, 6, 13, 0, 0, 234, 29, 1, 0, 0, 0, 235, 236, 5, 114, 0, 0, 236, 237, 5, 101, 0, 0, 237, 238, 5, 108, 0, 0, 238, 239, 5, 97, 0, 0, 239, 240, 5, 116, 0, 0, 240, 241, 5, 105, 0, 0, 241, 242, 5, 111, 0, 0, 242, 243, 5, 110, 0, 0, 243, 244, 5, 115, 0, 0, 244, 31, 1, 0, 0, 0, 245, 246, 5, 114, 0, 0, 246, 247, 5, 101, 0, 0, 247, 248, 5, 108, 0, 0, 248, 249, 5, 97, 0, 0, 249, 250, 5, 116, 0, 0, 250, 251, 5, 105, 0, 0, 251, 252, 5, 111, 0, 0, 252, 253, 5, 110, 0, 0, 253, 33, 1, 0, 0, 0, 254, 255, 5, 100, 0, 0, 255, 256, 5, 101, 0, 0, 256, 257, 5, 102, 0, 0, 257, 258, 5, 105, 0, 0, 258, 259, 5, 110, 0, 0, 259, 260, 5, 101, 0, 0, 260, 35, 1, 0, 0, 0, 261, 262, 5, 119, 0, 0, 262, 263, 5, 105, 0, 0, 263, 264, 5, 116, 0, 0, 264, 265, 5, 104, 0, 0, 265, 37, 1, 0, 0, 0, 266, 267, 5, 61, 0, 0, 267, 268, 5, 61, 0, 0, 268, 39, 1, 0, 0, 0, 269, 270, 5, 33, 0, 0, 270, 271, 5, 61, 0, 0, 271, 41, 1, 0, 0, 0, 272, 273, 5, 105, 0, 0, 273, 274, 5, 110, 0, 0, 274, 43, 1, 0, 0, 0, 275, 276, 5, 60, 0, 0, 276, 45, 1, 0, 0, 0, 277, 278, 5, 60, 0, 0, 278, 279, 5, 61, 0, 0, 279, 47, 1, 0, 0, 0, 280, 281, 5, 62, 0, 0, 281, 282, 5, 61, 0, 0, 282, 49, 1, 0, 0, 0, 283, 284, 5, 62, 0, 0, 284, 51, 1, 0, 0, 0, 285, 286, 5, 38, 0, 0, 286, 287, 5, 38, 0, 0, 287, 53, 1, 0, 0, 0, 288, 289, 5, 124, 0, 0, 289, 290, 5, 124, 0, 0, 290, 55, 1, 0, 0, 0, 291, 292, 5, 91, 0, 0, 292, 57, 1, 0, 0, 0, 293, 294, 5, 93, 0, 0, 294, 59, 1, 0, 0, 0, 295, 296, 5, 123, 0, 0, 296, 61, 1, 0, 0, 0, 297, 298, 5, 125, 0, 0, 298, 63, 1, 0, 0, 0, 299, 300, 5, 40, 0, 0, 300, 65, 1, 0, 0, 0, 301, 302, 5, 41, 0, 0, 302, 67, 1, 0, 0, 0, 303, 304, 5, 46, 0, 0, 304, 69, 1, 0, 0, 0, 305, 306, 5, 45, 0, 0, 306, 71, 1, 0, 0, 0, 307, 308, 5, 33, 0, 0, 308, 73, 1, 0, 0, 0, 309, 310, 5, 63, 0, 0, 310, 75, 1, 0, 0, 0, 311, 312, 5, 43, 0, 0, 312, 77, 1, 0, 0, 0, 313, 314, 5, 42, 0, 0, 314, 79, 1, 0, 0, 0, 315, 316, 5, 47, 0, 0, 316, 81, 1, 0, 0, 0, 317, 318, 5, 37, 0, 0, 318, 83, 1, 0, 0, 0, 319, 320, 5, 116, 0, 0, 320, 321, 5, 114, 0, 0, 321, 322, 5, 117, 0, 0, 322, 323, 5, 101, 0, 0, 323, 85, 1, 0, 0, 0, 324, 325, 5, 102, 0, 0, 325, 326, 5, 97, 0, 0, 326, 327, 5, 108, 0, 0, 327, 328, 5, 115, 0, 0, 328, 329, 5, 101, 0, 0, 329, 87, 1, 0, 0, 0, 330, 331, 5, 110, 0, 0, 331, 332, 5, 117, 0, 0, 332, 333, 5, 108, 0, 0, 333, 334, 5, 108, 0, 0, 334, 89, 1, 0, 0, 0, 335, 336, 5, 92, 0, 0, 336, 91, 1, 0, 0, 0, 337, 338, 7, 0, 0, 0, 338, 93, 1, 0, 0, 0, 339, 340, 2, 48, 57, 0, 340, 95, 1, 0, 0, 0, 341, 343, 7, 1, 0, 0, 342, 344, 7, 2, 0, 0, 343, 342, 1, 0, 0, 0, 343, 344, 1, 0, 0, 0, 344, 346, 1, 0, 0, 0, 345, 347, 3, 94, 46, 0, 346, 345, 1, 0, 0, 0, 347, 348, 1, 0, 0, 0, 348, 346, 1, 0, 0, 0, 348, 349, 1, 0, 0, 0, 349, 97, 1, 0, 0, 0, 350, 351, 7, 3, 0, 0, 351, 99, 1, 0, 0, 0, 352, 353, 7, 4, 0, 0, 353, 101, 1, 0, 0, 0, 354, 359, 3, 104, 51, 0, 355, 359, 3, 108, 53, 0, 356, 359, 3, 110, 54, 0, 357, 359, 3, 106, 52, 0, 358, 354, 1, 0, 0, 0, 358, 355, 1, 0, 0, 0, 358, 356, 1, 0, 0, 0, 358, 357, 1, 0, 0, 0, 359, 103, 1, 0, 0, 0, 360, 361, 3, 90, 44, 0, 361, 362, 7, 5, 0, 0, 362, 105, 1, 0, 0, 0, 363, 364, 3, 90, 44, 0, 364, 365, 2, 48, 51, 0, 365, 366, 2, 48, 55, 0, 366, 367, 2, 48, 55, 0, 367, 107, 1, 0, 0, 0, 368, 369, 3, 90, 44, 0, 369, 370, 7, 6, 0, 0, 370, 371, 3, 98, 48, 0, 371, 372, 3, 98, 48, 0, 372, 109, 1, 0, 0, 0, 373, 374, 3, 90, 44, 0, 374, 375, 5, 117, 0, 0, 375, 376, 3, 98, 48, 0, 376, 377, 3, 98, 48, 0, 377, 378, 3, 98, 48, 0, 378, 379, 3, 98, 48, 0, 379, 392, 1, 0, 0, 0, 380, 381, 3, 90, 44, 0, 381, 382, 5, 85, 0, 0, 382, 383, 3, 98, 48, 0, 383, 384, 3, 98, 48, 0, 384, 385, 3, 98, 48, 0, 385, 386, 3, 98, 48, 0, 386, 387, 3, 98, 48, 0, 387, 388, 3, 98, 48, 0, 388, 389, 3, 98, 48, 0, 389, 390, 3, 98, 48, 0, 390, 392, 1, 0, 0, 0, 391, 373, 1, 0, 0, 0, 391, 380, 1, 0, 0, 0, 392, 111, 1, 0, 0, 0, 393, 395, 7, 7, 0, 0, 394, 393, 1, 0, 0, 0, 395, 396, 1, 0, 0, 0, 396, 394, 1, 0, 0, 0, 396, 397, 1, 0, 0, 0, 397, 113, 1, 0, 0, 0, 398, 399, 5, 47, 0, 0, 399, 400, 5, 47, 0, 0, 400, 404, 1, 0, 0, 0, 401, 403, 8, 8, 0, 0, 402, 401, 1, 0, 0, 0, 403, 406, 1, 0, 0, 0, 404, 402, 1, 0, 0, 0, 404, 405, 1, 0, 0, 0, 405, 407, 1, 0, 0, 0, 406, 404, 1, 0, 0, 0, 407, 408, 6, 56, 1, 0, 408, 115, 1, 0, 0, 0, 409, 411, 3, 94, 46, 0, 410, 409, 1, 0, 0, 0, 411, 412, 1, 0, 0, 0, 412, 410, 1, 0, 0, 0, 412, 413, 1, 0, 0, 0, 413, 414, 1, 0, 0, 0, 414, 416, 5, 46, 0, 0, 415, 417, 3, 94, 46, 0, 416, 415, 1, 0, 0, 0, 417, 418, 1, 0, 0, 0, 418, 416, 1, 0, 0, 0, 418, 419, 1, 0, 0, 0, 419, 421, 1, 0, 0, 0, 420, 422, 3, 96, 47, 0, 421, 420, 1, 0, 0, 0, 421, 422, 1, 0, 0, 0, 422, 440, 1, 0, 0, 0, 423, 425, 3, 94, 46, 0, 424, 423, 1, 0, 0, 0, 425, 426, 1, 0, 0, 0, 426, 424, 1, 0, 0, 0, 426, 427, 1, 0, 0, 0, 427, 428, 1, 0, 0, 0, 428, 429, 3, 96, 47, 0, 429, 440, 1, 0, 0, 0, 430, 432, 5, 46, 0, 0, 431, 433, 3, 94, 46, 0, 432, 431, 1, 0, 0, 0, 433, 434, 1, 0, 0, 0, 434, 432, 1, 0, 0, 0, 434, 435, 1, 0, 0, 0, 435, 437, 1, 0, 0, 0, 436, 438, 3, 96, 47, 0, 437, 436, 1, 0, 0, 0, 437, 438, 1, 0, 0, 0, 438, 440, 1, 0, 0, 0, 439, 410, 1, 0, 0, 0, 439, 424, 1, 0, 0, 0, 439, 430, 1, 0, 0, 0, 440, 117, 1, 0, 0, 0, 441, 443, 3, 94, 46, 0, 442, 441, 1, 0, 0, 0, 443, 444, 1, 0, 0, 0, 444, 442, 1, 0, 0, 0, 444, 445, 1, 0, 0, 0, 445, 455, 1, 0, 0, 0, 446, 447, 5, 48, 0, 0, 447, 448, 5, 120, 0, 0, 448, 450, 1, 0, 0, 0, 449, 451, 3, 98, 48, 0, 450, 449, 1, 0, 0, 0, 451, 452, 1, 0, 0, 0, 452, 450, 1, 0, 0, 0, 452, 453, 1, 0, 0, 0, 453, 455, 1, 0, 0, 0, 454, 442, 1, 0, 0, 0, 454, 446, 1, 0, 0, 0, 455, 119, 1, 0, 0, 0, 456, 458, 3, 94, 46, 0, 457, 456, 1, 0, 0, 0, 458, 459, 1, 0, 0, 0, 459, 457, 1, 0, 0, 0, 459, 460, 1, 0, 0, 0, 460, 461, 1, 0, 0, 0, 461, 462, 7, 9, 0, 0, 462, 474, 1, 0, 0, 0, 463, 464, 5, 48, 0, 0, 464, 465, 5, 120, 0, 0, 465, 467, 1, 0, 0, 0, 466, 468, 3, 98, 48, 0, 467, 466, 1, 0, 0, 0, 468, 469, 1, 0, 0, 0, 469, 467, 1, 0, 0, 0, 469, 470, 1, 0, 0, 0, 470, 471, 1, 0, 0, 0, 471, 472, 7, 9, 0, 0, 472, 474, 1, 0, 0, 0, 473, 457, 1, 0, 0, 0, 473, 463, 1, 0, 0, 0, 474, 121, 1, 0, 0, 0, 475, 480, 5, 34, 0, 0, 476, 479, 3, 102, 50, 0, 477, 479, 8, 10, 0, 0, 478, 476, 1, 0, 0, 0, 478, 477, 1, 0, 0, 0, 479, 482, 1, 0, 0, 0, 480, 478, 1, 0, 0, 0, 480, 481, 1, 0, 0, 0, 481, 483, 1, 0, 0, 0, 482, 480, 1, 0, 0, 0, 483, 572, 5, 34, 0, 0, 484, 489, 5, 39, 0, 0, 485, 488, 3, 102, 50, 0, 486, 488, 8, 11, 0, 0, 487, 485, 1, 0, 0, 0, 487, 486, 1, 0, 0, 0, 488, 491, 1, 0, 0, 0, 489, 487, 1, 0, 0, 0, 489, 490, 1, 0, 0, 0, 490, 492, 1, 0, 0, 0, 491, 489, 1, 0, 0, 0, 492, 572, 5, 39, 0, 0, 493, 494, 5, 34, 0, 0, 494, 495, 5, 34, 0, 0, 495, 496, 5, 34, 0, 0, 496, 501, 1, 0, 0, 0, 497, 500, 3, 102, 50, 0, 498, 500, 8, 12, 0, 0, 499, 497, 1, 0, 0, 0, 499, 498, 1, 0, 0, 0, 500, 503, 1, 0, 0, 0, 501, 502, 1, 0, 0, 0, 501, 499, 1, 0, 0, 0, 502, 504, 1, 0, 0, 0, 503, 501, 1, 0, 0, 0, 504, 505, 5, 34, 0, 0, 505, 506, 5, 34, 0, 0, 506, 572, 5, 34, 0, 0, 507, 508, 5, 39, 0, 0, 508, 509, 5, 39, 0, 0, 509, 510, 5, 39, 0, 0, 510, 515, 1, 0, 0, 0, 511, 514, 3, 102, 50, 0, 512, 514, 8, 12, 0, 0, 513, 511, 1, 0, 0, 0, 513, 512, 1, 0, 0, 0, 514, 517, 1, 0, 0, 0, 515, 516, 1, 0, 0, 0, 515, 513, 1, 0, 0, 0, 516, 518, 1, 0, 0, 0, 517, 515, 1, 0, 0, 0, 518, 519, 5, 39, 0, 0, 519, 520, 5, 39, 0, 0, 520, 572, 5, 39, 0, 0, 521, 522, 3, 100, 49, 0, 522, 526, 5, 34, 0, 0, 523, 525, 8, 13, 0, 0, 524, 523, 1, 0, 0, 0, 525, 528, 1, 0, 0, 0, 526, 524, 1, 0, 0, 0, 526, 527, 1, 0, 0, 0, 527, 529, 1, 0, 0, 0, 528, 526, 1, 0, 0, 0, 529, 530, 5, 34, 0, 0, 530, 572, 1, 0, 0, 0, 531, 532, 3, 100, 49, 0, 532, 536, 5, 39, 0, 0, 533, 535, 8, 14, 0, 0, 534, 533, 1, 0, 0, 0, 535, 538, 1, 0, 0, 0, 536, 534, 1, 0, 0, 0, 536, 537, 1, 0, 0, 0, 537, 539, 1, 0, 0, 0, 538, 536, 1, 0, 0, 0, 539, 540, 5, 39, 0, 0, 540, 572, 1, 0, 0, 0, 541, 542, 3, 100, 49, 0, 542, 543, 5, 34, 0, 0, 543, 544, 5, 34, 0, 0, 544, 545, 5, 34, 0, 0, 545, 549, 1, 0, 0, 0, 546, 548, 9, 0, 0, 0, 547, 546, 1, 0, 0, 0, 548, 551, 1, 0, 0, 0, 549, 550, 1, 0, 0, 0, 549, 547, 1, 0, 0, 0, 550, 552, 1, 0, 0, 0, 551, 549, 1, 0, 0, 0, 552, 553, 5, 34, 0, 0, 553, 554, 5, 34, 0, 0, 554, 555, 5, 34, 0, 0, 555, 572, 1, 0, 0, 0, 556, 557, 3, 100, 49, 0, 557, 558, 5, 39, 0, 0, 558, 559, 5, 39, 0, 0, 559, 560, 5, 39, 0, 0, 560, 564, 1, 0, 0, 0, 561, 563, 9, 0, 0, 0, 562, 561, 1, 0, 0, 0, 563, 566, 1, 0, 0, 0, 564, 565, 1, 0, 0, 0, 564, 562, 1, 0, 0, 0, 565, 567, 1, 0, 0, 0, 566, 564, 1, 0, 0, 0, 567, 568, 5, 39, 0, 0, 568, 569, 5, 39, 0, 0, 569, 570, 5, 39, 0, 0, 570, 572, 1, 0, 0, 0, 571, 475, 1, 0, 0, 0, 571, 484, 1, 0, 0, 0, 571, 493, 1, 0, 0, 0, 571, 507, 1, 0, 0, 0, 571, 521, 1, 0, 0, 0, 571, 531, 1, 0, 0, 0, 571, 541, 1, 0, 0, 0, 571, 556, 1, 0, 0, 0, 572, 123, 1, 0, 0, 0, 573, 574, 7, 15, 0, 0, 574, 575, 3, 122, 60, 0, 575, 125, 1, 0, 0, 0, 576, 577, 5, 36, 0, 0, 577, 578, 5, 101, 0, 0, 578, 579, 5, 120, 0, 0, 579, 580, 5, 112, 0, 0, 580, 581, 5, 114, 0, 0, 581, 582, 5, 101, 0, 0, 582, 583, 5, 115, 0, 0, 583, 584, 5, 115, 0, 0, 584, 585, 5, 105, 0, 0, 585, 586, 5, 111, 0, 0, 586, 587, 5, 110, 0, 0, 587, 127, 1, 0, 0, 0, 588, 591, 3, 92, 45, 0, 589, 591, 5, 95, 0, 0, 590, 588, 1, 0, 0, 0, 590, 589, 1, 0, 0, 0, 591, 598, 1, 0, 0, 0, 592, 597, 3, 92, 45, 0, 593, 597, 3, 94, 46, 0, 594, 597, 5, 95, 0, 0, 595, 597, 3, 70, 34, 0, 596, 592, 1, 0, 0, 0, 596, 593, 1, 0, 0, 0, 596, 594, 1, 0, 0, 0, 596, 595, 1, 0, 0, 0, 597, 600, 1, 0, 0, 0, 598, 596, 1, 0, 0, 0, 598, 599, 1, 0, 0, 0, 599, 129, 1, 0, 0, 0, 600, 598, 1, 0, 0, 0, 601, 604, 3, 92, 45, 0, 602, 604, 5, 95, 0, 0, 603, 601, 1, 0, 0, 0, 603, 602, 1, 0, 0, 0, 604, 619, 1, 0, 0, 0, 605, 609, 3, 80, 39, 0, 606, 609, 3, 68, 33, 0, 607, 609, 3, 70, 34, 0, 608, 605, 1, 0, 0, 0, 608, 606, 1, 0, 0, 0, 608, 607, 1, 0, 0, 0, 608, 609, 1, 0, 0, 0, 609, 613, 1, 0, 0, 0, 610, 614, 3, 92, 45, 0, 611, 614, 3, 94, 46, 0, 612, 614, 5, 95, 0, 0, 613, 610, 1, 0, 0, 0, 613, 611, 1, 0, 0, 0, 613, 612, 1, 0, 0, 0, 614, 615, 1, 0, 0, 0, 615, 613, 1, 0, 0, 0, 615, 616, 1, 0, 0, 0, 616, 618, 1, 0, 0, 0, 617, 608, 1, 0, 0, 0, 618, 621, 1, 0, 0, 0, 619, 617, 1, 0, 0, 0, 619, 620, 1, 0, 0, 0, 620, 131, 1, 0, 0, 0, 621, 619, 1, 0, 0, 0, 622, 624, 3, 112, 55, 0, 623, 622, 1, 0, 0, 0, 623, 624, 1, 0, 0, 0, 624, 630, 1, 0, 0, 0, 625, 627, 5, 13, 0, 0, 626, 625, 1, 0, 0, 0, 626, 627, 1, 0, 0, 0, 627, 628, 1, 0, 0, 0, 628, 631, 5, 10, 0, 0, 629, 631, 2, 12, 13, 0, 630, 626, 1, 0, 0, 0, 630, 629, 1, 0, 0, 0, 631, 633, 1, 0, 0, 0, 632, 634, 3, 112, 55, 0, 633, 632, 1, 0, 0, 0, 633, 634, 1, 0, 0, 0, 634, 636, 1, 0, 0, 0, 635, 637, 3, 132, 65, 0, 636, 635, 1, 0, 0, 0, 636, 637, 1, 0, 0, 0, 637, 133, 1, 0, 0, 0, 638, 639, 3, 66, 32, 0, 639, 640, 1, 0, 0, 0, 640, 641, 6, 66, 2, 0, 641, 642, 6, 66, 3, 0, 642, 135, 1, 0, 0, 0, 643, 644, 5, 109, 0, 0, 644, 645, 5, 97, 0, 0, 645, 651, 5, 112, 0, 0, 646, 647, 5, 108, 0, 0, 647, 648, 5, 105, 0, 0, 648, 649, 5, 115, 0, 0, 649, 651, 5, 116, 0, 0, 650, 643, 1, 0, 0, 0, 650, 646, 1, 0, 0, 0, 651, 137, 1, 0, 0, 0, 652, 653, 5, 98, 0, 0, 653, 654, 5, 111, 0, 0, 654, 655, 5, 111, 0, 0, 655, 702, 5, 108, 0, 0, 656, 657, 5, 115, 0, 0, 657, 658, 5, 116, 0, 0, 658, 659, 5, 114, 0, 0, 659, 660, 5, 105, 0, 0, 660, 661, 5, 110, 0, 0, 661, 702, 5, 103, 0, 0, 662, 663, 5, 105, 0, 0, 663, 664, 5, 110, 0, 0, 664, 702, 5, 116, 0, 0, 665, 666, 5, 117, 0, 0, 666, 667, 5, 105, 0, 0, 667, 668, 5, 110, 0, 0, 668, 702, 5, 116, 0, 0, 669, 670, 5, 100, 0, 0, 670, 671, 5, 111, 0, 0, 671, 672, 5, 117, 0, 0, 672, 673, 5, 98, 0, 0, 673, 674, 5, 108, 0, 0, 674, 702, 5, 101, 0, 0, 675, 676, 5, 100, 0, 0, 676, 677, 5, 117, 0, 0, 677, 678, 5, 114, 0, 0, 678, 679, 5, 97, 0, 0, 679, 680, 5, 116, 0, 0, 680, 681, 5, 105, 0, 0, 681, 682, 5, 111, 0, 0, 682, 702, 5, 110, 0, 0, 683, 684, 5, 116, 0, 0, 684, 685, 5, 105, 0, 0, 685, 686, 5, 109, 0, 0, 686, 687, 5, 101, 0, 0, 687, 688, 5, 115, 0, 0, 688, 689, 5, 116, 0, 0, 689, 690, 5, 97, 0, 0, 690, 691, 5, 109, 0, 0, 691, 702, 5, 112, 0, 0, 692, 693, 5, 105, 0, 0, 693, 694, 5, 112, 0, 0, 694, 695, 5, 97, 0, 0, 695, 696, 5, 100, 0, 0, 696, 697, 5, 100, 0, 0, 697, 698, 5, 114, 0, 0, 698, 699, 5, 101, 0, 0, 699, 700, 5, 115, 0, 0, 700, 702, 5, 115, 0, 0, 701, 652, 1, 0, 0, 0, 701, 656, 1, 0, 0, 0, 701, 662, 1, 0, 0, 0, 701, 665, 1, 0, 0, 0, 701, 669, 1, 0, 0, 0, 701, 675, 1, 0, 0, 0, 701, 683, 1, 0, 0, 0, 701, 692, 1, 0, 0, 0, 702, 139, 1, 0, 0, 0, 703, 704, 3, 44, 21, 0, 704, 705, 1, 0, 0, 0, 705, 706, 6, 69, 4, 0, 706, 141, 1, 0, 0, 0, 707, 708, 3, 50, 24, 0, 708, 709, 1, 0, 0, 0, 709, 710, 6, 70, 5, 0, 710, 143, 1, 0, 0, 0, 711, 712, 3, 64, 31, 0, 712, 713, 1, 0, 0, 0, 713, 714, 6, 71, 6, 0, 714, 145, 1, 0, 0, 0, 715, 716, 3, 4, 1, 0, 716, 717, 1, 0, 0, 0, 717, 718, 6, 72, 7, 0, 718, 147, 1, 0, 0, 0, 719, 720, 3, 6, 2, 0, 720, 721, 1, 0, 0, 0, 721, 722, 6, 73, 8, 0, 722, 149, 1, 0, 0, 0, 723, 724, 3, 112, 55, 0, 724, 725, 1, 0, 0, 0, 725, 726, 6, 74, 9, 0, 726, 151, 1, 0, 0, 0, 727, 728, 3, 128, 63, 0, 728, 729, 1, 0, 0, 0, 729, 730, 6, 75, 10, 0, 730, 153, 1, 0, 0, 0, 51, 0, 1, 203, 209, 343, 348, 358, 391, 396, 404, 412, 418, 421, 426, 434, 437, 439, 444, 452, 454, 459, 469, 473, 478, 480, 487, 489, 499, 501, 513, 515, 526, 536, 549, 564, 571, 590, 596, 598, 603, 608, 613, 615, 619, 623, 626, 630, 633, 636, 650, 701, 11, 5, 1, 0, 0, 1, 0, 7, 8, 0, 4, 0, 0, 7, 3, 0, 7, 4, 0, 7, 7, 0, 7, 1, 0, 7, 2, 0, 7, 9, 0, 7, 10, 0] \ No newline at end of file diff --git a/vendor/github.com/openfga/language/pkg/go/gen/OpenFGALexer.tokens b/vendor/github.com/openfga/language/pkg/go/gen/OpenFGALexer.tokens index 512cec30b6..b2523ac809 100644 --- a/vendor/github.com/openfga/language/pkg/go/gen/OpenFGALexer.tokens +++ b/vendor/github.com/openfga/language/pkg/go/gen/OpenFGALexer.tokens @@ -51,10 +51,11 @@ NUM_INT=50 NUM_UINT=51 STRING=52 BYTES=53 -EXTENDED_IDENTIFIER=54 -NEWLINE=55 -CONDITION_PARAM_CONTAINER=56 -CONDITION_PARAM_TYPE=57 +DOLLAR_EXPRESSION=54 +EXTENDED_IDENTIFIER=55 +NEWLINE=56 +CONDITION_PARAM_CONTAINER=57 +CONDITION_PARAM_TYPE=58 '#'=11 ':'=1 ','=2 @@ -98,3 +99,4 @@ CONDITION_PARAM_TYPE=57 'true'=45 'false'=46 'null'=47 +'$expression'=54 diff --git a/vendor/github.com/openfga/language/pkg/go/gen/OpenFGAParser.interp b/vendor/github.com/openfga/language/pkg/go/gen/OpenFGAParser.interp index 56431d9752..fffd38475f 100644 --- a/vendor/github.com/openfga/language/pkg/go/gen/OpenFGAParser.interp +++ b/vendor/github.com/openfga/language/pkg/go/gen/OpenFGAParser.interp @@ -53,6 +53,7 @@ null null null null +'$expression' null null null @@ -113,6 +114,7 @@ NUM_INT NUM_UINT STRING BYTES +DOLLAR_EXPRESSION EXTENDED_IDENTIFIER NEWLINE CONDITION_PARAM_CONTAINER @@ -149,4 +151,4 @@ conditionExpression atn: -[4, 1, 57, 392, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, 20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25, 2, 26, 7, 26, 1, 0, 3, 0, 56, 8, 0, 1, 0, 3, 0, 59, 8, 0, 1, 0, 1, 0, 3, 0, 63, 8, 0, 1, 0, 3, 0, 66, 8, 0, 1, 0, 1, 0, 3, 0, 70, 8, 0, 1, 0, 1, 0, 3, 0, 74, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 3, 1, 81, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 89, 8, 1, 1, 2, 1, 2, 1, 2, 3, 2, 94, 8, 2, 1, 2, 1, 2, 1, 2, 1, 2, 3, 2, 100, 8, 2, 1, 3, 5, 3, 103, 8, 3, 10, 3, 12, 3, 106, 9, 3, 1, 4, 1, 4, 3, 4, 110, 8, 4, 1, 4, 1, 4, 1, 4, 3, 4, 115, 8, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 4, 4, 123, 8, 4, 11, 4, 12, 4, 124, 3, 4, 127, 8, 4, 1, 5, 1, 5, 3, 5, 131, 8, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 3, 5, 138, 8, 5, 1, 5, 1, 5, 3, 5, 142, 8, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 3, 7, 151, 8, 7, 1, 7, 3, 7, 154, 8, 7, 1, 8, 1, 8, 3, 8, 158, 8, 8, 1, 8, 3, 8, 161, 8, 8, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 3, 9, 168, 8, 9, 4, 9, 170, 8, 9, 11, 9, 12, 9, 171, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 3, 9, 179, 8, 9, 4, 9, 181, 8, 9, 11, 9, 12, 9, 182, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 3, 9, 190, 8, 9, 3, 9, 192, 8, 9, 1, 10, 1, 10, 1, 11, 1, 11, 5, 11, 198, 8, 11, 10, 11, 12, 11, 201, 9, 11, 1, 11, 1, 11, 3, 11, 205, 8, 11, 1, 11, 5, 11, 208, 8, 11, 10, 11, 12, 11, 211, 9, 11, 1, 11, 1, 11, 1, 12, 1, 12, 5, 12, 217, 8, 12, 10, 12, 12, 12, 220, 9, 12, 1, 12, 1, 12, 3, 12, 224, 8, 12, 1, 12, 5, 12, 227, 8, 12, 10, 12, 12, 12, 230, 9, 12, 1, 12, 1, 12, 1, 13, 1, 13, 3, 13, 236, 8, 13, 1, 13, 1, 13, 3, 13, 240, 8, 13, 1, 13, 1, 13, 3, 13, 244, 8, 13, 1, 13, 1, 13, 3, 13, 248, 8, 13, 5, 13, 250, 8, 13, 10, 13, 12, 13, 253, 9, 13, 1, 13, 1, 13, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 3, 14, 262, 8, 14, 1, 15, 3, 15, 265, 8, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 3, 15, 274, 8, 15, 1, 15, 3, 15, 277, 8, 15, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 3, 16, 284, 8, 16, 1, 17, 5, 17, 287, 8, 17, 10, 17, 12, 17, 290, 9, 17, 1, 18, 1, 18, 3, 18, 294, 8, 18, 1, 18, 1, 18, 1, 18, 1, 18, 1, 18, 3, 18, 301, 8, 18, 1, 18, 1, 18, 3, 18, 305, 8, 18, 1, 18, 1, 18, 3, 18, 309, 8, 18, 1, 18, 1, 18, 3, 18, 313, 8, 18, 1, 18, 1, 18, 3, 18, 317, 8, 18, 5, 18, 319, 8, 18, 10, 18, 12, 18, 322, 9, 18, 1, 18, 3, 18, 325, 8, 18, 1, 18, 1, 18, 3, 18, 329, 8, 18, 1, 18, 1, 18, 3, 18, 333, 8, 18, 1, 18, 3, 18, 336, 8, 18, 1, 18, 1, 18, 3, 18, 340, 8, 18, 1, 18, 1, 18, 1, 19, 1, 19, 1, 20, 3, 20, 347, 8, 20, 1, 20, 1, 20, 3, 20, 351, 8, 20, 1, 20, 1, 20, 3, 20, 355, 8, 20, 1, 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, 22, 1, 22, 1, 22, 3, 22, 366, 8, 22, 1, 23, 1, 23, 5, 23, 370, 8, 23, 10, 23, 12, 23, 373, 9, 23, 1, 23, 1, 23, 3, 23, 377, 8, 23, 1, 24, 1, 24, 1, 25, 1, 25, 3, 25, 383, 8, 25, 1, 26, 1, 26, 5, 26, 387, 8, 26, 10, 26, 12, 26, 390, 9, 26, 1, 26, 0, 0, 27, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 0, 4, 1, 0, 55, 55, 4, 0, 10, 10, 16, 18, 20, 21, 24, 24, 5, 0, 3, 5, 7, 10, 27, 35, 37, 53, 55, 55, 1, 0, 36, 36, 433, 0, 55, 1, 0, 0, 0, 2, 80, 1, 0, 0, 0, 4, 93, 1, 0, 0, 0, 6, 104, 1, 0, 0, 0, 8, 109, 1, 0, 0, 0, 10, 130, 1, 0, 0, 0, 12, 145, 1, 0, 0, 0, 14, 150, 1, 0, 0, 0, 16, 157, 1, 0, 0, 0, 18, 191, 1, 0, 0, 0, 20, 193, 1, 0, 0, 0, 22, 195, 1, 0, 0, 0, 24, 214, 1, 0, 0, 0, 26, 233, 1, 0, 0, 0, 28, 256, 1, 0, 0, 0, 30, 264, 1, 0, 0, 0, 32, 278, 1, 0, 0, 0, 34, 288, 1, 0, 0, 0, 36, 293, 1, 0, 0, 0, 38, 343, 1, 0, 0, 0, 40, 346, 1, 0, 0, 0, 42, 358, 1, 0, 0, 0, 44, 365, 1, 0, 0, 0, 46, 367, 1, 0, 0, 0, 48, 378, 1, 0, 0, 0, 50, 382, 1, 0, 0, 0, 52, 388, 1, 0, 0, 0, 54, 56, 5, 9, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 58, 1, 0, 0, 0, 57, 59, 5, 55, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 62, 1, 0, 0, 0, 60, 63, 3, 2, 1, 0, 61, 63, 3, 4, 2, 0, 62, 60, 1, 0, 0, 0, 62, 61, 1, 0, 0, 0, 63, 65, 1, 0, 0, 0, 64, 66, 5, 55, 0, 0, 65, 64, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 67, 1, 0, 0, 0, 67, 69, 3, 6, 3, 0, 68, 70, 5, 55, 0, 0, 69, 68, 1, 0, 0, 0, 69, 70, 1, 0, 0, 0, 70, 71, 1, 0, 0, 0, 71, 73, 3, 34, 17, 0, 72, 74, 5, 55, 0, 0, 73, 72, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 75, 1, 0, 0, 0, 75, 76, 5, 0, 0, 1, 76, 1, 1, 0, 0, 0, 77, 78, 3, 46, 23, 0, 78, 79, 5, 55, 0, 0, 79, 81, 1, 0, 0, 0, 80, 77, 1, 0, 0, 0, 80, 81, 1, 0, 0, 0, 81, 82, 1, 0, 0, 0, 82, 83, 5, 17, 0, 0, 83, 84, 5, 55, 0, 0, 84, 85, 5, 18, 0, 0, 85, 86, 5, 9, 0, 0, 86, 88, 5, 19, 0, 0, 87, 89, 5, 9, 0, 0, 88, 87, 1, 0, 0, 0, 88, 89, 1, 0, 0, 0, 89, 3, 1, 0, 0, 0, 90, 91, 3, 46, 23, 0, 91, 92, 5, 55, 0, 0, 92, 94, 1, 0, 0, 0, 93, 90, 1, 0, 0, 0, 93, 94, 1, 0, 0, 0, 94, 95, 1, 0, 0, 0, 95, 96, 5, 16, 0, 0, 96, 97, 5, 9, 0, 0, 97, 99, 3, 48, 24, 0, 98, 100, 5, 9, 0, 0, 99, 98, 1, 0, 0, 0, 99, 100, 1, 0, 0, 0, 100, 5, 1, 0, 0, 0, 101, 103, 3, 8, 4, 0, 102, 101, 1, 0, 0, 0, 103, 106, 1, 0, 0, 0, 104, 102, 1, 0, 0, 0, 104, 105, 1, 0, 0, 0, 105, 7, 1, 0, 0, 0, 106, 104, 1, 0, 0, 0, 107, 108, 5, 55, 0, 0, 108, 110, 3, 46, 23, 0, 109, 107, 1, 0, 0, 0, 109, 110, 1, 0, 0, 0, 110, 111, 1, 0, 0, 0, 111, 114, 5, 55, 0, 0, 112, 113, 5, 20, 0, 0, 113, 115, 5, 9, 0, 0, 114, 112, 1, 0, 0, 0, 114, 115, 1, 0, 0, 0, 115, 116, 1, 0, 0, 0, 116, 117, 5, 21, 0, 0, 117, 118, 5, 9, 0, 0, 118, 126, 3, 50, 25, 0, 119, 120, 5, 55, 0, 0, 120, 122, 5, 23, 0, 0, 121, 123, 3, 10, 5, 0, 122, 121, 1, 0, 0, 0, 123, 124, 1, 0, 0, 0, 124, 122, 1, 0, 0, 0, 124, 125, 1, 0, 0, 0, 125, 127, 1, 0, 0, 0, 126, 119, 1, 0, 0, 0, 126, 127, 1, 0, 0, 0, 127, 9, 1, 0, 0, 0, 128, 129, 5, 55, 0, 0, 129, 131, 3, 46, 23, 0, 130, 128, 1, 0, 0, 0, 130, 131, 1, 0, 0, 0, 131, 132, 1, 0, 0, 0, 132, 133, 5, 55, 0, 0, 133, 134, 5, 25, 0, 0, 134, 135, 5, 9, 0, 0, 135, 137, 3, 12, 6, 0, 136, 138, 5, 9, 0, 0, 137, 136, 1, 0, 0, 0, 137, 138, 1, 0, 0, 0, 138, 139, 1, 0, 0, 0, 139, 141, 5, 1, 0, 0, 140, 142, 5, 9, 0, 0, 141, 140, 1, 0, 0, 0, 141, 142, 1, 0, 0, 0, 142, 143, 1, 0, 0, 0, 143, 144, 3, 14, 7, 0, 144, 11, 1, 0, 0, 0, 145, 146, 3, 50, 25, 0, 146, 13, 1, 0, 0, 0, 147, 151, 3, 26, 13, 0, 148, 151, 3, 20, 10, 0, 149, 151, 3, 22, 11, 0, 150, 147, 1, 0, 0, 0, 150, 148, 1, 0, 0, 0, 150, 149, 1, 0, 0, 0, 151, 153, 1, 0, 0, 0, 152, 154, 3, 18, 9, 0, 153, 152, 1, 0, 0, 0, 153, 154, 1, 0, 0, 0, 154, 15, 1, 0, 0, 0, 155, 158, 3, 20, 10, 0, 156, 158, 3, 24, 12, 0, 157, 155, 1, 0, 0, 0, 157, 156, 1, 0, 0, 0, 158, 160, 1, 0, 0, 0, 159, 161, 3, 18, 9, 0, 160, 159, 1, 0, 0, 0, 160, 161, 1, 0, 0, 0, 161, 17, 1, 0, 0, 0, 162, 163, 5, 9, 0, 0, 163, 164, 5, 13, 0, 0, 164, 167, 5, 9, 0, 0, 165, 168, 3, 20, 10, 0, 166, 168, 3, 24, 12, 0, 167, 165, 1, 0, 0, 0, 167, 166, 1, 0, 0, 0, 168, 170, 1, 0, 0, 0, 169, 162, 1, 0, 0, 0, 170, 171, 1, 0, 0, 0, 171, 169, 1, 0, 0, 0, 171, 172, 1, 0, 0, 0, 172, 192, 1, 0, 0, 0, 173, 174, 5, 9, 0, 0, 174, 175, 5, 12, 0, 0, 175, 178, 5, 9, 0, 0, 176, 179, 3, 20, 10, 0, 177, 179, 3, 24, 12, 0, 178, 176, 1, 0, 0, 0, 178, 177, 1, 0, 0, 0, 179, 181, 1, 0, 0, 0, 180, 173, 1, 0, 0, 0, 181, 182, 1, 0, 0, 0, 182, 180, 1, 0, 0, 0, 182, 183, 1, 0, 0, 0, 183, 192, 1, 0, 0, 0, 184, 185, 5, 9, 0, 0, 185, 186, 5, 14, 0, 0, 186, 189, 5, 9, 0, 0, 187, 190, 3, 20, 10, 0, 188, 190, 3, 24, 12, 0, 189, 187, 1, 0, 0, 0, 189, 188, 1, 0, 0, 0, 190, 192, 1, 0, 0, 0, 191, 169, 1, 0, 0, 0, 191, 180, 1, 0, 0, 0, 191, 184, 1, 0, 0, 0, 192, 19, 1, 0, 0, 0, 193, 194, 3, 28, 14, 0, 194, 21, 1, 0, 0, 0, 195, 199, 5, 7, 0, 0, 196, 198, 5, 9, 0, 0, 197, 196, 1, 0, 0, 0, 198, 201, 1, 0, 0, 0, 199, 197, 1, 0, 0, 0, 199, 200, 1, 0, 0, 0, 200, 204, 1, 0, 0, 0, 201, 199, 1, 0, 0, 0, 202, 205, 3, 14, 7, 0, 203, 205, 3, 24, 12, 0, 204, 202, 1, 0, 0, 0, 204, 203, 1, 0, 0, 0, 205, 209, 1, 0, 0, 0, 206, 208, 5, 9, 0, 0, 207, 206, 1, 0, 0, 0, 208, 211, 1, 0, 0, 0, 209, 207, 1, 0, 0, 0, 209, 210, 1, 0, 0, 0, 210, 212, 1, 0, 0, 0, 211, 209, 1, 0, 0, 0, 212, 213, 5, 8, 0, 0, 213, 23, 1, 0, 0, 0, 214, 218, 5, 7, 0, 0, 215, 217, 5, 9, 0, 0, 216, 215, 1, 0, 0, 0, 217, 220, 1, 0, 0, 0, 218, 216, 1, 0, 0, 0, 218, 219, 1, 0, 0, 0, 219, 223, 1, 0, 0, 0, 220, 218, 1, 0, 0, 0, 221, 224, 3, 16, 8, 0, 222, 224, 3, 24, 12, 0, 223, 221, 1, 0, 0, 0, 223, 222, 1, 0, 0, 0, 224, 228, 1, 0, 0, 0, 225, 227, 5, 9, 0, 0, 226, 225, 1, 0, 0, 0, 227, 230, 1, 0, 0, 0, 228, 226, 1, 0, 0, 0, 228, 229, 1, 0, 0, 0, 229, 231, 1, 0, 0, 0, 230, 228, 1, 0, 0, 0, 231, 232, 5, 8, 0, 0, 232, 25, 1, 0, 0, 0, 233, 235, 5, 5, 0, 0, 234, 236, 5, 9, 0, 0, 235, 234, 1, 0, 0, 0, 235, 236, 1, 0, 0, 0, 236, 237, 1, 0, 0, 0, 237, 239, 3, 30, 15, 0, 238, 240, 5, 9, 0, 0, 239, 238, 1, 0, 0, 0, 239, 240, 1, 0, 0, 0, 240, 251, 1, 0, 0, 0, 241, 243, 5, 2, 0, 0, 242, 244, 5, 9, 0, 0, 243, 242, 1, 0, 0, 0, 243, 244, 1, 0, 0, 0, 244, 245, 1, 0, 0, 0, 245, 247, 3, 30, 15, 0, 246, 248, 5, 9, 0, 0, 247, 246, 1, 0, 0, 0, 247, 248, 1, 0, 0, 0, 248, 250, 1, 0, 0, 0, 249, 241, 1, 0, 0, 0, 250, 253, 1, 0, 0, 0, 251, 249, 1, 0, 0, 0, 251, 252, 1, 0, 0, 0, 252, 254, 1, 0, 0, 0, 253, 251, 1, 0, 0, 0, 254, 255, 5, 34, 0, 0, 255, 27, 1, 0, 0, 0, 256, 261, 3, 50, 25, 0, 257, 258, 5, 9, 0, 0, 258, 259, 5, 15, 0, 0, 259, 260, 5, 9, 0, 0, 260, 262, 3, 50, 25, 0, 261, 257, 1, 0, 0, 0, 261, 262, 1, 0, 0, 0, 262, 29, 1, 0, 0, 0, 263, 265, 5, 55, 0, 0, 264, 263, 1, 0, 0, 0, 264, 265, 1, 0, 0, 0, 265, 273, 1, 0, 0, 0, 266, 274, 3, 32, 16, 0, 267, 268, 3, 32, 16, 0, 268, 269, 5, 9, 0, 0, 269, 270, 5, 26, 0, 0, 270, 271, 5, 9, 0, 0, 271, 272, 3, 38, 19, 0, 272, 274, 1, 0, 0, 0, 273, 266, 1, 0, 0, 0, 273, 267, 1, 0, 0, 0, 274, 276, 1, 0, 0, 0, 275, 277, 5, 55, 0, 0, 276, 275, 1, 0, 0, 0, 276, 277, 1, 0, 0, 0, 277, 31, 1, 0, 0, 0, 278, 283, 3, 50, 25, 0, 279, 280, 5, 1, 0, 0, 280, 284, 5, 42, 0, 0, 281, 282, 5, 11, 0, 0, 282, 284, 3, 50, 25, 0, 283, 279, 1, 0, 0, 0, 283, 281, 1, 0, 0, 0, 283, 284, 1, 0, 0, 0, 284, 33, 1, 0, 0, 0, 285, 287, 3, 36, 18, 0, 286, 285, 1, 0, 0, 0, 287, 290, 1, 0, 0, 0, 288, 286, 1, 0, 0, 0, 288, 289, 1, 0, 0, 0, 289, 35, 1, 0, 0, 0, 290, 288, 1, 0, 0, 0, 291, 292, 5, 55, 0, 0, 292, 294, 3, 46, 23, 0, 293, 291, 1, 0, 0, 0, 293, 294, 1, 0, 0, 0, 294, 295, 1, 0, 0, 0, 295, 296, 5, 55, 0, 0, 296, 297, 5, 22, 0, 0, 297, 298, 5, 9, 0, 0, 298, 300, 3, 38, 19, 0, 299, 301, 5, 9, 0, 0, 300, 299, 1, 0, 0, 0, 300, 301, 1, 0, 0, 0, 301, 302, 1, 0, 0, 0, 302, 304, 5, 7, 0, 0, 303, 305, 5, 9, 0, 0, 304, 303, 1, 0, 0, 0, 304, 305, 1, 0, 0, 0, 305, 306, 1, 0, 0, 0, 306, 308, 3, 40, 20, 0, 307, 309, 5, 9, 0, 0, 308, 307, 1, 0, 0, 0, 308, 309, 1, 0, 0, 0, 309, 320, 1, 0, 0, 0, 310, 312, 5, 2, 0, 0, 311, 313, 5, 9, 0, 0, 312, 311, 1, 0, 0, 0, 312, 313, 1, 0, 0, 0, 313, 314, 1, 0, 0, 0, 314, 316, 3, 40, 20, 0, 315, 317, 5, 9, 0, 0, 316, 315, 1, 0, 0, 0, 316, 317, 1, 0, 0, 0, 317, 319, 1, 0, 0, 0, 318, 310, 1, 0, 0, 0, 319, 322, 1, 0, 0, 0, 320, 318, 1, 0, 0, 0, 320, 321, 1, 0, 0, 0, 321, 324, 1, 0, 0, 0, 322, 320, 1, 0, 0, 0, 323, 325, 5, 55, 0, 0, 324, 323, 1, 0, 0, 0, 324, 325, 1, 0, 0, 0, 325, 326, 1, 0, 0, 0, 326, 328, 5, 8, 0, 0, 327, 329, 5, 9, 0, 0, 328, 327, 1, 0, 0, 0, 328, 329, 1, 0, 0, 0, 329, 330, 1, 0, 0, 0, 330, 332, 5, 35, 0, 0, 331, 333, 5, 55, 0, 0, 332, 331, 1, 0, 0, 0, 332, 333, 1, 0, 0, 0, 333, 335, 1, 0, 0, 0, 334, 336, 5, 9, 0, 0, 335, 334, 1, 0, 0, 0, 335, 336, 1, 0, 0, 0, 336, 337, 1, 0, 0, 0, 337, 339, 3, 52, 26, 0, 338, 340, 5, 55, 0, 0, 339, 338, 1, 0, 0, 0, 339, 340, 1, 0, 0, 0, 340, 341, 1, 0, 0, 0, 341, 342, 5, 36, 0, 0, 342, 37, 1, 0, 0, 0, 343, 344, 5, 10, 0, 0, 344, 39, 1, 0, 0, 0, 345, 347, 5, 55, 0, 0, 346, 345, 1, 0, 0, 0, 346, 347, 1, 0, 0, 0, 347, 348, 1, 0, 0, 0, 348, 350, 3, 42, 21, 0, 349, 351, 5, 9, 0, 0, 350, 349, 1, 0, 0, 0, 350, 351, 1, 0, 0, 0, 351, 352, 1, 0, 0, 0, 352, 354, 5, 1, 0, 0, 353, 355, 5, 9, 0, 0, 354, 353, 1, 0, 0, 0, 354, 355, 1, 0, 0, 0, 355, 356, 1, 0, 0, 0, 356, 357, 3, 44, 22, 0, 357, 41, 1, 0, 0, 0, 358, 359, 5, 10, 0, 0, 359, 43, 1, 0, 0, 0, 360, 366, 5, 57, 0, 0, 361, 362, 5, 56, 0, 0, 362, 363, 5, 3, 0, 0, 363, 364, 5, 57, 0, 0, 364, 366, 5, 4, 0, 0, 365, 360, 1, 0, 0, 0, 365, 361, 1, 0, 0, 0, 366, 45, 1, 0, 0, 0, 367, 371, 5, 11, 0, 0, 368, 370, 8, 0, 0, 0, 369, 368, 1, 0, 0, 0, 370, 373, 1, 0, 0, 0, 371, 369, 1, 0, 0, 0, 371, 372, 1, 0, 0, 0, 372, 376, 1, 0, 0, 0, 373, 371, 1, 0, 0, 0, 374, 375, 5, 55, 0, 0, 375, 377, 3, 46, 23, 0, 376, 374, 1, 0, 0, 0, 376, 377, 1, 0, 0, 0, 377, 47, 1, 0, 0, 0, 378, 379, 7, 1, 0, 0, 379, 49, 1, 0, 0, 0, 380, 383, 3, 48, 24, 0, 381, 383, 5, 54, 0, 0, 382, 380, 1, 0, 0, 0, 382, 381, 1, 0, 0, 0, 383, 51, 1, 0, 0, 0, 384, 387, 7, 2, 0, 0, 385, 387, 8, 3, 0, 0, 386, 384, 1, 0, 0, 0, 386, 385, 1, 0, 0, 0, 387, 390, 1, 0, 0, 0, 388, 386, 1, 0, 0, 0, 388, 389, 1, 0, 0, 0, 389, 53, 1, 0, 0, 0, 390, 388, 1, 0, 0, 0, 66, 55, 58, 62, 65, 69, 73, 80, 88, 93, 99, 104, 109, 114, 124, 126, 130, 137, 141, 150, 153, 157, 160, 167, 171, 178, 182, 189, 191, 199, 204, 209, 218, 223, 228, 235, 239, 243, 247, 251, 261, 264, 273, 276, 283, 288, 293, 300, 304, 308, 312, 316, 320, 324, 328, 332, 335, 339, 346, 350, 354, 365, 371, 376, 382, 386, 388] \ No newline at end of file +[4, 1, 58, 394, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, 20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25, 2, 26, 7, 26, 1, 0, 3, 0, 56, 8, 0, 1, 0, 3, 0, 59, 8, 0, 1, 0, 1, 0, 3, 0, 63, 8, 0, 1, 0, 3, 0, 66, 8, 0, 1, 0, 1, 0, 3, 0, 70, 8, 0, 1, 0, 1, 0, 3, 0, 74, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 3, 1, 81, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 89, 8, 1, 1, 2, 1, 2, 1, 2, 3, 2, 94, 8, 2, 1, 2, 1, 2, 1, 2, 1, 2, 3, 2, 100, 8, 2, 1, 3, 5, 3, 103, 8, 3, 10, 3, 12, 3, 106, 9, 3, 1, 4, 1, 4, 3, 4, 110, 8, 4, 1, 4, 1, 4, 1, 4, 3, 4, 115, 8, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 4, 4, 123, 8, 4, 11, 4, 12, 4, 124, 3, 4, 127, 8, 4, 1, 5, 1, 5, 3, 5, 131, 8, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 3, 5, 138, 8, 5, 1, 5, 1, 5, 3, 5, 142, 8, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 3, 7, 151, 8, 7, 1, 7, 3, 7, 154, 8, 7, 1, 8, 1, 8, 3, 8, 158, 8, 8, 1, 8, 3, 8, 161, 8, 8, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 3, 9, 168, 8, 9, 4, 9, 170, 8, 9, 11, 9, 12, 9, 171, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 3, 9, 179, 8, 9, 4, 9, 181, 8, 9, 11, 9, 12, 9, 182, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 3, 9, 190, 8, 9, 3, 9, 192, 8, 9, 1, 10, 1, 10, 1, 11, 1, 11, 5, 11, 198, 8, 11, 10, 11, 12, 11, 201, 9, 11, 1, 11, 1, 11, 3, 11, 205, 8, 11, 1, 11, 5, 11, 208, 8, 11, 10, 11, 12, 11, 211, 9, 11, 1, 11, 1, 11, 1, 12, 1, 12, 5, 12, 217, 8, 12, 10, 12, 12, 12, 220, 9, 12, 1, 12, 1, 12, 3, 12, 224, 8, 12, 1, 12, 5, 12, 227, 8, 12, 10, 12, 12, 12, 230, 9, 12, 1, 12, 1, 12, 1, 13, 1, 13, 3, 13, 236, 8, 13, 1, 13, 1, 13, 3, 13, 240, 8, 13, 1, 13, 1, 13, 3, 13, 244, 8, 13, 1, 13, 1, 13, 3, 13, 248, 8, 13, 5, 13, 250, 8, 13, 10, 13, 12, 13, 253, 9, 13, 1, 13, 1, 13, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 3, 14, 262, 8, 14, 1, 15, 3, 15, 265, 8, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 3, 15, 274, 8, 15, 3, 15, 276, 8, 15, 1, 15, 3, 15, 279, 8, 15, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 3, 16, 286, 8, 16, 1, 17, 5, 17, 289, 8, 17, 10, 17, 12, 17, 292, 9, 17, 1, 18, 1, 18, 3, 18, 296, 8, 18, 1, 18, 1, 18, 1, 18, 1, 18, 1, 18, 3, 18, 303, 8, 18, 1, 18, 1, 18, 3, 18, 307, 8, 18, 1, 18, 1, 18, 3, 18, 311, 8, 18, 1, 18, 1, 18, 3, 18, 315, 8, 18, 1, 18, 1, 18, 3, 18, 319, 8, 18, 5, 18, 321, 8, 18, 10, 18, 12, 18, 324, 9, 18, 1, 18, 3, 18, 327, 8, 18, 1, 18, 1, 18, 3, 18, 331, 8, 18, 1, 18, 1, 18, 3, 18, 335, 8, 18, 1, 18, 3, 18, 338, 8, 18, 1, 18, 1, 18, 3, 18, 342, 8, 18, 1, 18, 1, 18, 1, 19, 1, 19, 1, 20, 3, 20, 349, 8, 20, 1, 20, 1, 20, 3, 20, 353, 8, 20, 1, 20, 1, 20, 3, 20, 357, 8, 20, 1, 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, 22, 1, 22, 1, 22, 3, 22, 368, 8, 22, 1, 23, 1, 23, 5, 23, 372, 8, 23, 10, 23, 12, 23, 375, 9, 23, 1, 23, 1, 23, 3, 23, 379, 8, 23, 1, 24, 1, 24, 1, 25, 1, 25, 3, 25, 385, 8, 25, 1, 26, 1, 26, 5, 26, 389, 8, 26, 10, 26, 12, 26, 392, 9, 26, 1, 26, 0, 0, 27, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 0, 4, 1, 0, 56, 56, 4, 0, 10, 10, 16, 18, 20, 21, 24, 24, 5, 0, 3, 5, 7, 10, 27, 35, 37, 53, 56, 56, 1, 0, 36, 36, 436, 0, 55, 1, 0, 0, 0, 2, 80, 1, 0, 0, 0, 4, 93, 1, 0, 0, 0, 6, 104, 1, 0, 0, 0, 8, 109, 1, 0, 0, 0, 10, 130, 1, 0, 0, 0, 12, 145, 1, 0, 0, 0, 14, 150, 1, 0, 0, 0, 16, 157, 1, 0, 0, 0, 18, 191, 1, 0, 0, 0, 20, 193, 1, 0, 0, 0, 22, 195, 1, 0, 0, 0, 24, 214, 1, 0, 0, 0, 26, 233, 1, 0, 0, 0, 28, 256, 1, 0, 0, 0, 30, 264, 1, 0, 0, 0, 32, 280, 1, 0, 0, 0, 34, 290, 1, 0, 0, 0, 36, 295, 1, 0, 0, 0, 38, 345, 1, 0, 0, 0, 40, 348, 1, 0, 0, 0, 42, 360, 1, 0, 0, 0, 44, 367, 1, 0, 0, 0, 46, 369, 1, 0, 0, 0, 48, 380, 1, 0, 0, 0, 50, 384, 1, 0, 0, 0, 52, 390, 1, 0, 0, 0, 54, 56, 5, 9, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 58, 1, 0, 0, 0, 57, 59, 5, 56, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 62, 1, 0, 0, 0, 60, 63, 3, 2, 1, 0, 61, 63, 3, 4, 2, 0, 62, 60, 1, 0, 0, 0, 62, 61, 1, 0, 0, 0, 63, 65, 1, 0, 0, 0, 64, 66, 5, 56, 0, 0, 65, 64, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 67, 1, 0, 0, 0, 67, 69, 3, 6, 3, 0, 68, 70, 5, 56, 0, 0, 69, 68, 1, 0, 0, 0, 69, 70, 1, 0, 0, 0, 70, 71, 1, 0, 0, 0, 71, 73, 3, 34, 17, 0, 72, 74, 5, 56, 0, 0, 73, 72, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 75, 1, 0, 0, 0, 75, 76, 5, 0, 0, 1, 76, 1, 1, 0, 0, 0, 77, 78, 3, 46, 23, 0, 78, 79, 5, 56, 0, 0, 79, 81, 1, 0, 0, 0, 80, 77, 1, 0, 0, 0, 80, 81, 1, 0, 0, 0, 81, 82, 1, 0, 0, 0, 82, 83, 5, 17, 0, 0, 83, 84, 5, 56, 0, 0, 84, 85, 5, 18, 0, 0, 85, 86, 5, 9, 0, 0, 86, 88, 5, 19, 0, 0, 87, 89, 5, 9, 0, 0, 88, 87, 1, 0, 0, 0, 88, 89, 1, 0, 0, 0, 89, 3, 1, 0, 0, 0, 90, 91, 3, 46, 23, 0, 91, 92, 5, 56, 0, 0, 92, 94, 1, 0, 0, 0, 93, 90, 1, 0, 0, 0, 93, 94, 1, 0, 0, 0, 94, 95, 1, 0, 0, 0, 95, 96, 5, 16, 0, 0, 96, 97, 5, 9, 0, 0, 97, 99, 3, 48, 24, 0, 98, 100, 5, 9, 0, 0, 99, 98, 1, 0, 0, 0, 99, 100, 1, 0, 0, 0, 100, 5, 1, 0, 0, 0, 101, 103, 3, 8, 4, 0, 102, 101, 1, 0, 0, 0, 103, 106, 1, 0, 0, 0, 104, 102, 1, 0, 0, 0, 104, 105, 1, 0, 0, 0, 105, 7, 1, 0, 0, 0, 106, 104, 1, 0, 0, 0, 107, 108, 5, 56, 0, 0, 108, 110, 3, 46, 23, 0, 109, 107, 1, 0, 0, 0, 109, 110, 1, 0, 0, 0, 110, 111, 1, 0, 0, 0, 111, 114, 5, 56, 0, 0, 112, 113, 5, 20, 0, 0, 113, 115, 5, 9, 0, 0, 114, 112, 1, 0, 0, 0, 114, 115, 1, 0, 0, 0, 115, 116, 1, 0, 0, 0, 116, 117, 5, 21, 0, 0, 117, 118, 5, 9, 0, 0, 118, 126, 3, 50, 25, 0, 119, 120, 5, 56, 0, 0, 120, 122, 5, 23, 0, 0, 121, 123, 3, 10, 5, 0, 122, 121, 1, 0, 0, 0, 123, 124, 1, 0, 0, 0, 124, 122, 1, 0, 0, 0, 124, 125, 1, 0, 0, 0, 125, 127, 1, 0, 0, 0, 126, 119, 1, 0, 0, 0, 126, 127, 1, 0, 0, 0, 127, 9, 1, 0, 0, 0, 128, 129, 5, 56, 0, 0, 129, 131, 3, 46, 23, 0, 130, 128, 1, 0, 0, 0, 130, 131, 1, 0, 0, 0, 131, 132, 1, 0, 0, 0, 132, 133, 5, 56, 0, 0, 133, 134, 5, 25, 0, 0, 134, 135, 5, 9, 0, 0, 135, 137, 3, 12, 6, 0, 136, 138, 5, 9, 0, 0, 137, 136, 1, 0, 0, 0, 137, 138, 1, 0, 0, 0, 138, 139, 1, 0, 0, 0, 139, 141, 5, 1, 0, 0, 140, 142, 5, 9, 0, 0, 141, 140, 1, 0, 0, 0, 141, 142, 1, 0, 0, 0, 142, 143, 1, 0, 0, 0, 143, 144, 3, 14, 7, 0, 144, 11, 1, 0, 0, 0, 145, 146, 3, 50, 25, 0, 146, 13, 1, 0, 0, 0, 147, 151, 3, 26, 13, 0, 148, 151, 3, 20, 10, 0, 149, 151, 3, 22, 11, 0, 150, 147, 1, 0, 0, 0, 150, 148, 1, 0, 0, 0, 150, 149, 1, 0, 0, 0, 151, 153, 1, 0, 0, 0, 152, 154, 3, 18, 9, 0, 153, 152, 1, 0, 0, 0, 153, 154, 1, 0, 0, 0, 154, 15, 1, 0, 0, 0, 155, 158, 3, 20, 10, 0, 156, 158, 3, 24, 12, 0, 157, 155, 1, 0, 0, 0, 157, 156, 1, 0, 0, 0, 158, 160, 1, 0, 0, 0, 159, 161, 3, 18, 9, 0, 160, 159, 1, 0, 0, 0, 160, 161, 1, 0, 0, 0, 161, 17, 1, 0, 0, 0, 162, 163, 5, 9, 0, 0, 163, 164, 5, 13, 0, 0, 164, 167, 5, 9, 0, 0, 165, 168, 3, 20, 10, 0, 166, 168, 3, 24, 12, 0, 167, 165, 1, 0, 0, 0, 167, 166, 1, 0, 0, 0, 168, 170, 1, 0, 0, 0, 169, 162, 1, 0, 0, 0, 170, 171, 1, 0, 0, 0, 171, 169, 1, 0, 0, 0, 171, 172, 1, 0, 0, 0, 172, 192, 1, 0, 0, 0, 173, 174, 5, 9, 0, 0, 174, 175, 5, 12, 0, 0, 175, 178, 5, 9, 0, 0, 176, 179, 3, 20, 10, 0, 177, 179, 3, 24, 12, 0, 178, 176, 1, 0, 0, 0, 178, 177, 1, 0, 0, 0, 179, 181, 1, 0, 0, 0, 180, 173, 1, 0, 0, 0, 181, 182, 1, 0, 0, 0, 182, 180, 1, 0, 0, 0, 182, 183, 1, 0, 0, 0, 183, 192, 1, 0, 0, 0, 184, 185, 5, 9, 0, 0, 185, 186, 5, 14, 0, 0, 186, 189, 5, 9, 0, 0, 187, 190, 3, 20, 10, 0, 188, 190, 3, 24, 12, 0, 189, 187, 1, 0, 0, 0, 189, 188, 1, 0, 0, 0, 190, 192, 1, 0, 0, 0, 191, 169, 1, 0, 0, 0, 191, 180, 1, 0, 0, 0, 191, 184, 1, 0, 0, 0, 192, 19, 1, 0, 0, 0, 193, 194, 3, 28, 14, 0, 194, 21, 1, 0, 0, 0, 195, 199, 5, 7, 0, 0, 196, 198, 5, 9, 0, 0, 197, 196, 1, 0, 0, 0, 198, 201, 1, 0, 0, 0, 199, 197, 1, 0, 0, 0, 199, 200, 1, 0, 0, 0, 200, 204, 1, 0, 0, 0, 201, 199, 1, 0, 0, 0, 202, 205, 3, 14, 7, 0, 203, 205, 3, 24, 12, 0, 204, 202, 1, 0, 0, 0, 204, 203, 1, 0, 0, 0, 205, 209, 1, 0, 0, 0, 206, 208, 5, 9, 0, 0, 207, 206, 1, 0, 0, 0, 208, 211, 1, 0, 0, 0, 209, 207, 1, 0, 0, 0, 209, 210, 1, 0, 0, 0, 210, 212, 1, 0, 0, 0, 211, 209, 1, 0, 0, 0, 212, 213, 5, 8, 0, 0, 213, 23, 1, 0, 0, 0, 214, 218, 5, 7, 0, 0, 215, 217, 5, 9, 0, 0, 216, 215, 1, 0, 0, 0, 217, 220, 1, 0, 0, 0, 218, 216, 1, 0, 0, 0, 218, 219, 1, 0, 0, 0, 219, 223, 1, 0, 0, 0, 220, 218, 1, 0, 0, 0, 221, 224, 3, 16, 8, 0, 222, 224, 3, 24, 12, 0, 223, 221, 1, 0, 0, 0, 223, 222, 1, 0, 0, 0, 224, 228, 1, 0, 0, 0, 225, 227, 5, 9, 0, 0, 226, 225, 1, 0, 0, 0, 227, 230, 1, 0, 0, 0, 228, 226, 1, 0, 0, 0, 228, 229, 1, 0, 0, 0, 229, 231, 1, 0, 0, 0, 230, 228, 1, 0, 0, 0, 231, 232, 5, 8, 0, 0, 232, 25, 1, 0, 0, 0, 233, 235, 5, 5, 0, 0, 234, 236, 5, 9, 0, 0, 235, 234, 1, 0, 0, 0, 235, 236, 1, 0, 0, 0, 236, 237, 1, 0, 0, 0, 237, 239, 3, 30, 15, 0, 238, 240, 5, 9, 0, 0, 239, 238, 1, 0, 0, 0, 239, 240, 1, 0, 0, 0, 240, 251, 1, 0, 0, 0, 241, 243, 5, 2, 0, 0, 242, 244, 5, 9, 0, 0, 243, 242, 1, 0, 0, 0, 243, 244, 1, 0, 0, 0, 244, 245, 1, 0, 0, 0, 245, 247, 3, 30, 15, 0, 246, 248, 5, 9, 0, 0, 247, 246, 1, 0, 0, 0, 247, 248, 1, 0, 0, 0, 248, 250, 1, 0, 0, 0, 249, 241, 1, 0, 0, 0, 250, 253, 1, 0, 0, 0, 251, 249, 1, 0, 0, 0, 251, 252, 1, 0, 0, 0, 252, 254, 1, 0, 0, 0, 253, 251, 1, 0, 0, 0, 254, 255, 5, 34, 0, 0, 255, 27, 1, 0, 0, 0, 256, 261, 3, 50, 25, 0, 257, 258, 5, 9, 0, 0, 258, 259, 5, 15, 0, 0, 259, 260, 5, 9, 0, 0, 260, 262, 3, 50, 25, 0, 261, 257, 1, 0, 0, 0, 261, 262, 1, 0, 0, 0, 262, 29, 1, 0, 0, 0, 263, 265, 5, 56, 0, 0, 264, 263, 1, 0, 0, 0, 264, 265, 1, 0, 0, 0, 265, 275, 1, 0, 0, 0, 266, 276, 3, 32, 16, 0, 267, 268, 3, 32, 16, 0, 268, 269, 5, 9, 0, 0, 269, 270, 5, 26, 0, 0, 270, 273, 5, 9, 0, 0, 271, 274, 3, 38, 19, 0, 272, 274, 5, 54, 0, 0, 273, 271, 1, 0, 0, 0, 273, 272, 1, 0, 0, 0, 274, 276, 1, 0, 0, 0, 275, 266, 1, 0, 0, 0, 275, 267, 1, 0, 0, 0, 276, 278, 1, 0, 0, 0, 277, 279, 5, 56, 0, 0, 278, 277, 1, 0, 0, 0, 278, 279, 1, 0, 0, 0, 279, 31, 1, 0, 0, 0, 280, 285, 3, 50, 25, 0, 281, 282, 5, 1, 0, 0, 282, 286, 5, 42, 0, 0, 283, 284, 5, 11, 0, 0, 284, 286, 3, 50, 25, 0, 285, 281, 1, 0, 0, 0, 285, 283, 1, 0, 0, 0, 285, 286, 1, 0, 0, 0, 286, 33, 1, 0, 0, 0, 287, 289, 3, 36, 18, 0, 288, 287, 1, 0, 0, 0, 289, 292, 1, 0, 0, 0, 290, 288, 1, 0, 0, 0, 290, 291, 1, 0, 0, 0, 291, 35, 1, 0, 0, 0, 292, 290, 1, 0, 0, 0, 293, 294, 5, 56, 0, 0, 294, 296, 3, 46, 23, 0, 295, 293, 1, 0, 0, 0, 295, 296, 1, 0, 0, 0, 296, 297, 1, 0, 0, 0, 297, 298, 5, 56, 0, 0, 298, 299, 5, 22, 0, 0, 299, 300, 5, 9, 0, 0, 300, 302, 3, 38, 19, 0, 301, 303, 5, 9, 0, 0, 302, 301, 1, 0, 0, 0, 302, 303, 1, 0, 0, 0, 303, 304, 1, 0, 0, 0, 304, 306, 5, 7, 0, 0, 305, 307, 5, 9, 0, 0, 306, 305, 1, 0, 0, 0, 306, 307, 1, 0, 0, 0, 307, 308, 1, 0, 0, 0, 308, 310, 3, 40, 20, 0, 309, 311, 5, 9, 0, 0, 310, 309, 1, 0, 0, 0, 310, 311, 1, 0, 0, 0, 311, 322, 1, 0, 0, 0, 312, 314, 5, 2, 0, 0, 313, 315, 5, 9, 0, 0, 314, 313, 1, 0, 0, 0, 314, 315, 1, 0, 0, 0, 315, 316, 1, 0, 0, 0, 316, 318, 3, 40, 20, 0, 317, 319, 5, 9, 0, 0, 318, 317, 1, 0, 0, 0, 318, 319, 1, 0, 0, 0, 319, 321, 1, 0, 0, 0, 320, 312, 1, 0, 0, 0, 321, 324, 1, 0, 0, 0, 322, 320, 1, 0, 0, 0, 322, 323, 1, 0, 0, 0, 323, 326, 1, 0, 0, 0, 324, 322, 1, 0, 0, 0, 325, 327, 5, 56, 0, 0, 326, 325, 1, 0, 0, 0, 326, 327, 1, 0, 0, 0, 327, 328, 1, 0, 0, 0, 328, 330, 5, 8, 0, 0, 329, 331, 5, 9, 0, 0, 330, 329, 1, 0, 0, 0, 330, 331, 1, 0, 0, 0, 331, 332, 1, 0, 0, 0, 332, 334, 5, 35, 0, 0, 333, 335, 5, 56, 0, 0, 334, 333, 1, 0, 0, 0, 334, 335, 1, 0, 0, 0, 335, 337, 1, 0, 0, 0, 336, 338, 5, 9, 0, 0, 337, 336, 1, 0, 0, 0, 337, 338, 1, 0, 0, 0, 338, 339, 1, 0, 0, 0, 339, 341, 3, 52, 26, 0, 340, 342, 5, 56, 0, 0, 341, 340, 1, 0, 0, 0, 341, 342, 1, 0, 0, 0, 342, 343, 1, 0, 0, 0, 343, 344, 5, 36, 0, 0, 344, 37, 1, 0, 0, 0, 345, 346, 5, 10, 0, 0, 346, 39, 1, 0, 0, 0, 347, 349, 5, 56, 0, 0, 348, 347, 1, 0, 0, 0, 348, 349, 1, 0, 0, 0, 349, 350, 1, 0, 0, 0, 350, 352, 3, 42, 21, 0, 351, 353, 5, 9, 0, 0, 352, 351, 1, 0, 0, 0, 352, 353, 1, 0, 0, 0, 353, 354, 1, 0, 0, 0, 354, 356, 5, 1, 0, 0, 355, 357, 5, 9, 0, 0, 356, 355, 1, 0, 0, 0, 356, 357, 1, 0, 0, 0, 357, 358, 1, 0, 0, 0, 358, 359, 3, 44, 22, 0, 359, 41, 1, 0, 0, 0, 360, 361, 5, 10, 0, 0, 361, 43, 1, 0, 0, 0, 362, 368, 5, 58, 0, 0, 363, 364, 5, 57, 0, 0, 364, 365, 5, 3, 0, 0, 365, 366, 5, 58, 0, 0, 366, 368, 5, 4, 0, 0, 367, 362, 1, 0, 0, 0, 367, 363, 1, 0, 0, 0, 368, 45, 1, 0, 0, 0, 369, 373, 5, 11, 0, 0, 370, 372, 8, 0, 0, 0, 371, 370, 1, 0, 0, 0, 372, 375, 1, 0, 0, 0, 373, 371, 1, 0, 0, 0, 373, 374, 1, 0, 0, 0, 374, 378, 1, 0, 0, 0, 375, 373, 1, 0, 0, 0, 376, 377, 5, 56, 0, 0, 377, 379, 3, 46, 23, 0, 378, 376, 1, 0, 0, 0, 378, 379, 1, 0, 0, 0, 379, 47, 1, 0, 0, 0, 380, 381, 7, 1, 0, 0, 381, 49, 1, 0, 0, 0, 382, 385, 3, 48, 24, 0, 383, 385, 5, 55, 0, 0, 384, 382, 1, 0, 0, 0, 384, 383, 1, 0, 0, 0, 385, 51, 1, 0, 0, 0, 386, 389, 7, 2, 0, 0, 387, 389, 8, 3, 0, 0, 388, 386, 1, 0, 0, 0, 388, 387, 1, 0, 0, 0, 389, 392, 1, 0, 0, 0, 390, 388, 1, 0, 0, 0, 390, 391, 1, 0, 0, 0, 391, 53, 1, 0, 0, 0, 392, 390, 1, 0, 0, 0, 67, 55, 58, 62, 65, 69, 73, 80, 88, 93, 99, 104, 109, 114, 124, 126, 130, 137, 141, 150, 153, 157, 160, 167, 171, 178, 182, 189, 191, 199, 204, 209, 218, 223, 228, 235, 239, 243, 247, 251, 261, 264, 273, 275, 278, 285, 290, 295, 302, 306, 310, 314, 318, 322, 326, 330, 334, 337, 341, 348, 352, 356, 367, 373, 378, 384, 388, 390] \ No newline at end of file diff --git a/vendor/github.com/openfga/language/pkg/go/gen/OpenFGAParser.tokens b/vendor/github.com/openfga/language/pkg/go/gen/OpenFGAParser.tokens index 512cec30b6..b2523ac809 100644 --- a/vendor/github.com/openfga/language/pkg/go/gen/OpenFGAParser.tokens +++ b/vendor/github.com/openfga/language/pkg/go/gen/OpenFGAParser.tokens @@ -51,10 +51,11 @@ NUM_INT=50 NUM_UINT=51 STRING=52 BYTES=53 -EXTENDED_IDENTIFIER=54 -NEWLINE=55 -CONDITION_PARAM_CONTAINER=56 -CONDITION_PARAM_TYPE=57 +DOLLAR_EXPRESSION=54 +EXTENDED_IDENTIFIER=55 +NEWLINE=56 +CONDITION_PARAM_CONTAINER=57 +CONDITION_PARAM_TYPE=58 '#'=11 ':'=1 ','=2 @@ -98,3 +99,4 @@ CONDITION_PARAM_TYPE=57 'true'=45 'false'=46 'null'=47 +'$expression'=54 diff --git a/vendor/github.com/openfga/language/pkg/go/gen/openfga_lexer.go b/vendor/github.com/openfga/language/pkg/go/gen/openfga_lexer.go index e661ccd044..ae88f954b8 100644 --- a/vendor/github.com/openfga/language/pkg/go/gen/openfga_lexer.go +++ b/vendor/github.com/openfga/language/pkg/go/gen/openfga_lexer.go @@ -48,7 +48,8 @@ func openfgalexerLexerInit() { "", "'extend'", "'type'", "'condition'", "'relations'", "'relation'", "'define'", "'with'", "'=='", "'!='", "'in'", "'<='", "'>='", "'&&'", "'||'", "']'", "'{'", "'}'", "'.'", "'-'", "'!'", "'?'", "'+'", "'*'", - "'/'", "'%'", "'true'", "'false'", "'null'", + "'/'", "'%'", "'true'", "'false'", "'null'", "", "", "", "", "", "", + "'$expression'", } staticData.SymbolicNames = []string{ "", "COLON", "COMMA", "LESS", "GREATER", "LBRACKET", "RBRACKET", "LPAREN", @@ -59,7 +60,7 @@ func openfgalexerLexerInit() { "LOGICAL_OR", "RPRACKET", "LBRACE", "RBRACE", "DOT", "MINUS", "EXCLAM", "QUESTIONMARK", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE", "NUL", "CEL_COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT", "STRING", - "BYTES", "EXTENDED_IDENTIFIER", "NEWLINE", "CONDITION_PARAM_CONTAINER", + "BYTES", "DOLLAR_EXPRESSION", "EXTENDED_IDENTIFIER", "NEWLINE", "CONDITION_PARAM_CONTAINER", "CONDITION_PARAM_TYPE", } staticData.RuleNames = []string{ @@ -72,14 +73,15 @@ func openfgalexerLexerInit() { "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE", "NUL", "BACKSLASH", "LETTER", "DIGIT", "EXPONENT", "HEXDIGIT", "RAW", "ESC_SEQ", "ESC_CHAR_SEQ", "ESC_OCT_SEQ", "ESC_BYTE_SEQ", "ESC_UNI_SEQ", "WHITESPACE", "CEL_COMMENT", "NUM_FLOAT", - "NUM_INT", "NUM_UINT", "STRING", "BYTES", "IDENTIFIER", "EXTENDED_IDENTIFIER", - "NEWLINE", "CONDITION_DEF_END", "CONDITION_PARAM_CONTAINER", "CONDITION_PARAM_TYPE", - "CONDITION_PARAM_TYPE_LESS", "CONDITION_PARAM_TYPE_GREATER", "CONDITION_OPEN", - "CONDITION_COLON", "CONDITION_COMMA", "CONDITION_WS", "CONDITION_NAME", + "NUM_INT", "NUM_UINT", "STRING", "BYTES", "DOLLAR_EXPRESSION", "IDENTIFIER", + "EXTENDED_IDENTIFIER", "NEWLINE", "CONDITION_DEF_END", "CONDITION_PARAM_CONTAINER", + "CONDITION_PARAM_TYPE", "CONDITION_PARAM_TYPE_LESS", "CONDITION_PARAM_TYPE_GREATER", + "CONDITION_OPEN", "CONDITION_COLON", "CONDITION_COMMA", "CONDITION_WS", + "CONDITION_NAME", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 0, 57, 717, 6, -1, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, + 4, 0, 58, 731, 6, -1, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, @@ -93,325 +95,331 @@ func openfgalexerLexerInit() { 56, 2, 57, 7, 57, 2, 58, 7, 58, 2, 59, 7, 59, 2, 60, 7, 60, 2, 61, 7, 61, 2, 62, 7, 62, 2, 63, 7, 63, 2, 64, 7, 64, 2, 65, 7, 65, 2, 66, 7, 66, 2, 67, 7, 67, 2, 68, 7, 68, 2, 69, 7, 69, 2, 70, 7, 70, 2, 71, 7, 71, 2, 72, - 7, 72, 2, 73, 7, 73, 2, 74, 7, 74, 1, 0, 1, 0, 1, 1, 1, 1, 1, 2, 1, 2, - 1, 3, 1, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, - 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 1, 7, - 1, 7, 1, 7, 1, 7, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 1, 9, - 1, 9, 1, 9, 1, 9, 1, 9, 1, 10, 4, 10, 200, 8, 10, 11, 10, 12, 10, 201, - 1, 10, 1, 10, 4, 10, 206, 8, 10, 11, 10, 12, 10, 207, 1, 11, 1, 11, 1, - 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 13, + 7, 72, 2, 73, 7, 73, 2, 74, 7, 74, 2, 75, 7, 75, 1, 0, 1, 0, 1, 1, 1, 1, + 1, 2, 1, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, + 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, + 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 9, + 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 10, 4, 10, 202, 8, 10, 11, 10, 12, + 10, 203, 1, 10, 1, 10, 4, 10, 208, 8, 10, 11, 10, 12, 10, 209, 1, 11, 1, + 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, - 13, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, - 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 16, 1, - 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 17, 1, 17, 1, 17, 1, 17, 1, 17, - 1, 18, 1, 18, 1, 18, 1, 19, 1, 19, 1, 19, 1, 20, 1, 20, 1, 20, 1, 21, 1, - 21, 1, 22, 1, 22, 1, 22, 1, 23, 1, 23, 1, 23, 1, 24, 1, 24, 1, 25, 1, 25, - 1, 25, 1, 26, 1, 26, 1, 26, 1, 27, 1, 27, 1, 28, 1, 28, 1, 29, 1, 29, 1, - 30, 1, 30, 1, 31, 1, 31, 1, 32, 1, 32, 1, 33, 1, 33, 1, 34, 1, 34, 1, 35, - 1, 35, 1, 36, 1, 36, 1, 37, 1, 37, 1, 38, 1, 38, 1, 39, 1, 39, 1, 40, 1, - 40, 1, 41, 1, 41, 1, 41, 1, 41, 1, 41, 1, 42, 1, 42, 1, 42, 1, 42, 1, 42, - 1, 42, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 1, 44, 1, 44, 1, 45, 1, 45, 1, - 46, 1, 46, 1, 47, 1, 47, 3, 47, 342, 8, 47, 1, 47, 4, 47, 345, 8, 47, 11, - 47, 12, 47, 346, 1, 48, 1, 48, 1, 49, 1, 49, 1, 50, 1, 50, 1, 50, 1, 50, - 3, 50, 357, 8, 50, 1, 51, 1, 51, 1, 51, 1, 52, 1, 52, 1, 52, 1, 52, 1, - 52, 1, 53, 1, 53, 1, 53, 1, 53, 1, 53, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, + 13, 1, 13, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, + 1, 14, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, + 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 17, 1, 17, 1, 17, 1, 17, + 1, 17, 1, 18, 1, 18, 1, 18, 1, 19, 1, 19, 1, 19, 1, 20, 1, 20, 1, 20, 1, + 21, 1, 21, 1, 22, 1, 22, 1, 22, 1, 23, 1, 23, 1, 23, 1, 24, 1, 24, 1, 25, + 1, 25, 1, 25, 1, 26, 1, 26, 1, 26, 1, 27, 1, 27, 1, 28, 1, 28, 1, 29, 1, + 29, 1, 30, 1, 30, 1, 31, 1, 31, 1, 32, 1, 32, 1, 33, 1, 33, 1, 34, 1, 34, + 1, 35, 1, 35, 1, 36, 1, 36, 1, 37, 1, 37, 1, 38, 1, 38, 1, 39, 1, 39, 1, + 40, 1, 40, 1, 41, 1, 41, 1, 41, 1, 41, 1, 41, 1, 42, 1, 42, 1, 42, 1, 42, + 1, 42, 1, 42, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 1, 44, 1, 44, 1, 45, 1, + 45, 1, 46, 1, 46, 1, 47, 1, 47, 3, 47, 344, 8, 47, 1, 47, 4, 47, 347, 8, + 47, 11, 47, 12, 47, 348, 1, 48, 1, 48, 1, 49, 1, 49, 1, 50, 1, 50, 1, 50, + 1, 50, 3, 50, 359, 8, 50, 1, 51, 1, 51, 1, 51, 1, 52, 1, 52, 1, 52, 1, + 52, 1, 52, 1, 53, 1, 53, 1, 53, 1, 53, 1, 53, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, 54, 1, - 54, 1, 54, 1, 54, 3, 54, 390, 8, 54, 1, 55, 4, 55, 393, 8, 55, 11, 55, - 12, 55, 394, 1, 56, 1, 56, 1, 56, 1, 56, 5, 56, 401, 8, 56, 10, 56, 12, - 56, 404, 9, 56, 1, 56, 1, 56, 1, 57, 4, 57, 409, 8, 57, 11, 57, 12, 57, - 410, 1, 57, 1, 57, 4, 57, 415, 8, 57, 11, 57, 12, 57, 416, 1, 57, 3, 57, - 420, 8, 57, 1, 57, 4, 57, 423, 8, 57, 11, 57, 12, 57, 424, 1, 57, 1, 57, - 1, 57, 1, 57, 4, 57, 431, 8, 57, 11, 57, 12, 57, 432, 1, 57, 3, 57, 436, - 8, 57, 3, 57, 438, 8, 57, 1, 58, 4, 58, 441, 8, 58, 11, 58, 12, 58, 442, - 1, 58, 1, 58, 1, 58, 1, 58, 4, 58, 449, 8, 58, 11, 58, 12, 58, 450, 3, - 58, 453, 8, 58, 1, 59, 4, 59, 456, 8, 59, 11, 59, 12, 59, 457, 1, 59, 1, - 59, 1, 59, 1, 59, 1, 59, 1, 59, 4, 59, 466, 8, 59, 11, 59, 12, 59, 467, - 1, 59, 1, 59, 3, 59, 472, 8, 59, 1, 60, 1, 60, 1, 60, 5, 60, 477, 8, 60, - 10, 60, 12, 60, 480, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 486, 8, - 60, 10, 60, 12, 60, 489, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, - 1, 60, 5, 60, 498, 8, 60, 10, 60, 12, 60, 501, 9, 60, 1, 60, 1, 60, 1, - 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 512, 8, 60, 10, 60, - 12, 60, 515, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 523, - 8, 60, 10, 60, 12, 60, 526, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, - 60, 533, 8, 60, 10, 60, 12, 60, 536, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, - 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 546, 8, 60, 10, 60, 12, 60, 549, 9, + 54, 1, 54, 1, 54, 1, 54, 3, 54, 392, 8, 54, 1, 55, 4, 55, 395, 8, 55, 11, + 55, 12, 55, 396, 1, 56, 1, 56, 1, 56, 1, 56, 5, 56, 403, 8, 56, 10, 56, + 12, 56, 406, 9, 56, 1, 56, 1, 56, 1, 57, 4, 57, 411, 8, 57, 11, 57, 12, + 57, 412, 1, 57, 1, 57, 4, 57, 417, 8, 57, 11, 57, 12, 57, 418, 1, 57, 3, + 57, 422, 8, 57, 1, 57, 4, 57, 425, 8, 57, 11, 57, 12, 57, 426, 1, 57, 1, + 57, 1, 57, 1, 57, 4, 57, 433, 8, 57, 11, 57, 12, 57, 434, 1, 57, 3, 57, + 438, 8, 57, 3, 57, 440, 8, 57, 1, 58, 4, 58, 443, 8, 58, 11, 58, 12, 58, + 444, 1, 58, 1, 58, 1, 58, 1, 58, 4, 58, 451, 8, 58, 11, 58, 12, 58, 452, + 3, 58, 455, 8, 58, 1, 59, 4, 59, 458, 8, 59, 11, 59, 12, 59, 459, 1, 59, + 1, 59, 1, 59, 1, 59, 1, 59, 1, 59, 4, 59, 468, 8, 59, 11, 59, 12, 59, 469, + 1, 59, 1, 59, 3, 59, 474, 8, 59, 1, 60, 1, 60, 1, 60, 5, 60, 479, 8, 60, + 10, 60, 12, 60, 482, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 488, 8, + 60, 10, 60, 12, 60, 491, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, + 1, 60, 5, 60, 500, 8, 60, 10, 60, 12, 60, 503, 9, 60, 1, 60, 1, 60, 1, + 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 514, 8, 60, 10, 60, + 12, 60, 517, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 525, + 8, 60, 10, 60, 12, 60, 528, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 5, + 60, 535, 8, 60, 10, 60, 12, 60, 538, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, + 1, 60, 1, 60, 1, 60, 1, 60, 5, 60, 548, 8, 60, 10, 60, 12, 60, 551, 9, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, 1, 60, - 5, 60, 561, 8, 60, 10, 60, 12, 60, 564, 9, 60, 1, 60, 1, 60, 1, 60, 1, - 60, 3, 60, 570, 8, 60, 1, 61, 1, 61, 1, 61, 1, 62, 1, 62, 3, 62, 577, 8, - 62, 1, 62, 1, 62, 1, 62, 1, 62, 5, 62, 583, 8, 62, 10, 62, 12, 62, 586, - 9, 62, 1, 63, 1, 63, 3, 63, 590, 8, 63, 1, 63, 1, 63, 1, 63, 3, 63, 595, - 8, 63, 1, 63, 1, 63, 1, 63, 4, 63, 600, 8, 63, 11, 63, 12, 63, 601, 5, - 63, 604, 8, 63, 10, 63, 12, 63, 607, 9, 63, 1, 64, 3, 64, 610, 8, 64, 1, - 64, 3, 64, 613, 8, 64, 1, 64, 1, 64, 3, 64, 617, 8, 64, 1, 64, 3, 64, 620, - 8, 64, 1, 64, 3, 64, 623, 8, 64, 1, 65, 1, 65, 1, 65, 1, 65, 1, 65, 1, - 66, 1, 66, 1, 66, 1, 66, 1, 66, 1, 66, 1, 66, 3, 66, 637, 8, 66, 1, 67, - 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, - 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, - 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, - 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, - 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 3, 67, 688, 8, 67, 1, 68, 1, - 68, 1, 68, 1, 68, 1, 69, 1, 69, 1, 69, 1, 69, 1, 70, 1, 70, 1, 70, 1, 70, - 1, 71, 1, 71, 1, 71, 1, 71, 1, 72, 1, 72, 1, 72, 1, 72, 1, 73, 1, 73, 1, - 73, 1, 73, 1, 74, 1, 74, 1, 74, 1, 74, 4, 499, 513, 547, 562, 0, 75, 2, - 11, 4, 1, 6, 2, 8, 12, 10, 13, 12, 14, 14, 15, 16, 16, 18, 17, 20, 18, - 22, 19, 24, 20, 26, 21, 28, 22, 30, 23, 32, 24, 34, 25, 36, 26, 38, 27, - 40, 28, 42, 29, 44, 3, 46, 30, 48, 31, 50, 4, 52, 32, 54, 33, 56, 5, 58, - 34, 60, 35, 62, 36, 64, 7, 66, 8, 68, 37, 70, 38, 72, 39, 74, 40, 76, 41, - 78, 42, 80, 43, 82, 44, 84, 45, 86, 46, 88, 47, 90, 0, 92, 0, 94, 0, 96, - 0, 98, 0, 100, 0, 102, 0, 104, 0, 106, 0, 108, 0, 110, 0, 112, 9, 114, - 48, 116, 49, 118, 50, 120, 51, 122, 52, 124, 53, 126, 10, 128, 54, 130, - 55, 132, 0, 134, 56, 136, 57, 138, 0, 140, 0, 142, 0, 144, 0, 146, 0, 148, - 0, 150, 0, 2, 0, 1, 16, 2, 0, 65, 90, 97, 122, 2, 0, 69, 69, 101, 101, - 2, 0, 43, 43, 45, 45, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 82, 82, 114, - 114, 10, 0, 34, 34, 39, 39, 63, 63, 92, 92, 96, 98, 102, 102, 110, 110, - 114, 114, 116, 116, 118, 118, 2, 0, 88, 88, 120, 120, 3, 0, 9, 9, 12, 12, - 32, 32, 1, 0, 10, 10, 2, 0, 85, 85, 117, 117, 4, 0, 10, 10, 13, 13, 34, - 34, 92, 92, 4, 0, 10, 10, 13, 13, 39, 39, 92, 92, 1, 0, 92, 92, 3, 0, 10, - 10, 13, 13, 34, 34, 3, 0, 10, 10, 13, 13, 39, 39, 2, 0, 66, 66, 98, 98, - 773, 0, 2, 1, 0, 0, 0, 0, 4, 1, 0, 0, 0, 0, 6, 1, 0, 0, 0, 0, 8, 1, 0, - 0, 0, 0, 10, 1, 0, 0, 0, 0, 12, 1, 0, 0, 0, 0, 14, 1, 0, 0, 0, 0, 16, 1, - 0, 0, 0, 0, 18, 1, 0, 0, 0, 0, 20, 1, 0, 0, 0, 0, 22, 1, 0, 0, 0, 0, 24, - 1, 0, 0, 0, 0, 26, 1, 0, 0, 0, 0, 28, 1, 0, 0, 0, 0, 30, 1, 0, 0, 0, 0, - 32, 1, 0, 0, 0, 0, 34, 1, 0, 0, 0, 0, 36, 1, 0, 0, 0, 0, 38, 1, 0, 0, 0, - 0, 40, 1, 0, 0, 0, 0, 42, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 46, 1, 0, 0, - 0, 0, 48, 1, 0, 0, 0, 0, 50, 1, 0, 0, 0, 0, 52, 1, 0, 0, 0, 0, 54, 1, 0, - 0, 0, 0, 56, 1, 0, 0, 0, 0, 58, 1, 0, 0, 0, 0, 60, 1, 0, 0, 0, 0, 62, 1, - 0, 0, 0, 0, 64, 1, 0, 0, 0, 0, 66, 1, 0, 0, 0, 0, 68, 1, 0, 0, 0, 0, 70, - 1, 0, 0, 0, 0, 72, 1, 0, 0, 0, 0, 74, 1, 0, 0, 0, 0, 76, 1, 0, 0, 0, 0, - 78, 1, 0, 0, 0, 0, 80, 1, 0, 0, 0, 0, 82, 1, 0, 0, 0, 0, 84, 1, 0, 0, 0, - 0, 86, 1, 0, 0, 0, 0, 88, 1, 0, 0, 0, 0, 112, 1, 0, 0, 0, 0, 114, 1, 0, - 0, 0, 0, 116, 1, 0, 0, 0, 0, 118, 1, 0, 0, 0, 0, 120, 1, 0, 0, 0, 0, 122, - 1, 0, 0, 0, 0, 124, 1, 0, 0, 0, 0, 126, 1, 0, 0, 0, 0, 128, 1, 0, 0, 0, - 0, 130, 1, 0, 0, 0, 1, 132, 1, 0, 0, 0, 1, 134, 1, 0, 0, 0, 1, 136, 1, - 0, 0, 0, 1, 138, 1, 0, 0, 0, 1, 140, 1, 0, 0, 0, 1, 142, 1, 0, 0, 0, 1, - 144, 1, 0, 0, 0, 1, 146, 1, 0, 0, 0, 1, 148, 1, 0, 0, 0, 1, 150, 1, 0, - 0, 0, 2, 152, 1, 0, 0, 0, 4, 154, 1, 0, 0, 0, 6, 156, 1, 0, 0, 0, 8, 158, - 1, 0, 0, 0, 10, 162, 1, 0, 0, 0, 12, 165, 1, 0, 0, 0, 14, 173, 1, 0, 0, - 0, 16, 178, 1, 0, 0, 0, 18, 185, 1, 0, 0, 0, 20, 191, 1, 0, 0, 0, 22, 199, - 1, 0, 0, 0, 24, 209, 1, 0, 0, 0, 26, 216, 1, 0, 0, 0, 28, 221, 1, 0, 0, - 0, 30, 233, 1, 0, 0, 0, 32, 243, 1, 0, 0, 0, 34, 252, 1, 0, 0, 0, 36, 259, - 1, 0, 0, 0, 38, 264, 1, 0, 0, 0, 40, 267, 1, 0, 0, 0, 42, 270, 1, 0, 0, - 0, 44, 273, 1, 0, 0, 0, 46, 275, 1, 0, 0, 0, 48, 278, 1, 0, 0, 0, 50, 281, - 1, 0, 0, 0, 52, 283, 1, 0, 0, 0, 54, 286, 1, 0, 0, 0, 56, 289, 1, 0, 0, - 0, 58, 291, 1, 0, 0, 0, 60, 293, 1, 0, 0, 0, 62, 295, 1, 0, 0, 0, 64, 297, - 1, 0, 0, 0, 66, 299, 1, 0, 0, 0, 68, 301, 1, 0, 0, 0, 70, 303, 1, 0, 0, - 0, 72, 305, 1, 0, 0, 0, 74, 307, 1, 0, 0, 0, 76, 309, 1, 0, 0, 0, 78, 311, - 1, 0, 0, 0, 80, 313, 1, 0, 0, 0, 82, 315, 1, 0, 0, 0, 84, 317, 1, 0, 0, - 0, 86, 322, 1, 0, 0, 0, 88, 328, 1, 0, 0, 0, 90, 333, 1, 0, 0, 0, 92, 335, - 1, 0, 0, 0, 94, 337, 1, 0, 0, 0, 96, 339, 1, 0, 0, 0, 98, 348, 1, 0, 0, - 0, 100, 350, 1, 0, 0, 0, 102, 356, 1, 0, 0, 0, 104, 358, 1, 0, 0, 0, 106, - 361, 1, 0, 0, 0, 108, 366, 1, 0, 0, 0, 110, 389, 1, 0, 0, 0, 112, 392, - 1, 0, 0, 0, 114, 396, 1, 0, 0, 0, 116, 437, 1, 0, 0, 0, 118, 452, 1, 0, - 0, 0, 120, 471, 1, 0, 0, 0, 122, 569, 1, 0, 0, 0, 124, 571, 1, 0, 0, 0, - 126, 576, 1, 0, 0, 0, 128, 589, 1, 0, 0, 0, 130, 609, 1, 0, 0, 0, 132, - 624, 1, 0, 0, 0, 134, 636, 1, 0, 0, 0, 136, 687, 1, 0, 0, 0, 138, 689, - 1, 0, 0, 0, 140, 693, 1, 0, 0, 0, 142, 697, 1, 0, 0, 0, 144, 701, 1, 0, - 0, 0, 146, 705, 1, 0, 0, 0, 148, 709, 1, 0, 0, 0, 150, 713, 1, 0, 0, 0, - 152, 153, 5, 35, 0, 0, 153, 3, 1, 0, 0, 0, 154, 155, 5, 58, 0, 0, 155, - 5, 1, 0, 0, 0, 156, 157, 5, 44, 0, 0, 157, 7, 1, 0, 0, 0, 158, 159, 5, - 97, 0, 0, 159, 160, 5, 110, 0, 0, 160, 161, 5, 100, 0, 0, 161, 9, 1, 0, - 0, 0, 162, 163, 5, 111, 0, 0, 163, 164, 5, 114, 0, 0, 164, 11, 1, 0, 0, - 0, 165, 166, 5, 98, 0, 0, 166, 167, 5, 117, 0, 0, 167, 168, 5, 116, 0, - 0, 168, 169, 5, 32, 0, 0, 169, 170, 5, 110, 0, 0, 170, 171, 5, 111, 0, - 0, 171, 172, 5, 116, 0, 0, 172, 13, 1, 0, 0, 0, 173, 174, 5, 102, 0, 0, - 174, 175, 5, 114, 0, 0, 175, 176, 5, 111, 0, 0, 176, 177, 5, 109, 0, 0, - 177, 15, 1, 0, 0, 0, 178, 179, 5, 109, 0, 0, 179, 180, 5, 111, 0, 0, 180, - 181, 5, 100, 0, 0, 181, 182, 5, 117, 0, 0, 182, 183, 5, 108, 0, 0, 183, - 184, 5, 101, 0, 0, 184, 17, 1, 0, 0, 0, 185, 186, 5, 109, 0, 0, 186, 187, - 5, 111, 0, 0, 187, 188, 5, 100, 0, 0, 188, 189, 5, 101, 0, 0, 189, 190, - 5, 108, 0, 0, 190, 19, 1, 0, 0, 0, 191, 192, 5, 115, 0, 0, 192, 193, 5, - 99, 0, 0, 193, 194, 5, 104, 0, 0, 194, 195, 5, 101, 0, 0, 195, 196, 5, - 109, 0, 0, 196, 197, 5, 97, 0, 0, 197, 21, 1, 0, 0, 0, 198, 200, 3, 94, - 46, 0, 199, 198, 1, 0, 0, 0, 200, 201, 1, 0, 0, 0, 201, 199, 1, 0, 0, 0, - 201, 202, 1, 0, 0, 0, 202, 203, 1, 0, 0, 0, 203, 205, 5, 46, 0, 0, 204, - 206, 3, 94, 46, 0, 205, 204, 1, 0, 0, 0, 206, 207, 1, 0, 0, 0, 207, 205, - 1, 0, 0, 0, 207, 208, 1, 0, 0, 0, 208, 23, 1, 0, 0, 0, 209, 210, 5, 101, - 0, 0, 210, 211, 5, 120, 0, 0, 211, 212, 5, 116, 0, 0, 212, 213, 5, 101, - 0, 0, 213, 214, 5, 110, 0, 0, 214, 215, 5, 100, 0, 0, 215, 25, 1, 0, 0, - 0, 216, 217, 5, 116, 0, 0, 217, 218, 5, 121, 0, 0, 218, 219, 5, 112, 0, - 0, 219, 220, 5, 101, 0, 0, 220, 27, 1, 0, 0, 0, 221, 222, 5, 99, 0, 0, - 222, 223, 5, 111, 0, 0, 223, 224, 5, 110, 0, 0, 224, 225, 5, 100, 0, 0, - 225, 226, 5, 105, 0, 0, 226, 227, 5, 116, 0, 0, 227, 228, 5, 105, 0, 0, - 228, 229, 5, 111, 0, 0, 229, 230, 5, 110, 0, 0, 230, 231, 1, 0, 0, 0, 231, - 232, 6, 13, 0, 0, 232, 29, 1, 0, 0, 0, 233, 234, 5, 114, 0, 0, 234, 235, - 5, 101, 0, 0, 235, 236, 5, 108, 0, 0, 236, 237, 5, 97, 0, 0, 237, 238, - 5, 116, 0, 0, 238, 239, 5, 105, 0, 0, 239, 240, 5, 111, 0, 0, 240, 241, - 5, 110, 0, 0, 241, 242, 5, 115, 0, 0, 242, 31, 1, 0, 0, 0, 243, 244, 5, - 114, 0, 0, 244, 245, 5, 101, 0, 0, 245, 246, 5, 108, 0, 0, 246, 247, 5, - 97, 0, 0, 247, 248, 5, 116, 0, 0, 248, 249, 5, 105, 0, 0, 249, 250, 5, - 111, 0, 0, 250, 251, 5, 110, 0, 0, 251, 33, 1, 0, 0, 0, 252, 253, 5, 100, - 0, 0, 253, 254, 5, 101, 0, 0, 254, 255, 5, 102, 0, 0, 255, 256, 5, 105, - 0, 0, 256, 257, 5, 110, 0, 0, 257, 258, 5, 101, 0, 0, 258, 35, 1, 0, 0, - 0, 259, 260, 5, 119, 0, 0, 260, 261, 5, 105, 0, 0, 261, 262, 5, 116, 0, - 0, 262, 263, 5, 104, 0, 0, 263, 37, 1, 0, 0, 0, 264, 265, 5, 61, 0, 0, - 265, 266, 5, 61, 0, 0, 266, 39, 1, 0, 0, 0, 267, 268, 5, 33, 0, 0, 268, - 269, 5, 61, 0, 0, 269, 41, 1, 0, 0, 0, 270, 271, 5, 105, 0, 0, 271, 272, - 5, 110, 0, 0, 272, 43, 1, 0, 0, 0, 273, 274, 5, 60, 0, 0, 274, 45, 1, 0, - 0, 0, 275, 276, 5, 60, 0, 0, 276, 277, 5, 61, 0, 0, 277, 47, 1, 0, 0, 0, - 278, 279, 5, 62, 0, 0, 279, 280, 5, 61, 0, 0, 280, 49, 1, 0, 0, 0, 281, - 282, 5, 62, 0, 0, 282, 51, 1, 0, 0, 0, 283, 284, 5, 38, 0, 0, 284, 285, - 5, 38, 0, 0, 285, 53, 1, 0, 0, 0, 286, 287, 5, 124, 0, 0, 287, 288, 5, - 124, 0, 0, 288, 55, 1, 0, 0, 0, 289, 290, 5, 91, 0, 0, 290, 57, 1, 0, 0, - 0, 291, 292, 5, 93, 0, 0, 292, 59, 1, 0, 0, 0, 293, 294, 5, 123, 0, 0, - 294, 61, 1, 0, 0, 0, 295, 296, 5, 125, 0, 0, 296, 63, 1, 0, 0, 0, 297, - 298, 5, 40, 0, 0, 298, 65, 1, 0, 0, 0, 299, 300, 5, 41, 0, 0, 300, 67, - 1, 0, 0, 0, 301, 302, 5, 46, 0, 0, 302, 69, 1, 0, 0, 0, 303, 304, 5, 45, - 0, 0, 304, 71, 1, 0, 0, 0, 305, 306, 5, 33, 0, 0, 306, 73, 1, 0, 0, 0, - 307, 308, 5, 63, 0, 0, 308, 75, 1, 0, 0, 0, 309, 310, 5, 43, 0, 0, 310, - 77, 1, 0, 0, 0, 311, 312, 5, 42, 0, 0, 312, 79, 1, 0, 0, 0, 313, 314, 5, - 47, 0, 0, 314, 81, 1, 0, 0, 0, 315, 316, 5, 37, 0, 0, 316, 83, 1, 0, 0, - 0, 317, 318, 5, 116, 0, 0, 318, 319, 5, 114, 0, 0, 319, 320, 5, 117, 0, - 0, 320, 321, 5, 101, 0, 0, 321, 85, 1, 0, 0, 0, 322, 323, 5, 102, 0, 0, - 323, 324, 5, 97, 0, 0, 324, 325, 5, 108, 0, 0, 325, 326, 5, 115, 0, 0, - 326, 327, 5, 101, 0, 0, 327, 87, 1, 0, 0, 0, 328, 329, 5, 110, 0, 0, 329, - 330, 5, 117, 0, 0, 330, 331, 5, 108, 0, 0, 331, 332, 5, 108, 0, 0, 332, - 89, 1, 0, 0, 0, 333, 334, 5, 92, 0, 0, 334, 91, 1, 0, 0, 0, 335, 336, 7, - 0, 0, 0, 336, 93, 1, 0, 0, 0, 337, 338, 2, 48, 57, 0, 338, 95, 1, 0, 0, - 0, 339, 341, 7, 1, 0, 0, 340, 342, 7, 2, 0, 0, 341, 340, 1, 0, 0, 0, 341, - 342, 1, 0, 0, 0, 342, 344, 1, 0, 0, 0, 343, 345, 3, 94, 46, 0, 344, 343, - 1, 0, 0, 0, 345, 346, 1, 0, 0, 0, 346, 344, 1, 0, 0, 0, 346, 347, 1, 0, - 0, 0, 347, 97, 1, 0, 0, 0, 348, 349, 7, 3, 0, 0, 349, 99, 1, 0, 0, 0, 350, - 351, 7, 4, 0, 0, 351, 101, 1, 0, 0, 0, 352, 357, 3, 104, 51, 0, 353, 357, - 3, 108, 53, 0, 354, 357, 3, 110, 54, 0, 355, 357, 3, 106, 52, 0, 356, 352, - 1, 0, 0, 0, 356, 353, 1, 0, 0, 0, 356, 354, 1, 0, 0, 0, 356, 355, 1, 0, - 0, 0, 357, 103, 1, 0, 0, 0, 358, 359, 3, 90, 44, 0, 359, 360, 7, 5, 0, - 0, 360, 105, 1, 0, 0, 0, 361, 362, 3, 90, 44, 0, 362, 363, 2, 48, 51, 0, - 363, 364, 2, 48, 55, 0, 364, 365, 2, 48, 55, 0, 365, 107, 1, 0, 0, 0, 366, - 367, 3, 90, 44, 0, 367, 368, 7, 6, 0, 0, 368, 369, 3, 98, 48, 0, 369, 370, - 3, 98, 48, 0, 370, 109, 1, 0, 0, 0, 371, 372, 3, 90, 44, 0, 372, 373, 5, - 117, 0, 0, 373, 374, 3, 98, 48, 0, 374, 375, 3, 98, 48, 0, 375, 376, 3, - 98, 48, 0, 376, 377, 3, 98, 48, 0, 377, 390, 1, 0, 0, 0, 378, 379, 3, 90, - 44, 0, 379, 380, 5, 85, 0, 0, 380, 381, 3, 98, 48, 0, 381, 382, 3, 98, - 48, 0, 382, 383, 3, 98, 48, 0, 383, 384, 3, 98, 48, 0, 384, 385, 3, 98, - 48, 0, 385, 386, 3, 98, 48, 0, 386, 387, 3, 98, 48, 0, 387, 388, 3, 98, - 48, 0, 388, 390, 1, 0, 0, 0, 389, 371, 1, 0, 0, 0, 389, 378, 1, 0, 0, 0, - 390, 111, 1, 0, 0, 0, 391, 393, 7, 7, 0, 0, 392, 391, 1, 0, 0, 0, 393, - 394, 1, 0, 0, 0, 394, 392, 1, 0, 0, 0, 394, 395, 1, 0, 0, 0, 395, 113, - 1, 0, 0, 0, 396, 397, 5, 47, 0, 0, 397, 398, 5, 47, 0, 0, 398, 402, 1, - 0, 0, 0, 399, 401, 8, 8, 0, 0, 400, 399, 1, 0, 0, 0, 401, 404, 1, 0, 0, - 0, 402, 400, 1, 0, 0, 0, 402, 403, 1, 0, 0, 0, 403, 405, 1, 0, 0, 0, 404, - 402, 1, 0, 0, 0, 405, 406, 6, 56, 1, 0, 406, 115, 1, 0, 0, 0, 407, 409, - 3, 94, 46, 0, 408, 407, 1, 0, 0, 0, 409, 410, 1, 0, 0, 0, 410, 408, 1, - 0, 0, 0, 410, 411, 1, 0, 0, 0, 411, 412, 1, 0, 0, 0, 412, 414, 5, 46, 0, - 0, 413, 415, 3, 94, 46, 0, 414, 413, 1, 0, 0, 0, 415, 416, 1, 0, 0, 0, - 416, 414, 1, 0, 0, 0, 416, 417, 1, 0, 0, 0, 417, 419, 1, 0, 0, 0, 418, - 420, 3, 96, 47, 0, 419, 418, 1, 0, 0, 0, 419, 420, 1, 0, 0, 0, 420, 438, - 1, 0, 0, 0, 421, 423, 3, 94, 46, 0, 422, 421, 1, 0, 0, 0, 423, 424, 1, - 0, 0, 0, 424, 422, 1, 0, 0, 0, 424, 425, 1, 0, 0, 0, 425, 426, 1, 0, 0, - 0, 426, 427, 3, 96, 47, 0, 427, 438, 1, 0, 0, 0, 428, 430, 5, 46, 0, 0, - 429, 431, 3, 94, 46, 0, 430, 429, 1, 0, 0, 0, 431, 432, 1, 0, 0, 0, 432, - 430, 1, 0, 0, 0, 432, 433, 1, 0, 0, 0, 433, 435, 1, 0, 0, 0, 434, 436, - 3, 96, 47, 0, 435, 434, 1, 0, 0, 0, 435, 436, 1, 0, 0, 0, 436, 438, 1, - 0, 0, 0, 437, 408, 1, 0, 0, 0, 437, 422, 1, 0, 0, 0, 437, 428, 1, 0, 0, - 0, 438, 117, 1, 0, 0, 0, 439, 441, 3, 94, 46, 0, 440, 439, 1, 0, 0, 0, - 441, 442, 1, 0, 0, 0, 442, 440, 1, 0, 0, 0, 442, 443, 1, 0, 0, 0, 443, - 453, 1, 0, 0, 0, 444, 445, 5, 48, 0, 0, 445, 446, 5, 120, 0, 0, 446, 448, - 1, 0, 0, 0, 447, 449, 3, 98, 48, 0, 448, 447, 1, 0, 0, 0, 449, 450, 1, - 0, 0, 0, 450, 448, 1, 0, 0, 0, 450, 451, 1, 0, 0, 0, 451, 453, 1, 0, 0, - 0, 452, 440, 1, 0, 0, 0, 452, 444, 1, 0, 0, 0, 453, 119, 1, 0, 0, 0, 454, - 456, 3, 94, 46, 0, 455, 454, 1, 0, 0, 0, 456, 457, 1, 0, 0, 0, 457, 455, - 1, 0, 0, 0, 457, 458, 1, 0, 0, 0, 458, 459, 1, 0, 0, 0, 459, 460, 7, 9, - 0, 0, 460, 472, 1, 0, 0, 0, 461, 462, 5, 48, 0, 0, 462, 463, 5, 120, 0, - 0, 463, 465, 1, 0, 0, 0, 464, 466, 3, 98, 48, 0, 465, 464, 1, 0, 0, 0, - 466, 467, 1, 0, 0, 0, 467, 465, 1, 0, 0, 0, 467, 468, 1, 0, 0, 0, 468, - 469, 1, 0, 0, 0, 469, 470, 7, 9, 0, 0, 470, 472, 1, 0, 0, 0, 471, 455, - 1, 0, 0, 0, 471, 461, 1, 0, 0, 0, 472, 121, 1, 0, 0, 0, 473, 478, 5, 34, - 0, 0, 474, 477, 3, 102, 50, 0, 475, 477, 8, 10, 0, 0, 476, 474, 1, 0, 0, - 0, 476, 475, 1, 0, 0, 0, 477, 480, 1, 0, 0, 0, 478, 476, 1, 0, 0, 0, 478, - 479, 1, 0, 0, 0, 479, 481, 1, 0, 0, 0, 480, 478, 1, 0, 0, 0, 481, 570, - 5, 34, 0, 0, 482, 487, 5, 39, 0, 0, 483, 486, 3, 102, 50, 0, 484, 486, - 8, 11, 0, 0, 485, 483, 1, 0, 0, 0, 485, 484, 1, 0, 0, 0, 486, 489, 1, 0, - 0, 0, 487, 485, 1, 0, 0, 0, 487, 488, 1, 0, 0, 0, 488, 490, 1, 0, 0, 0, - 489, 487, 1, 0, 0, 0, 490, 570, 5, 39, 0, 0, 491, 492, 5, 34, 0, 0, 492, - 493, 5, 34, 0, 0, 493, 494, 5, 34, 0, 0, 494, 499, 1, 0, 0, 0, 495, 498, - 3, 102, 50, 0, 496, 498, 8, 12, 0, 0, 497, 495, 1, 0, 0, 0, 497, 496, 1, - 0, 0, 0, 498, 501, 1, 0, 0, 0, 499, 500, 1, 0, 0, 0, 499, 497, 1, 0, 0, - 0, 500, 502, 1, 0, 0, 0, 501, 499, 1, 0, 0, 0, 502, 503, 5, 34, 0, 0, 503, - 504, 5, 34, 0, 0, 504, 570, 5, 34, 0, 0, 505, 506, 5, 39, 0, 0, 506, 507, - 5, 39, 0, 0, 507, 508, 5, 39, 0, 0, 508, 513, 1, 0, 0, 0, 509, 512, 3, - 102, 50, 0, 510, 512, 8, 12, 0, 0, 511, 509, 1, 0, 0, 0, 511, 510, 1, 0, - 0, 0, 512, 515, 1, 0, 0, 0, 513, 514, 1, 0, 0, 0, 513, 511, 1, 0, 0, 0, - 514, 516, 1, 0, 0, 0, 515, 513, 1, 0, 0, 0, 516, 517, 5, 39, 0, 0, 517, - 518, 5, 39, 0, 0, 518, 570, 5, 39, 0, 0, 519, 520, 3, 100, 49, 0, 520, - 524, 5, 34, 0, 0, 521, 523, 8, 13, 0, 0, 522, 521, 1, 0, 0, 0, 523, 526, - 1, 0, 0, 0, 524, 522, 1, 0, 0, 0, 524, 525, 1, 0, 0, 0, 525, 527, 1, 0, - 0, 0, 526, 524, 1, 0, 0, 0, 527, 528, 5, 34, 0, 0, 528, 570, 1, 0, 0, 0, - 529, 530, 3, 100, 49, 0, 530, 534, 5, 39, 0, 0, 531, 533, 8, 14, 0, 0, - 532, 531, 1, 0, 0, 0, 533, 536, 1, 0, 0, 0, 534, 532, 1, 0, 0, 0, 534, - 535, 1, 0, 0, 0, 535, 537, 1, 0, 0, 0, 536, 534, 1, 0, 0, 0, 537, 538, - 5, 39, 0, 0, 538, 570, 1, 0, 0, 0, 539, 540, 3, 100, 49, 0, 540, 541, 5, - 34, 0, 0, 541, 542, 5, 34, 0, 0, 542, 543, 5, 34, 0, 0, 543, 547, 1, 0, - 0, 0, 544, 546, 9, 0, 0, 0, 545, 544, 1, 0, 0, 0, 546, 549, 1, 0, 0, 0, - 547, 548, 1, 0, 0, 0, 547, 545, 1, 0, 0, 0, 548, 550, 1, 0, 0, 0, 549, - 547, 1, 0, 0, 0, 550, 551, 5, 34, 0, 0, 551, 552, 5, 34, 0, 0, 552, 553, - 5, 34, 0, 0, 553, 570, 1, 0, 0, 0, 554, 555, 3, 100, 49, 0, 555, 556, 5, - 39, 0, 0, 556, 557, 5, 39, 0, 0, 557, 558, 5, 39, 0, 0, 558, 562, 1, 0, - 0, 0, 559, 561, 9, 0, 0, 0, 560, 559, 1, 0, 0, 0, 561, 564, 1, 0, 0, 0, - 562, 563, 1, 0, 0, 0, 562, 560, 1, 0, 0, 0, 563, 565, 1, 0, 0, 0, 564, - 562, 1, 0, 0, 0, 565, 566, 5, 39, 0, 0, 566, 567, 5, 39, 0, 0, 567, 568, - 5, 39, 0, 0, 568, 570, 1, 0, 0, 0, 569, 473, 1, 0, 0, 0, 569, 482, 1, 0, - 0, 0, 569, 491, 1, 0, 0, 0, 569, 505, 1, 0, 0, 0, 569, 519, 1, 0, 0, 0, - 569, 529, 1, 0, 0, 0, 569, 539, 1, 0, 0, 0, 569, 554, 1, 0, 0, 0, 570, - 123, 1, 0, 0, 0, 571, 572, 7, 15, 0, 0, 572, 573, 3, 122, 60, 0, 573, 125, - 1, 0, 0, 0, 574, 577, 3, 92, 45, 0, 575, 577, 5, 95, 0, 0, 576, 574, 1, - 0, 0, 0, 576, 575, 1, 0, 0, 0, 577, 584, 1, 0, 0, 0, 578, 583, 3, 92, 45, - 0, 579, 583, 3, 94, 46, 0, 580, 583, 5, 95, 0, 0, 581, 583, 3, 70, 34, - 0, 582, 578, 1, 0, 0, 0, 582, 579, 1, 0, 0, 0, 582, 580, 1, 0, 0, 0, 582, - 581, 1, 0, 0, 0, 583, 586, 1, 0, 0, 0, 584, 582, 1, 0, 0, 0, 584, 585, - 1, 0, 0, 0, 585, 127, 1, 0, 0, 0, 586, 584, 1, 0, 0, 0, 587, 590, 3, 92, - 45, 0, 588, 590, 5, 95, 0, 0, 589, 587, 1, 0, 0, 0, 589, 588, 1, 0, 0, - 0, 590, 605, 1, 0, 0, 0, 591, 595, 3, 80, 39, 0, 592, 595, 3, 68, 33, 0, - 593, 595, 3, 70, 34, 0, 594, 591, 1, 0, 0, 0, 594, 592, 1, 0, 0, 0, 594, - 593, 1, 0, 0, 0, 594, 595, 1, 0, 0, 0, 595, 599, 1, 0, 0, 0, 596, 600, - 3, 92, 45, 0, 597, 600, 3, 94, 46, 0, 598, 600, 5, 95, 0, 0, 599, 596, - 1, 0, 0, 0, 599, 597, 1, 0, 0, 0, 599, 598, 1, 0, 0, 0, 600, 601, 1, 0, - 0, 0, 601, 599, 1, 0, 0, 0, 601, 602, 1, 0, 0, 0, 602, 604, 1, 0, 0, 0, - 603, 594, 1, 0, 0, 0, 604, 607, 1, 0, 0, 0, 605, 603, 1, 0, 0, 0, 605, - 606, 1, 0, 0, 0, 606, 129, 1, 0, 0, 0, 607, 605, 1, 0, 0, 0, 608, 610, - 3, 112, 55, 0, 609, 608, 1, 0, 0, 0, 609, 610, 1, 0, 0, 0, 610, 616, 1, - 0, 0, 0, 611, 613, 5, 13, 0, 0, 612, 611, 1, 0, 0, 0, 612, 613, 1, 0, 0, - 0, 613, 614, 1, 0, 0, 0, 614, 617, 5, 10, 0, 0, 615, 617, 2, 12, 13, 0, - 616, 612, 1, 0, 0, 0, 616, 615, 1, 0, 0, 0, 617, 619, 1, 0, 0, 0, 618, - 620, 3, 112, 55, 0, 619, 618, 1, 0, 0, 0, 619, 620, 1, 0, 0, 0, 620, 622, - 1, 0, 0, 0, 621, 623, 3, 130, 64, 0, 622, 621, 1, 0, 0, 0, 622, 623, 1, - 0, 0, 0, 623, 131, 1, 0, 0, 0, 624, 625, 3, 66, 32, 0, 625, 626, 1, 0, - 0, 0, 626, 627, 6, 65, 2, 0, 627, 628, 6, 65, 3, 0, 628, 133, 1, 0, 0, - 0, 629, 630, 5, 109, 0, 0, 630, 631, 5, 97, 0, 0, 631, 637, 5, 112, 0, - 0, 632, 633, 5, 108, 0, 0, 633, 634, 5, 105, 0, 0, 634, 635, 5, 115, 0, - 0, 635, 637, 5, 116, 0, 0, 636, 629, 1, 0, 0, 0, 636, 632, 1, 0, 0, 0, - 637, 135, 1, 0, 0, 0, 638, 639, 5, 98, 0, 0, 639, 640, 5, 111, 0, 0, 640, - 641, 5, 111, 0, 0, 641, 688, 5, 108, 0, 0, 642, 643, 5, 115, 0, 0, 643, - 644, 5, 116, 0, 0, 644, 645, 5, 114, 0, 0, 645, 646, 5, 105, 0, 0, 646, - 647, 5, 110, 0, 0, 647, 688, 5, 103, 0, 0, 648, 649, 5, 105, 0, 0, 649, - 650, 5, 110, 0, 0, 650, 688, 5, 116, 0, 0, 651, 652, 5, 117, 0, 0, 652, - 653, 5, 105, 0, 0, 653, 654, 5, 110, 0, 0, 654, 688, 5, 116, 0, 0, 655, - 656, 5, 100, 0, 0, 656, 657, 5, 111, 0, 0, 657, 658, 5, 117, 0, 0, 658, - 659, 5, 98, 0, 0, 659, 660, 5, 108, 0, 0, 660, 688, 5, 101, 0, 0, 661, - 662, 5, 100, 0, 0, 662, 663, 5, 117, 0, 0, 663, 664, 5, 114, 0, 0, 664, - 665, 5, 97, 0, 0, 665, 666, 5, 116, 0, 0, 666, 667, 5, 105, 0, 0, 667, - 668, 5, 111, 0, 0, 668, 688, 5, 110, 0, 0, 669, 670, 5, 116, 0, 0, 670, - 671, 5, 105, 0, 0, 671, 672, 5, 109, 0, 0, 672, 673, 5, 101, 0, 0, 673, - 674, 5, 115, 0, 0, 674, 675, 5, 116, 0, 0, 675, 676, 5, 97, 0, 0, 676, - 677, 5, 109, 0, 0, 677, 688, 5, 112, 0, 0, 678, 679, 5, 105, 0, 0, 679, - 680, 5, 112, 0, 0, 680, 681, 5, 97, 0, 0, 681, 682, 5, 100, 0, 0, 682, - 683, 5, 100, 0, 0, 683, 684, 5, 114, 0, 0, 684, 685, 5, 101, 0, 0, 685, - 686, 5, 115, 0, 0, 686, 688, 5, 115, 0, 0, 687, 638, 1, 0, 0, 0, 687, 642, - 1, 0, 0, 0, 687, 648, 1, 0, 0, 0, 687, 651, 1, 0, 0, 0, 687, 655, 1, 0, - 0, 0, 687, 661, 1, 0, 0, 0, 687, 669, 1, 0, 0, 0, 687, 678, 1, 0, 0, 0, - 688, 137, 1, 0, 0, 0, 689, 690, 3, 44, 21, 0, 690, 691, 1, 0, 0, 0, 691, - 692, 6, 68, 4, 0, 692, 139, 1, 0, 0, 0, 693, 694, 3, 50, 24, 0, 694, 695, - 1, 0, 0, 0, 695, 696, 6, 69, 5, 0, 696, 141, 1, 0, 0, 0, 697, 698, 3, 64, - 31, 0, 698, 699, 1, 0, 0, 0, 699, 700, 6, 70, 6, 0, 700, 143, 1, 0, 0, - 0, 701, 702, 3, 4, 1, 0, 702, 703, 1, 0, 0, 0, 703, 704, 6, 71, 7, 0, 704, - 145, 1, 0, 0, 0, 705, 706, 3, 6, 2, 0, 706, 707, 1, 0, 0, 0, 707, 708, - 6, 72, 8, 0, 708, 147, 1, 0, 0, 0, 709, 710, 3, 112, 55, 0, 710, 711, 1, - 0, 0, 0, 711, 712, 6, 73, 9, 0, 712, 149, 1, 0, 0, 0, 713, 714, 3, 126, - 62, 0, 714, 715, 1, 0, 0, 0, 715, 716, 6, 74, 10, 0, 716, 151, 1, 0, 0, - 0, 51, 0, 1, 201, 207, 341, 346, 356, 389, 394, 402, 410, 416, 419, 424, - 432, 435, 437, 442, 450, 452, 457, 467, 471, 476, 478, 485, 487, 497, 499, - 511, 513, 524, 534, 547, 562, 569, 576, 582, 584, 589, 594, 599, 601, 605, - 609, 612, 616, 619, 622, 636, 687, 11, 5, 1, 0, 0, 1, 0, 7, 8, 0, 4, 0, - 0, 7, 3, 0, 7, 4, 0, 7, 7, 0, 7, 1, 0, 7, 2, 0, 7, 9, 0, 7, 10, 0, + 5, 60, 563, 8, 60, 10, 60, 12, 60, 566, 9, 60, 1, 60, 1, 60, 1, 60, 1, + 60, 3, 60, 572, 8, 60, 1, 61, 1, 61, 1, 61, 1, 62, 1, 62, 1, 62, 1, 62, + 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 62, 1, 63, 1, 63, 3, + 63, 591, 8, 63, 1, 63, 1, 63, 1, 63, 1, 63, 5, 63, 597, 8, 63, 10, 63, + 12, 63, 600, 9, 63, 1, 64, 1, 64, 3, 64, 604, 8, 64, 1, 64, 1, 64, 1, 64, + 3, 64, 609, 8, 64, 1, 64, 1, 64, 1, 64, 4, 64, 614, 8, 64, 11, 64, 12, + 64, 615, 5, 64, 618, 8, 64, 10, 64, 12, 64, 621, 9, 64, 1, 65, 3, 65, 624, + 8, 65, 1, 65, 3, 65, 627, 8, 65, 1, 65, 1, 65, 3, 65, 631, 8, 65, 1, 65, + 3, 65, 634, 8, 65, 1, 65, 3, 65, 637, 8, 65, 1, 66, 1, 66, 1, 66, 1, 66, + 1, 66, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 1, 67, 3, 67, 651, 8, + 67, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, + 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, + 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, + 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, + 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 1, 68, 3, 68, 702, 8, 68, + 1, 69, 1, 69, 1, 69, 1, 69, 1, 70, 1, 70, 1, 70, 1, 70, 1, 71, 1, 71, 1, + 71, 1, 71, 1, 72, 1, 72, 1, 72, 1, 72, 1, 73, 1, 73, 1, 73, 1, 73, 1, 74, + 1, 74, 1, 74, 1, 74, 1, 75, 1, 75, 1, 75, 1, 75, 4, 501, 515, 549, 564, + 0, 76, 2, 11, 4, 1, 6, 2, 8, 12, 10, 13, 12, 14, 14, 15, 16, 16, 18, 17, + 20, 18, 22, 19, 24, 20, 26, 21, 28, 22, 30, 23, 32, 24, 34, 25, 36, 26, + 38, 27, 40, 28, 42, 29, 44, 3, 46, 30, 48, 31, 50, 4, 52, 32, 54, 33, 56, + 5, 58, 34, 60, 35, 62, 36, 64, 7, 66, 8, 68, 37, 70, 38, 72, 39, 74, 40, + 76, 41, 78, 42, 80, 43, 82, 44, 84, 45, 86, 46, 88, 47, 90, 0, 92, 0, 94, + 0, 96, 0, 98, 0, 100, 0, 102, 0, 104, 0, 106, 0, 108, 0, 110, 0, 112, 9, + 114, 48, 116, 49, 118, 50, 120, 51, 122, 52, 124, 53, 126, 54, 128, 10, + 130, 55, 132, 56, 134, 0, 136, 57, 138, 58, 140, 0, 142, 0, 144, 0, 146, + 0, 148, 0, 150, 0, 152, 0, 2, 0, 1, 16, 2, 0, 65, 90, 97, 122, 2, 0, 69, + 69, 101, 101, 2, 0, 43, 43, 45, 45, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, + 82, 82, 114, 114, 10, 0, 34, 34, 39, 39, 63, 63, 92, 92, 96, 98, 102, 102, + 110, 110, 114, 114, 116, 116, 118, 118, 2, 0, 88, 88, 120, 120, 3, 0, 9, + 9, 12, 12, 32, 32, 1, 0, 10, 10, 2, 0, 85, 85, 117, 117, 4, 0, 10, 10, + 13, 13, 34, 34, 92, 92, 4, 0, 10, 10, 13, 13, 39, 39, 92, 92, 1, 0, 92, + 92, 3, 0, 10, 10, 13, 13, 34, 34, 3, 0, 10, 10, 13, 13, 39, 39, 2, 0, 66, + 66, 98, 98, 787, 0, 2, 1, 0, 0, 0, 0, 4, 1, 0, 0, 0, 0, 6, 1, 0, 0, 0, + 0, 8, 1, 0, 0, 0, 0, 10, 1, 0, 0, 0, 0, 12, 1, 0, 0, 0, 0, 14, 1, 0, 0, + 0, 0, 16, 1, 0, 0, 0, 0, 18, 1, 0, 0, 0, 0, 20, 1, 0, 0, 0, 0, 22, 1, 0, + 0, 0, 0, 24, 1, 0, 0, 0, 0, 26, 1, 0, 0, 0, 0, 28, 1, 0, 0, 0, 0, 30, 1, + 0, 0, 0, 0, 32, 1, 0, 0, 0, 0, 34, 1, 0, 0, 0, 0, 36, 1, 0, 0, 0, 0, 38, + 1, 0, 0, 0, 0, 40, 1, 0, 0, 0, 0, 42, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, + 46, 1, 0, 0, 0, 0, 48, 1, 0, 0, 0, 0, 50, 1, 0, 0, 0, 0, 52, 1, 0, 0, 0, + 0, 54, 1, 0, 0, 0, 0, 56, 1, 0, 0, 0, 0, 58, 1, 0, 0, 0, 0, 60, 1, 0, 0, + 0, 0, 62, 1, 0, 0, 0, 0, 64, 1, 0, 0, 0, 0, 66, 1, 0, 0, 0, 0, 68, 1, 0, + 0, 0, 0, 70, 1, 0, 0, 0, 0, 72, 1, 0, 0, 0, 0, 74, 1, 0, 0, 0, 0, 76, 1, + 0, 0, 0, 0, 78, 1, 0, 0, 0, 0, 80, 1, 0, 0, 0, 0, 82, 1, 0, 0, 0, 0, 84, + 1, 0, 0, 0, 0, 86, 1, 0, 0, 0, 0, 88, 1, 0, 0, 0, 0, 112, 1, 0, 0, 0, 0, + 114, 1, 0, 0, 0, 0, 116, 1, 0, 0, 0, 0, 118, 1, 0, 0, 0, 0, 120, 1, 0, + 0, 0, 0, 122, 1, 0, 0, 0, 0, 124, 1, 0, 0, 0, 0, 126, 1, 0, 0, 0, 0, 128, + 1, 0, 0, 0, 0, 130, 1, 0, 0, 0, 0, 132, 1, 0, 0, 0, 1, 134, 1, 0, 0, 0, + 1, 136, 1, 0, 0, 0, 1, 138, 1, 0, 0, 0, 1, 140, 1, 0, 0, 0, 1, 142, 1, + 0, 0, 0, 1, 144, 1, 0, 0, 0, 1, 146, 1, 0, 0, 0, 1, 148, 1, 0, 0, 0, 1, + 150, 1, 0, 0, 0, 1, 152, 1, 0, 0, 0, 2, 154, 1, 0, 0, 0, 4, 156, 1, 0, + 0, 0, 6, 158, 1, 0, 0, 0, 8, 160, 1, 0, 0, 0, 10, 164, 1, 0, 0, 0, 12, + 167, 1, 0, 0, 0, 14, 175, 1, 0, 0, 0, 16, 180, 1, 0, 0, 0, 18, 187, 1, + 0, 0, 0, 20, 193, 1, 0, 0, 0, 22, 201, 1, 0, 0, 0, 24, 211, 1, 0, 0, 0, + 26, 218, 1, 0, 0, 0, 28, 223, 1, 0, 0, 0, 30, 235, 1, 0, 0, 0, 32, 245, + 1, 0, 0, 0, 34, 254, 1, 0, 0, 0, 36, 261, 1, 0, 0, 0, 38, 266, 1, 0, 0, + 0, 40, 269, 1, 0, 0, 0, 42, 272, 1, 0, 0, 0, 44, 275, 1, 0, 0, 0, 46, 277, + 1, 0, 0, 0, 48, 280, 1, 0, 0, 0, 50, 283, 1, 0, 0, 0, 52, 285, 1, 0, 0, + 0, 54, 288, 1, 0, 0, 0, 56, 291, 1, 0, 0, 0, 58, 293, 1, 0, 0, 0, 60, 295, + 1, 0, 0, 0, 62, 297, 1, 0, 0, 0, 64, 299, 1, 0, 0, 0, 66, 301, 1, 0, 0, + 0, 68, 303, 1, 0, 0, 0, 70, 305, 1, 0, 0, 0, 72, 307, 1, 0, 0, 0, 74, 309, + 1, 0, 0, 0, 76, 311, 1, 0, 0, 0, 78, 313, 1, 0, 0, 0, 80, 315, 1, 0, 0, + 0, 82, 317, 1, 0, 0, 0, 84, 319, 1, 0, 0, 0, 86, 324, 1, 0, 0, 0, 88, 330, + 1, 0, 0, 0, 90, 335, 1, 0, 0, 0, 92, 337, 1, 0, 0, 0, 94, 339, 1, 0, 0, + 0, 96, 341, 1, 0, 0, 0, 98, 350, 1, 0, 0, 0, 100, 352, 1, 0, 0, 0, 102, + 358, 1, 0, 0, 0, 104, 360, 1, 0, 0, 0, 106, 363, 1, 0, 0, 0, 108, 368, + 1, 0, 0, 0, 110, 391, 1, 0, 0, 0, 112, 394, 1, 0, 0, 0, 114, 398, 1, 0, + 0, 0, 116, 439, 1, 0, 0, 0, 118, 454, 1, 0, 0, 0, 120, 473, 1, 0, 0, 0, + 122, 571, 1, 0, 0, 0, 124, 573, 1, 0, 0, 0, 126, 576, 1, 0, 0, 0, 128, + 590, 1, 0, 0, 0, 130, 603, 1, 0, 0, 0, 132, 623, 1, 0, 0, 0, 134, 638, + 1, 0, 0, 0, 136, 650, 1, 0, 0, 0, 138, 701, 1, 0, 0, 0, 140, 703, 1, 0, + 0, 0, 142, 707, 1, 0, 0, 0, 144, 711, 1, 0, 0, 0, 146, 715, 1, 0, 0, 0, + 148, 719, 1, 0, 0, 0, 150, 723, 1, 0, 0, 0, 152, 727, 1, 0, 0, 0, 154, + 155, 5, 35, 0, 0, 155, 3, 1, 0, 0, 0, 156, 157, 5, 58, 0, 0, 157, 5, 1, + 0, 0, 0, 158, 159, 5, 44, 0, 0, 159, 7, 1, 0, 0, 0, 160, 161, 5, 97, 0, + 0, 161, 162, 5, 110, 0, 0, 162, 163, 5, 100, 0, 0, 163, 9, 1, 0, 0, 0, + 164, 165, 5, 111, 0, 0, 165, 166, 5, 114, 0, 0, 166, 11, 1, 0, 0, 0, 167, + 168, 5, 98, 0, 0, 168, 169, 5, 117, 0, 0, 169, 170, 5, 116, 0, 0, 170, + 171, 5, 32, 0, 0, 171, 172, 5, 110, 0, 0, 172, 173, 5, 111, 0, 0, 173, + 174, 5, 116, 0, 0, 174, 13, 1, 0, 0, 0, 175, 176, 5, 102, 0, 0, 176, 177, + 5, 114, 0, 0, 177, 178, 5, 111, 0, 0, 178, 179, 5, 109, 0, 0, 179, 15, + 1, 0, 0, 0, 180, 181, 5, 109, 0, 0, 181, 182, 5, 111, 0, 0, 182, 183, 5, + 100, 0, 0, 183, 184, 5, 117, 0, 0, 184, 185, 5, 108, 0, 0, 185, 186, 5, + 101, 0, 0, 186, 17, 1, 0, 0, 0, 187, 188, 5, 109, 0, 0, 188, 189, 5, 111, + 0, 0, 189, 190, 5, 100, 0, 0, 190, 191, 5, 101, 0, 0, 191, 192, 5, 108, + 0, 0, 192, 19, 1, 0, 0, 0, 193, 194, 5, 115, 0, 0, 194, 195, 5, 99, 0, + 0, 195, 196, 5, 104, 0, 0, 196, 197, 5, 101, 0, 0, 197, 198, 5, 109, 0, + 0, 198, 199, 5, 97, 0, 0, 199, 21, 1, 0, 0, 0, 200, 202, 3, 94, 46, 0, + 201, 200, 1, 0, 0, 0, 202, 203, 1, 0, 0, 0, 203, 201, 1, 0, 0, 0, 203, + 204, 1, 0, 0, 0, 204, 205, 1, 0, 0, 0, 205, 207, 5, 46, 0, 0, 206, 208, + 3, 94, 46, 0, 207, 206, 1, 0, 0, 0, 208, 209, 1, 0, 0, 0, 209, 207, 1, + 0, 0, 0, 209, 210, 1, 0, 0, 0, 210, 23, 1, 0, 0, 0, 211, 212, 5, 101, 0, + 0, 212, 213, 5, 120, 0, 0, 213, 214, 5, 116, 0, 0, 214, 215, 5, 101, 0, + 0, 215, 216, 5, 110, 0, 0, 216, 217, 5, 100, 0, 0, 217, 25, 1, 0, 0, 0, + 218, 219, 5, 116, 0, 0, 219, 220, 5, 121, 0, 0, 220, 221, 5, 112, 0, 0, + 221, 222, 5, 101, 0, 0, 222, 27, 1, 0, 0, 0, 223, 224, 5, 99, 0, 0, 224, + 225, 5, 111, 0, 0, 225, 226, 5, 110, 0, 0, 226, 227, 5, 100, 0, 0, 227, + 228, 5, 105, 0, 0, 228, 229, 5, 116, 0, 0, 229, 230, 5, 105, 0, 0, 230, + 231, 5, 111, 0, 0, 231, 232, 5, 110, 0, 0, 232, 233, 1, 0, 0, 0, 233, 234, + 6, 13, 0, 0, 234, 29, 1, 0, 0, 0, 235, 236, 5, 114, 0, 0, 236, 237, 5, + 101, 0, 0, 237, 238, 5, 108, 0, 0, 238, 239, 5, 97, 0, 0, 239, 240, 5, + 116, 0, 0, 240, 241, 5, 105, 0, 0, 241, 242, 5, 111, 0, 0, 242, 243, 5, + 110, 0, 0, 243, 244, 5, 115, 0, 0, 244, 31, 1, 0, 0, 0, 245, 246, 5, 114, + 0, 0, 246, 247, 5, 101, 0, 0, 247, 248, 5, 108, 0, 0, 248, 249, 5, 97, + 0, 0, 249, 250, 5, 116, 0, 0, 250, 251, 5, 105, 0, 0, 251, 252, 5, 111, + 0, 0, 252, 253, 5, 110, 0, 0, 253, 33, 1, 0, 0, 0, 254, 255, 5, 100, 0, + 0, 255, 256, 5, 101, 0, 0, 256, 257, 5, 102, 0, 0, 257, 258, 5, 105, 0, + 0, 258, 259, 5, 110, 0, 0, 259, 260, 5, 101, 0, 0, 260, 35, 1, 0, 0, 0, + 261, 262, 5, 119, 0, 0, 262, 263, 5, 105, 0, 0, 263, 264, 5, 116, 0, 0, + 264, 265, 5, 104, 0, 0, 265, 37, 1, 0, 0, 0, 266, 267, 5, 61, 0, 0, 267, + 268, 5, 61, 0, 0, 268, 39, 1, 0, 0, 0, 269, 270, 5, 33, 0, 0, 270, 271, + 5, 61, 0, 0, 271, 41, 1, 0, 0, 0, 272, 273, 5, 105, 0, 0, 273, 274, 5, + 110, 0, 0, 274, 43, 1, 0, 0, 0, 275, 276, 5, 60, 0, 0, 276, 45, 1, 0, 0, + 0, 277, 278, 5, 60, 0, 0, 278, 279, 5, 61, 0, 0, 279, 47, 1, 0, 0, 0, 280, + 281, 5, 62, 0, 0, 281, 282, 5, 61, 0, 0, 282, 49, 1, 0, 0, 0, 283, 284, + 5, 62, 0, 0, 284, 51, 1, 0, 0, 0, 285, 286, 5, 38, 0, 0, 286, 287, 5, 38, + 0, 0, 287, 53, 1, 0, 0, 0, 288, 289, 5, 124, 0, 0, 289, 290, 5, 124, 0, + 0, 290, 55, 1, 0, 0, 0, 291, 292, 5, 91, 0, 0, 292, 57, 1, 0, 0, 0, 293, + 294, 5, 93, 0, 0, 294, 59, 1, 0, 0, 0, 295, 296, 5, 123, 0, 0, 296, 61, + 1, 0, 0, 0, 297, 298, 5, 125, 0, 0, 298, 63, 1, 0, 0, 0, 299, 300, 5, 40, + 0, 0, 300, 65, 1, 0, 0, 0, 301, 302, 5, 41, 0, 0, 302, 67, 1, 0, 0, 0, + 303, 304, 5, 46, 0, 0, 304, 69, 1, 0, 0, 0, 305, 306, 5, 45, 0, 0, 306, + 71, 1, 0, 0, 0, 307, 308, 5, 33, 0, 0, 308, 73, 1, 0, 0, 0, 309, 310, 5, + 63, 0, 0, 310, 75, 1, 0, 0, 0, 311, 312, 5, 43, 0, 0, 312, 77, 1, 0, 0, + 0, 313, 314, 5, 42, 0, 0, 314, 79, 1, 0, 0, 0, 315, 316, 5, 47, 0, 0, 316, + 81, 1, 0, 0, 0, 317, 318, 5, 37, 0, 0, 318, 83, 1, 0, 0, 0, 319, 320, 5, + 116, 0, 0, 320, 321, 5, 114, 0, 0, 321, 322, 5, 117, 0, 0, 322, 323, 5, + 101, 0, 0, 323, 85, 1, 0, 0, 0, 324, 325, 5, 102, 0, 0, 325, 326, 5, 97, + 0, 0, 326, 327, 5, 108, 0, 0, 327, 328, 5, 115, 0, 0, 328, 329, 5, 101, + 0, 0, 329, 87, 1, 0, 0, 0, 330, 331, 5, 110, 0, 0, 331, 332, 5, 117, 0, + 0, 332, 333, 5, 108, 0, 0, 333, 334, 5, 108, 0, 0, 334, 89, 1, 0, 0, 0, + 335, 336, 5, 92, 0, 0, 336, 91, 1, 0, 0, 0, 337, 338, 7, 0, 0, 0, 338, + 93, 1, 0, 0, 0, 339, 340, 2, 48, 57, 0, 340, 95, 1, 0, 0, 0, 341, 343, + 7, 1, 0, 0, 342, 344, 7, 2, 0, 0, 343, 342, 1, 0, 0, 0, 343, 344, 1, 0, + 0, 0, 344, 346, 1, 0, 0, 0, 345, 347, 3, 94, 46, 0, 346, 345, 1, 0, 0, + 0, 347, 348, 1, 0, 0, 0, 348, 346, 1, 0, 0, 0, 348, 349, 1, 0, 0, 0, 349, + 97, 1, 0, 0, 0, 350, 351, 7, 3, 0, 0, 351, 99, 1, 0, 0, 0, 352, 353, 7, + 4, 0, 0, 353, 101, 1, 0, 0, 0, 354, 359, 3, 104, 51, 0, 355, 359, 3, 108, + 53, 0, 356, 359, 3, 110, 54, 0, 357, 359, 3, 106, 52, 0, 358, 354, 1, 0, + 0, 0, 358, 355, 1, 0, 0, 0, 358, 356, 1, 0, 0, 0, 358, 357, 1, 0, 0, 0, + 359, 103, 1, 0, 0, 0, 360, 361, 3, 90, 44, 0, 361, 362, 7, 5, 0, 0, 362, + 105, 1, 0, 0, 0, 363, 364, 3, 90, 44, 0, 364, 365, 2, 48, 51, 0, 365, 366, + 2, 48, 55, 0, 366, 367, 2, 48, 55, 0, 367, 107, 1, 0, 0, 0, 368, 369, 3, + 90, 44, 0, 369, 370, 7, 6, 0, 0, 370, 371, 3, 98, 48, 0, 371, 372, 3, 98, + 48, 0, 372, 109, 1, 0, 0, 0, 373, 374, 3, 90, 44, 0, 374, 375, 5, 117, + 0, 0, 375, 376, 3, 98, 48, 0, 376, 377, 3, 98, 48, 0, 377, 378, 3, 98, + 48, 0, 378, 379, 3, 98, 48, 0, 379, 392, 1, 0, 0, 0, 380, 381, 3, 90, 44, + 0, 381, 382, 5, 85, 0, 0, 382, 383, 3, 98, 48, 0, 383, 384, 3, 98, 48, + 0, 384, 385, 3, 98, 48, 0, 385, 386, 3, 98, 48, 0, 386, 387, 3, 98, 48, + 0, 387, 388, 3, 98, 48, 0, 388, 389, 3, 98, 48, 0, 389, 390, 3, 98, 48, + 0, 390, 392, 1, 0, 0, 0, 391, 373, 1, 0, 0, 0, 391, 380, 1, 0, 0, 0, 392, + 111, 1, 0, 0, 0, 393, 395, 7, 7, 0, 0, 394, 393, 1, 0, 0, 0, 395, 396, + 1, 0, 0, 0, 396, 394, 1, 0, 0, 0, 396, 397, 1, 0, 0, 0, 397, 113, 1, 0, + 0, 0, 398, 399, 5, 47, 0, 0, 399, 400, 5, 47, 0, 0, 400, 404, 1, 0, 0, + 0, 401, 403, 8, 8, 0, 0, 402, 401, 1, 0, 0, 0, 403, 406, 1, 0, 0, 0, 404, + 402, 1, 0, 0, 0, 404, 405, 1, 0, 0, 0, 405, 407, 1, 0, 0, 0, 406, 404, + 1, 0, 0, 0, 407, 408, 6, 56, 1, 0, 408, 115, 1, 0, 0, 0, 409, 411, 3, 94, + 46, 0, 410, 409, 1, 0, 0, 0, 411, 412, 1, 0, 0, 0, 412, 410, 1, 0, 0, 0, + 412, 413, 1, 0, 0, 0, 413, 414, 1, 0, 0, 0, 414, 416, 5, 46, 0, 0, 415, + 417, 3, 94, 46, 0, 416, 415, 1, 0, 0, 0, 417, 418, 1, 0, 0, 0, 418, 416, + 1, 0, 0, 0, 418, 419, 1, 0, 0, 0, 419, 421, 1, 0, 0, 0, 420, 422, 3, 96, + 47, 0, 421, 420, 1, 0, 0, 0, 421, 422, 1, 0, 0, 0, 422, 440, 1, 0, 0, 0, + 423, 425, 3, 94, 46, 0, 424, 423, 1, 0, 0, 0, 425, 426, 1, 0, 0, 0, 426, + 424, 1, 0, 0, 0, 426, 427, 1, 0, 0, 0, 427, 428, 1, 0, 0, 0, 428, 429, + 3, 96, 47, 0, 429, 440, 1, 0, 0, 0, 430, 432, 5, 46, 0, 0, 431, 433, 3, + 94, 46, 0, 432, 431, 1, 0, 0, 0, 433, 434, 1, 0, 0, 0, 434, 432, 1, 0, + 0, 0, 434, 435, 1, 0, 0, 0, 435, 437, 1, 0, 0, 0, 436, 438, 3, 96, 47, + 0, 437, 436, 1, 0, 0, 0, 437, 438, 1, 0, 0, 0, 438, 440, 1, 0, 0, 0, 439, + 410, 1, 0, 0, 0, 439, 424, 1, 0, 0, 0, 439, 430, 1, 0, 0, 0, 440, 117, + 1, 0, 0, 0, 441, 443, 3, 94, 46, 0, 442, 441, 1, 0, 0, 0, 443, 444, 1, + 0, 0, 0, 444, 442, 1, 0, 0, 0, 444, 445, 1, 0, 0, 0, 445, 455, 1, 0, 0, + 0, 446, 447, 5, 48, 0, 0, 447, 448, 5, 120, 0, 0, 448, 450, 1, 0, 0, 0, + 449, 451, 3, 98, 48, 0, 450, 449, 1, 0, 0, 0, 451, 452, 1, 0, 0, 0, 452, + 450, 1, 0, 0, 0, 452, 453, 1, 0, 0, 0, 453, 455, 1, 0, 0, 0, 454, 442, + 1, 0, 0, 0, 454, 446, 1, 0, 0, 0, 455, 119, 1, 0, 0, 0, 456, 458, 3, 94, + 46, 0, 457, 456, 1, 0, 0, 0, 458, 459, 1, 0, 0, 0, 459, 457, 1, 0, 0, 0, + 459, 460, 1, 0, 0, 0, 460, 461, 1, 0, 0, 0, 461, 462, 7, 9, 0, 0, 462, + 474, 1, 0, 0, 0, 463, 464, 5, 48, 0, 0, 464, 465, 5, 120, 0, 0, 465, 467, + 1, 0, 0, 0, 466, 468, 3, 98, 48, 0, 467, 466, 1, 0, 0, 0, 468, 469, 1, + 0, 0, 0, 469, 467, 1, 0, 0, 0, 469, 470, 1, 0, 0, 0, 470, 471, 1, 0, 0, + 0, 471, 472, 7, 9, 0, 0, 472, 474, 1, 0, 0, 0, 473, 457, 1, 0, 0, 0, 473, + 463, 1, 0, 0, 0, 474, 121, 1, 0, 0, 0, 475, 480, 5, 34, 0, 0, 476, 479, + 3, 102, 50, 0, 477, 479, 8, 10, 0, 0, 478, 476, 1, 0, 0, 0, 478, 477, 1, + 0, 0, 0, 479, 482, 1, 0, 0, 0, 480, 478, 1, 0, 0, 0, 480, 481, 1, 0, 0, + 0, 481, 483, 1, 0, 0, 0, 482, 480, 1, 0, 0, 0, 483, 572, 5, 34, 0, 0, 484, + 489, 5, 39, 0, 0, 485, 488, 3, 102, 50, 0, 486, 488, 8, 11, 0, 0, 487, + 485, 1, 0, 0, 0, 487, 486, 1, 0, 0, 0, 488, 491, 1, 0, 0, 0, 489, 487, + 1, 0, 0, 0, 489, 490, 1, 0, 0, 0, 490, 492, 1, 0, 0, 0, 491, 489, 1, 0, + 0, 0, 492, 572, 5, 39, 0, 0, 493, 494, 5, 34, 0, 0, 494, 495, 5, 34, 0, + 0, 495, 496, 5, 34, 0, 0, 496, 501, 1, 0, 0, 0, 497, 500, 3, 102, 50, 0, + 498, 500, 8, 12, 0, 0, 499, 497, 1, 0, 0, 0, 499, 498, 1, 0, 0, 0, 500, + 503, 1, 0, 0, 0, 501, 502, 1, 0, 0, 0, 501, 499, 1, 0, 0, 0, 502, 504, + 1, 0, 0, 0, 503, 501, 1, 0, 0, 0, 504, 505, 5, 34, 0, 0, 505, 506, 5, 34, + 0, 0, 506, 572, 5, 34, 0, 0, 507, 508, 5, 39, 0, 0, 508, 509, 5, 39, 0, + 0, 509, 510, 5, 39, 0, 0, 510, 515, 1, 0, 0, 0, 511, 514, 3, 102, 50, 0, + 512, 514, 8, 12, 0, 0, 513, 511, 1, 0, 0, 0, 513, 512, 1, 0, 0, 0, 514, + 517, 1, 0, 0, 0, 515, 516, 1, 0, 0, 0, 515, 513, 1, 0, 0, 0, 516, 518, + 1, 0, 0, 0, 517, 515, 1, 0, 0, 0, 518, 519, 5, 39, 0, 0, 519, 520, 5, 39, + 0, 0, 520, 572, 5, 39, 0, 0, 521, 522, 3, 100, 49, 0, 522, 526, 5, 34, + 0, 0, 523, 525, 8, 13, 0, 0, 524, 523, 1, 0, 0, 0, 525, 528, 1, 0, 0, 0, + 526, 524, 1, 0, 0, 0, 526, 527, 1, 0, 0, 0, 527, 529, 1, 0, 0, 0, 528, + 526, 1, 0, 0, 0, 529, 530, 5, 34, 0, 0, 530, 572, 1, 0, 0, 0, 531, 532, + 3, 100, 49, 0, 532, 536, 5, 39, 0, 0, 533, 535, 8, 14, 0, 0, 534, 533, + 1, 0, 0, 0, 535, 538, 1, 0, 0, 0, 536, 534, 1, 0, 0, 0, 536, 537, 1, 0, + 0, 0, 537, 539, 1, 0, 0, 0, 538, 536, 1, 0, 0, 0, 539, 540, 5, 39, 0, 0, + 540, 572, 1, 0, 0, 0, 541, 542, 3, 100, 49, 0, 542, 543, 5, 34, 0, 0, 543, + 544, 5, 34, 0, 0, 544, 545, 5, 34, 0, 0, 545, 549, 1, 0, 0, 0, 546, 548, + 9, 0, 0, 0, 547, 546, 1, 0, 0, 0, 548, 551, 1, 0, 0, 0, 549, 550, 1, 0, + 0, 0, 549, 547, 1, 0, 0, 0, 550, 552, 1, 0, 0, 0, 551, 549, 1, 0, 0, 0, + 552, 553, 5, 34, 0, 0, 553, 554, 5, 34, 0, 0, 554, 555, 5, 34, 0, 0, 555, + 572, 1, 0, 0, 0, 556, 557, 3, 100, 49, 0, 557, 558, 5, 39, 0, 0, 558, 559, + 5, 39, 0, 0, 559, 560, 5, 39, 0, 0, 560, 564, 1, 0, 0, 0, 561, 563, 9, + 0, 0, 0, 562, 561, 1, 0, 0, 0, 563, 566, 1, 0, 0, 0, 564, 565, 1, 0, 0, + 0, 564, 562, 1, 0, 0, 0, 565, 567, 1, 0, 0, 0, 566, 564, 1, 0, 0, 0, 567, + 568, 5, 39, 0, 0, 568, 569, 5, 39, 0, 0, 569, 570, 5, 39, 0, 0, 570, 572, + 1, 0, 0, 0, 571, 475, 1, 0, 0, 0, 571, 484, 1, 0, 0, 0, 571, 493, 1, 0, + 0, 0, 571, 507, 1, 0, 0, 0, 571, 521, 1, 0, 0, 0, 571, 531, 1, 0, 0, 0, + 571, 541, 1, 0, 0, 0, 571, 556, 1, 0, 0, 0, 572, 123, 1, 0, 0, 0, 573, + 574, 7, 15, 0, 0, 574, 575, 3, 122, 60, 0, 575, 125, 1, 0, 0, 0, 576, 577, + 5, 36, 0, 0, 577, 578, 5, 101, 0, 0, 578, 579, 5, 120, 0, 0, 579, 580, + 5, 112, 0, 0, 580, 581, 5, 114, 0, 0, 581, 582, 5, 101, 0, 0, 582, 583, + 5, 115, 0, 0, 583, 584, 5, 115, 0, 0, 584, 585, 5, 105, 0, 0, 585, 586, + 5, 111, 0, 0, 586, 587, 5, 110, 0, 0, 587, 127, 1, 0, 0, 0, 588, 591, 3, + 92, 45, 0, 589, 591, 5, 95, 0, 0, 590, 588, 1, 0, 0, 0, 590, 589, 1, 0, + 0, 0, 591, 598, 1, 0, 0, 0, 592, 597, 3, 92, 45, 0, 593, 597, 3, 94, 46, + 0, 594, 597, 5, 95, 0, 0, 595, 597, 3, 70, 34, 0, 596, 592, 1, 0, 0, 0, + 596, 593, 1, 0, 0, 0, 596, 594, 1, 0, 0, 0, 596, 595, 1, 0, 0, 0, 597, + 600, 1, 0, 0, 0, 598, 596, 1, 0, 0, 0, 598, 599, 1, 0, 0, 0, 599, 129, + 1, 0, 0, 0, 600, 598, 1, 0, 0, 0, 601, 604, 3, 92, 45, 0, 602, 604, 5, + 95, 0, 0, 603, 601, 1, 0, 0, 0, 603, 602, 1, 0, 0, 0, 604, 619, 1, 0, 0, + 0, 605, 609, 3, 80, 39, 0, 606, 609, 3, 68, 33, 0, 607, 609, 3, 70, 34, + 0, 608, 605, 1, 0, 0, 0, 608, 606, 1, 0, 0, 0, 608, 607, 1, 0, 0, 0, 608, + 609, 1, 0, 0, 0, 609, 613, 1, 0, 0, 0, 610, 614, 3, 92, 45, 0, 611, 614, + 3, 94, 46, 0, 612, 614, 5, 95, 0, 0, 613, 610, 1, 0, 0, 0, 613, 611, 1, + 0, 0, 0, 613, 612, 1, 0, 0, 0, 614, 615, 1, 0, 0, 0, 615, 613, 1, 0, 0, + 0, 615, 616, 1, 0, 0, 0, 616, 618, 1, 0, 0, 0, 617, 608, 1, 0, 0, 0, 618, + 621, 1, 0, 0, 0, 619, 617, 1, 0, 0, 0, 619, 620, 1, 0, 0, 0, 620, 131, + 1, 0, 0, 0, 621, 619, 1, 0, 0, 0, 622, 624, 3, 112, 55, 0, 623, 622, 1, + 0, 0, 0, 623, 624, 1, 0, 0, 0, 624, 630, 1, 0, 0, 0, 625, 627, 5, 13, 0, + 0, 626, 625, 1, 0, 0, 0, 626, 627, 1, 0, 0, 0, 627, 628, 1, 0, 0, 0, 628, + 631, 5, 10, 0, 0, 629, 631, 2, 12, 13, 0, 630, 626, 1, 0, 0, 0, 630, 629, + 1, 0, 0, 0, 631, 633, 1, 0, 0, 0, 632, 634, 3, 112, 55, 0, 633, 632, 1, + 0, 0, 0, 633, 634, 1, 0, 0, 0, 634, 636, 1, 0, 0, 0, 635, 637, 3, 132, + 65, 0, 636, 635, 1, 0, 0, 0, 636, 637, 1, 0, 0, 0, 637, 133, 1, 0, 0, 0, + 638, 639, 3, 66, 32, 0, 639, 640, 1, 0, 0, 0, 640, 641, 6, 66, 2, 0, 641, + 642, 6, 66, 3, 0, 642, 135, 1, 0, 0, 0, 643, 644, 5, 109, 0, 0, 644, 645, + 5, 97, 0, 0, 645, 651, 5, 112, 0, 0, 646, 647, 5, 108, 0, 0, 647, 648, + 5, 105, 0, 0, 648, 649, 5, 115, 0, 0, 649, 651, 5, 116, 0, 0, 650, 643, + 1, 0, 0, 0, 650, 646, 1, 0, 0, 0, 651, 137, 1, 0, 0, 0, 652, 653, 5, 98, + 0, 0, 653, 654, 5, 111, 0, 0, 654, 655, 5, 111, 0, 0, 655, 702, 5, 108, + 0, 0, 656, 657, 5, 115, 0, 0, 657, 658, 5, 116, 0, 0, 658, 659, 5, 114, + 0, 0, 659, 660, 5, 105, 0, 0, 660, 661, 5, 110, 0, 0, 661, 702, 5, 103, + 0, 0, 662, 663, 5, 105, 0, 0, 663, 664, 5, 110, 0, 0, 664, 702, 5, 116, + 0, 0, 665, 666, 5, 117, 0, 0, 666, 667, 5, 105, 0, 0, 667, 668, 5, 110, + 0, 0, 668, 702, 5, 116, 0, 0, 669, 670, 5, 100, 0, 0, 670, 671, 5, 111, + 0, 0, 671, 672, 5, 117, 0, 0, 672, 673, 5, 98, 0, 0, 673, 674, 5, 108, + 0, 0, 674, 702, 5, 101, 0, 0, 675, 676, 5, 100, 0, 0, 676, 677, 5, 117, + 0, 0, 677, 678, 5, 114, 0, 0, 678, 679, 5, 97, 0, 0, 679, 680, 5, 116, + 0, 0, 680, 681, 5, 105, 0, 0, 681, 682, 5, 111, 0, 0, 682, 702, 5, 110, + 0, 0, 683, 684, 5, 116, 0, 0, 684, 685, 5, 105, 0, 0, 685, 686, 5, 109, + 0, 0, 686, 687, 5, 101, 0, 0, 687, 688, 5, 115, 0, 0, 688, 689, 5, 116, + 0, 0, 689, 690, 5, 97, 0, 0, 690, 691, 5, 109, 0, 0, 691, 702, 5, 112, + 0, 0, 692, 693, 5, 105, 0, 0, 693, 694, 5, 112, 0, 0, 694, 695, 5, 97, + 0, 0, 695, 696, 5, 100, 0, 0, 696, 697, 5, 100, 0, 0, 697, 698, 5, 114, + 0, 0, 698, 699, 5, 101, 0, 0, 699, 700, 5, 115, 0, 0, 700, 702, 5, 115, + 0, 0, 701, 652, 1, 0, 0, 0, 701, 656, 1, 0, 0, 0, 701, 662, 1, 0, 0, 0, + 701, 665, 1, 0, 0, 0, 701, 669, 1, 0, 0, 0, 701, 675, 1, 0, 0, 0, 701, + 683, 1, 0, 0, 0, 701, 692, 1, 0, 0, 0, 702, 139, 1, 0, 0, 0, 703, 704, + 3, 44, 21, 0, 704, 705, 1, 0, 0, 0, 705, 706, 6, 69, 4, 0, 706, 141, 1, + 0, 0, 0, 707, 708, 3, 50, 24, 0, 708, 709, 1, 0, 0, 0, 709, 710, 6, 70, + 5, 0, 710, 143, 1, 0, 0, 0, 711, 712, 3, 64, 31, 0, 712, 713, 1, 0, 0, + 0, 713, 714, 6, 71, 6, 0, 714, 145, 1, 0, 0, 0, 715, 716, 3, 4, 1, 0, 716, + 717, 1, 0, 0, 0, 717, 718, 6, 72, 7, 0, 718, 147, 1, 0, 0, 0, 719, 720, + 3, 6, 2, 0, 720, 721, 1, 0, 0, 0, 721, 722, 6, 73, 8, 0, 722, 149, 1, 0, + 0, 0, 723, 724, 3, 112, 55, 0, 724, 725, 1, 0, 0, 0, 725, 726, 6, 74, 9, + 0, 726, 151, 1, 0, 0, 0, 727, 728, 3, 128, 63, 0, 728, 729, 1, 0, 0, 0, + 729, 730, 6, 75, 10, 0, 730, 153, 1, 0, 0, 0, 51, 0, 1, 203, 209, 343, + 348, 358, 391, 396, 404, 412, 418, 421, 426, 434, 437, 439, 444, 452, 454, + 459, 469, 473, 478, 480, 487, 489, 499, 501, 513, 515, 526, 536, 549, 564, + 571, 590, 596, 598, 603, 608, 613, 615, 619, 623, 626, 630, 633, 636, 650, + 701, 11, 5, 1, 0, 0, 1, 0, 7, 8, 0, 4, 0, 0, 7, 3, 0, 7, 4, 0, 7, 7, 0, + 7, 1, 0, 7, 2, 0, 7, 9, 0, 7, 10, 0, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -505,10 +513,11 @@ const ( OpenFGALexerNUM_UINT = 51 OpenFGALexerSTRING = 52 OpenFGALexerBYTES = 53 - OpenFGALexerEXTENDED_IDENTIFIER = 54 - OpenFGALexerNEWLINE = 55 - OpenFGALexerCONDITION_PARAM_CONTAINER = 56 - OpenFGALexerCONDITION_PARAM_TYPE = 57 + OpenFGALexerDOLLAR_EXPRESSION = 54 + OpenFGALexerEXTENDED_IDENTIFIER = 55 + OpenFGALexerNEWLINE = 56 + OpenFGALexerCONDITION_PARAM_CONTAINER = 57 + OpenFGALexerCONDITION_PARAM_TYPE = 58 ) // OpenFGALexerCONDITION_DEF is the OpenFGALexer mode. diff --git a/vendor/github.com/openfga/language/pkg/go/gen/openfga_parser.go b/vendor/github.com/openfga/language/pkg/go/gen/openfga_parser.go index 6a6e525df9..1ba46da5ce 100644 --- a/vendor/github.com/openfga/language/pkg/go/gen/openfga_parser.go +++ b/vendor/github.com/openfga/language/pkg/go/gen/openfga_parser.go @@ -39,7 +39,8 @@ func openfgaparserParserInit() { "", "'extend'", "'type'", "'condition'", "'relations'", "'relation'", "'define'", "'with'", "'=='", "'!='", "'in'", "'<='", "'>='", "'&&'", "'||'", "']'", "'{'", "'}'", "'.'", "'-'", "'!'", "'?'", "'+'", "'*'", - "'/'", "'%'", "'true'", "'false'", "'null'", + "'/'", "'%'", "'true'", "'false'", "'null'", "", "", "", "", "", "", + "'$expression'", } staticData.SymbolicNames = []string{ "", "COLON", "COMMA", "LESS", "GREATER", "LBRACKET", "RBRACKET", "LPAREN", @@ -50,7 +51,7 @@ func openfgaparserParserInit() { "LOGICAL_OR", "RPRACKET", "LBRACE", "RBRACE", "DOT", "MINUS", "EXCLAM", "QUESTIONMARK", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE", "NUL", "CEL_COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT", "STRING", - "BYTES", "EXTENDED_IDENTIFIER", "NEWLINE", "CONDITION_PARAM_CONTAINER", + "BYTES", "DOLLAR_EXPRESSION", "EXTENDED_IDENTIFIER", "NEWLINE", "CONDITION_PARAM_CONTAINER", "CONDITION_PARAM_TYPE", } staticData.RuleNames = []string{ @@ -64,7 +65,7 @@ func openfgaparserParserInit() { } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 57, 392, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, + 4, 1, 58, 394, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, 20, 2, @@ -92,159 +93,160 @@ func openfgaparserParserInit() { 1, 13, 1, 13, 3, 13, 248, 8, 13, 5, 13, 250, 8, 13, 10, 13, 12, 13, 253, 9, 13, 1, 13, 1, 13, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 3, 14, 262, 8, 14, 1, 15, 3, 15, 265, 8, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, - 1, 15, 3, 15, 274, 8, 15, 1, 15, 3, 15, 277, 8, 15, 1, 16, 1, 16, 1, 16, - 1, 16, 1, 16, 3, 16, 284, 8, 16, 1, 17, 5, 17, 287, 8, 17, 10, 17, 12, - 17, 290, 9, 17, 1, 18, 1, 18, 3, 18, 294, 8, 18, 1, 18, 1, 18, 1, 18, 1, - 18, 1, 18, 3, 18, 301, 8, 18, 1, 18, 1, 18, 3, 18, 305, 8, 18, 1, 18, 1, - 18, 3, 18, 309, 8, 18, 1, 18, 1, 18, 3, 18, 313, 8, 18, 1, 18, 1, 18, 3, - 18, 317, 8, 18, 5, 18, 319, 8, 18, 10, 18, 12, 18, 322, 9, 18, 1, 18, 3, - 18, 325, 8, 18, 1, 18, 1, 18, 3, 18, 329, 8, 18, 1, 18, 1, 18, 3, 18, 333, - 8, 18, 1, 18, 3, 18, 336, 8, 18, 1, 18, 1, 18, 3, 18, 340, 8, 18, 1, 18, - 1, 18, 1, 19, 1, 19, 1, 20, 3, 20, 347, 8, 20, 1, 20, 1, 20, 3, 20, 351, - 8, 20, 1, 20, 1, 20, 3, 20, 355, 8, 20, 1, 20, 1, 20, 1, 21, 1, 21, 1, - 22, 1, 22, 1, 22, 1, 22, 1, 22, 3, 22, 366, 8, 22, 1, 23, 1, 23, 5, 23, - 370, 8, 23, 10, 23, 12, 23, 373, 9, 23, 1, 23, 1, 23, 3, 23, 377, 8, 23, - 1, 24, 1, 24, 1, 25, 1, 25, 3, 25, 383, 8, 25, 1, 26, 1, 26, 5, 26, 387, - 8, 26, 10, 26, 12, 26, 390, 9, 26, 1, 26, 0, 0, 27, 0, 2, 4, 6, 8, 10, - 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, - 48, 50, 52, 0, 4, 1, 0, 55, 55, 4, 0, 10, 10, 16, 18, 20, 21, 24, 24, 5, - 0, 3, 5, 7, 10, 27, 35, 37, 53, 55, 55, 1, 0, 36, 36, 433, 0, 55, 1, 0, - 0, 0, 2, 80, 1, 0, 0, 0, 4, 93, 1, 0, 0, 0, 6, 104, 1, 0, 0, 0, 8, 109, - 1, 0, 0, 0, 10, 130, 1, 0, 0, 0, 12, 145, 1, 0, 0, 0, 14, 150, 1, 0, 0, - 0, 16, 157, 1, 0, 0, 0, 18, 191, 1, 0, 0, 0, 20, 193, 1, 0, 0, 0, 22, 195, - 1, 0, 0, 0, 24, 214, 1, 0, 0, 0, 26, 233, 1, 0, 0, 0, 28, 256, 1, 0, 0, - 0, 30, 264, 1, 0, 0, 0, 32, 278, 1, 0, 0, 0, 34, 288, 1, 0, 0, 0, 36, 293, - 1, 0, 0, 0, 38, 343, 1, 0, 0, 0, 40, 346, 1, 0, 0, 0, 42, 358, 1, 0, 0, - 0, 44, 365, 1, 0, 0, 0, 46, 367, 1, 0, 0, 0, 48, 378, 1, 0, 0, 0, 50, 382, - 1, 0, 0, 0, 52, 388, 1, 0, 0, 0, 54, 56, 5, 9, 0, 0, 55, 54, 1, 0, 0, 0, - 55, 56, 1, 0, 0, 0, 56, 58, 1, 0, 0, 0, 57, 59, 5, 55, 0, 0, 58, 57, 1, - 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 62, 1, 0, 0, 0, 60, 63, 3, 2, 1, 0, 61, - 63, 3, 4, 2, 0, 62, 60, 1, 0, 0, 0, 62, 61, 1, 0, 0, 0, 63, 65, 1, 0, 0, - 0, 64, 66, 5, 55, 0, 0, 65, 64, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 67, - 1, 0, 0, 0, 67, 69, 3, 6, 3, 0, 68, 70, 5, 55, 0, 0, 69, 68, 1, 0, 0, 0, - 69, 70, 1, 0, 0, 0, 70, 71, 1, 0, 0, 0, 71, 73, 3, 34, 17, 0, 72, 74, 5, - 55, 0, 0, 73, 72, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 75, 1, 0, 0, 0, 75, - 76, 5, 0, 0, 1, 76, 1, 1, 0, 0, 0, 77, 78, 3, 46, 23, 0, 78, 79, 5, 55, - 0, 0, 79, 81, 1, 0, 0, 0, 80, 77, 1, 0, 0, 0, 80, 81, 1, 0, 0, 0, 81, 82, - 1, 0, 0, 0, 82, 83, 5, 17, 0, 0, 83, 84, 5, 55, 0, 0, 84, 85, 5, 18, 0, - 0, 85, 86, 5, 9, 0, 0, 86, 88, 5, 19, 0, 0, 87, 89, 5, 9, 0, 0, 88, 87, - 1, 0, 0, 0, 88, 89, 1, 0, 0, 0, 89, 3, 1, 0, 0, 0, 90, 91, 3, 46, 23, 0, - 91, 92, 5, 55, 0, 0, 92, 94, 1, 0, 0, 0, 93, 90, 1, 0, 0, 0, 93, 94, 1, - 0, 0, 0, 94, 95, 1, 0, 0, 0, 95, 96, 5, 16, 0, 0, 96, 97, 5, 9, 0, 0, 97, - 99, 3, 48, 24, 0, 98, 100, 5, 9, 0, 0, 99, 98, 1, 0, 0, 0, 99, 100, 1, - 0, 0, 0, 100, 5, 1, 0, 0, 0, 101, 103, 3, 8, 4, 0, 102, 101, 1, 0, 0, 0, - 103, 106, 1, 0, 0, 0, 104, 102, 1, 0, 0, 0, 104, 105, 1, 0, 0, 0, 105, - 7, 1, 0, 0, 0, 106, 104, 1, 0, 0, 0, 107, 108, 5, 55, 0, 0, 108, 110, 3, - 46, 23, 0, 109, 107, 1, 0, 0, 0, 109, 110, 1, 0, 0, 0, 110, 111, 1, 0, - 0, 0, 111, 114, 5, 55, 0, 0, 112, 113, 5, 20, 0, 0, 113, 115, 5, 9, 0, - 0, 114, 112, 1, 0, 0, 0, 114, 115, 1, 0, 0, 0, 115, 116, 1, 0, 0, 0, 116, - 117, 5, 21, 0, 0, 117, 118, 5, 9, 0, 0, 118, 126, 3, 50, 25, 0, 119, 120, - 5, 55, 0, 0, 120, 122, 5, 23, 0, 0, 121, 123, 3, 10, 5, 0, 122, 121, 1, - 0, 0, 0, 123, 124, 1, 0, 0, 0, 124, 122, 1, 0, 0, 0, 124, 125, 1, 0, 0, - 0, 125, 127, 1, 0, 0, 0, 126, 119, 1, 0, 0, 0, 126, 127, 1, 0, 0, 0, 127, - 9, 1, 0, 0, 0, 128, 129, 5, 55, 0, 0, 129, 131, 3, 46, 23, 0, 130, 128, - 1, 0, 0, 0, 130, 131, 1, 0, 0, 0, 131, 132, 1, 0, 0, 0, 132, 133, 5, 55, - 0, 0, 133, 134, 5, 25, 0, 0, 134, 135, 5, 9, 0, 0, 135, 137, 3, 12, 6, - 0, 136, 138, 5, 9, 0, 0, 137, 136, 1, 0, 0, 0, 137, 138, 1, 0, 0, 0, 138, - 139, 1, 0, 0, 0, 139, 141, 5, 1, 0, 0, 140, 142, 5, 9, 0, 0, 141, 140, - 1, 0, 0, 0, 141, 142, 1, 0, 0, 0, 142, 143, 1, 0, 0, 0, 143, 144, 3, 14, - 7, 0, 144, 11, 1, 0, 0, 0, 145, 146, 3, 50, 25, 0, 146, 13, 1, 0, 0, 0, - 147, 151, 3, 26, 13, 0, 148, 151, 3, 20, 10, 0, 149, 151, 3, 22, 11, 0, - 150, 147, 1, 0, 0, 0, 150, 148, 1, 0, 0, 0, 150, 149, 1, 0, 0, 0, 151, - 153, 1, 0, 0, 0, 152, 154, 3, 18, 9, 0, 153, 152, 1, 0, 0, 0, 153, 154, - 1, 0, 0, 0, 154, 15, 1, 0, 0, 0, 155, 158, 3, 20, 10, 0, 156, 158, 3, 24, - 12, 0, 157, 155, 1, 0, 0, 0, 157, 156, 1, 0, 0, 0, 158, 160, 1, 0, 0, 0, - 159, 161, 3, 18, 9, 0, 160, 159, 1, 0, 0, 0, 160, 161, 1, 0, 0, 0, 161, - 17, 1, 0, 0, 0, 162, 163, 5, 9, 0, 0, 163, 164, 5, 13, 0, 0, 164, 167, - 5, 9, 0, 0, 165, 168, 3, 20, 10, 0, 166, 168, 3, 24, 12, 0, 167, 165, 1, - 0, 0, 0, 167, 166, 1, 0, 0, 0, 168, 170, 1, 0, 0, 0, 169, 162, 1, 0, 0, - 0, 170, 171, 1, 0, 0, 0, 171, 169, 1, 0, 0, 0, 171, 172, 1, 0, 0, 0, 172, - 192, 1, 0, 0, 0, 173, 174, 5, 9, 0, 0, 174, 175, 5, 12, 0, 0, 175, 178, - 5, 9, 0, 0, 176, 179, 3, 20, 10, 0, 177, 179, 3, 24, 12, 0, 178, 176, 1, - 0, 0, 0, 178, 177, 1, 0, 0, 0, 179, 181, 1, 0, 0, 0, 180, 173, 1, 0, 0, - 0, 181, 182, 1, 0, 0, 0, 182, 180, 1, 0, 0, 0, 182, 183, 1, 0, 0, 0, 183, - 192, 1, 0, 0, 0, 184, 185, 5, 9, 0, 0, 185, 186, 5, 14, 0, 0, 186, 189, - 5, 9, 0, 0, 187, 190, 3, 20, 10, 0, 188, 190, 3, 24, 12, 0, 189, 187, 1, - 0, 0, 0, 189, 188, 1, 0, 0, 0, 190, 192, 1, 0, 0, 0, 191, 169, 1, 0, 0, - 0, 191, 180, 1, 0, 0, 0, 191, 184, 1, 0, 0, 0, 192, 19, 1, 0, 0, 0, 193, - 194, 3, 28, 14, 0, 194, 21, 1, 0, 0, 0, 195, 199, 5, 7, 0, 0, 196, 198, - 5, 9, 0, 0, 197, 196, 1, 0, 0, 0, 198, 201, 1, 0, 0, 0, 199, 197, 1, 0, - 0, 0, 199, 200, 1, 0, 0, 0, 200, 204, 1, 0, 0, 0, 201, 199, 1, 0, 0, 0, - 202, 205, 3, 14, 7, 0, 203, 205, 3, 24, 12, 0, 204, 202, 1, 0, 0, 0, 204, - 203, 1, 0, 0, 0, 205, 209, 1, 0, 0, 0, 206, 208, 5, 9, 0, 0, 207, 206, - 1, 0, 0, 0, 208, 211, 1, 0, 0, 0, 209, 207, 1, 0, 0, 0, 209, 210, 1, 0, - 0, 0, 210, 212, 1, 0, 0, 0, 211, 209, 1, 0, 0, 0, 212, 213, 5, 8, 0, 0, - 213, 23, 1, 0, 0, 0, 214, 218, 5, 7, 0, 0, 215, 217, 5, 9, 0, 0, 216, 215, - 1, 0, 0, 0, 217, 220, 1, 0, 0, 0, 218, 216, 1, 0, 0, 0, 218, 219, 1, 0, - 0, 0, 219, 223, 1, 0, 0, 0, 220, 218, 1, 0, 0, 0, 221, 224, 3, 16, 8, 0, - 222, 224, 3, 24, 12, 0, 223, 221, 1, 0, 0, 0, 223, 222, 1, 0, 0, 0, 224, - 228, 1, 0, 0, 0, 225, 227, 5, 9, 0, 0, 226, 225, 1, 0, 0, 0, 227, 230, - 1, 0, 0, 0, 228, 226, 1, 0, 0, 0, 228, 229, 1, 0, 0, 0, 229, 231, 1, 0, - 0, 0, 230, 228, 1, 0, 0, 0, 231, 232, 5, 8, 0, 0, 232, 25, 1, 0, 0, 0, - 233, 235, 5, 5, 0, 0, 234, 236, 5, 9, 0, 0, 235, 234, 1, 0, 0, 0, 235, - 236, 1, 0, 0, 0, 236, 237, 1, 0, 0, 0, 237, 239, 3, 30, 15, 0, 238, 240, - 5, 9, 0, 0, 239, 238, 1, 0, 0, 0, 239, 240, 1, 0, 0, 0, 240, 251, 1, 0, - 0, 0, 241, 243, 5, 2, 0, 0, 242, 244, 5, 9, 0, 0, 243, 242, 1, 0, 0, 0, - 243, 244, 1, 0, 0, 0, 244, 245, 1, 0, 0, 0, 245, 247, 3, 30, 15, 0, 246, - 248, 5, 9, 0, 0, 247, 246, 1, 0, 0, 0, 247, 248, 1, 0, 0, 0, 248, 250, - 1, 0, 0, 0, 249, 241, 1, 0, 0, 0, 250, 253, 1, 0, 0, 0, 251, 249, 1, 0, - 0, 0, 251, 252, 1, 0, 0, 0, 252, 254, 1, 0, 0, 0, 253, 251, 1, 0, 0, 0, - 254, 255, 5, 34, 0, 0, 255, 27, 1, 0, 0, 0, 256, 261, 3, 50, 25, 0, 257, - 258, 5, 9, 0, 0, 258, 259, 5, 15, 0, 0, 259, 260, 5, 9, 0, 0, 260, 262, - 3, 50, 25, 0, 261, 257, 1, 0, 0, 0, 261, 262, 1, 0, 0, 0, 262, 29, 1, 0, - 0, 0, 263, 265, 5, 55, 0, 0, 264, 263, 1, 0, 0, 0, 264, 265, 1, 0, 0, 0, - 265, 273, 1, 0, 0, 0, 266, 274, 3, 32, 16, 0, 267, 268, 3, 32, 16, 0, 268, - 269, 5, 9, 0, 0, 269, 270, 5, 26, 0, 0, 270, 271, 5, 9, 0, 0, 271, 272, - 3, 38, 19, 0, 272, 274, 1, 0, 0, 0, 273, 266, 1, 0, 0, 0, 273, 267, 1, - 0, 0, 0, 274, 276, 1, 0, 0, 0, 275, 277, 5, 55, 0, 0, 276, 275, 1, 0, 0, - 0, 276, 277, 1, 0, 0, 0, 277, 31, 1, 0, 0, 0, 278, 283, 3, 50, 25, 0, 279, - 280, 5, 1, 0, 0, 280, 284, 5, 42, 0, 0, 281, 282, 5, 11, 0, 0, 282, 284, - 3, 50, 25, 0, 283, 279, 1, 0, 0, 0, 283, 281, 1, 0, 0, 0, 283, 284, 1, - 0, 0, 0, 284, 33, 1, 0, 0, 0, 285, 287, 3, 36, 18, 0, 286, 285, 1, 0, 0, - 0, 287, 290, 1, 0, 0, 0, 288, 286, 1, 0, 0, 0, 288, 289, 1, 0, 0, 0, 289, - 35, 1, 0, 0, 0, 290, 288, 1, 0, 0, 0, 291, 292, 5, 55, 0, 0, 292, 294, - 3, 46, 23, 0, 293, 291, 1, 0, 0, 0, 293, 294, 1, 0, 0, 0, 294, 295, 1, - 0, 0, 0, 295, 296, 5, 55, 0, 0, 296, 297, 5, 22, 0, 0, 297, 298, 5, 9, - 0, 0, 298, 300, 3, 38, 19, 0, 299, 301, 5, 9, 0, 0, 300, 299, 1, 0, 0, - 0, 300, 301, 1, 0, 0, 0, 301, 302, 1, 0, 0, 0, 302, 304, 5, 7, 0, 0, 303, - 305, 5, 9, 0, 0, 304, 303, 1, 0, 0, 0, 304, 305, 1, 0, 0, 0, 305, 306, - 1, 0, 0, 0, 306, 308, 3, 40, 20, 0, 307, 309, 5, 9, 0, 0, 308, 307, 1, - 0, 0, 0, 308, 309, 1, 0, 0, 0, 309, 320, 1, 0, 0, 0, 310, 312, 5, 2, 0, - 0, 311, 313, 5, 9, 0, 0, 312, 311, 1, 0, 0, 0, 312, 313, 1, 0, 0, 0, 313, - 314, 1, 0, 0, 0, 314, 316, 3, 40, 20, 0, 315, 317, 5, 9, 0, 0, 316, 315, - 1, 0, 0, 0, 316, 317, 1, 0, 0, 0, 317, 319, 1, 0, 0, 0, 318, 310, 1, 0, - 0, 0, 319, 322, 1, 0, 0, 0, 320, 318, 1, 0, 0, 0, 320, 321, 1, 0, 0, 0, - 321, 324, 1, 0, 0, 0, 322, 320, 1, 0, 0, 0, 323, 325, 5, 55, 0, 0, 324, - 323, 1, 0, 0, 0, 324, 325, 1, 0, 0, 0, 325, 326, 1, 0, 0, 0, 326, 328, - 5, 8, 0, 0, 327, 329, 5, 9, 0, 0, 328, 327, 1, 0, 0, 0, 328, 329, 1, 0, - 0, 0, 329, 330, 1, 0, 0, 0, 330, 332, 5, 35, 0, 0, 331, 333, 5, 55, 0, - 0, 332, 331, 1, 0, 0, 0, 332, 333, 1, 0, 0, 0, 333, 335, 1, 0, 0, 0, 334, - 336, 5, 9, 0, 0, 335, 334, 1, 0, 0, 0, 335, 336, 1, 0, 0, 0, 336, 337, - 1, 0, 0, 0, 337, 339, 3, 52, 26, 0, 338, 340, 5, 55, 0, 0, 339, 338, 1, - 0, 0, 0, 339, 340, 1, 0, 0, 0, 340, 341, 1, 0, 0, 0, 341, 342, 5, 36, 0, - 0, 342, 37, 1, 0, 0, 0, 343, 344, 5, 10, 0, 0, 344, 39, 1, 0, 0, 0, 345, - 347, 5, 55, 0, 0, 346, 345, 1, 0, 0, 0, 346, 347, 1, 0, 0, 0, 347, 348, - 1, 0, 0, 0, 348, 350, 3, 42, 21, 0, 349, 351, 5, 9, 0, 0, 350, 349, 1, - 0, 0, 0, 350, 351, 1, 0, 0, 0, 351, 352, 1, 0, 0, 0, 352, 354, 5, 1, 0, - 0, 353, 355, 5, 9, 0, 0, 354, 353, 1, 0, 0, 0, 354, 355, 1, 0, 0, 0, 355, - 356, 1, 0, 0, 0, 356, 357, 3, 44, 22, 0, 357, 41, 1, 0, 0, 0, 358, 359, - 5, 10, 0, 0, 359, 43, 1, 0, 0, 0, 360, 366, 5, 57, 0, 0, 361, 362, 5, 56, - 0, 0, 362, 363, 5, 3, 0, 0, 363, 364, 5, 57, 0, 0, 364, 366, 5, 4, 0, 0, - 365, 360, 1, 0, 0, 0, 365, 361, 1, 0, 0, 0, 366, 45, 1, 0, 0, 0, 367, 371, - 5, 11, 0, 0, 368, 370, 8, 0, 0, 0, 369, 368, 1, 0, 0, 0, 370, 373, 1, 0, - 0, 0, 371, 369, 1, 0, 0, 0, 371, 372, 1, 0, 0, 0, 372, 376, 1, 0, 0, 0, - 373, 371, 1, 0, 0, 0, 374, 375, 5, 55, 0, 0, 375, 377, 3, 46, 23, 0, 376, - 374, 1, 0, 0, 0, 376, 377, 1, 0, 0, 0, 377, 47, 1, 0, 0, 0, 378, 379, 7, - 1, 0, 0, 379, 49, 1, 0, 0, 0, 380, 383, 3, 48, 24, 0, 381, 383, 5, 54, - 0, 0, 382, 380, 1, 0, 0, 0, 382, 381, 1, 0, 0, 0, 383, 51, 1, 0, 0, 0, - 384, 387, 7, 2, 0, 0, 385, 387, 8, 3, 0, 0, 386, 384, 1, 0, 0, 0, 386, - 385, 1, 0, 0, 0, 387, 390, 1, 0, 0, 0, 388, 386, 1, 0, 0, 0, 388, 389, - 1, 0, 0, 0, 389, 53, 1, 0, 0, 0, 390, 388, 1, 0, 0, 0, 66, 55, 58, 62, - 65, 69, 73, 80, 88, 93, 99, 104, 109, 114, 124, 126, 130, 137, 141, 150, - 153, 157, 160, 167, 171, 178, 182, 189, 191, 199, 204, 209, 218, 223, 228, - 235, 239, 243, 247, 251, 261, 264, 273, 276, 283, 288, 293, 300, 304, 308, - 312, 316, 320, 324, 328, 332, 335, 339, 346, 350, 354, 365, 371, 376, 382, - 386, 388, + 1, 15, 3, 15, 274, 8, 15, 3, 15, 276, 8, 15, 1, 15, 3, 15, 279, 8, 15, + 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 3, 16, 286, 8, 16, 1, 17, 5, 17, 289, + 8, 17, 10, 17, 12, 17, 292, 9, 17, 1, 18, 1, 18, 3, 18, 296, 8, 18, 1, + 18, 1, 18, 1, 18, 1, 18, 1, 18, 3, 18, 303, 8, 18, 1, 18, 1, 18, 3, 18, + 307, 8, 18, 1, 18, 1, 18, 3, 18, 311, 8, 18, 1, 18, 1, 18, 3, 18, 315, + 8, 18, 1, 18, 1, 18, 3, 18, 319, 8, 18, 5, 18, 321, 8, 18, 10, 18, 12, + 18, 324, 9, 18, 1, 18, 3, 18, 327, 8, 18, 1, 18, 1, 18, 3, 18, 331, 8, + 18, 1, 18, 1, 18, 3, 18, 335, 8, 18, 1, 18, 3, 18, 338, 8, 18, 1, 18, 1, + 18, 3, 18, 342, 8, 18, 1, 18, 1, 18, 1, 19, 1, 19, 1, 20, 3, 20, 349, 8, + 20, 1, 20, 1, 20, 3, 20, 353, 8, 20, 1, 20, 1, 20, 3, 20, 357, 8, 20, 1, + 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, 22, 1, 22, 1, 22, 3, 22, 368, + 8, 22, 1, 23, 1, 23, 5, 23, 372, 8, 23, 10, 23, 12, 23, 375, 9, 23, 1, + 23, 1, 23, 3, 23, 379, 8, 23, 1, 24, 1, 24, 1, 25, 1, 25, 3, 25, 385, 8, + 25, 1, 26, 1, 26, 5, 26, 389, 8, 26, 10, 26, 12, 26, 392, 9, 26, 1, 26, + 0, 0, 27, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, + 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 0, 4, 1, 0, 56, 56, 4, 0, 10, 10, + 16, 18, 20, 21, 24, 24, 5, 0, 3, 5, 7, 10, 27, 35, 37, 53, 56, 56, 1, 0, + 36, 36, 436, 0, 55, 1, 0, 0, 0, 2, 80, 1, 0, 0, 0, 4, 93, 1, 0, 0, 0, 6, + 104, 1, 0, 0, 0, 8, 109, 1, 0, 0, 0, 10, 130, 1, 0, 0, 0, 12, 145, 1, 0, + 0, 0, 14, 150, 1, 0, 0, 0, 16, 157, 1, 0, 0, 0, 18, 191, 1, 0, 0, 0, 20, + 193, 1, 0, 0, 0, 22, 195, 1, 0, 0, 0, 24, 214, 1, 0, 0, 0, 26, 233, 1, + 0, 0, 0, 28, 256, 1, 0, 0, 0, 30, 264, 1, 0, 0, 0, 32, 280, 1, 0, 0, 0, + 34, 290, 1, 0, 0, 0, 36, 295, 1, 0, 0, 0, 38, 345, 1, 0, 0, 0, 40, 348, + 1, 0, 0, 0, 42, 360, 1, 0, 0, 0, 44, 367, 1, 0, 0, 0, 46, 369, 1, 0, 0, + 0, 48, 380, 1, 0, 0, 0, 50, 384, 1, 0, 0, 0, 52, 390, 1, 0, 0, 0, 54, 56, + 5, 9, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 58, 1, 0, 0, 0, + 57, 59, 5, 56, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 62, 1, + 0, 0, 0, 60, 63, 3, 2, 1, 0, 61, 63, 3, 4, 2, 0, 62, 60, 1, 0, 0, 0, 62, + 61, 1, 0, 0, 0, 63, 65, 1, 0, 0, 0, 64, 66, 5, 56, 0, 0, 65, 64, 1, 0, + 0, 0, 65, 66, 1, 0, 0, 0, 66, 67, 1, 0, 0, 0, 67, 69, 3, 6, 3, 0, 68, 70, + 5, 56, 0, 0, 69, 68, 1, 0, 0, 0, 69, 70, 1, 0, 0, 0, 70, 71, 1, 0, 0, 0, + 71, 73, 3, 34, 17, 0, 72, 74, 5, 56, 0, 0, 73, 72, 1, 0, 0, 0, 73, 74, + 1, 0, 0, 0, 74, 75, 1, 0, 0, 0, 75, 76, 5, 0, 0, 1, 76, 1, 1, 0, 0, 0, + 77, 78, 3, 46, 23, 0, 78, 79, 5, 56, 0, 0, 79, 81, 1, 0, 0, 0, 80, 77, + 1, 0, 0, 0, 80, 81, 1, 0, 0, 0, 81, 82, 1, 0, 0, 0, 82, 83, 5, 17, 0, 0, + 83, 84, 5, 56, 0, 0, 84, 85, 5, 18, 0, 0, 85, 86, 5, 9, 0, 0, 86, 88, 5, + 19, 0, 0, 87, 89, 5, 9, 0, 0, 88, 87, 1, 0, 0, 0, 88, 89, 1, 0, 0, 0, 89, + 3, 1, 0, 0, 0, 90, 91, 3, 46, 23, 0, 91, 92, 5, 56, 0, 0, 92, 94, 1, 0, + 0, 0, 93, 90, 1, 0, 0, 0, 93, 94, 1, 0, 0, 0, 94, 95, 1, 0, 0, 0, 95, 96, + 5, 16, 0, 0, 96, 97, 5, 9, 0, 0, 97, 99, 3, 48, 24, 0, 98, 100, 5, 9, 0, + 0, 99, 98, 1, 0, 0, 0, 99, 100, 1, 0, 0, 0, 100, 5, 1, 0, 0, 0, 101, 103, + 3, 8, 4, 0, 102, 101, 1, 0, 0, 0, 103, 106, 1, 0, 0, 0, 104, 102, 1, 0, + 0, 0, 104, 105, 1, 0, 0, 0, 105, 7, 1, 0, 0, 0, 106, 104, 1, 0, 0, 0, 107, + 108, 5, 56, 0, 0, 108, 110, 3, 46, 23, 0, 109, 107, 1, 0, 0, 0, 109, 110, + 1, 0, 0, 0, 110, 111, 1, 0, 0, 0, 111, 114, 5, 56, 0, 0, 112, 113, 5, 20, + 0, 0, 113, 115, 5, 9, 0, 0, 114, 112, 1, 0, 0, 0, 114, 115, 1, 0, 0, 0, + 115, 116, 1, 0, 0, 0, 116, 117, 5, 21, 0, 0, 117, 118, 5, 9, 0, 0, 118, + 126, 3, 50, 25, 0, 119, 120, 5, 56, 0, 0, 120, 122, 5, 23, 0, 0, 121, 123, + 3, 10, 5, 0, 122, 121, 1, 0, 0, 0, 123, 124, 1, 0, 0, 0, 124, 122, 1, 0, + 0, 0, 124, 125, 1, 0, 0, 0, 125, 127, 1, 0, 0, 0, 126, 119, 1, 0, 0, 0, + 126, 127, 1, 0, 0, 0, 127, 9, 1, 0, 0, 0, 128, 129, 5, 56, 0, 0, 129, 131, + 3, 46, 23, 0, 130, 128, 1, 0, 0, 0, 130, 131, 1, 0, 0, 0, 131, 132, 1, + 0, 0, 0, 132, 133, 5, 56, 0, 0, 133, 134, 5, 25, 0, 0, 134, 135, 5, 9, + 0, 0, 135, 137, 3, 12, 6, 0, 136, 138, 5, 9, 0, 0, 137, 136, 1, 0, 0, 0, + 137, 138, 1, 0, 0, 0, 138, 139, 1, 0, 0, 0, 139, 141, 5, 1, 0, 0, 140, + 142, 5, 9, 0, 0, 141, 140, 1, 0, 0, 0, 141, 142, 1, 0, 0, 0, 142, 143, + 1, 0, 0, 0, 143, 144, 3, 14, 7, 0, 144, 11, 1, 0, 0, 0, 145, 146, 3, 50, + 25, 0, 146, 13, 1, 0, 0, 0, 147, 151, 3, 26, 13, 0, 148, 151, 3, 20, 10, + 0, 149, 151, 3, 22, 11, 0, 150, 147, 1, 0, 0, 0, 150, 148, 1, 0, 0, 0, + 150, 149, 1, 0, 0, 0, 151, 153, 1, 0, 0, 0, 152, 154, 3, 18, 9, 0, 153, + 152, 1, 0, 0, 0, 153, 154, 1, 0, 0, 0, 154, 15, 1, 0, 0, 0, 155, 158, 3, + 20, 10, 0, 156, 158, 3, 24, 12, 0, 157, 155, 1, 0, 0, 0, 157, 156, 1, 0, + 0, 0, 158, 160, 1, 0, 0, 0, 159, 161, 3, 18, 9, 0, 160, 159, 1, 0, 0, 0, + 160, 161, 1, 0, 0, 0, 161, 17, 1, 0, 0, 0, 162, 163, 5, 9, 0, 0, 163, 164, + 5, 13, 0, 0, 164, 167, 5, 9, 0, 0, 165, 168, 3, 20, 10, 0, 166, 168, 3, + 24, 12, 0, 167, 165, 1, 0, 0, 0, 167, 166, 1, 0, 0, 0, 168, 170, 1, 0, + 0, 0, 169, 162, 1, 0, 0, 0, 170, 171, 1, 0, 0, 0, 171, 169, 1, 0, 0, 0, + 171, 172, 1, 0, 0, 0, 172, 192, 1, 0, 0, 0, 173, 174, 5, 9, 0, 0, 174, + 175, 5, 12, 0, 0, 175, 178, 5, 9, 0, 0, 176, 179, 3, 20, 10, 0, 177, 179, + 3, 24, 12, 0, 178, 176, 1, 0, 0, 0, 178, 177, 1, 0, 0, 0, 179, 181, 1, + 0, 0, 0, 180, 173, 1, 0, 0, 0, 181, 182, 1, 0, 0, 0, 182, 180, 1, 0, 0, + 0, 182, 183, 1, 0, 0, 0, 183, 192, 1, 0, 0, 0, 184, 185, 5, 9, 0, 0, 185, + 186, 5, 14, 0, 0, 186, 189, 5, 9, 0, 0, 187, 190, 3, 20, 10, 0, 188, 190, + 3, 24, 12, 0, 189, 187, 1, 0, 0, 0, 189, 188, 1, 0, 0, 0, 190, 192, 1, + 0, 0, 0, 191, 169, 1, 0, 0, 0, 191, 180, 1, 0, 0, 0, 191, 184, 1, 0, 0, + 0, 192, 19, 1, 0, 0, 0, 193, 194, 3, 28, 14, 0, 194, 21, 1, 0, 0, 0, 195, + 199, 5, 7, 0, 0, 196, 198, 5, 9, 0, 0, 197, 196, 1, 0, 0, 0, 198, 201, + 1, 0, 0, 0, 199, 197, 1, 0, 0, 0, 199, 200, 1, 0, 0, 0, 200, 204, 1, 0, + 0, 0, 201, 199, 1, 0, 0, 0, 202, 205, 3, 14, 7, 0, 203, 205, 3, 24, 12, + 0, 204, 202, 1, 0, 0, 0, 204, 203, 1, 0, 0, 0, 205, 209, 1, 0, 0, 0, 206, + 208, 5, 9, 0, 0, 207, 206, 1, 0, 0, 0, 208, 211, 1, 0, 0, 0, 209, 207, + 1, 0, 0, 0, 209, 210, 1, 0, 0, 0, 210, 212, 1, 0, 0, 0, 211, 209, 1, 0, + 0, 0, 212, 213, 5, 8, 0, 0, 213, 23, 1, 0, 0, 0, 214, 218, 5, 7, 0, 0, + 215, 217, 5, 9, 0, 0, 216, 215, 1, 0, 0, 0, 217, 220, 1, 0, 0, 0, 218, + 216, 1, 0, 0, 0, 218, 219, 1, 0, 0, 0, 219, 223, 1, 0, 0, 0, 220, 218, + 1, 0, 0, 0, 221, 224, 3, 16, 8, 0, 222, 224, 3, 24, 12, 0, 223, 221, 1, + 0, 0, 0, 223, 222, 1, 0, 0, 0, 224, 228, 1, 0, 0, 0, 225, 227, 5, 9, 0, + 0, 226, 225, 1, 0, 0, 0, 227, 230, 1, 0, 0, 0, 228, 226, 1, 0, 0, 0, 228, + 229, 1, 0, 0, 0, 229, 231, 1, 0, 0, 0, 230, 228, 1, 0, 0, 0, 231, 232, + 5, 8, 0, 0, 232, 25, 1, 0, 0, 0, 233, 235, 5, 5, 0, 0, 234, 236, 5, 9, + 0, 0, 235, 234, 1, 0, 0, 0, 235, 236, 1, 0, 0, 0, 236, 237, 1, 0, 0, 0, + 237, 239, 3, 30, 15, 0, 238, 240, 5, 9, 0, 0, 239, 238, 1, 0, 0, 0, 239, + 240, 1, 0, 0, 0, 240, 251, 1, 0, 0, 0, 241, 243, 5, 2, 0, 0, 242, 244, + 5, 9, 0, 0, 243, 242, 1, 0, 0, 0, 243, 244, 1, 0, 0, 0, 244, 245, 1, 0, + 0, 0, 245, 247, 3, 30, 15, 0, 246, 248, 5, 9, 0, 0, 247, 246, 1, 0, 0, + 0, 247, 248, 1, 0, 0, 0, 248, 250, 1, 0, 0, 0, 249, 241, 1, 0, 0, 0, 250, + 253, 1, 0, 0, 0, 251, 249, 1, 0, 0, 0, 251, 252, 1, 0, 0, 0, 252, 254, + 1, 0, 0, 0, 253, 251, 1, 0, 0, 0, 254, 255, 5, 34, 0, 0, 255, 27, 1, 0, + 0, 0, 256, 261, 3, 50, 25, 0, 257, 258, 5, 9, 0, 0, 258, 259, 5, 15, 0, + 0, 259, 260, 5, 9, 0, 0, 260, 262, 3, 50, 25, 0, 261, 257, 1, 0, 0, 0, + 261, 262, 1, 0, 0, 0, 262, 29, 1, 0, 0, 0, 263, 265, 5, 56, 0, 0, 264, + 263, 1, 0, 0, 0, 264, 265, 1, 0, 0, 0, 265, 275, 1, 0, 0, 0, 266, 276, + 3, 32, 16, 0, 267, 268, 3, 32, 16, 0, 268, 269, 5, 9, 0, 0, 269, 270, 5, + 26, 0, 0, 270, 273, 5, 9, 0, 0, 271, 274, 3, 38, 19, 0, 272, 274, 5, 54, + 0, 0, 273, 271, 1, 0, 0, 0, 273, 272, 1, 0, 0, 0, 274, 276, 1, 0, 0, 0, + 275, 266, 1, 0, 0, 0, 275, 267, 1, 0, 0, 0, 276, 278, 1, 0, 0, 0, 277, + 279, 5, 56, 0, 0, 278, 277, 1, 0, 0, 0, 278, 279, 1, 0, 0, 0, 279, 31, + 1, 0, 0, 0, 280, 285, 3, 50, 25, 0, 281, 282, 5, 1, 0, 0, 282, 286, 5, + 42, 0, 0, 283, 284, 5, 11, 0, 0, 284, 286, 3, 50, 25, 0, 285, 281, 1, 0, + 0, 0, 285, 283, 1, 0, 0, 0, 285, 286, 1, 0, 0, 0, 286, 33, 1, 0, 0, 0, + 287, 289, 3, 36, 18, 0, 288, 287, 1, 0, 0, 0, 289, 292, 1, 0, 0, 0, 290, + 288, 1, 0, 0, 0, 290, 291, 1, 0, 0, 0, 291, 35, 1, 0, 0, 0, 292, 290, 1, + 0, 0, 0, 293, 294, 5, 56, 0, 0, 294, 296, 3, 46, 23, 0, 295, 293, 1, 0, + 0, 0, 295, 296, 1, 0, 0, 0, 296, 297, 1, 0, 0, 0, 297, 298, 5, 56, 0, 0, + 298, 299, 5, 22, 0, 0, 299, 300, 5, 9, 0, 0, 300, 302, 3, 38, 19, 0, 301, + 303, 5, 9, 0, 0, 302, 301, 1, 0, 0, 0, 302, 303, 1, 0, 0, 0, 303, 304, + 1, 0, 0, 0, 304, 306, 5, 7, 0, 0, 305, 307, 5, 9, 0, 0, 306, 305, 1, 0, + 0, 0, 306, 307, 1, 0, 0, 0, 307, 308, 1, 0, 0, 0, 308, 310, 3, 40, 20, + 0, 309, 311, 5, 9, 0, 0, 310, 309, 1, 0, 0, 0, 310, 311, 1, 0, 0, 0, 311, + 322, 1, 0, 0, 0, 312, 314, 5, 2, 0, 0, 313, 315, 5, 9, 0, 0, 314, 313, + 1, 0, 0, 0, 314, 315, 1, 0, 0, 0, 315, 316, 1, 0, 0, 0, 316, 318, 3, 40, + 20, 0, 317, 319, 5, 9, 0, 0, 318, 317, 1, 0, 0, 0, 318, 319, 1, 0, 0, 0, + 319, 321, 1, 0, 0, 0, 320, 312, 1, 0, 0, 0, 321, 324, 1, 0, 0, 0, 322, + 320, 1, 0, 0, 0, 322, 323, 1, 0, 0, 0, 323, 326, 1, 0, 0, 0, 324, 322, + 1, 0, 0, 0, 325, 327, 5, 56, 0, 0, 326, 325, 1, 0, 0, 0, 326, 327, 1, 0, + 0, 0, 327, 328, 1, 0, 0, 0, 328, 330, 5, 8, 0, 0, 329, 331, 5, 9, 0, 0, + 330, 329, 1, 0, 0, 0, 330, 331, 1, 0, 0, 0, 331, 332, 1, 0, 0, 0, 332, + 334, 5, 35, 0, 0, 333, 335, 5, 56, 0, 0, 334, 333, 1, 0, 0, 0, 334, 335, + 1, 0, 0, 0, 335, 337, 1, 0, 0, 0, 336, 338, 5, 9, 0, 0, 337, 336, 1, 0, + 0, 0, 337, 338, 1, 0, 0, 0, 338, 339, 1, 0, 0, 0, 339, 341, 3, 52, 26, + 0, 340, 342, 5, 56, 0, 0, 341, 340, 1, 0, 0, 0, 341, 342, 1, 0, 0, 0, 342, + 343, 1, 0, 0, 0, 343, 344, 5, 36, 0, 0, 344, 37, 1, 0, 0, 0, 345, 346, + 5, 10, 0, 0, 346, 39, 1, 0, 0, 0, 347, 349, 5, 56, 0, 0, 348, 347, 1, 0, + 0, 0, 348, 349, 1, 0, 0, 0, 349, 350, 1, 0, 0, 0, 350, 352, 3, 42, 21, + 0, 351, 353, 5, 9, 0, 0, 352, 351, 1, 0, 0, 0, 352, 353, 1, 0, 0, 0, 353, + 354, 1, 0, 0, 0, 354, 356, 5, 1, 0, 0, 355, 357, 5, 9, 0, 0, 356, 355, + 1, 0, 0, 0, 356, 357, 1, 0, 0, 0, 357, 358, 1, 0, 0, 0, 358, 359, 3, 44, + 22, 0, 359, 41, 1, 0, 0, 0, 360, 361, 5, 10, 0, 0, 361, 43, 1, 0, 0, 0, + 362, 368, 5, 58, 0, 0, 363, 364, 5, 57, 0, 0, 364, 365, 5, 3, 0, 0, 365, + 366, 5, 58, 0, 0, 366, 368, 5, 4, 0, 0, 367, 362, 1, 0, 0, 0, 367, 363, + 1, 0, 0, 0, 368, 45, 1, 0, 0, 0, 369, 373, 5, 11, 0, 0, 370, 372, 8, 0, + 0, 0, 371, 370, 1, 0, 0, 0, 372, 375, 1, 0, 0, 0, 373, 371, 1, 0, 0, 0, + 373, 374, 1, 0, 0, 0, 374, 378, 1, 0, 0, 0, 375, 373, 1, 0, 0, 0, 376, + 377, 5, 56, 0, 0, 377, 379, 3, 46, 23, 0, 378, 376, 1, 0, 0, 0, 378, 379, + 1, 0, 0, 0, 379, 47, 1, 0, 0, 0, 380, 381, 7, 1, 0, 0, 381, 49, 1, 0, 0, + 0, 382, 385, 3, 48, 24, 0, 383, 385, 5, 55, 0, 0, 384, 382, 1, 0, 0, 0, + 384, 383, 1, 0, 0, 0, 385, 51, 1, 0, 0, 0, 386, 389, 7, 2, 0, 0, 387, 389, + 8, 3, 0, 0, 388, 386, 1, 0, 0, 0, 388, 387, 1, 0, 0, 0, 389, 392, 1, 0, + 0, 0, 390, 388, 1, 0, 0, 0, 390, 391, 1, 0, 0, 0, 391, 53, 1, 0, 0, 0, + 392, 390, 1, 0, 0, 0, 67, 55, 58, 62, 65, 69, 73, 80, 88, 93, 99, 104, + 109, 114, 124, 126, 130, 137, 141, 150, 153, 157, 160, 167, 171, 178, 182, + 189, 191, 199, 204, 209, 218, 223, 228, 235, 239, 243, 247, 251, 261, 264, + 273, 275, 278, 285, 290, 295, 302, 306, 310, 314, 318, 322, 326, 330, 334, + 337, 341, 348, 352, 356, 367, 373, 378, 384, 388, 390, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -337,10 +339,11 @@ const ( OpenFGAParserNUM_UINT = 51 OpenFGAParserSTRING = 52 OpenFGAParserBYTES = 53 - OpenFGAParserEXTENDED_IDENTIFIER = 54 - OpenFGAParserNEWLINE = 55 - OpenFGAParserCONDITION_PARAM_CONTAINER = 56 - OpenFGAParserCONDITION_PARAM_TYPE = 57 + OpenFGAParserDOLLAR_EXPRESSION = 54 + OpenFGAParserEXTENDED_IDENTIFIER = 55 + OpenFGAParserNEWLINE = 56 + OpenFGAParserCONDITION_PARAM_CONTAINER = 57 + OpenFGAParserCONDITION_PARAM_TYPE = 58 ) // OpenFGAParser rules. @@ -3989,6 +3992,7 @@ type IRelationDefTypeRestrictionContext interface { WHITESPACE(i int) antlr.TerminalNode KEYWORD_WITH() antlr.TerminalNode ConditionName() IConditionNameContext + DOLLAR_EXPRESSION() antlr.TerminalNode // IsRelationDefTypeRestrictionContext differentiates from other interfaces. IsRelationDefTypeRestrictionContext() @@ -4078,6 +4082,10 @@ func (s *RelationDefTypeRestrictionContext) ConditionName() IConditionNameContex return t.(IConditionNameContext) } +func (s *RelationDefTypeRestrictionContext) DOLLAR_EXPRESSION() antlr.TerminalNode { + return s.GetToken(OpenFGAParserDOLLAR_EXPRESSION, 0) +} + func (s *RelationDefTypeRestrictionContext) GetRuleContext() antlr.RuleContext { return s } @@ -4127,13 +4135,13 @@ func (p *OpenFGAParser) RelationDefTypeRestriction() (localctx IRelationDefTypeR } } - p.SetState(273) + p.SetState(275) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 41, p.GetParserRuleContext()) { + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 42, p.GetParserRuleContext()) { case 1: { p.SetState(266) @@ -4170,16 +4178,42 @@ func (p *OpenFGAParser) RelationDefTypeRestriction() (localctx IRelationDefTypeR goto errorExit } } - { - p.SetState(271) - p.ConditionName() + p.SetState(273) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + + switch p.GetTokenStream().LA(1) { + case OpenFGAParserIDENTIFIER: + { + p.SetState(271) + p.ConditionName() + } + + + case OpenFGAParserDOLLAR_EXPRESSION: + { + p.SetState(272) + p.Match(OpenFGAParserDOLLAR_EXPRESSION) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + + + default: + p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) + goto errorExit } case antlr.ATNInvalidAltNumber: goto errorExit } - p.SetState(276) + p.SetState(278) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -4189,7 +4223,7 @@ func (p *OpenFGAParser) RelationDefTypeRestriction() (localctx IRelationDefTypeR if _la == OpenFGAParserNEWLINE { { - p.SetState(275) + p.SetState(277) p.Match(OpenFGAParserNEWLINE) if p.HasError() { // Recognition error - abort rule @@ -4388,14 +4422,14 @@ func (p *OpenFGAParser) RelationDefTypeRestrictionBase() (localctx IRelationDefT p.EnterRule(localctx, 32, OpenFGAParserRULE_relationDefTypeRestrictionBase) p.EnterOuterAlt(localctx, 1) { - p.SetState(278) + p.SetState(280) var _x = p.Extended_identifier() localctx.(*RelationDefTypeRestrictionBaseContext).relationDefTypeRestrictionType = _x } - p.SetState(283) + p.SetState(285) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -4403,7 +4437,7 @@ func (p *OpenFGAParser) RelationDefTypeRestrictionBase() (localctx IRelationDefT switch p.GetTokenStream().LA(1) { case OpenFGAParserCOLON: { - p.SetState(279) + p.SetState(281) p.Match(OpenFGAParserCOLON) if p.HasError() { // Recognition error - abort rule @@ -4411,7 +4445,7 @@ func (p *OpenFGAParser) RelationDefTypeRestrictionBase() (localctx IRelationDefT } } { - p.SetState(280) + p.SetState(282) var _m = p.Match(OpenFGAParserSTAR) @@ -4426,7 +4460,7 @@ func (p *OpenFGAParser) RelationDefTypeRestrictionBase() (localctx IRelationDefT case OpenFGAParserHASH: { - p.SetState(281) + p.SetState(283) p.Match(OpenFGAParserHASH) if p.HasError() { // Recognition error - abort rule @@ -4434,7 +4468,7 @@ func (p *OpenFGAParser) RelationDefTypeRestrictionBase() (localctx IRelationDefT } } { - p.SetState(282) + p.SetState(284) var _x = p.Extended_identifier() @@ -4585,30 +4619,30 @@ func (p *OpenFGAParser) Conditions() (localctx IConditionsContext) { var _alt int p.EnterOuterAlt(localctx, 1) - p.SetState(288) + p.SetState(290) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 44, p.GetParserRuleContext()) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 45, p.GetParserRuleContext()) if p.HasError() { goto errorExit } for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { if _alt == 1 { { - p.SetState(285) + p.SetState(287) p.Condition() } } - p.SetState(290) + p.SetState(292) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 44, p.GetParserRuleContext()) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 45, p.GetParserRuleContext()) if p.HasError() { goto errorExit } @@ -4854,13 +4888,13 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(293) + p.SetState(295) p.GetErrorHandler().Sync(p) - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 45, p.GetParserRuleContext()) == 1 { + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 46, p.GetParserRuleContext()) == 1 { { - p.SetState(291) + p.SetState(293) p.Match(OpenFGAParserNEWLINE) if p.HasError() { // Recognition error - abort rule @@ -4868,7 +4902,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } } { - p.SetState(292) + p.SetState(294) p.MultiLineComment() } @@ -4876,7 +4910,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { goto errorExit } { - p.SetState(295) + p.SetState(297) p.Match(OpenFGAParserNEWLINE) if p.HasError() { // Recognition error - abort rule @@ -4884,7 +4918,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } } { - p.SetState(296) + p.SetState(298) p.Match(OpenFGAParserCONDITION) if p.HasError() { // Recognition error - abort rule @@ -4892,7 +4926,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } } { - p.SetState(297) + p.SetState(299) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -4900,10 +4934,10 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } } { - p.SetState(298) + p.SetState(300) p.ConditionName() } - p.SetState(300) + p.SetState(302) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -4913,7 +4947,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { if _la == OpenFGAParserWHITESPACE { { - p.SetState(299) + p.SetState(301) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -4923,14 +4957,14 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } { - p.SetState(302) + p.SetState(304) p.Match(OpenFGAParserLPAREN) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(304) + p.SetState(306) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -4940,7 +4974,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { if _la == OpenFGAParserWHITESPACE { { - p.SetState(303) + p.SetState(305) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -4950,10 +4984,10 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } { - p.SetState(306) + p.SetState(308) p.ConditionParameter() } - p.SetState(308) + p.SetState(310) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -4963,7 +4997,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { if _la == OpenFGAParserWHITESPACE { { - p.SetState(307) + p.SetState(309) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -4972,7 +5006,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } } - p.SetState(320) + p.SetState(322) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -4982,14 +5016,14 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { for _la == OpenFGAParserCOMMA { { - p.SetState(310) + p.SetState(312) p.Match(OpenFGAParserCOMMA) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(312) + p.SetState(314) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -4999,7 +5033,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { if _la == OpenFGAParserWHITESPACE { { - p.SetState(311) + p.SetState(313) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -5009,10 +5043,10 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } { - p.SetState(314) + p.SetState(316) p.ConditionParameter() } - p.SetState(316) + p.SetState(318) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5022,7 +5056,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { if _la == OpenFGAParserWHITESPACE { { - p.SetState(315) + p.SetState(317) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -5033,14 +5067,14 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } - p.SetState(322) + p.SetState(324) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) } - p.SetState(324) + p.SetState(326) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5050,7 +5084,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { if _la == OpenFGAParserNEWLINE { { - p.SetState(323) + p.SetState(325) p.Match(OpenFGAParserNEWLINE) if p.HasError() { // Recognition error - abort rule @@ -5060,14 +5094,14 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } { - p.SetState(326) + p.SetState(328) p.Match(OpenFGAParserRPAREN) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(328) + p.SetState(330) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5077,7 +5111,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { if _la == OpenFGAParserWHITESPACE { { - p.SetState(327) + p.SetState(329) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -5087,20 +5121,20 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } { - p.SetState(330) + p.SetState(332) p.Match(OpenFGAParserLBRACE) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(332) + p.SetState(334) p.GetErrorHandler().Sync(p) - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 54, p.GetParserRuleContext()) == 1 { + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 55, p.GetParserRuleContext()) == 1 { { - p.SetState(331) + p.SetState(333) p.Match(OpenFGAParserNEWLINE) if p.HasError() { // Recognition error - abort rule @@ -5111,13 +5145,13 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } else if p.HasError() { // JIM goto errorExit } - p.SetState(335) + p.SetState(337) p.GetErrorHandler().Sync(p) - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 55, p.GetParserRuleContext()) == 1 { + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 56, p.GetParserRuleContext()) == 1 { { - p.SetState(334) + p.SetState(336) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -5129,10 +5163,10 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { goto errorExit } { - p.SetState(337) + p.SetState(339) p.ConditionExpression() } - p.SetState(339) + p.SetState(341) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5142,7 +5176,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { if _la == OpenFGAParserNEWLINE { { - p.SetState(338) + p.SetState(340) p.Match(OpenFGAParserNEWLINE) if p.HasError() { // Recognition error - abort rule @@ -5152,7 +5186,7 @@ func (p *OpenFGAParser) Condition() (localctx IConditionContext) { } { - p.SetState(341) + p.SetState(343) p.Match(OpenFGAParserRBRACE) if p.HasError() { // Recognition error - abort rule @@ -5255,7 +5289,7 @@ func (p *OpenFGAParser) ConditionName() (localctx IConditionNameContext) { p.EnterRule(localctx, 38, OpenFGAParserRULE_conditionName) p.EnterOuterAlt(localctx, 1) { - p.SetState(343) + p.SetState(345) p.Match(OpenFGAParserIDENTIFIER) if p.HasError() { // Recognition error - abort rule @@ -5408,7 +5442,7 @@ func (p *OpenFGAParser) ConditionParameter() (localctx IConditionParameterContex var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(346) + p.SetState(348) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5418,7 +5452,7 @@ func (p *OpenFGAParser) ConditionParameter() (localctx IConditionParameterContex if _la == OpenFGAParserNEWLINE { { - p.SetState(345) + p.SetState(347) p.Match(OpenFGAParserNEWLINE) if p.HasError() { // Recognition error - abort rule @@ -5428,10 +5462,10 @@ func (p *OpenFGAParser) ConditionParameter() (localctx IConditionParameterContex } { - p.SetState(348) + p.SetState(350) p.ParameterName() } - p.SetState(350) + p.SetState(352) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5441,7 +5475,7 @@ func (p *OpenFGAParser) ConditionParameter() (localctx IConditionParameterContex if _la == OpenFGAParserWHITESPACE { { - p.SetState(349) + p.SetState(351) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -5451,14 +5485,14 @@ func (p *OpenFGAParser) ConditionParameter() (localctx IConditionParameterContex } { - p.SetState(352) + p.SetState(354) p.Match(OpenFGAParserCOLON) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(354) + p.SetState(356) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5468,7 +5502,7 @@ func (p *OpenFGAParser) ConditionParameter() (localctx IConditionParameterContex if _la == OpenFGAParserWHITESPACE { { - p.SetState(353) + p.SetState(355) p.Match(OpenFGAParserWHITESPACE) if p.HasError() { // Recognition error - abort rule @@ -5478,7 +5512,7 @@ func (p *OpenFGAParser) ConditionParameter() (localctx IConditionParameterContex } { - p.SetState(356) + p.SetState(358) p.ParameterType() } @@ -5577,7 +5611,7 @@ func (p *OpenFGAParser) ParameterName() (localctx IParameterNameContext) { p.EnterRule(localctx, 42, OpenFGAParserRULE_parameterName) p.EnterOuterAlt(localctx, 1) { - p.SetState(358) + p.SetState(360) p.Match(OpenFGAParserIDENTIFIER) if p.HasError() { // Recognition error - abort rule @@ -5693,7 +5727,7 @@ func (s *ParameterTypeContext) ExitRule(listener antlr.ParseTreeListener) { func (p *OpenFGAParser) ParameterType() (localctx IParameterTypeContext) { localctx = NewParameterTypeContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 44, OpenFGAParserRULE_parameterType) - p.SetState(365) + p.SetState(367) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5703,7 +5737,7 @@ func (p *OpenFGAParser) ParameterType() (localctx IParameterTypeContext) { case OpenFGAParserCONDITION_PARAM_TYPE: p.EnterOuterAlt(localctx, 1) { - p.SetState(360) + p.SetState(362) p.Match(OpenFGAParserCONDITION_PARAM_TYPE) if p.HasError() { // Recognition error - abort rule @@ -5715,7 +5749,7 @@ func (p *OpenFGAParser) ParameterType() (localctx IParameterTypeContext) { case OpenFGAParserCONDITION_PARAM_CONTAINER: p.EnterOuterAlt(localctx, 2) { - p.SetState(361) + p.SetState(363) p.Match(OpenFGAParserCONDITION_PARAM_CONTAINER) if p.HasError() { // Recognition error - abort rule @@ -5723,7 +5757,7 @@ func (p *OpenFGAParser) ParameterType() (localctx IParameterTypeContext) { } } { - p.SetState(362) + p.SetState(364) p.Match(OpenFGAParserLESS) if p.HasError() { // Recognition error - abort rule @@ -5731,7 +5765,7 @@ func (p *OpenFGAParser) ParameterType() (localctx IParameterTypeContext) { } } { - p.SetState(363) + p.SetState(365) p.Match(OpenFGAParserCONDITION_PARAM_TYPE) if p.HasError() { // Recognition error - abort rule @@ -5739,7 +5773,7 @@ func (p *OpenFGAParser) ParameterType() (localctx IParameterTypeContext) { } } { - p.SetState(364) + p.SetState(366) p.Match(OpenFGAParserGREATER) if p.HasError() { // Recognition error - abort rule @@ -5878,14 +5912,14 @@ func (p *OpenFGAParser) MultiLineComment() (localctx IMultiLineCommentContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(367) + p.SetState(369) p.Match(OpenFGAParserHASH) if p.HasError() { // Recognition error - abort rule goto errorExit } } - p.SetState(371) + p.SetState(373) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5893,9 +5927,9 @@ func (p *OpenFGAParser) MultiLineComment() (localctx IMultiLineCommentContext) { _la = p.GetTokenStream().LA(1) - for ((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 252201579132747774) != 0) { + for ((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 504403158265495550) != 0) { { - p.SetState(368) + p.SetState(370) _la = p.GetTokenStream().LA(1) if _la <= 0 || _la == OpenFGAParserNEWLINE { @@ -5907,20 +5941,20 @@ func (p *OpenFGAParser) MultiLineComment() (localctx IMultiLineCommentContext) { } - p.SetState(373) + p.SetState(375) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) } - p.SetState(376) + p.SetState(378) p.GetErrorHandler().Sync(p) - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 62, p.GetParserRuleContext()) == 1 { + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 63, p.GetParserRuleContext()) == 1 { { - p.SetState(374) + p.SetState(376) p.Match(OpenFGAParserNEWLINE) if p.HasError() { // Recognition error - abort rule @@ -5928,7 +5962,7 @@ func (p *OpenFGAParser) MultiLineComment() (localctx IMultiLineCommentContext) { } } { - p.SetState(375) + p.SetState(377) p.MultiLineComment() } @@ -6063,7 +6097,7 @@ func (p *OpenFGAParser) Identifier() (localctx IIdentifierContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(378) + p.SetState(380) _la = p.GetTokenStream().LA(1) if !(((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 20382720) != 0)) { @@ -6184,7 +6218,7 @@ func (s *Extended_identifierContext) ExitRule(listener antlr.ParseTreeListener) func (p *OpenFGAParser) Extended_identifier() (localctx IExtended_identifierContext) { localctx = NewExtended_identifierContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 50, OpenFGAParserRULE_extended_identifier) - p.SetState(382) + p.SetState(384) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -6194,7 +6228,7 @@ func (p *OpenFGAParser) Extended_identifier() (localctx IExtended_identifierCont case OpenFGAParserIDENTIFIER, OpenFGAParserMODULE, OpenFGAParserMODEL, OpenFGAParserSCHEMA, OpenFGAParserEXTEND, OpenFGAParserTYPE, OpenFGAParserRELATION: p.EnterOuterAlt(localctx, 1) { - p.SetState(380) + p.SetState(382) p.Identifier() } @@ -6202,7 +6236,7 @@ func (p *OpenFGAParser) Extended_identifier() (localctx IExtended_identifierCont case OpenFGAParserEXTENDED_IDENTIFIER: p.EnterOuterAlt(localctx, 2) { - p.SetState(381) + p.SetState(383) p.Match(OpenFGAParserEXTENDED_IDENTIFIER) if p.HasError() { // Recognition error - abort rule @@ -6659,30 +6693,30 @@ func (p *OpenFGAParser) ConditionExpression() (localctx IConditionExpressionCont var _alt int p.EnterOuterAlt(localctx, 1) - p.SetState(388) + p.SetState(390) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 65, p.GetParserRuleContext()) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 66, p.GetParserRuleContext()) if p.HasError() { goto errorExit } for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { if _alt == 1 { - p.SetState(386) + p.SetState(388) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 64, p.GetParserRuleContext()) { + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 65, p.GetParserRuleContext()) { case 1: { - p.SetState(384) + p.SetState(386) _la = p.GetTokenStream().LA(1) - if !(((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 54043126674753464) != 0)) { + if !(((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 90071923693717432) != 0)) { p.GetErrorHandler().RecoverInline(p) } else { p.GetErrorHandler().ReportMatch(p) @@ -6693,7 +6727,7 @@ func (p *OpenFGAParser) ConditionExpression() (localctx IConditionExpressionCont case 2: { - p.SetState(385) + p.SetState(387) _la = p.GetTokenStream().LA(1) if _la <= 0 || _la == OpenFGAParserRBRACE { @@ -6709,12 +6743,12 @@ func (p *OpenFGAParser) ConditionExpression() (localctx IConditionExpressionCont } } - p.SetState(390) + p.SetState(392) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 65, p.GetParserRuleContext()) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 66, p.GetParserRuleContext()) if p.HasError() { goto errorExit } diff --git a/vendor/github.com/openfga/language/pkg/go/graph/graph.go b/vendor/github.com/openfga/language/pkg/go/graph/graph.go index 3f1b0dfe53..775ee66f98 100644 --- a/vendor/github.com/openfga/language/pkg/go/graph/graph.go +++ b/vendor/github.com/openfga/language/pkg/go/graph/graph.go @@ -83,6 +83,10 @@ func (g *AuthorizationModelGraph) Reversed() (*AuthorizationModelGraph, error) { if !ok { return nil, fmt.Errorf("%w: could not cast to AuthorizationModelEdge", ErrBuildingGraph) } + // AddEdge returns nil if either endpoint is nil (isNilNode check). If the source + // graph is corrupted with nil endpoints, this silently drops those edges. An error + // would be more correct, but AddEdge is also called from parseModel which shouldn't + // error on the builder's own nil checks. Documenting the behavior instead. graphBuilder.AddEdge(nextLine.To(), nextLine.From(), casted.edgeType, casted.tuplesetRelation, casted.conditions) } } diff --git a/vendor/github.com/openfga/language/pkg/go/graph/graph_builder.go b/vendor/github.com/openfga/language/pkg/go/graph/graph_builder.go index 8051c8323c..9c47313d7f 100644 --- a/vendor/github.com/openfga/language/pkg/go/graph/graph_builder.go +++ b/vendor/github.com/openfga/language/pkg/go/graph/graph_builder.go @@ -4,6 +4,7 @@ import ( "cmp" "fmt" "slices" + "strings" "github.com/oklog/ulid/v2" openfgav1 "github.com/openfga/api/proto/openfga/v1" @@ -117,32 +118,48 @@ func checkRewrite(graphBuilder *AuthorizationModelGraphBuilder, parentNode *Auth } } +// classifyRelationReference determines the label and node type for a RelationReference. +// It validates the Type field and classifies the reference based on its RelationOrWildcard oneof. +// Returns empty label if the Type is invalid (empty or contains special characters). +func classifyRelationReference(ref *openfgav1.RelationReference) (label string, nodeType NodeType) { + typeName := ref.GetType() + // Skip entries with invalid Type field: empty, or containing special characters + // that would break node label format (e.g., "user:admin" → "user:admin:*", + // "type#rel" → "type#rel#member"). + if typeName == "" || strings.ContainsAny(typeName, ":#") { + return "", 0 + } + + switch { + case ref.GetWildcard() != nil: + // direct assignment to wildcard + return typeName + ":*", SpecificTypeWildcard + case ref.GetRelation() != "": + // direct assignment to userset + return typeName + "#" + ref.GetRelation(), SpecificTypeAndRelation + default: + // Direct assignment to concrete type. Covers oneof unset and set-but-empty + // (openfga/api gates relation pattern on non-empty, so "" survives validation). + // Matches transformer/jsontodsl.go parseTypeRestriction behavior. + return typeName, SpecificType + } +} + func parseThis(graphBuilder *AuthorizationModelGraphBuilder, parentNode graph.Node, typeDef *openfgav1.TypeDefinition, relation string) { directlyRelated := make([]*openfgav1.RelationReference, 0) - var curNode *AuthorizationModelNode if relationMetadata, ok := typeDef.GetMetadata().GetRelations()[relation]; ok { directlyRelated = relationMetadata.GetDirectlyRelatedUserTypes() } for _, directlyRelatedDef := range directlyRelated { - if directlyRelatedDef.GetRelationOrWildcard() == nil { - // direct assignment to concrete type - assignableType := directlyRelatedDef.GetType() - curNode = graphBuilder.getOrAddNode(assignableType, assignableType, SpecificType) - } - - if directlyRelatedDef.GetWildcard() != nil { - // direct assignment to wildcard - assignableWildcard := directlyRelatedDef.GetType() + ":*" - curNode = graphBuilder.getOrAddNode(assignableWildcard, assignableWildcard, SpecificTypeWildcard) + label, nodeType := classifyRelationReference(directlyRelatedDef) + if label == "" { + // Invalid Type field (empty or contains special characters) + continue } - if directlyRelatedDef.GetRelation() != "" { - // direct assignment to userset - assignableUserset := directlyRelatedDef.GetType() + "#" + directlyRelatedDef.GetRelation() - curNode = graphBuilder.getOrAddNode(assignableUserset, assignableUserset, SpecificTypeAndRelation) - } + curNode := graphBuilder.getOrAddNode(label, label, nodeType) // de-dup types that are conditioned, e.g. if define viewer: [user, user with condX] // we only draw one edge from user to x#viewer, but with two conditions: none and condX @@ -238,8 +255,18 @@ func (g *AuthorizationModelGraphBuilder) getNodeByLabel(uniqueLabel string) *Aut return authModelNode } +// isNilNode reports whether n is nil or a typed-nil *AuthorizationModelNode. The latter is +// not == nil once boxed into graph.Node, and its promoted ID() nil-derefs. +func isNilNode(n graph.Node) bool { + if n == nil { + return true + } + amn, ok := n.(*AuthorizationModelNode) + return ok && amn == nil +} + func (g *AuthorizationModelGraphBuilder) AddEdge(from, to graph.Node, edgeType EdgeType, tuplesetRelation string, conditions []string) *AuthorizationModelEdge { - if from == nil || to == nil { + if isNilNode(from) || isNilNode(to) { return nil } if len(conditions) == 0 { @@ -254,14 +281,17 @@ func (g *AuthorizationModelGraphBuilder) AddEdge(from, to graph.Node, edgeType E } func (g *AuthorizationModelGraphBuilder) upsertEdge(from, to graph.Node, edgeType EdgeType, tuplesetRelation string, condition string) { - if from == nil || to == nil { + if isNilNode(from) || isNilNode(to) { return } iter := g.Lines(from.ID(), to.ID()) for iter.Next() { l := iter.Line() - edge, _ := l.(*AuthorizationModelEdge) + edge, ok := l.(*AuthorizationModelEdge) + if !ok { + continue + } if edge.edgeType == edgeType && edge.tuplesetRelation == tuplesetRelation { for _, cond := range edge.conditions { if cond == condition { @@ -277,14 +307,17 @@ func (g *AuthorizationModelGraphBuilder) upsertEdge(from, to graph.Node, edgeTyp } func (g *AuthorizationModelGraphBuilder) hasEdge(from, to graph.Node, edgeType EdgeType, tuplesetRelation string) bool { - if from == nil || to == nil { + if isNilNode(from) || isNilNode(to) { return false } iter := g.Lines(from.ID(), to.ID()) for iter.Next() { l := iter.Line() - edge, _ := l.(*AuthorizationModelEdge) + edge, ok := l.(*AuthorizationModelEdge) + if !ok { + continue + } if edge.edgeType == edgeType && edge.tuplesetRelation == tuplesetRelation { return true } diff --git a/vendor/github.com/openfga/language/pkg/go/graph/weighted_graph_builder.go b/vendor/github.com/openfga/language/pkg/go/graph/weighted_graph_builder.go index 9a05c9a2be..653ea4be30 100644 --- a/vendor/github.com/openfga/language/pkg/go/graph/weighted_graph_builder.go +++ b/vendor/github.com/openfga/language/pkg/go/graph/weighted_graph_builder.go @@ -188,7 +188,6 @@ func (wgb *WeightedAuthorizationModelGraphBuilder) parseComputed(wg *WeightedAut func (wgb *WeightedAuthorizationModelGraphBuilder) parseThis(wg *WeightedAuthorizationModelGraph, parentNode *WeightedAuthorizationModelNode, typeDef *openfgav1.TypeDefinition, relation string, parentRelationName string) error { var directlyRelated []*openfgav1.RelationReference - var curNode *WeightedAuthorizationModelNode if relationMetadata, ok := typeDef.GetMetadata().GetRelations()[relation]; ok { directlyRelated = relationMetadata.GetDirectlyRelatedUserTypes() @@ -207,21 +206,14 @@ func (wgb *WeightedAuthorizationModelGraphBuilder) parseThis(wg *WeightedAuthori return fmt.Errorf("%w: parent relation node %s not found", ErrInvalidModel, parentRelationName) } for _, directlyRelatedDef := range directlyRelated { - switch { - case directlyRelatedDef.GetRelationOrWildcard() == nil: - // direct assignment to concrete type - assignableType := directlyRelatedDef.GetType() - curNode = wg.GetOrAddNode(assignableType, assignableType, SpecificType) - case directlyRelatedDef.GetWildcard() != nil: - // direct assignment to wildcard - assignableWildcard := directlyRelatedDef.GetType() + ":*" - curNode = wg.GetOrAddNode(assignableWildcard, assignableWildcard, SpecificTypeWildcard) - default: - // direct assignment to userset - assignableUserset := directlyRelatedDef.GetType() + "#" + directlyRelatedDef.GetRelation() - curNode = wg.GetOrAddNode(assignableUserset, assignableUserset, SpecificTypeAndRelation) + label, nodeType := classifyRelationReference(directlyRelatedDef) + if label == "" { + // Invalid Type field (empty or contains special characters) + continue } + curNode := wg.GetOrAddNode(label, label, nodeType) + parentRelationNode.directAssigns = append(parentRelationNode.directAssigns, curNode.uniqueLabel) // de-dup types that are conditioned, e.g. if define viewer: [user, user with condX] // we only draw one edge from user to x#viewer, but with two conditions: none and condX diff --git a/vendor/github.com/openfga/language/pkg/go/transformer/dsltojson.go b/vendor/github.com/openfga/language/pkg/go/transformer/dsltojson.go index 44b930dca1..889fb2835d 100644 --- a/vendor/github.com/openfga/language/pkg/go/transformer/dsltojson.go +++ b/vendor/github.com/openfga/language/pkg/go/transformer/dsltojson.go @@ -330,6 +330,10 @@ func (l *OpenFgaDslListener) ExitRelationDefTypeRestriction(ctx *parser.Relation if conditionName != nil { relationRef.Condition = conditionName.GetText() + } else if dollarExpression := ctx.DOLLAR_EXPRESSION(); dollarExpression != nil { + // `$expression` is a reserved condition name for inline expressions; it + // is carried on the RelationReference exactly like a named condition. + relationRef.Condition = dollarExpression.GetText() } if usersetRestriction != nil { diff --git a/vendor/github.com/openfga/openfga/assets/tests/abac_tests.yaml b/vendor/github.com/openfga/openfga/assets/tests/abac_tests.yaml index c3229d0c21..120f248d92 100644 --- a/vendor/github.com/openfga/openfga/assets/tests/abac_tests.yaml +++ b/vendor/github.com/openfga/openfga/assets/tests/abac_tests.yaml @@ -3127,3 +3127,550 @@ tests: condition: name: isOk errorCode: 2000 + + # Regression test: when the subtract side of a "but not" exclusion has a userset $expression + # with a missing request parameter, the missing-parameter error must surface rather than be + # silently discarded. The bug: ConditionsFilteredTupleKeyIterator records the always-true + # group:1 tuple (onceValid=true), then stores group:2's missing-param error in lastError; + # when the iterator is exhausted with onceValid=true it returns ErrIteratorDone instead of + # the error. The caller then finds alice is not in group:1, misses group:2 entirely, and + # concludes alice is not excluded — returning Allowed: true instead of an error. + - name: inline_expression_exclusion_subtract_missing_param + stages: + - model: | + model + schema 1.1 + type user + type group + relations + define member: [user] + type document + relations + define viewer: [group#member] but not excluded + define excluded: [group#member with $expression] + tuples: + # alice is ONLY in group:2 — not group:1 + - user: user:alice + relation: member + object: group:2 + # both groups grant viewer access to document:1 + - user: group:1#member + relation: viewer + object: document:1 + - user: group:2#member + relation: viewer + object: document:1 + # group:1 members are always excluded (no parameters required) + - user: group:1#member + relation: excluded + object: document:1 + condition: + name: $expression + context: + expression: "true" + # group:2 members are excluded only when channel == 'X' + - user: group:2#member + relation: excluded + object: document:1 + condition: + name: $expression + context: + expression: "channel == 'X'" + parameters: + channel: string + checkAssertions: + # alice (group:2 only) with channel=X → excluded → not allowed + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + channel: "X" + expectation: false + # alice (group:2 only) with channel=Y → not excluded → allowed + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + channel: "Y" + expectation: true + # alice (group:2 only) with no context → group:2's $expression cannot be evaluated → + # must return an error. Without the fix, the always-true group:1 tuple sets + # onceValid=true, group:2's missing-param error is discarded, alice appears + # not-excluded, and the check incorrectly returns Allowed: true. + - tuple: + user: user:alice + relation: viewer + object: document:1 + errorCode: 2000 + + - name: inline_expression_basic + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define editor: [user with $expression] + define viewer: [user] or editor + tuples: + - user: user:alice + relation: editor + object: document:1 + condition: + name: $expression + context: + expression: "channel_id == 'X123456'" + parameters: + channel_id: string + checkAssertions: + - tuple: + user: user:alice + relation: editor + object: document:1 + context: + channel_id: "X123456" + expectation: true + - tuple: + user: user:alice + relation: editor + object: document:1 + context: + channel_id: "WRONG" + expectation: false + - tuple: + user: user:alice + relation: editor + object: document:1 + errorCode: 2000 + listObjectsAssertions: + - request: + user: user:alice + type: document + relation: editor + context: + channel_id: "X123456" + expectation: + - document:1 + - request: + user: user:alice + type: document + relation: editor + context: + channel_id: "WRONG" + expectation: [] + listUsersAssertions: + - request: + object: document:1 + relation: editor + filters: + - user + context: + channel_id: "X123456" + expectation: + - user:alice + - request: + object: document:1 + relation: editor + filters: + - user + context: + channel_id: "WRONG" + expectation: [] + + - name: inline_expression_inferred_string_param + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define viewer: [user with $expression] + tuples: + - user: user:bob + relation: viewer + object: document:2 + condition: + name: $expression + context: + expression: "env == 'prod'" + checkAssertions: + - tuple: + user: user:bob + relation: viewer + object: document:2 + context: + env: "prod" + expectation: true + - tuple: + user: user:bob + relation: viewer + object: document:2 + context: + env: "staging" + expectation: false + + - name: inline_expression_alongside_named_condition + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define viewer: [user with $expression, user with is_employee] + + condition is_employee(emp: bool) { + emp == true + } + tuples: + - user: user:alice + relation: viewer + object: document:1 + condition: + name: $expression + context: + expression: "dept == 'eng'" + parameters: + dept: string + - user: user:bob + relation: viewer + object: document:1 + condition: + name: is_employee + checkAssertions: + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + dept: "eng" + expectation: true + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + dept: "sales" + expectation: false + - tuple: + user: user:bob + relation: viewer + object: document:1 + context: + emp: true + expectation: true + + - name: inline_expression_int_param + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define viewer: [user with $expression] + tuples: + - user: user:alice + relation: viewer + object: document:1 + condition: + name: $expression + context: + expression: "count > 5" + parameters: + count: int + checkAssertions: + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + count: 10 + expectation: true + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + count: 3 + expectation: false + + - name: inline_expression_timestamp_param + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define viewer: [user with $expression] + tuples: + - user: user:alice + relation: viewer + object: document:1 + condition: + name: $expression + context: + expression: "ts < timestamp(\"2023-10-11T10:00:00.000Z\")" + parameters: + ts: timestamp + checkAssertions: + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + ts: "2023-10-11T09:00:00.000Z" + expectation: true + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + ts: "2023-10-11T11:00:00.000Z" + expectation: false + + - name: inline_expression_ipaddress_param + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define viewer: [user with $expression] + tuples: + - user: user:alice + relation: viewer + object: document:1 + condition: + name: $expression + context: + expression: "ip.in_cidr(\"10.0.0.0/8\")" + parameters: + ip: ipaddress + checkAssertions: + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + ip: "10.1.2.3" + expectation: true + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + ip: "192.168.1.1" + expectation: false + + - name: inline_expression_userset_subject + stages: + - model: | + model + schema 1.1 + type user + + type group + relations + define member: [user] + + type document + relations + define viewer: [group#member with $expression] + tuples: + - user: group:eng#member + relation: viewer + object: document:1 + condition: + name: $expression + context: + expression: "env == 'prod'" + parameters: + env: string + - user: user:alice + relation: member + object: group:eng + checkAssertions: + - tuple: + user: group:eng#member + relation: viewer + object: document:1 + context: + env: "prod" + expectation: true + - tuple: + user: group:eng#member + relation: viewer + object: document:1 + context: + env: "staging" + expectation: false + listObjectsAssertions: + - request: + user: group:eng#member + type: document + relation: viewer + context: + env: "prod" + expectation: + - document:1 + - request: + user: group:eng#member + type: document + relation: viewer + context: + env: "staging" + expectation: [] + + - name: inline_expression_ttu + stages: + - model: | + model + schema 1.1 + type user + + type folder + relations + define owner: [user] + + type document + relations + define parent: [folder with $expression] + define viewer: owner from parent + tuples: + - user: folder:1 + relation: parent + object: document:1 + condition: + name: $expression + context: + expression: "env == 'prod'" + parameters: + env: string + - user: user:alice + relation: owner + object: folder:1 + checkAssertions: + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + env: "prod" + expectation: true + - tuple: + user: user:alice + relation: viewer + object: document:1 + context: + env: "staging" + expectation: false + listUsersAssertions: + - request: + object: document:1 + relation: viewer + filters: + - user + context: + env: "prod" + expectation: + - user:alice + - request: + object: document:1 + relation: viewer + filters: + - user + context: + env: "staging" + expectation: [] + - name: wildcard_with_false_conditional_same_user + stages: + - model: | + model + schema 1.1 + type user + + type group + relations + define member: [user with xcond, user:*] + define blocked: [user with xcond, user:*] + define viewer: [user:*] + define allowed: viewer but not blocked + + type document + relations + define viewer: [group#member] + define access: [group#allowed] + + condition xcond(x: string) { + x == '1' + } + tuples: + - user: user:u + relation: member + object: group:g + condition: + name: xcond + - user: user:* + relation: member + object: group:g + - user: group:g#member + relation: viewer + object: document:d + - user: user:* + relation: viewer + object: group:g + - user: user:u + relation: blocked + object: group:g + condition: + name: xcond + - user: user:* + relation: blocked + object: group:g + - user: group:g#allowed + relation: access + object: document:d + checkAssertions: + - tuple: + object: document:d + relation: viewer + user: user:u + context: + "x": "2" + expectation: true + - tuple: + object: document:d + relation: access + user: user:u + context: + "x": "2" + expectation: false + listObjectsAssertions: + - request: + user: user:u + type: document + relation: viewer + context: + "x": "2" + expectation: + - document:d + - request: + user: user:u + type: document + relation: access + context: + "x": "2" + expectation: diff --git a/vendor/github.com/openfga/openfga/assets/tests/consolidated_1_1_tests.yaml b/vendor/github.com/openfga/openfga/assets/tests/consolidated_1_1_tests.yaml index cdbebe070e..a9bdebec3f 100644 --- a/vendor/github.com/openfga/openfga/assets/tests/consolidated_1_1_tests.yaml +++ b/vendor/github.com/openfga/openfga/assets/tests/consolidated_1_1_tests.yaml @@ -2665,6 +2665,879 @@ tests: relation: viewer expectation: - user:cheetah + - name: exclusion_of_exclusion_under_base_wildcard_carveout + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define everyone: [user:*] + define member: [user] + define viewer: (everyone but not member) but not (member but not member) + tuples: + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: member + user: user:alice + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: false + - tuple: + object: document:1 + relation: viewer + user: user:bob + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:* + - name: base_pure_wildcard_exclusion_includes_user + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define everyone: [user:*] + define member: [user] + define viewer: everyone but not (member but not member) + tuples: + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: member + user: user:alice + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:* + - user:alice + - name: nested_exclusion_intersection_wrapped_wildcard_base + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define everyone: [user:*] + define member: [user] + define viewer: ((everyone but not member) and everyone) but not (member but not member) + tuples: + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: member + user: user:alice + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: false + - tuple: + object: document:1 + relation: viewer + user: user:bob + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:* + - name: nested_exclusion_union_wrapped_wildcard_base + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define everyone: [user:*] + define member: [user] + define banned: [user] + define viewer: ((everyone but not member) or (everyone but not banned)) but not (member but not member) + tuples: + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: member + user: user:alice + - object: document:1 + relation: banned + user: user:alice + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: false + - tuple: + object: document:1 + relation: viewer + user: user:bob + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:* + - name: nested_exclusion_base_user_granted_by_other_parent + stages: + - model: | + model + schema 1.1 + type user + + type folder + relations + define everyone: [user:*] + define banned: [user] + define allowed: [user] + define viewer: (everyone but not banned) or allowed + + type document + relations + define parent: [folder] + define member: [user] + define viewer: viewer from parent but not (member but not member) + tuples: + - object: folder:1 + relation: everyone + user: user:* + - object: folder:1 + relation: banned + user: user:alice + - object: folder:2 + relation: allowed + user: user:alice + - object: document:1 + relation: parent + user: folder:1 + - object: document:1 + relation: parent + user: folder:2 + - object: document:1 + relation: member + user: user:alice + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:* + - user:alice + - name: nested_exclusion_base_wildcard_granted_by_other_parent + stages: + - model: | + model + schema 1.1 + type user + + type folder + relations + define everyone: [user:*] + define banned: [user] + define viewer: everyone but not banned + + type document + relations + define parent: [folder] + define member: [user] + define viewer: viewer from parent but not (member but not member) + tuples: + - object: folder:1 + relation: everyone + user: user:* + - object: folder:1 + relation: banned + user: user:alice + - object: folder:2 + relation: everyone + user: user:* + - object: document:1 + relation: parent + user: folder:1 + - object: document:1 + relation: parent + user: folder:2 + - object: document:1 + relation: member + user: user:alice + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:* + - user:alice + - name: nested_exclusion_base_union_regrants_wildcard_user + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define everyone: [user, user:*] + define everyone2: [user:*] + define member: [user] + define viewer: ((everyone but not member) or everyone2) but not (member but not member) + tuples: + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: everyone + user: user:bob + - object: document:1 + relation: everyone2 + user: user:* + - object: document:1 + relation: member + user: user:alice + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:* + - user:alice + - user:bob + - name: exclusion_wildcard_base_minus_union_carveout + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define everyone: [user:*] + define member: [user] + define banned: [user] + define viewer: everyone but not ((everyone but not member) or banned) + tuples: + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: member + user: user:alice + - object: document:1 + relation: member + user: user:bob + - object: document:1 + relation: banned + user: user:bob + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: true + - tuple: + object: document:1 + relation: viewer + user: user:bob + expectation: false + - tuple: + object: document:1 + relation: viewer + user: user:charlie + expectation: false + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:alice + - name: exclusion_user_base_minus_union_carveout + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define everyone: [user:*] + define member: [user] + define banned: [user] + define viewer: [user] but not ((everyone but not member) or banned) + tuples: + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: member + user: user:alice + - object: document:1 + relation: member + user: user:bob + - object: document:1 + relation: banned + user: user:bob + - object: document:1 + relation: viewer + user: user:alice + - object: document:1 + relation: viewer + user: user:bob + - object: document:1 + relation: viewer + user: user:charlie + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: true + - tuple: + object: document:1 + relation: viewer + user: user:bob + expectation: false + - tuple: + object: document:1 + relation: viewer + user: user:charlie + expectation: false + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:alice + - name: exclusion_wildcard_base_minus_union_of_carveouts + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define everyone: [user:*] + define member: [user] + define banned: [user] + define viewer: everyone but not ((everyone but not member) or (everyone but not banned)) + tuples: + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: member + user: user:alice + - object: document:1 + relation: banned + user: user:bob + - object: document:1 + relation: member + user: user:carl + - object: document:1 + relation: banned + user: user:carl + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: false + - tuple: + object: document:1 + relation: viewer + user: user:bob + expectation: false + - tuple: + object: document:1 + relation: viewer + user: user:carl + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:carl + - name: exclusion_subtract_wildcard_and_userset_no_relation + stages: + - model: | + model + schema 1.1 + type user + + type group + relations + define member: [user] + define banned: [user] + define allowed: member but not banned + + type document + relations + define everyone: [user:*] + define blocked: [user:*, group#allowed] + define viewer: everyone but not blocked + tuples: + - object: group:1 + relation: member + user: user:alice + - object: group:1 + relation: banned + user: user:alice + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: blocked + user: user:* + - object: document:1 + relation: blocked + user: group:1#allowed + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: false + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: [] + - name: nested_exclusion_in_both_base_and_subtract + stages: + - model: | + model + schema 1.1 + type user + + type document + relations + define member: [user] + define viewer: (member but not member) but not (member but not member) + tuples: + - object: document:1 + relation: member + user: user:alice + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: false + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - name: union_wildcard_exclusion_then_intersection + stages: + - model: | + model + schema 1.1 + type user + + type group + relations + define everyone: [user:*] + define banned: [user] + define allowed: everyone but not banned + + type document + relations + define everyone: [user:*] + define everyone2: [user:*] + define banned: [user] + define other: [user] + define rel2: [user] + define src: [user, user:*, group#allowed] + define base_excl: everyone but not banned + define viewer: (base_excl or other) and rel2 + define viewer_wc: (base_excl or everyone2) and rel2 + define viewer_src: (src or other) and rel2 + define src_excl: src but not banned + define viewer_src_excl: (src_excl or other) and rel2 + tuples: + - object: document:1 + relation: everyone + user: user:* + - object: document:1 + relation: banned + user: user:bob + - object: document:1 + relation: rel2 + user: user:bob + - object: document:1 + relation: rel2 + user: user:alice + - object: document:2 + relation: everyone + user: user:* + - object: document:2 + relation: banned + user: user:bob + - object: document:2 + relation: other + user: user:bob + - object: document:2 + relation: rel2 + user: user:bob + - object: document:3 + relation: everyone + user: user:* + - object: document:3 + relation: everyone2 + user: user:* + - object: document:3 + relation: banned + user: user:bob + - object: document:3 + relation: rel2 + user: user:bob + - object: document:4 + relation: src + user: user:* + - object: document:4 + relation: src + user: group:g#allowed + - object: group:g + relation: everyone + user: user:* + - object: group:g + relation: banned + user: user:bob + - object: document:4 + relation: rel2 + user: user:bob + - object: document:5 + relation: src + user: user:bob + - object: document:5 + relation: src + user: group:g#allowed + - object: document:5 + relation: rel2 + user: user:bob + checkAssertions: + - tuple: + object: document:1 + relation: viewer + user: user:bob + expectation: false + - tuple: + object: document:1 + relation: viewer + user: user:alice + expectation: true + - tuple: + object: document:2 + relation: viewer + user: user:bob + expectation: true + - tuple: + object: document:3 + relation: viewer_wc + user: user:bob + expectation: true + - tuple: + object: document:4 + relation: viewer_src + user: user:bob + expectation: true + - tuple: + object: document:4 + relation: viewer_src_excl + user: user:bob + expectation: true + - tuple: + object: document:5 + relation: viewer_src_excl + user: user:bob + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: viewer + expectation: + - user:alice + - request: + filters: + - user + object: document:2 + relation: viewer + expectation: + - user:bob + - request: + filters: + - user + object: document:3 + relation: viewer_wc + expectation: + - user:bob + - request: + filters: + - user + object: document:4 + relation: viewer_src + expectation: + - user:bob + - request: + filters: + - user + object: document:4 + relation: viewer_src_excl + expectation: + - user:bob + - request: + filters: + - user + object: document:5 + relation: viewer_src_excl + expectation: + - user:bob + - name: user_through_multiple_paths_with_nested_exclusion + stages: + - model: | + model + schema 1.1 + type user + + type group + relations + define member: [user] + define everyone: [user:*] + define banned: [user] + define allowed: member but not banned + define allowed_wc: everyone but not banned + + type document + relations + define parent: [group] + define editor: [user] + define nobody: [user] + define rel2: [user] + define direct: [user, group#allowed] + define ttu: allowed from parent + define blocked: [user, group#allowed] + define viewer_sub: editor but not blocked + define viewer_sub_ttu: editor but not ttu + define viewer_base: direct but not nobody + define src: [user:*, group#allowed_wc] + define src_excl: src but not nobody + define viewer_and: src and rel2 + define viewer_and_excl: src_excl and rel2 + tuples: + - object: document:1 + relation: direct + user: user:bob + - object: document:1 + relation: direct + user: group:g#allowed + - object: document:1 + relation: editor + user: user:bob + - object: document:1 + relation: blocked + user: user:bob + - object: document:1 + relation: blocked + user: group:g#allowed + - object: group:g + relation: member + user: user:bob + - object: group:g + relation: banned + user: user:bob + - object: document:2 + relation: parent + user: group:g1 + - object: document:2 + relation: parent + user: group:g2 + - object: document:2 + relation: editor + user: user:bob + - object: group:g1 + relation: member + user: user:bob + - object: group:g2 + relation: member + user: user:bob + - object: group:g2 + relation: banned + user: user:bob + - object: document:3 + relation: src + user: user:* + - object: document:3 + relation: src + user: group:gw#allowed_wc + - object: group:gw + relation: everyone + user: user:* + - object: group:gw + relation: banned + user: user:bob + - object: document:3 + relation: rel2 + user: user:bob + checkAssertions: + - tuple: + object: document:1 + relation: direct + user: user:bob + expectation: true + - tuple: + object: document:1 + relation: viewer_sub + user: user:bob + expectation: false + - tuple: + object: document:1 + relation: viewer_base + user: user:bob + expectation: true + - tuple: + object: document:2 + relation: ttu + user: user:bob + expectation: true + - tuple: + object: document:2 + relation: viewer_sub_ttu + user: user:bob + expectation: false + - tuple: + object: document:3 + relation: viewer_and + user: user:bob + expectation: true + - tuple: + object: document:3 + relation: viewer_and_excl + user: user:bob + expectation: true + listUsersAssertions: + - request: + filters: + - user + object: document:1 + relation: direct + expectation: + - user:bob + - request: + filters: + - user + object: document:1 + relation: viewer_sub + expectation: [] + - request: + filters: + - user + object: document:1 + relation: viewer_base + expectation: + - user:bob + - request: + filters: + - user + object: document:2 + relation: ttu + expectation: + - user:bob + - request: + filters: + - user + object: document:2 + relation: viewer_sub_ttu + expectation: [] + - request: + filters: + - user + object: document:3 + relation: viewer_and + expectation: + - user:bob + - request: + filters: + - user + object: document:3 + relation: viewer_and_excl + expectation: + - user:bob - name: exclusion_and_exclusion_in_base_with_wildcard stages: - model: | @@ -9833,3 +10706,55 @@ tests: relation: access object: resource:1 expectation: false + - name: wildcard_and_user_same_object_exclusion + stages: + - model: | + model + schema 1.1 + type user + + type group + relations + define viewer: [user, user:*] + define blocked: [user] + define allowed: viewer but not blocked + + type document + relations + define access: [group#allowed] + tuples: + - user: user:u + relation: viewer + object: group:g + - user: user:* + relation: viewer + object: group:g + - user: user:u + relation: blocked + object: group:g + - user: group:g#allowed + relation: access + object: document:d + checkAssertions: + - tuple: + object: document:d + relation: access + user: user:u + expectation: false + - tuple: + object: document:d + relation: access + user: user:other + expectation: true + listObjectsAssertions: + - request: + user: user:u + type: document + relation: access + expectation: + - request: + user: user:other + type: document + relation: access + expectation: + - document:d diff --git a/vendor/github.com/openfga/openfga/internal/authz/server_interface.go b/vendor/github.com/openfga/openfga/internal/authz/server_interface.go index 08379da4e5..aabec3aeb0 100644 --- a/vendor/github.com/openfga/openfga/internal/authz/server_interface.go +++ b/vendor/github.com/openfga/openfga/internal/authz/server_interface.go @@ -1,5 +1,7 @@ package authz +//go:generate mockgen -source server_interface.go -destination ../mocks/mock_authz_server.go -package mocks + import ( "context" diff --git a/vendor/github.com/openfga/openfga/internal/cachecontroller/cache_controller.go b/vendor/github.com/openfga/openfga/internal/cachecontroller/cache_controller.go index a1ce7b62d9..90c8646adc 100644 --- a/vendor/github.com/openfga/openfga/internal/cachecontroller/cache_controller.go +++ b/vendor/github.com/openfga/openfga/internal/cachecontroller/cache_controller.go @@ -1,5 +1,7 @@ package cachecontroller +//go:generate mockgen -source cache_controller.go -destination ../mocks/mock_cachecontroller.go -package mocks + import ( "context" "math" diff --git a/vendor/github.com/openfga/openfga/internal/check/check.go b/vendor/github.com/openfga/openfga/internal/check/check.go index 892546a686..8e59d55601 100644 --- a/vendor/github.com/openfga/openfga/internal/check/check.go +++ b/vendor/github.com/openfga/openfga/internal/check/check.go @@ -357,6 +357,9 @@ func (r *Resolver) executeStrategy(ctx context.Context, selector planner.Selecto res, err := fn() duration := time.Since(start) span.SetAttributes(attribute.Int64("strategy_duration_ms", duration.Milliseconds())) + if err == nil { + err = ctx.Err() + } if err != nil { // penalize plans that timeout from the upstream context if errors.Is(err, context.DeadlineExceeded) { diff --git a/vendor/github.com/openfga/openfga/internal/check/filters.go b/vendor/github.com/openfga/openfga/internal/check/filters.go index cc4edd4e2b..464a166568 100644 --- a/vendor/github.com/openfga/openfga/internal/check/filters.go +++ b/vendor/github.com/openfga/openfga/internal/check/filters.go @@ -9,6 +9,7 @@ import ( openfgav1 "github.com/openfga/api/proto/openfga/v1" + "github.com/openfga/openfga/internal/condition" "github.com/openfga/openfga/internal/condition/eval" "github.com/openfga/openfga/internal/iterator" "github.com/openfga/openfga/internal/modelgraph" @@ -16,12 +17,18 @@ import ( ) func evaluateCondition(ctx context.Context, model *modelgraph.AuthorizationModelGraph, conditions []string, t *openfgav1.TupleKey, reqCtx *structpb.Struct) (bool, error) { - if !slices.Contains(conditions, t.GetCondition().GetName()) { + name := t.GetCondition().GetName() + + if !slices.Contains(conditions, name) { return false, nil } + if condition.IsInlineExpression(name) { + return eval.EvaluateInlineExpression(ctx, t, reqCtx) + } + // consider converting slice to map for faster lookup once we see a large adoption in conditions - return eval.EvaluateTupleCondition(ctx, t, model.GetConditions()[t.GetCondition().GetName()], reqCtx) + return eval.EvaluateTupleCondition(ctx, t, model.GetConditions()[name], reqCtx) } func BuildConditionTupleKeyFilter(ctx context.Context, model *modelgraph.AuthorizationModelGraph, conditions []string, reqCtx *structpb.Struct) iterator.FilterFunc[*openfgav1.TupleKey] { diff --git a/vendor/github.com/openfga/openfga/internal/checkutil/checkutil.go b/vendor/github.com/openfga/openfga/internal/checkutil/checkutil.go index 09ca27ee5a..1f98e66e4e 100644 --- a/vendor/github.com/openfga/openfga/internal/checkutil/checkutil.go +++ b/vendor/github.com/openfga/openfga/internal/checkutil/checkutil.go @@ -7,7 +7,9 @@ import ( openfgav1 "github.com/openfga/api/proto/openfga/v1" + "github.com/openfga/openfga/internal/condition" "github.com/openfga/openfga/internal/condition/eval" + interrors "github.com/openfga/openfga/internal/errors" "github.com/openfga/openfga/internal/validation" "github.com/openfga/openfga/pkg/storage" "github.com/openfga/openfga/pkg/tuple" @@ -18,9 +20,16 @@ import ( // evaluates whether condition is met. func BuildTupleKeyConditionFilter(ctx context.Context, reqCtx *structpb.Struct, typesys *typesystem.TypeSystem) storage.TupleKeyConditionFilterFunc { return func(t *openfgav1.TupleKey) (bool, error) { + if condition.IsInlineExpression(t.GetCondition().GetName()) { + met, err := eval.EvaluateInlineExpression(ctx, t, reqCtx) + if err != nil { + return false, &interrors.FatalError{Cause: err} + } + return met, nil + } + // no condition on tuple or not found gets handled by eval.EvaluateTupleCondition cond, _ := typesys.GetCondition(t.GetCondition().GetName()) - return eval.EvaluateTupleCondition(ctx, t, cond, reqCtx) } } diff --git a/vendor/github.com/openfga/openfga/internal/condition/condition.go b/vendor/github.com/openfga/openfga/internal/condition/condition.go index 60ccb27c98..09ed24df60 100644 --- a/vendor/github.com/openfga/openfga/internal/condition/condition.go +++ b/vendor/github.com/openfga/openfga/internal/condition/condition.go @@ -5,12 +5,13 @@ import ( "fmt" "maps" "reflect" + "slices" "sync" "time" - "github.com/google/cel-go/cel" - "github.com/google/cel-go/common" - celtypes "github.com/google/cel-go/common/types" + "cel.dev/cel-go/cel" + "cel.dev/cel-go/common" + celtypes "cel.dev/cel-go/common/types" "go.opentelemetry.io/otel" "google.golang.org/protobuf/types/known/structpb" @@ -239,6 +240,7 @@ func (e *EvaluableCondition) Evaluate( missingParameters = append(missingParameters, key) } + slices.Sort(missingParameters) out, details, err := e.celProgram.ContextEval(ctx, activation) if err != nil { diff --git a/vendor/github.com/openfga/openfga/internal/condition/eval/eval.go b/vendor/github.com/openfga/openfga/internal/condition/eval/eval.go index 3eed64978e..2cbc57db03 100644 --- a/vendor/github.com/openfga/openfga/internal/condition/eval/eval.go +++ b/vendor/github.com/openfga/openfga/internal/condition/eval/eval.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "strconv" + "strings" "time" "go.opentelemetry.io/otel" @@ -15,12 +16,74 @@ import ( "github.com/openfga/openfga/internal/condition" "github.com/openfga/openfga/internal/condition/metrics" + interrors "github.com/openfga/openfga/internal/errors" "github.com/openfga/openfga/internal/telemetry" "github.com/openfga/openfga/pkg/tuple" ) var tracer = otel.Tracer("openfga/internal/condition/eval") +func EvaluateInlineExpression(ctx context.Context, tk *openfgav1.TupleKey, reqCtx *structpb.Struct) (bool, error) { + cond := tk.GetCondition() + + if cond == nil || cond.GetName() == "" { + return true, nil + } + + if !condition.IsInlineExpression(cond.GetName()) { + return false, &interrors.FatalError{ + Cause: condition.NewEvaluationError(cond.GetName(), fmt.Errorf("condition is not $expression")), + } + } + + ieCond, err := condition.FromInlineExpression(tk) + if err != nil { + return false, &interrors.FatalError{ + Cause: condition.NewEvaluationError(condition.InlineExpressionName, err), + } + } + + ctx, span := tracer.Start(ctx, "EvaluateInlineExpression", trace.WithAttributes( + attribute.String("tuple_key", tuple.TupleKeyWithConditionToString(tk)), + attribute.String("condition_name", condition.InlineExpressionName))) + defer span.End() + + start := time.Now() + + // Only pass request-context fields that the expression actually declares as parameters. + // Extra fields in the shared request context (provided for other tuples in the same + // request) must not trigger "no parameters defined" errors on zero-param expressions. + var reqFields map[string]*structpb.Value + if reqCtx != nil && len(ieCond.GetParameters()) > 0 { + reqFields = reqCtx.GetFields() + } + + result, err := ieCond.Evaluate(ctx, reqFields) + if err != nil { + telemetry.TraceError(span, err) + return false, &interrors.FatalError{Cause: err} + } + + if len(result.MissingParameters) > 0 { + return false, &interrors.FatalError{ + Cause: condition.NewEvaluationError( + condition.InlineExpressionName, + fmt.Errorf("missing required parameters: %s", strings.Join(result.MissingParameters, ", ")), + ), + } + } + + metrics.Metrics.ObserveEvaluationDuration(time.Since(start)) + metrics.Metrics.ObserveEvaluationCost(result.Cost) + + span.SetAttributes(attribute.Bool("condition_met", result.ConditionMet), + attribute.String("condition_cost", strconv.FormatUint(result.Cost, 10)), + attribute.StringSlice("condition_missing_params", result.MissingParameters), + ) + + return result.ConditionMet, nil +} + // EvaluateTupleCondition looks at the given tuple's condition and returns an evaluation result for the given context. // If the tuple doesn't have a condition, it exits early and doesn't create a span. // If the tuple's condition isn't found in the model it returns an EvaluationError. diff --git a/vendor/github.com/openfga/openfga/internal/condition/inline.go b/vendor/github.com/openfga/openfga/internal/condition/inline.go new file mode 100644 index 0000000000..e96056e216 --- /dev/null +++ b/vendor/github.com/openfga/openfga/internal/condition/inline.go @@ -0,0 +1,239 @@ +package condition + +import ( + "fmt" + "maps" + "slices" + "strings" + + celast "cel.dev/cel-go/common/ast" + "google.golang.org/protobuf/types/known/structpb" + + openfgav1 "github.com/openfga/api/proto/openfga/v1" + + "github.com/openfga/openfga/internal/condition/types" + "github.com/openfga/openfga/pkg/server/config" +) + +// InlineExpressionName is the reserved condition name used for $expression inline conditions. +const InlineExpressionName = "$expression" + +// inlineContextExpressionKey and inlineContextParametersKey are the reserved keys +// in the $expression condition context Struct. +const ( + inlineContextExpressionKey = "expression" + inlineContextParametersKey = "parameters" +) + +// IsInlineExpression reports whether a condition name is the $expression reserved symbol. +func IsInlineExpression(name string) bool { + return name == InlineExpressionName +} + +type conditionParameters = map[string]*openfgav1.ConditionParamTypeRef + +// parseTypeRef converts a type-spec string (e.g. "string", "map", "list") +// to a ConditionParamTypeRef. Container types require an explicit element type: +// bare "map" or "list" are rejected early with a descriptive error rather than letting +// the opaque "requires 1 generic types; found 0" surface from DecodeParameterType. +func parseTypeRef(typeStr string) (*openfgav1.ConditionParamTypeRef, error) { + open := strings.IndexByte(typeStr, '<') + if open >= 0 { + if !strings.HasSuffix(typeStr, ">") { + return nil, fmt.Errorf("malformed generic type %q: missing closing >", typeStr) + } + outerName, ok := types.TypeNameFromString(typeStr[:open]) + if !ok { + return nil, fmt.Errorf("unknown parameter type %q", typeStr[:open]) + } + innerRef, err := parseTypeRef(typeStr[open+1 : len(typeStr)-1]) + if err != nil { + return nil, err + } + return &openfgav1.ConditionParamTypeRef{ + TypeName: outerName, + GenericTypes: []*openfgav1.ConditionParamTypeRef{innerRef}, + }, nil + } + + typeName, ok := types.TypeNameFromString(typeStr) + if !ok { + return nil, fmt.Errorf("unknown parameter type %q", typeStr) + } + ref := &openfgav1.ConditionParamTypeRef{TypeName: typeName} + // Use DecodeParameterType to detect container types that require a generic element. + if _, err := types.DecodeParameterType(ref); err != nil { + return nil, fmt.Errorf("parameter type %q requires a generic element type, e.g. %q", typeStr, typeStr+"") + } + return ref, nil +} + +func extractDeclaredParameters(fields map[string]*structpb.Value) (conditionParameters, error) { + var declaredParams conditionParameters + + if paramVal, ok := fields[inlineContextParametersKey]; ok { + ps := paramVal.GetStructValue() + if ps == nil { + return nil, fmt.Errorf("%s: context field %q must be a struct", InlineExpressionName, inlineContextParametersKey) + } + for paramName, typeVal := range ps.GetFields() { + typeRef, err := parseTypeRef(typeVal.GetStringValue()) + if err != nil { + return nil, fmt.Errorf( + "%s: invalid parameter type for parameter %q: %w", InlineExpressionName, paramName, err, + ) + } + if declaredParams == nil { + declaredParams = make(conditionParameters) + } + declaredParams[paramName] = typeRef + } + } + return declaredParams, nil +} + +// FromInlineExpression parses, compiles, and returns an EvaluableCondition for the +// $expression inline condition carried by tk. +func FromInlineExpression(tk *openfgav1.TupleKey) (*EvaluableCondition, error) { + return compileInlineExpression(tk.GetCondition().GetContext()) +} + +// compileInlineExpression parses the $expression struct, infers parameter types, +// creates an EvaluableCondition, and compiles the CEL program before returning. +func compileInlineExpression(structCtx *structpb.Struct) (*EvaluableCondition, error) { + fields := structCtx.GetFields() + + exprVal, ok := fields[inlineContextExpressionKey] + if !ok { + return nil, fmt.Errorf("%s: missing required context field %q", InlineExpressionName, inlineContextExpressionKey) + } + + exprStr := exprVal.GetStringValue() + if exprStr == "" { + return nil, fmt.Errorf("%s: context field %q must be a non-empty string", InlineExpressionName, inlineContextExpressionKey) + } + + declaredParams, err := extractDeclaredParameters(fields) + if err != nil { + return nil, err + } + + ast, issues := celBaseEnv.Parse(exprStr) + if issues != nil && issues.Err() != nil { + return nil, fmt.Errorf("%s: invalid CEL expression: %w", InlineExpressionName, issues.Err()) + } + + inferredIdents := extractIdents(ast.NativeRep().Expr()) + + if declaredParams == nil && len(inferredIdents) > 0 { + declaredParams = make(conditionParameters, len(inferredIdents)) + } + + for _, ident := range inferredIdents { + if _, alreadyDeclared := declaredParams[ident]; !alreadyDeclared { + declaredParams[ident] = &openfgav1.ConditionParamTypeRef{ + TypeName: openfgav1.ConditionParamTypeRef_TYPE_NAME_STRING, + } + } + } + + ec := NewUncompiled(&openfgav1.Condition{ + Name: InlineExpressionName, + Expression: exprStr, + Parameters: declaredParams, + }). + WithTrackEvaluationCost(). + WithMaxEvaluationCost(config.MaxConditionEvaluationCost()). + WithInterruptCheckFrequency(config.DefaultInterruptCheckFrequency) + + if err := ec.Compile(); err != nil { + return nil, err + } + return ec, nil +} + +// extractIdents iteratively walks a CEL expression and returns the names of all +// variable identifiers, excluding those bound by enclosing comprehensions (locals). +func extractIdents(expr celast.Expr) []string { + if expr == nil { + return nil + } + + type stackItem struct { + expr celast.Expr + locals map[string]bool + } + + var results []string + + stack := []stackItem{{expr: expr, locals: nil}} + + for len(stack) > 0 { + idx := len(stack) - 1 + current := stack[idx] + stack = stack[:idx] + + expr := current.expr + locals := current.locals + + switch expr.Kind() { + case celast.IdentKind: + name := expr.AsIdent() + if locals[name] { + continue + } + results = append(results, name) + + case celast.SelectKind: + stack = append(stack, stackItem{expr: expr.AsSelect().Operand(), locals: locals}) + + case celast.CallKind: + call := expr.AsCall() + + for _, arg := range slices.Backward(call.Args()) { + stack = append(stack, stackItem{expr: arg, locals: locals}) + } + + if call.IsMemberFunction() { + stack = append(stack, stackItem{expr: call.Target(), locals: locals}) + } + + case celast.ListKind: + for _, elem := range slices.Backward(expr.AsList().Elements()) { + stack = append(stack, stackItem{expr: elem, locals: locals}) + } + + case celast.MapKind: + for _, entry := range slices.Backward(expr.AsMap().Entries()) { + me := entry.AsMapEntry() + stack = append(stack, stackItem{expr: me.Key(), locals: locals}) + stack = append(stack, stackItem{expr: me.Value(), locals: locals}) + } + + case celast.StructKind: + for _, field := range slices.Backward(expr.AsStruct().Fields()) { + stack = append(stack, stackItem{expr: field.AsStructField().Value(), locals: locals}) + } + + case celast.ComprehensionKind: + comp := expr.AsComprehension() + // Create a new locals scope that includes the comprehension-bound variables. + innerLocals := maps.Clone(locals) + if innerLocals == nil { + innerLocals = map[string]bool{} + } + innerLocals[comp.IterVar()] = true + if comp.HasIterVar2() { + innerLocals[comp.IterVar2()] = true + } + innerLocals[comp.AccuVar()] = true + + stack = append(stack, stackItem{expr: comp.Result(), locals: innerLocals}) + stack = append(stack, stackItem{expr: comp.LoopStep(), locals: innerLocals}) + stack = append(stack, stackItem{expr: comp.LoopCondition(), locals: innerLocals}) + stack = append(stack, stackItem{expr: comp.AccuInit(), locals: innerLocals}) + stack = append(stack, stackItem{expr: comp.IterRange(), locals: locals}) + } + } + return results +} diff --git a/vendor/github.com/openfga/openfga/internal/condition/types/converters.go b/vendor/github.com/openfga/openfga/internal/condition/types/converters.go index 13dce6e354..814779e2b0 100644 --- a/vendor/github.com/openfga/openfga/internal/condition/types/converters.go +++ b/vendor/github.com/openfga/openfga/internal/condition/types/converters.go @@ -2,6 +2,7 @@ package types import ( "fmt" + "math" "math/big" "reflect" "time" @@ -45,7 +46,10 @@ func numericTypeConverterFunc[T int64 | uint64 | float64](value any) (any, error return nil, fmt.Errorf("expected an int value, but found numeric value '%s'", bigFloat.String()) } - numericValue, _ := bigFloat.Int64() + numericValue, acc := bigFloat.Int64() + if acc != big.Exact { + return nil, fmt.Errorf("number cannot be represented as an int64: %s", bigFloat.String()) + } return numericValue, nil case uint64: @@ -53,17 +57,24 @@ func numericTypeConverterFunc[T int64 | uint64 | float64](value any) (any, error return nil, fmt.Errorf("expected a uint value, but found numeric value '%s'", bigFloat.String()) } - numericValue, _ := bigFloat.Int64() - if numericValue < 0 { + if bigFloat.Sign() < 0 { return nil, fmt.Errorf("expected a uint value, but found int64 value '%s'", bigFloat.String()) } - return uint64(numericValue), nil + + numericValue, acc := bigFloat.Uint64() + if acc != big.Exact { + return nil, fmt.Errorf("number cannot be represented as a uint64: %s", bigFloat.String()) + } + return numericValue, nil case float64: numericValue, a := bigFloat.Float64() if a == big.Above || a == big.Below { return nil, fmt.Errorf("number cannot be represented as a float64: %s", bigFloat.String()) } + if math.IsInf(numericValue, 0) { + return nil, fmt.Errorf("number cannot be represented as a float64: %s", bigFloat.String()) + } return numericValue, nil default: diff --git a/vendor/github.com/openfga/openfga/internal/condition/types/generic.go b/vendor/github.com/openfga/openfga/internal/condition/types/generic.go index 85524cc1e7..f7d8204ac3 100644 --- a/vendor/github.com/openfga/openfga/internal/condition/types/generic.go +++ b/vendor/github.com/openfga/openfga/internal/condition/types/generic.go @@ -3,7 +3,7 @@ package types import ( "fmt" - "github.com/google/cel-go/cel" + "cel.dev/cel-go/cel" openfgav1 "github.com/openfga/api/proto/openfga/v1" ) diff --git a/vendor/github.com/openfga/openfga/internal/condition/types/ipaddress.go b/vendor/github.com/openfga/openfga/internal/condition/types/ipaddress.go index 6379b683f7..781bd333e9 100644 --- a/vendor/github.com/openfga/openfga/internal/condition/types/ipaddress.go +++ b/vendor/github.com/openfga/openfga/internal/condition/types/ipaddress.go @@ -5,10 +5,10 @@ import ( "net/netip" "reflect" - "github.com/google/cel-go/cel" - "github.com/google/cel-go/common/types" - "github.com/google/cel-go/common/types/ref" - "github.com/google/cel-go/common/types/traits" + "cel.dev/cel-go/cel" + "cel.dev/cel-go/common/types" + "cel.dev/cel-go/common/types/ref" + "cel.dev/cel-go/common/types/traits" openfgav1 "github.com/openfga/api/proto/openfga/v1" ) @@ -73,7 +73,7 @@ var ipaddrCelType = cel.ObjectType("IPAddress", traits.ReceiverType) // ConvertToNative implements the CEL ref.Val.ConvertToNative. // -// See https://pkg.go.dev/github.com/google/cel-go/common/types/ref#Val +// See https://pkg.go.dev/cel.dev/cel-go/common/types/ref#Val func (ip IPAddress) ConvertToNative(typeDesc reflect.Type) (any, error) { if reflect.TypeOf(ip).AssignableTo(typeDesc) { return ip, nil @@ -89,7 +89,7 @@ func (ip IPAddress) ConvertToNative(typeDesc reflect.Type) (any, error) { // ConvertToType implements the CEL ref.Val.ConvertToType. // -// See https://pkg.go.dev/github.com/google/cel-go/common/types/ref#Val +// See https://pkg.go.dev/cel.dev/cel-go/common/types/ref#Val func (ip IPAddress) ConvertToType(typeValue ref.Type) ref.Val { switch typeValue { case types.StringType: @@ -103,7 +103,7 @@ func (ip IPAddress) ConvertToType(typeValue ref.Type) ref.Val { // Equal implements the CEL ref.Val.Equal. // -// See https://pkg.go.dev/github.com/google/cel-go/common/types/ref#Val +// See https://pkg.go.dev/cel.dev/cel-go/common/types/ref#Val func (ip IPAddress) Equal(other ref.Val) ref.Val { otherip, ok := other.(IPAddress) if !ok { @@ -115,14 +115,14 @@ func (ip IPAddress) Equal(other ref.Val) ref.Val { // Type implements the CEL ref.Val.Type. // -// See https://pkg.go.dev/github.com/google/cel-go/common/types/ref#Val +// See https://pkg.go.dev/cel.dev/cel-go/common/types/ref#Val func (ip IPAddress) Type() ref.Type { return ipaddrCelType } // Value implements ref.Val.Value. // -// See https://pkg.go.dev/github.com/google/cel-go/common/types/ref#Val +// See https://pkg.go.dev/cel.dev/cel-go/common/types/ref#Val func (ip IPAddress) Value() any { return ip } @@ -131,7 +131,7 @@ func (ip IPAddress) Value() any { // comparing an ipaddress value against a network CIDR defined as a string. If the ipaddress is // within the CIDR range this binding will return true, otherwise it will return false or an error. // -// See https://pkg.go.dev/github.com/google/cel-go/cel#BinaryBinding +// See https://pkg.go.dev/cel.dev/cel-go/cel#BinaryBinding func ipaddressCELBinaryBinding(lhs, rhs ref.Val) ref.Val { cidr, ok := rhs.Value().(string) if !ok { diff --git a/vendor/github.com/openfga/openfga/internal/condition/types/primitives.go b/vendor/github.com/openfga/openfga/internal/condition/types/primitives.go index cff305a202..4deb5a071d 100644 --- a/vendor/github.com/openfga/openfga/internal/condition/types/primitives.go +++ b/vendor/github.com/openfga/openfga/internal/condition/types/primitives.go @@ -1,7 +1,7 @@ package types import ( - "github.com/google/cel-go/cel" + "cel.dev/cel-go/cel" openfgav1 "github.com/openfga/api/proto/openfga/v1" ) diff --git a/vendor/github.com/openfga/openfga/internal/condition/types/types.go b/vendor/github.com/openfga/openfga/internal/condition/types/types.go index 45d1dd8433..89303efb6c 100644 --- a/vendor/github.com/openfga/openfga/internal/condition/types/types.go +++ b/vendor/github.com/openfga/openfga/internal/condition/types/types.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/google/cel-go/cel" + "cel.dev/cel-go/cel" openfgav1 "github.com/openfga/api/proto/openfga/v1" ) @@ -49,6 +49,23 @@ var paramTypeString = map[openfgav1.ConditionParamTypeRef_TypeName]string{ openfgav1.ConditionParamTypeRef_TYPE_NAME_IPADDRESS: "ipaddress", } +// typeNameFromString is the inverse of paramTypeString: maps a type name string to its enum value. +var typeNameFromString map[string]openfgav1.ConditionParamTypeRef_TypeName + +func init() { + typeNameFromString = make(map[string]openfgav1.ConditionParamTypeRef_TypeName, len(paramTypeString)) + for enum, str := range paramTypeString { + typeNameFromString[str] = enum + } +} + +// TypeNameFromString converts a type name string (e.g. "string", "int") to its +// ConditionParamTypeRef_TypeName enum value. Returns false if the name is unknown. +func TypeNameFromString(s string) (openfgav1.ConditionParamTypeRef_TypeName, bool) { + v, ok := typeNameFromString[s] + return v, ok +} + func registerParamTypeWithGenerics( paramTypeKeyword openfgav1.ConditionParamTypeRef_TypeName, genericTypeCount uint, diff --git a/vendor/github.com/openfga/openfga/internal/errors/errors.go b/vendor/github.com/openfga/openfga/internal/errors/errors.go index e67e32b802..c9968dbf0f 100644 --- a/vendor/github.com/openfga/openfga/internal/errors/errors.go +++ b/vendor/github.com/openfga/openfga/internal/errors/errors.go @@ -7,3 +7,14 @@ import "errors" // use error wrapping (https://github.com/tomarrell/wrapcheck#why) var ErrUnknown = errors.New("internal server error") + +// FatalError wraps an error that must be propagated immediately by any consumer, +// regardless of whether other results have already been produced. It is not tied +// to any specific layer: any producer (filter, evaluator, resolver) may wrap an +// error as fatal, and any consumer can detect it with errors.As. +type FatalError struct { + Cause error +} + +func (e *FatalError) Error() string { return e.Cause.Error() } +func (e *FatalError) Unwrap() error { return e.Cause } diff --git a/vendor/github.com/openfga/openfga/internal/graph/cached_resolver.go b/vendor/github.com/openfga/openfga/internal/graph/cached_resolver.go index 38fd5b54c5..7fe0687549 100644 --- a/vendor/github.com/openfga/openfga/internal/graph/cached_resolver.go +++ b/vendor/github.com/openfga/openfga/internal/graph/cached_resolver.go @@ -197,6 +197,10 @@ func (c *CachedCheckResolver) ResolveCheck( return resp, nil } + if ctx.Err() != nil { + return resp, nil + } + clonedResp := resp.clone() c.cache.Set(cacheKey, &CheckResponseCacheEntry{LastModified: time.Now(), CheckResponse: clonedResp}, storage.JitteredTTL(c.cacheTTL, c.jitterPercentage)) diff --git a/vendor/github.com/openfga/openfga/internal/graph/check.go b/vendor/github.com/openfga/openfga/internal/graph/check.go index a983c905cf..560c348763 100644 --- a/vendor/github.com/openfga/openfga/internal/graph/check.go +++ b/vendor/github.com/openfga/openfga/internal/graph/check.go @@ -171,7 +171,7 @@ func union(ctx context.Context, concurrencyLimit int, handlers ...CheckHandlerFu for _, handler := range handlers { h := handler pool.Go(func(ctx context.Context) error { - concurrency.TrySendThroughChannel(cancellableCtx, runHandler(ctx, h), out) + out <- runHandler(ctx, h) return nil }) } @@ -191,9 +191,8 @@ func union(ctx context.Context, concurrencyLimit int, handlers ...CheckHandlerFu case outcome, ok := <-out: if !ok { - break + return nil, fmt.Errorf("%w: reducer outcome channel closed before all handlers reported", openfgaErrors.ErrUnknown) } - if outcome.err != nil { finalErr = outcome.err continue // Continue to see if we find an 'Allowed: true' @@ -237,7 +236,7 @@ func intersection(ctx context.Context, concurrencyLimit int, handlers ...CheckHa for _, handler := range handlers { h := handler // Capture loop variable for the goroutine pool.Go(func(ctx context.Context) error { - concurrency.TrySendThroughChannel(cancellableCtx, runHandler(ctx, h), out) + out <- runHandler(ctx, h) return nil }) } @@ -259,9 +258,8 @@ func intersection(ctx context.Context, concurrencyLimit int, handlers ...CheckHa case outcome, ok := <-out: if !ok { - break + return nil, fmt.Errorf("%w: reducer outcome channel closed before all handlers reported", openfgaErrors.ErrUnknown) } - if outcome.err != nil { // Store the first error we see, but don't exit yet. // A definitive 'false' result from another handler can override this. @@ -633,6 +631,9 @@ func (c *LocalChecker) profiledCheckHandler(keyPlan planner.Selector, strategy * return func(ctx context.Context) (*ResolveCheckResponse, error) { start := time.Now() res, err := resolver(ctx) + if err == nil { + err = ctx.Err() + } if err != nil { // penalize plans that timeout from the upstream context if errors.Is(err, context.DeadlineExceeded) { diff --git a/vendor/github.com/openfga/openfga/internal/graph/recursive_resolver.go b/vendor/github.com/openfga/openfga/internal/graph/recursive_resolver.go index c60bd9cc8d..4570f5803d 100644 --- a/vendor/github.com/openfga/openfga/internal/graph/recursive_resolver.go +++ b/vendor/github.com/openfga/openfga/internal/graph/recursive_resolver.go @@ -103,7 +103,10 @@ func (c *LocalChecker) recursiveFastPath(ctx context.Context, req *ResolveCheckR return nil, ctx.Err() case objectToUsersetMessage, ok := <-objectToUsersetMessageChan: if !ok { - return res, ctx.Err() + if ctx.Err() != nil { + return nil, ctx.Err() + } + return res, nil } if objectToUsersetMessage.err != nil { return nil, objectToUsersetMessage.err @@ -129,8 +132,12 @@ func (c *LocalChecker) recursiveFastPath(ctx context.Context, req *ResolveCheckR case userToUsersetMessage, ok := <-userToUsersetMessageChan: if !ok { userToUsersetDone = true + userToUsersetMessageChan = nil + if ctx.Err() != nil { + return nil, ctx.Err() + } if usersetFromUser.Size() == 0 { - return res, ctx.Err() + return res, nil } break } @@ -145,6 +152,10 @@ func (c *LocalChecker) recursiveFastPath(ctx context.Context, req *ResolveCheckR if !ok { // usersetFromObject must not be empty because we would have caught it earlier. objectToUsersetDone = true + objectToUsersetMessageChan = nil + if ctx.Err() != nil { + return nil, ctx.Err() + } break } if objectToUsersetMessage.err != nil { diff --git a/vendor/github.com/openfga/openfga/internal/graph/weight_two_resolver.go b/vendor/github.com/openfga/openfga/internal/graph/weight_two_resolver.go index bb19b81b16..1ffff2cb3c 100644 --- a/vendor/github.com/openfga/openfga/internal/graph/weight_two_resolver.go +++ b/vendor/github.com/openfga/openfga/internal/graph/weight_two_resolver.go @@ -135,7 +135,10 @@ func (c *LocalChecker) weight2(ctx context.Context, leftChans []<-chan *iterator return nil, ctx.Err() case r, ok := <-rightChan: if !ok { - return res, ctx.Err() + if ctx.Err() != nil { + return nil, ctx.Err() + } + return res, nil } if r.err != nil { return nil, r.err @@ -154,10 +157,12 @@ ConsumerLoop: case msg, ok := <-leftChan: if !ok { leftOpen = false + leftChan = nil + if ctx.Err() != nil { + lastErr = ctx.Err() + break ConsumerLoop + } if leftSet.Size() == 0 { - if ctx.Err() != nil { - lastErr = ctx.Err() - } break ConsumerLoop } break @@ -170,11 +175,12 @@ ConsumerLoop: t, err := msg.Iter.Next(ctx) if err != nil { msg.Iter.Stop() - if storage.IterIsDoneOrCancelled(err) { - break + if !errors.Is(err, storage.ErrIteratorDone) { + lastErr = err } - lastErr = err - continue + // Do not read again: a stopped iterator may keep returning its error (Dedupe reads Head, which the + // ordered merge caches), and a match from another iterator can still override lastErr. + break } if processUsersetMessage(t, leftSet, rightSet) { msg.Iter.Stop() @@ -186,6 +192,11 @@ ConsumerLoop: case msg, ok := <-rightChan: if !ok { rightOpen = false + rightChan = nil + if ctx.Err() != nil { + lastErr = ctx.Err() + break ConsumerLoop + } break } if msg.err != nil { @@ -199,7 +210,10 @@ ConsumerLoop: } } } - return res, lastErr + if lastErr != nil { + return nil, lastErr + } + return res, nil } // member: [user, user:*] @@ -256,7 +270,8 @@ func fastPathDirect(ctx context.Context, req *ResolveCheckRequest) (chan *iterat return nil, err } iterChan := make(chan *iterator.Msg, 1) - iter := storage.WrapIterator(storage.ObjectIDKind, i) + // The sorted merge keeps a user's and the wildcard's tuple for the same object; fastPathDifference needs unique IDs. + iter := iterator.Dedupe(storage.WrapIterator(storage.ObjectIDKind, i)) if !concurrency.TrySendThroughChannel(ctx, &iterator.Msg{Iter: iter}, iterChan) { iter.Stop() // will not be received to be cleaned up } @@ -302,10 +317,6 @@ func fastPathUnion(ctx context.Context, streams *iterator.Streams, outChan chan< batch := make([]string, 0) defer func() { - // flush - if len(batch) > 0 { - concurrency.TrySendThroughChannel(ctx, &iterator.Msg{Iter: storage.NewStaticIterator[string](batch)}, outChan) - } close(outChan) streams.Stop() }() @@ -331,7 +342,7 @@ func fastPathUnion(ctx context.Context, streams *iterator.Streams, outChan chan< for idx, stream := range iterStreams { v, err := stream.Head(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { allIters = false // we need to ensure we have all iterators at all times break @@ -368,16 +379,16 @@ func fastPathUnion(ctx context.Context, streams *iterator.Streams, outChan chan< return } } + + if len(batch) > 0 { + concurrency.TrySendThroughChannel(ctx, &iterator.Msg{Iter: storage.NewStaticIterator[string](batch)}, outChan) + } } func fastPathIntersection(ctx context.Context, streams *iterator.Streams, outChan chan<- *iterator.Msg) { batch := make([]string, 0) defer func() { - // flush - if len(batch) > 0 { - concurrency.TrySendThroughChannel(ctx, &iterator.Msg{Iter: storage.NewStaticIterator[string](batch)}, outChan) - } close(outChan) streams.Stop() }() @@ -400,7 +411,7 @@ func fastPathIntersection(ctx context.Context, streams *iterator.Streams, outCha } if len(iterStreams) != childrenTotal { // short circuit - return + break } maxObject := "" @@ -409,7 +420,7 @@ func fastPathIntersection(ctx context.Context, streams *iterator.Streams, outCha for idx, stream := range iterStreams { v, err := stream.Head(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { allIters = false // we need to ensure we have all iterators at all times break @@ -458,16 +469,16 @@ func fastPathIntersection(ctx context.Context, streams *iterator.Streams, outCha } } } + + if len(batch) > 0 { + concurrency.TrySendThroughChannel(ctx, &iterator.Msg{Iter: storage.NewStaticIterator[string](batch)}, outChan) + } } func fastPathDifference(ctx context.Context, streams *iterator.Streams, outChan chan<- *iterator.Msg) { batch := make([]string, 0) defer func() { - // flush - if len(batch) > 0 { - concurrency.TrySendThroughChannel(ctx, &iterator.Msg{Iter: storage.NewStaticIterator[string](batch)}, outChan) - } close(outChan) streams.Stop() }() @@ -493,7 +504,7 @@ func fastPathDifference(ctx context.Context, streams *iterator.Streams, outChan for idx, stream := range iterStreams { v, err := stream.Head(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { allIters = false // we need to ensure we have all iterators at all times break @@ -577,6 +588,10 @@ func fastPathDifference(ctx context.Context, streams *iterator.Streams, outChan } } } + + if len(batch) > 0 { + concurrency.TrySendThroughChannel(ctx, &iterator.Msg{Iter: storage.NewStaticIterator[string](batch)}, outChan) + } } // fastPathOperationSetup returns a channel with a number of elements that is >= the number of children. diff --git a/vendor/github.com/openfga/openfga/internal/iterator/channel.go b/vendor/github.com/openfga/openfga/internal/iterator/channel.go index 12fff1f54c..481d745f36 100644 --- a/vendor/github.com/openfga/openfga/internal/iterator/channel.go +++ b/vendor/github.com/openfga/openfga/internal/iterator/channel.go @@ -2,6 +2,7 @@ package iterator import ( "context" + "errors" "sync" "github.com/openfga/openfga/internal/concurrency" @@ -63,6 +64,9 @@ func (c *channelIterator) Next(ctx context.Context) (string, error) { return "", ctx.Err() case msg, ok := <-c.source: if !ok { + if ctx.Err() != nil { + return "", ctx.Err() + } return "", storage.ErrIteratorDone } if msg.Err != nil { @@ -78,7 +82,7 @@ func (c *channelIterator) Next(ctx context.Context) (string, error) { // Try to get next from current iterator val, err := c.current.Next(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { c.current.Stop() c.current = nil continue // Fetch next iterator @@ -103,6 +107,9 @@ func (c *channelIterator) Head(ctx context.Context) (string, error) { return "", ctx.Err() case msg, ok := <-c.source: if !ok { + if ctx.Err() != nil { + return "", ctx.Err() + } return "", storage.ErrIteratorDone } if msg.Err != nil { @@ -118,7 +125,7 @@ func (c *channelIterator) Head(ctx context.Context) (string, error) { // Try to get head from current iterator val, err := c.current.Head(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { c.current.Stop() c.current = nil continue // Fetch next iterator diff --git a/vendor/github.com/openfga/openfga/internal/iterator/dedupe.go b/vendor/github.com/openfga/openfga/internal/iterator/dedupe.go new file mode 100644 index 0000000000..fc37b06a5b --- /dev/null +++ b/vendor/github.com/openfga/openfga/internal/iterator/dedupe.go @@ -0,0 +1,66 @@ +package iterator + +import ( + "context" + "sync" + + "github.com/openfga/openfga/pkg/storage" +) + +type dedupe struct { + iter storage.Iterator[string] + mu sync.Mutex + last string // GUARDED_BY(mu) + hasLast bool // GUARDED_BY(mu) +} + +var _ storage.Iterator[string] = (*dedupe)(nil) + +// Dedupe skips repeated values of a sorted iterator. NewFilteredIterator cannot be used: it has no Head, which Stream needs. +func Dedupe(iter storage.Iterator[string]) storage.Iterator[string] { + return &dedupe{iter: iter} +} + +// skipDuplicates returns inner errors as is and never retries, so a failing Head cannot loop. The caller holds mu. +func (d *dedupe) skipDuplicates(ctx context.Context) (string, error) { + for { + head, err := d.iter.Head(ctx) + if err != nil { + return "", err + } + if !d.hasLast || head != d.last { + return head, nil + } + if _, err := d.iter.Next(ctx); err != nil { + return "", err + } + } +} + +// Head see [storage.Iterator.Head]. +func (d *dedupe) Head(ctx context.Context) (string, error) { + d.mu.Lock() + defer d.mu.Unlock() + return d.skipDuplicates(ctx) +} + +// Next see [storage.Iterator.Next]. +func (d *dedupe) Next(ctx context.Context) (string, error) { + d.mu.Lock() + defer d.mu.Unlock() + if _, err := d.skipDuplicates(ctx); err != nil { + return "", err + } + v, err := d.iter.Next(ctx) + if err != nil { + return "", err + } + d.last, d.hasLast = v, true + return v, nil +} + +// Stop see [storage.Iterator.Stop]. +func (d *dedupe) Stop() { d.iter.Stop() } + +// IsOrdered forwards from the inner iterator. +func (d *dedupe) IsOrdered() bool { return d.iter.IsOrdered() } diff --git a/vendor/github.com/openfga/openfga/internal/iterator/filter.go b/vendor/github.com/openfga/openfga/internal/iterator/filter.go index d3019be2f0..6cda41129f 100644 --- a/vendor/github.com/openfga/openfga/internal/iterator/filter.go +++ b/vendor/github.com/openfga/openfga/internal/iterator/filter.go @@ -5,6 +5,7 @@ import ( "errors" "sync" + interrors "github.com/openfga/openfga/internal/errors" "github.com/openfga/openfga/pkg/storage" ) @@ -62,6 +63,10 @@ func (f *filter[T]) Next(ctx context.Context) (T, error) { valid, err := f.applyFilters(entry) if err != nil { + var fatal *interrors.FatalError + if errors.As(err, &fatal) { + return null, err // propagate immediately; keep wrapper so callers can detect it + } f.lastErr = err continue } diff --git a/vendor/github.com/openfga/openfga/internal/iterator/stream.go b/vendor/github.com/openfga/openfga/internal/iterator/stream.go index d2d89fbbb7..086098e9ed 100644 --- a/vendor/github.com/openfga/openfga/internal/iterator/stream.go +++ b/vendor/github.com/openfga/openfga/internal/iterator/stream.go @@ -2,6 +2,7 @@ package iterator import ( "context" + "errors" "fmt" "slices" @@ -28,15 +29,15 @@ func (s *Stream) Idx() int { return s.idx } -// Head returns the first item in the buffer. If the Head is sourceIsClosed or -// cancelled, it will stop the buffer and set the buffer to nil. +// Head returns the first item in the buffer. If the Head is exhausted, it +// stops the buffer and sets the buffer to nil. func (s *Stream) Head(ctx context.Context) (string, error) { if s.buffer == nil { return "", storage.ErrIteratorDone } t, err := s.buffer.Head(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { s.buffer.Stop() s.buffer = nil } @@ -51,7 +52,7 @@ func (s *Stream) Next(ctx context.Context) (string, error) { } t, err := s.buffer.Next(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { s.buffer.Stop() s.buffer = nil } @@ -88,7 +89,7 @@ func (s *Stream) SkipToTargetObject(ctx context.Context, target string) error { for { t, err := s.Head(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { return nil } return err @@ -102,7 +103,7 @@ func (s *Stream) SkipToTargetObject(ctx context.Context, target string) error { // Otherwise advance the iterator _, err = s.Next(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { return nil } return err @@ -116,7 +117,7 @@ func (s *Stream) Drain(ctx context.Context) ([]string, error) { for { t, err := s.Next(ctx) if err != nil { - if storage.IterIsDoneOrCancelled(err) { + if errors.Is(err, storage.ErrIteratorDone) { break } return nil, err @@ -127,6 +128,9 @@ func (s *Stream) Drain(ctx context.Context) ([]string, error) { } func (s *Stream) fetchSource(ctx context.Context) error { + if ctx.Err() != nil { + return ctx.Err() + } if s.buffer != nil || s.sourceIsClosed { // no need to poll further return nil @@ -137,6 +141,9 @@ func (s *Stream) fetchSource(ctx context.Context) error { return ctx.Err() case i, ok := <-s.source: if !ok { + if ctx.Err() != nil { + return ctx.Err() + } s.sourceIsClosed = true break } diff --git a/vendor/github.com/openfga/openfga/internal/planner/interface.go b/vendor/github.com/openfga/openfga/internal/planner/interface.go index 45d8385c39..41451761c6 100644 --- a/vendor/github.com/openfga/openfga/internal/planner/interface.go +++ b/vendor/github.com/openfga/openfga/internal/planner/interface.go @@ -1,5 +1,7 @@ package planner +//go:generate mockgen -package=mocks -destination=../mocks/mock_planner.go github.com/openfga/openfga/internal/planner Manager,Selector + import ( "time" diff --git a/vendor/github.com/openfga/openfga/internal/validation/validation.go b/vendor/github.com/openfga/openfga/internal/validation/validation.go index 2df0a5d7e2..ced1931f81 100644 --- a/vendor/github.com/openfga/openfga/internal/validation/validation.go +++ b/vendor/github.com/openfga/openfga/internal/validation/validation.go @@ -8,6 +8,7 @@ import ( openfgav1 "github.com/openfga/api/proto/openfga/v1" + "github.com/openfga/openfga/internal/condition" "github.com/openfga/openfga/internal/utils" "github.com/openfga/openfga/pkg/storage" "github.com/openfga/openfga/pkg/tuple" @@ -40,7 +41,18 @@ func ValidateTupleForWrite(typesys *typesystem.TypeSystem, tk *openfgav1.TupleKe } // now we assume our tuple is well-formed, it's time to check // the tuple against other model and type-restriction constraints - return ValidateTupleForRead(typesys, tk) + if err := ValidateTupleForRead(typesys, tk); err != nil { + return err + } + // Inline expressions are compiled only on write so that malformed + // expressions are rejected at write time. Read paths skip compilation + // and let any error surface during evaluation. + if condition.IsInlineExpression(tk.GetCondition().GetName()) { + if _, err := condition.FromInlineExpression(tk); err != nil { + return &tuple.InvalidConditionalTupleError{Cause: err, TupleKey: tk} + } + } + return nil } // ValidateTupleForRead returns nil if a tuple is valid according to the provided model. @@ -236,7 +248,13 @@ func validateCondition(typesys *typesystem.TypeSystem, tk *openfgav1.TupleKey) e } } - condition, ok := typesys.GetConditions()[tk.GetCondition().GetName()] + // $expression is a reserved inline condition — validate its context and type restriction + // without looking it up in the model's named conditions map. + if condition.IsInlineExpression(tk.GetCondition().GetName()) { + return validateInlineExpressionCondition(typesys, tk) + } + + namedCondition, ok := typesys.GetConditions()[tk.GetCondition().GetName()] if !ok { return &tuple.InvalidConditionalTupleError{ Cause: fmt.Errorf("undefined condition"), TupleKey: tk, @@ -273,7 +291,7 @@ func validateCondition(typesys *typesystem.TypeSystem, tk *openfgav1.TupleKey) e contextFieldMap := contextStruct.GetFields() - typedParams, err := condition.CastContextToTypedParameters(contextFieldMap) + typedParams, err := namedCondition.CastContextToTypedParameters(contextFieldMap) if err != nil { return &tuple.InvalidConditionalTupleError{ Cause: err, TupleKey: tk, @@ -293,6 +311,70 @@ func validateCondition(typesys *typesystem.TypeSystem, tk *openfgav1.TupleKey) e return nil } +// validateInlineExpressionCondition validates that a $expression tuple is well-formed: +// - the type restriction on the relation includes $expression for the user type +// - the condition context is structurally valid. +func validateInlineExpressionCondition(typesys *typesystem.TypeSystem, tk *openfgav1.TupleKey) error { + cond := tk.GetCondition() + + if cond == nil { + return &tuple.InvalidConditionalTupleError{ + Cause: fmt.Errorf("condition is missing"), TupleKey: tk, + } + } + + if !condition.IsInlineExpression(cond.GetName()) { + return &tuple.InvalidConditionalTupleError{ + Cause: fmt.Errorf("expected $expression got: %s", cond.GetName()), + TupleKey: tk, + } + } + + objectType := tuple.GetType(tk.GetObject()) + userType := tuple.GetType(tk.GetUser()) + userRelation := tuple.GetRelation(tk.GetUser()) + + typeRestrictions, err := typesys.GetDirectlyRelatedUserTypes(objectType, tk.GetRelation()) + if err != nil { + return err + } + + if utils.ContainsForbiddenChars(cond.GetName()) { + return &tuple.InvalidConditionalTupleError{ + Cause: fmt.Errorf("condition name contains forbidden characters"), TupleKey: tk, + } + } + + var validCondition bool + + for _, directlyRelatedType := range typeRestrictions { + if directlyRelatedType.GetType() != userType || directlyRelatedType.GetCondition() != condition.InlineExpressionName { + continue + } + if !restrictionFacetMatches(directlyRelatedType, tk.GetUser(), userRelation) { + continue + } + validCondition = true + break + } + + if !validCondition { + return &tuple.InvalidConditionalTupleError{ + Cause: fmt.Errorf("invalid condition for type restriction"), TupleKey: tk, + } + } + + contextStruct := cond.GetContext() + + if err := ValidateStruct(contextStruct); err != nil { + return &tuple.InvalidConditionalTupleError{ + Cause: err, TupleKey: tk, + } + } + + return nil +} + // FilterInvalidTuples filters out tuples that aren't valid according to the provided model. func FilterInvalidTuples(typesys *typesystem.TypeSystem) storage.TupleKeyFilterFunc { return func(tupleKey *openfgav1.TupleKey) bool { diff --git a/vendor/github.com/openfga/openfga/pkg/logger/logger.go b/vendor/github.com/openfga/openfga/pkg/logger/logger.go index 2c045072b5..43b6eda411 100644 --- a/vendor/github.com/openfga/openfga/pkg/logger/logger.go +++ b/vendor/github.com/openfga/openfga/pkg/logger/logger.go @@ -1,5 +1,7 @@ package logger +//go:generate mockgen -source logger.go -destination ../../internal/mocks/mock_logger.go -package mocks + import ( "context" "fmt" diff --git a/vendor/github.com/openfga/openfga/pkg/server/authorization_models.go b/vendor/github.com/openfga/openfga/pkg/server/authorization_models.go index 856e34853b..310e5c519e 100644 --- a/vendor/github.com/openfga/openfga/pkg/server/authorization_models.go +++ b/vendor/github.com/openfga/openfga/pkg/server/authorization_models.go @@ -2,6 +2,7 @@ package server import ( "context" + "fmt" "net/http" "strconv" @@ -12,11 +13,14 @@ import ( openfgav1 "github.com/openfga/api/proto/openfga/v1" + "github.com/openfga/openfga/internal/condition" "github.com/openfga/openfga/internal/telemetry" "github.com/openfga/openfga/internal/utils/apimethod" httpmiddleware "github.com/openfga/openfga/pkg/middleware/http" "github.com/openfga/openfga/pkg/middleware/validator" "github.com/openfga/openfga/pkg/server/commands" + serverconfig "github.com/openfga/openfga/pkg/server/config" + serverErrors "github.com/openfga/openfga/pkg/server/errors" ) func (s *Server) ReadAuthorizationModel(ctx context.Context, req *openfgav1.ReadAuthorizationModelRequest) (*openfgav1.ReadAuthorizationModelResponse, error) { @@ -68,6 +72,14 @@ func (s *Server) WriteAuthorizationModel(ctx context.Context, req *openfgav1.Wri return nil, err } + if !s.featureFlagClient.Boolean(serverconfig.ExperimentalInlineExpressions, req.GetStoreId()) { + if modelUsesInlineExpressions(req.GetTypeDefinitions()) { + return nil, serverErrors.ValidationError( + fmt.Errorf("$expression requires the %q experimental feature flag", serverconfig.ExperimentalInlineExpressions), + ) + } + } + c := commands.NewWriteAuthorizationModelCommand(s.datastore, commands.WithWriteAuthModelLogger(s.logger), commands.WithWriteAuthModelMaxSizeInBytes(s.maxAuthorizationModelSizeInBytes), @@ -110,3 +122,18 @@ func (s *Server) ReadAuthorizationModels(ctx context.Context, req *openfgav1.Rea ) return c.Execute(ctx, req) } + +// modelUsesInlineExpressions reports whether any relation type restriction in the provided +// type definitions references the $expression reserved condition name. +func modelUsesInlineExpressions(tds []*openfgav1.TypeDefinition) bool { + for _, td := range tds { + for _, relMeta := range td.GetMetadata().GetRelations() { + for _, rr := range relMeta.GetDirectlyRelatedUserTypes() { + if condition.IsInlineExpression(rr.GetCondition()) { + return true + } + } + } + } + return false +} diff --git a/vendor/github.com/openfga/openfga/pkg/server/commands/list_objects.go b/vendor/github.com/openfga/openfga/pkg/server/commands/list_objects.go index b1fecc5c0c..8d711d124f 100644 --- a/vendor/github.com/openfga/openfga/pkg/server/commands/list_objects.go +++ b/vendor/github.com/openfga/openfga/pkg/server/commands/list_objects.go @@ -643,6 +643,9 @@ func (q *ListObjectsQuery) Execute( if err := p.Err(); err != nil { // current list objects behavior is to elide context cancelation errors if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { + if errors.Is(err, condition.ErrEvaluationFailed) { + return nil, serverErrors.ValidationError(err) + } return nil, serverErrors.HandleError("", err) } } diff --git a/vendor/github.com/openfga/openfga/pkg/server/commands/listusers/list_users_rpc.go b/vendor/github.com/openfga/openfga/pkg/server/commands/listusers/list_users_rpc.go index a2ce186b88..bb838ebc6b 100644 --- a/vendor/github.com/openfga/openfga/pkg/server/commands/listusers/list_users_rpc.go +++ b/vendor/github.com/openfga/openfga/pkg/server/commands/listusers/list_users_rpc.go @@ -1,6 +1,7 @@ package listusers import ( + "cmp" "context" "errors" "fmt" @@ -247,7 +248,12 @@ func (l *listUsersQuery) ListUsers( doneWithFoundUsersCh := make(chan struct{}, 1) go func() { for foundUser := range foundUsersCh { - foundUsersUnique[tuple.UserProtoToString(foundUser.user)] = foundUser + // A user may arrive from several sources, and has the relationship if any + // of them grants it. + key := tuple.UserProtoToString(foundUser.user) + if existing, ok := foundUsersUnique[key]; !ok || existing.relationshipStatus == NoRelationship { + foundUsersUnique[key] = foundUser + } if l.maxResults > 0 { if uint32(len(foundUsersUnique)) >= l.maxResults { @@ -283,8 +289,9 @@ func (l *listUsersQuery) ListUsers( select { case err := <-expandErrCh: - if deadlineExceeded || errors.Is(err, context.DeadlineExceeded) { - // We skip the error because we want to send at least partial results to the user (but we should probably set response headers) + if (deadlineExceeded || errors.Is(err, context.DeadlineExceeded)) && isOnlyContextError(err) { + // We skip the error because we want to send at least partial results to the user (but we should probably set response headers). + // Any other error may have truncated an exclusion's subtract operand, so the partial results could over-grant. break } telemetry.TraceError(span, err) @@ -320,6 +327,23 @@ func (l *listUsersQuery) ListUsers( }, nil } +// isOnlyContextError reports whether every error within err, which may join +// several, is a context cancellation or deadline error. +func isOnlyContextError(err error) bool { + switch wrapped := err.(type) { //nolint:errorlint // unwraps each layer itself + case interface{ Unwrap() []error }: + for _, e := range wrapped.Unwrap() { + if !isOnlyContextError(e) { + return false + } + } + return true + case interface{ Unwrap() error }: + return isOnlyContextError(wrapped.Unwrap()) + } + return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) +} + func doesHavePossibleEdges(typesys *typesystem.TypeSystem, req *openfgav1.ListUsersRequest) (bool, error) { g := graph.New(typesys) @@ -470,8 +494,10 @@ func (l *listUsersQuery) expandDirect( }, opts) if err != nil { telemetry.TraceError(span, err) + // Once the context is done, report its error instead: the cancellation may + // have caused this one, and the request then returns partial results. return expandResponse{ - err: err, + err: cmp.Or(ctx.Err(), err), } } defer iter.Stop() @@ -491,16 +517,21 @@ LoopOnIterator: tupleKey, err := filteredIter.Next(ctx) if err != nil { if !errors.Is(err, storage.ErrIteratorDone) { - errs = errors.Join(errs, err) + errs = errors.Join(errs, cmp.Or(ctx.Err(), err)) } break LoopOnIterator } - cond, _ := typesys.GetCondition(tupleKey.GetCondition().GetName()) - condMet, err := eval.EvaluateTupleCondition(ctx, tupleKey, cond, req.Context) + var condMet bool + if condition.IsInlineExpression(tupleKey.GetCondition().GetName()) { + condMet, err = eval.EvaluateInlineExpression(ctx, tupleKey, req.Context) + } else { + cond, _ := typesys.GetCondition(tupleKey.GetCondition().GetName()) + condMet, err = eval.EvaluateTupleCondition(ctx, tupleKey, cond, req.Context) + } if err != nil { - errs = errors.Join(errs, err) + errs = errors.Join(errs, cmp.Or(ctx.Err(), err)) if !errors.Is(err, condition.ErrEvaluationFailed) { break LoopOnIterator } @@ -577,53 +608,37 @@ func (l *listUsersQuery) expandIntersection( intersectionFoundUsersChans[i] = make(chan foundUser, 1) } - var mu sync.Mutex - var wg sync.WaitGroup wg.Add(len(childOperands)) - wildcardCount := atomic.Uint32{} wildcardKey := tuple.TypedPublicWildcard(req.GetUserFilters()[0].GetType()) - foundUsersCountMap := make(map[string]uint32, 0) - excludedUsersMap := make(map[string]struct{}, 0) + // Per operand, the users it grants and the users excluded from each wildcard it + // found. Several sources may feed one operand, so an exclusion from one source + // must not cancel a grant from another. + operandFoundUsers := make([]map[string]struct{}, len(childOperands)) + operandWildcardExclusions := make([][]map[string]struct{}, len(childOperands)) // Consumers must start before the producer pool below: a producer blocks on // its second send into a size-1 channel until drained, so if the bounded // pool fills before consumers run, the submit loop deadlocks. - for _, foundUsersChan := range intersectionFoundUsersChans { - go func(foundUsersChan chan foundUser) { + for i, foundUsersChan := range intersectionFoundUsersChans { + operandFoundUsers[i] = make(map[string]struct{}) + go func(i int, foundUsersChan chan foundUser) { defer wg.Done() - foundUsersMap := make(map[string]uint32, 0) for foundUser := range foundUsersChan { - key := tuple.UserProtoToString(foundUser.user) - for _, excludedUser := range foundUser.excludedUsers { - key := tuple.UserProtoToString(excludedUser) - mu.Lock() - excludedUsersMap[key] = struct{}{} - mu.Unlock() - } if foundUser.relationshipStatus == NoRelationship { continue } - foundUsersMap[key]++ - } - - _, wildcardExists := foundUsersMap[wildcardKey] - if wildcardExists { - wildcardCount.Add(1) - } - for userKey := range foundUsersMap { - mu.Lock() - // Increment the count for a user but decrement if a wildcard - // also exists to prevent double counting. This ensures accurate - // tracking for intersection criteria, avoiding inflated counts - // when both a user and a wildcard are present. - foundUsersCountMap[userKey]++ - if wildcardExists { - foundUsersCountMap[userKey]-- + key := tuple.UserProtoToString(foundUser.user) + operandFoundUsers[i][key] = struct{}{} + if key == wildcardKey { + excluded := make(map[string]struct{}, len(foundUser.excludedUsers)) + for _, excludedUser := range foundUser.excludedUsers { + excluded[tuple.UserProtoToString(excludedUser)] = struct{}{} + } + operandWildcardExclusions[i] = append(operandWildcardExclusions[i], excluded) } - mu.Unlock() } - }(foundUsersChan) + }(i, foundUsersChan) } for i, rewrite := range childOperands { @@ -646,22 +661,52 @@ func (l *listUsersQuery) expandIntersection( wg.Wait() + // An operand grants a user directly or through a wildcard that does not exclude them. + operandGrants := func(i int, key string) bool { + if _, ok := operandFoundUsers[i][key]; ok { + return true + } + for _, excluded := range operandWildcardExclusions[i] { + if _, ok := excluded[key]; !ok { + return true + } + } + return false + } + intersectionGrants := func(key string) bool { + for i := range childOperands { + if !operandGrants(i, key) { + return false + } + } + return true + } + + // Users excluded from some operand's wildcards stay excluded from the + // intersection's wildcard unless every operand grants them. + excludedUsersMap := make(map[string]struct{}, 0) + for _, wildcardExclusions := range operandWildcardExclusions { + for _, excluded := range wildcardExclusions { + for key := range excluded { + excludedUsersMap[key] = struct{}{} + } + } + } excludedUsers := []*openfgav1.User{} for key := range excludedUsersMap { - excludedUsers = append(excludedUsers, tuple.StringToUserProto(key)) + if !intersectionGrants(key) { + excludedUsers = append(excludedUsers, tuple.StringToUserProto(key)) + } } - for key, count := range foundUsersCountMap { - // A user may have already been explicitly excluded by an operand, and cannot satisfy the intersection - // e.g. the banned relation here: `(member but not banned) and active` - if _, excluded := excludedUsersMap[key]; excluded { - continue + candidates := make(map[string]struct{}, 0) + for _, found := range operandFoundUsers { + for key := range found { + candidates[key] = struct{}{} } - // Compare the number of times the specific user was returned for - // all intersection operands plus the number of wildcards. - // If this summed value equals the number of operands, the user satisfies - // the intersection expression and can be sent on `foundUsersChan` - if (count + wildcardCount.Load()) == uint32(len(childOperands)) { + } + for key := range candidates { + if intersectionGrants(key) { fu := foundUser{ user: tuple.StringToUserProto(key), excludedUsers: excludedUsers, @@ -696,8 +741,12 @@ func (l *listUsersQuery) expandUnion( var wg sync.WaitGroup wg.Add(len(childOperands)) + wildcardKey := tuple.TypedPublicWildcard(req.GetUserFilters()[0].GetType()) foundUsersMap := make(map[string]struct{}, 0) - excludedUsersCountMap := make(map[string]uint32, 0) + excludedUsersMap := make(map[string]struct{}, 0) + // The users excluded from each wildcard found, so that a wildcard only re-grants + // the users it does not itself exclude. + wildcardExclusions := []map[string]struct{}{} // Consumers must start before the producer pool below: a producer blocks on // its second send into a size-1 channel until drained, so if the bounded // pool fills before consumers run, the submit loop deadlocks. @@ -707,17 +756,20 @@ func (l *listUsersQuery) expandUnion( for foundUser := range foundUsersChan { key := tuple.UserProtoToString(foundUser.user) + excluded := make(map[string]struct{}, len(foundUser.excludedUsers)) for _, excludedUser := range foundUser.excludedUsers { - key := tuple.UserProtoToString(excludedUser) - mu.Lock() - excludedUsersCountMap[key]++ - mu.Unlock() - } - if foundUser.relationshipStatus == NoRelationship { - continue + excluded[tuple.UserProtoToString(excludedUser)] = struct{}{} } mu.Lock() - foundUsersMap[key] = struct{}{} + for excludedKey := range excluded { + excludedUsersMap[excludedKey] = struct{}{} + } + if foundUser.relationshipStatus == HasRelationship { + foundUsersMap[key] = struct{}{} + if key == wildcardKey { + wildcardExclusions = append(wildcardExclusions, excluded) + } + } mu.Unlock() } }(foundUsersChan) @@ -743,9 +795,19 @@ func (l *listUsersQuery) expandUnion( wg.Wait() + // A user excluded anywhere in the union stays excluded unless the union grants + // them, either directly or through a wildcard that does not exclude them. + // Otherwise a wildcard forwarded by the union would re-grant them. excludedUsers := []*openfgav1.User{} - for key, count := range excludedUsersCountMap { - if count == uint32(len(childOperands)) { + for key := range excludedUsersMap { + _, granted := foundUsersMap[key] + for _, excluded := range wildcardExclusions { + if _, ok := excluded[key]; !ok { + granted = true + break + } + } + if !granted { excludedUsers = append(excludedUsers, tuple.StringToUserProto(key)) } } @@ -790,17 +852,46 @@ func (l *listUsersQuery) expandExclusion( close(subtractFoundUsersCh) }() + wildcardKey := tuple.TypedPublicWildcard(req.GetUserFilters()[0].GetType()) + baseFoundUsersMap := make(map[string]foundUser, 0) + // The base wildcard may arrive from several sources, and it only excludes the + // users that every copy excludes. + var baseWildcardExcluded map[string]struct{} for fu := range baseFoundUsersCh { key := tuple.UserProtoToString(fu.user) - baseFoundUsersMap[key] = fu + // A user may also arrive from several base sources, and has the relationship + // if any of them grants it. + if existing, ok := baseFoundUsersMap[key]; !ok || existing.relationshipStatus == NoRelationship { + baseFoundUsersMap[key] = fu + } + if key == wildcardKey && fu.relationshipStatus == HasRelationship { + baseWildcardExcluded = intersectUserKeys(baseWildcardExcluded, fu.excludedUsers) + } } subtractFoundUsersMap := make(map[string]foundUser, len(baseFoundUsersMap)) + // As with base, the subtracted wildcard only excludes the users that every copy excludes. + var subtractWildcardExcluded map[string]struct{} for fu := range subtractFoundUsersCh { key := tuple.UserProtoToString(fu.user) - subtractFoundUsersMap[key] = fu + // As with base, a subtracted user has the relationship if any source grants it. + if existing, ok := subtractFoundUsersMap[key]; !ok || existing.relationshipStatus == NoRelationship { + subtractFoundUsersMap[key] = fu + } + if key == wildcardKey && fu.relationshipStatus == HasRelationship { + subtractWildcardExcluded = intersectUserKeys(subtractWildcardExcluded, fu.excludedUsers) + } + } + + // A cancelled subtract operand may be missing users, and subtracting an + // incomplete set would grant them. Sends can still succeed after cancellation, + // so emit nothing. + if ctx.Err() != nil { + errs := errors.Join(ctx.Err(), baseError, subtractError) + telemetry.TraceError(span, errs) + return expandResponse{err: errs} } if subtractHasCycle { @@ -814,13 +905,54 @@ func (l *listUsersQuery) expandExclusion( } } - wildcardKey := tuple.TypedPublicWildcard(req.GetUserFilters()[0].GetType()) - _, baseWildcardExists := baseFoundUsersMap[wildcardKey] _, subtractWildcardExists := subtractFoundUsersMap[wildcardKey] + // The users carved out of a base wildcard, attached to the wildcard itself so that + // a union combining it with other sources knows which users it does not grant. + var wildcardExcludedUsers []*openfgav1.User + if baseWildcardExists { + for excludedKey := range baseWildcardExcluded { + if baseFu, ok := baseFoundUsersMap[excludedKey]; ok && baseFu.relationshipStatus == HasRelationship { + continue + } + wildcardExcludedUsers = append(wildcardExcludedUsers, tuple.StringToUserProto(excludedKey)) + } + for subtractedUserKey, subtractedFu := range subtractFoundUsersMap { + if !tuple.IsTypedWildcard(subtractedUserKey) && subtractedFu.relationshipStatus == HasRelationship { + wildcardExcludedUsers = append(wildcardExcludedUsers, tuple.StringToUserProto(subtractedUserKey)) + } + } + } + + // The subtract branch has a user directly or through a wildcard that does not exclude them. + subtractGrants := func(key string) bool { + if subtractedFu, ok := subtractFoundUsersMap[key]; ok && subtractedFu.relationshipStatus == HasRelationship { + return true + } + _, excluded := subtractWildcardExcluded[key] + return subtractWildcardExists && !excluded + } + + if baseWildcardExists && subtractWildcardExists { + // A subtracted wildcard does not take away the users it excludes, so those + // keep the relationship wherever the base grants them. + for excludedKey := range subtractWildcardExcluded { + if subtractGrants(excludedKey) { + continue + } + _, excludedFromBase := baseWildcardExcluded[excludedKey] + if baseFu, ok := baseFoundUsersMap[excludedKey]; !excludedFromBase || (ok && baseFu.relationshipStatus == HasRelationship) { + concurrency.TrySendThroughChannel(ctx, foundUser{ + user: tuple.StringToUserProto(excludedKey), + relationshipStatus: HasRelationship, + }, foundUsersChan) + } + } + } + for userKey, fu := range baseFoundUsersMap { - subtractedUser, userIsSubtracted := subtractFoundUsersMap[userKey] + _, userIsSubtracted := subtractFoundUsersMap[userKey] _, wildcardSubtracted := subtractFoundUsersMap[wildcardKey] switch { @@ -828,10 +960,14 @@ func (l *listUsersQuery) expandExclusion( if !userIsSubtracted && !wildcardSubtracted { // Preserve the relationship status and exclusions the base branch // already determined in case base on its own contains another exclusion. + excludedUsers := fu.excludedUsers + if userKey == wildcardKey { + excludedUsers = wildcardExcludedUsers + } concurrency.TrySendThroughChannel(ctx, foundUser{ user: tuple.StringToUserProto(userKey), relationshipStatus: fu.relationshipStatus, - excludedUsers: fu.excludedUsers, + excludedUsers: excludedUsers, }, foundUsersChan) } @@ -846,11 +982,20 @@ func (l *listUsersQuery) expandExclusion( continue } - if subtractedFu.relationshipStatus == NoRelationship { - concurrency.TrySendThroughChannel(ctx, foundUser{ - user: tuple.StringToUserProto(subtractedUserKey), - relationshipStatus: HasRelationship, - }, foundUsersChan) + // Another subtract source may still grant a user that one source reports + // without the relationship. + if subtractedFu.relationshipStatus == NoRelationship && !subtractGrants(subtractedUserKey) { + // Only surface the subtracted user as having the relationship when the base + // grants them, directly or through a wildcard that does not exclude them. When + // the base is a wildcard carve-out (e.g. `user:* but not member`), re-inflating + // an excluded user here would return a user that Check denies. + _, excludedFromBase := baseWildcardExcluded[subtractedUserKey] + if baseFu, ok := baseFoundUsersMap[subtractedUserKey]; !excludedFromBase || (ok && baseFu.relationshipStatus == HasRelationship) { + concurrency.TrySendThroughChannel(ctx, foundUser{ + user: tuple.StringToUserProto(subtractedUserKey), + relationshipStatus: HasRelationship, + }, foundUsersChan) + } } // a found user under the subtracted branch causes the subtracted user to have a negated relationship with respect @@ -866,14 +1011,12 @@ func (l *listUsersQuery) expandExclusion( } } case subtractWildcardExists, userIsSubtracted: - if subtractedUser.relationshipStatus == HasRelationship { + if subtractGrants(userKey) { concurrency.TrySendThroughChannel(ctx, foundUser{ user: tuple.StringToUserProto(userKey), relationshipStatus: NoRelationship, }, foundUsersChan) - } - - if subtractedUser.relationshipStatus == NoRelationship { + } else if fu.relationshipStatus == HasRelationship { concurrency.TrySendThroughChannel(ctx, foundUser{ user: tuple.StringToUserProto(userKey), relationshipStatus: HasRelationship, @@ -897,6 +1040,21 @@ func (l *listUsersQuery) expandExclusion( } } +// intersectUserKeys narrows common to the keys of users that it also holds. A nil common +// map means nothing has been intersected yet, so every user is kept. It is used to narrow +// the users excluded from a wildcard, which may arrive from several sources, to those +// that every copy excludes. +func intersectUserKeys(common map[string]struct{}, users []*openfgav1.User) map[string]struct{} { + narrowed := make(map[string]struct{}, len(users)) + for _, user := range users { + key := tuple.UserProtoToString(user) + if _, ok := common[key]; ok || common == nil { + narrowed[key] = struct{}{} + } + } + return narrowed +} + func (l *listUsersQuery) expandTTU( ctx context.Context, req *internalListUsersRequest, @@ -921,8 +1079,10 @@ func (l *listUsersQuery) expandTTU( }, opts) if err != nil { telemetry.TraceError(span, err) + // Once the context is done, report its error instead: the cancellation may + // have caused this one, and the request then returns partial results. return expandResponse{ - err: err, + err: cmp.Or(ctx.Err(), err), } } defer iter.Stop() @@ -942,16 +1102,21 @@ LoopOnIterator: tupleKey, err := filteredIter.Next(ctx) if err != nil { if !errors.Is(err, storage.ErrIteratorDone) { - errs = errors.Join(errs, err) + errs = errors.Join(errs, cmp.Or(ctx.Err(), err)) } break LoopOnIterator } - cond, _ := typesys.GetCondition(tupleKey.GetCondition().GetName()) - condMet, err := eval.EvaluateTupleCondition(ctx, tupleKey, cond, req.Context) + var condMet bool + if condition.IsInlineExpression(tupleKey.GetCondition().GetName()) { + condMet, err = eval.EvaluateInlineExpression(ctx, tupleKey, req.Context) + } else { + cond, _ := typesys.GetCondition(tupleKey.GetCondition().GetName()) + condMet, err = eval.EvaluateTupleCondition(ctx, tupleKey, cond, req.Context) + } if err != nil { - errs = errors.Join(errs, err) + errs = errors.Join(errs, cmp.Or(ctx.Err(), err)) if !errors.Is(err, condition.ErrEvaluationFailed) { break LoopOnIterator } diff --git a/vendor/github.com/openfga/openfga/pkg/server/commands/reverseexpand/reverse_expand.go b/vendor/github.com/openfga/openfga/pkg/server/commands/reverseexpand/reverse_expand.go index 0f66d62fef..9a9ef8008f 100644 --- a/vendor/github.com/openfga/openfga/pkg/server/commands/reverseexpand/reverse_expand.go +++ b/vendor/github.com/openfga/openfga/pkg/server/commands/reverseexpand/reverse_expand.go @@ -18,6 +18,7 @@ import ( weightedGraph "github.com/openfga/language/pkg/go/graph" "github.com/openfga/openfga/internal/concurrency" + "github.com/openfga/openfga/internal/condition" "github.com/openfga/openfga/internal/condition/eval" "github.com/openfga/openfga/internal/graph" "github.com/openfga/openfga/internal/stack" @@ -643,8 +644,13 @@ LoopOnIterator: break LoopOnIterator } - cond, _ := c.typesystem.GetCondition(tk.GetCondition().GetName()) - condMet, err := eval.EvaluateTupleCondition(ctx, tk, cond, req.Context) + var condMet bool + if condition.IsInlineExpression(tk.GetCondition().GetName()) { + condMet, err = eval.EvaluateInlineExpression(ctx, tk, req.Context) + } else { + cond, _ := c.typesystem.GetCondition(tk.GetCondition().GetName()) + condMet, err = eval.EvaluateTupleCondition(ctx, tk, cond, req.Context) + } if err != nil { errs = errors.Join(errs, err) continue diff --git a/vendor/github.com/openfga/openfga/pkg/server/config/config.go b/vendor/github.com/openfga/openfga/pkg/server/config/config.go index 2f6e328c26..ba3cf9e613 100644 --- a/vendor/github.com/openfga/openfga/pkg/server/config/config.go +++ b/vendor/github.com/openfga/openfga/pkg/server/config/config.go @@ -121,6 +121,7 @@ const ( ExperimentalShadowWeightedGraphCheck = "shadow_weighted_graph_check" ExperimentalWeightedGraphCheck = "weighted_graph_check" ExperimentalAuthZen = "authzen" + ExperimentalInlineExpressions = "inline_expressions" ) type DatastoreMetricsConfig struct { diff --git a/vendor/github.com/openfga/openfga/pkg/server/server.go b/vendor/github.com/openfga/openfga/pkg/server/server.go index 47580b6118..47d010d3c8 100644 --- a/vendor/github.com/openfga/openfga/pkg/server/server.go +++ b/vendor/github.com/openfga/openfga/pkg/server/server.go @@ -647,9 +647,14 @@ func WithPlanner(planner *planner.Planner) OpenFGAServiceV1Option { } } +// WithRequestTimeout tells the server's internals, such as the Check planner, the timeout applied to every +// request. Values <= 0 are ignored, leaving the current value (by default [serverconfig.DefaultRequestTimeout]) unchanged. +// This does not enforce the timeout; callers must do so themselves. func WithRequestTimeout(timeout time.Duration) OpenFGAServiceV1Option { return func(s *Server) { - s.requestTimeout = timeout + if timeout > 0 { + s.requestTimeout = timeout + } } } diff --git a/vendor/github.com/openfga/openfga/pkg/server/write.go b/vendor/github.com/openfga/openfga/pkg/server/write.go index 9982069984..43d74f32f8 100644 --- a/vendor/github.com/openfga/openfga/pkg/server/write.go +++ b/vendor/github.com/openfga/openfga/pkg/server/write.go @@ -2,6 +2,7 @@ package server import ( "context" + "fmt" "strconv" "time" @@ -12,11 +13,14 @@ import ( openfgav1 "github.com/openfga/api/proto/openfga/v1" + "github.com/openfga/openfga/internal/condition" "github.com/openfga/openfga/internal/telemetry" "github.com/openfga/openfga/internal/utils/apimethod" "github.com/openfga/openfga/pkg/authclaims" "github.com/openfga/openfga/pkg/middleware/validator" "github.com/openfga/openfga/pkg/server/commands" + serverconfig "github.com/openfga/openfga/pkg/server/config" + serverErrors "github.com/openfga/openfga/pkg/server/errors" ) func (s *Server) Write(ctx context.Context, req *openfgav1.WriteRequest) (*openfgav1.WriteResponse, error) { @@ -51,6 +55,16 @@ func (s *Server) Write(ctx context.Context, req *openfgav1.WriteRequest) (*openf return nil, err } + if !s.featureFlagClient.Boolean(serverconfig.ExperimentalInlineExpressions, storeID) { + for _, tk := range req.GetWrites().GetTupleKeys() { + if condition.IsInlineExpression(tk.GetCondition().GetName()) { + return nil, serverErrors.ValidationError( + fmt.Errorf("$expression requires the %q experimental feature flag", serverconfig.ExperimentalInlineExpressions), + ) + } + } + } + cmd := commands.NewWriteCommand( s.datastore, commands.WithWriteCmdLogger(s.logger), diff --git a/vendor/github.com/openfga/openfga/pkg/storage/adapter/ast/ast.go b/vendor/github.com/openfga/openfga/pkg/storage/adapter/ast/ast.go new file mode 100644 index 0000000000..04624339c0 --- /dev/null +++ b/vendor/github.com/openfga/openfga/pkg/storage/adapter/ast/ast.go @@ -0,0 +1,496 @@ +// Package ast holds a SELECT query as plain Go structs with no SQL text. Package query builds it; +// each backend renders it. +package ast + +import "strconv" + +// Node is any node in the tree. Walkers should accept the narrowest of the four slot interfaces. +type Node interface { + isNode() + + // Validate returns the first structural problem in the node or its children. It does not + // check alias scope, driver value types, or GROUP BY coverage. + Validate() error +} + +// Projection is a node allowed in the SELECT list. +// +// Unlike the enums, node types have no Count value, so backends should panic on unknown types. +type Projection interface { + Node + isProjection() +} + +// ScalarValue is a node that is a single value. +type ScalarValue interface { + Projection + isScalarValue() +} + +// SetValue is a node that is a group of values; only valid as QuantifiedNode.Set. +type SetValue interface { + Node + isSetValue() +} + +// Predicate is a true/false test. It is deliberately not a value, since some databases have no +// boolean type; use a CASE for a boolean result column. +type Predicate interface { + Node + isPredicate() +} + +// --- enums the same on every SQL database ----------------------------------------------- + +// Op is a comparison operator. +type Op int + +const ( + OpEq Op = iota + OpNe + OpLt + OpLte + OpGt + OpGte +) + +// LogicalOp is AND or OR. +type LogicalOp int + +const ( + And LogicalOp = iota + Or +) + +// Quantifier is ANY or ALL. +type Quantifier int + +const ( + Any Quantifier = iota + All +) + +// JoinType omits RIGHT and FULL OUTER, which MySQL and older SQLite lack. +type JoinType int + +const ( + JoinInner JoinType = iota + JoinLeftOuter + JoinCross +) + +// SortDirection is the direction of an ORDER BY term. +type SortDirection int + +const ( + Ascending SortDirection = iota + Descending +) + +// --- enums that differ between databases (each backend supplies the spelling) ---------- + +// Column is a logical column of the tuple table. +type Column uint8 + +const ( + ColObjectType Column = iota + ColObjectID + ColObjectRelation + + ColSubjectType + ColSubjectID + // ColSubjectRelation is e.g., `member` in `group:eng#member`. + ColSubjectRelation + + ColStore + + ColCondition + ColConditionContext + + // ColCount is not a column - it's the number of columns, so backends can ensure full coverage. + ColCount +) + +// String is for error messages only. +func (c Column) String() string { + switch c { + case ColObjectType: + return "ObjectType" + case ColObjectID: + return "ObjectID" + case ColObjectRelation: + return "ObjectRelation" + case ColSubjectType: + return "SubjectType" + case ColSubjectID: + return "SubjectID" + case ColSubjectRelation: + return "SubjectRelation" + case ColStore: + return "Store" + case ColCondition: + return "Condition" + case ColConditionContext: + return "ConditionContext" + default: + return "Column(" + strconv.Itoa(int(c)) + ")" + } +} + +// SubjectKinds is a set of subject kinds; it is a userset when +// (SubjectRelation != "" || SubjectID = "*"), else a user (see tuple.GetUserTypeFromUser). +type SubjectKinds uint8 + +const ( + KindUser SubjectKinds = 1 << iota + KindUserset + + // KindAll is not a kind - it's every kind, so backends can ensure full coverage. + KindAll = KindUser | KindUserset +) + +// CastType is the target type of a CAST. It has no boolean member and no length/precision. +type CastType uint8 + +const ( + TypeVarchar CastType = iota + TypeInteger + TypeBigint + TypeNumeric + TypeVarbinary + + // TypeCount is not a cast type - it's the number of types, so backends can ensure full coverage. + TypeCount +) + +// String is for error messages only. +func (t CastType) String() string { + switch t { + case TypeVarchar: + return "Varchar" + case TypeInteger: + return "Integer" + case TypeBigint: + return "Bigint" + case TypeNumeric: + return "Numeric" + case TypeVarbinary: + return "Varbinary" + default: + return "CastType(" + strconv.Itoa(int(t)) + ")" + } +} + +// ScalarFunc is a scalar function. +type ScalarFunc uint8 + +const ( + // FuncCoalesce takes one or more arguments. + FuncCoalesce ScalarFunc = iota + // FuncLower and FuncUpper take exactly one. + FuncLower + FuncUpper + // FuncJSONArray takes zero or more. + FuncJSONArray + + // FuncCount is not a scalar function - it's the number of functions, so backends can ensure full coverage. + FuncCount +) + +// String is for error messages only. +func (f ScalarFunc) String() string { + switch f { + case FuncCoalesce: + return "Coalesce" + case FuncLower: + return "Lower" + case FuncUpper: + return "Upper" + case FuncJSONArray: + return "JSONArray" + default: + return "ScalarFunc(" + strconv.Itoa(int(f)) + ")" + } +} + +// AggFunc is an aggregate function. Only aggregates every supported database has are included. +type AggFunc uint8 + +const ( + // AggCount takes zero arguments (COUNT(*)) or one. + AggCount AggFunc = iota + + // AggCount_ is not an aggregate function - it's the number of functions, so backends can ensure full coverage. + AggCount_ +) + +// String is for error messages only. +func (a AggFunc) String() string { + switch a { + case AggCount: + return "Count" + default: + return "AggFunc(" + strconv.Itoa(int(a)) + ")" + } +} + +// --- leaf nodes ------------------------------------------------------------------------- + +// ColNode is a column of the table with the given alias. +type ColNode struct { + Alias string + Name Column +} + +// BindNode is a value sent as a parameter. Value is passed to the driver as-is, so unsupported +// types fail only at execution. Positional parameters must be numbered in SQL output order. +type BindNode struct{ Value any } + +// LitNode is a value inlined into the SQL text. The backend escapes it, or may bind it instead. +// Switch on reflect.Kind, not Go type: a named string type misses "case string" and may be inlined unquoted. +type LitNode struct{ Value any } + +// SetBindNode is a list of values sent as a parameter. Elems may be empty. +type SetBindNode struct{ Elems []any } + +// --- predicate nodes -------------------------------------------------------------------- + +// CompareNode is "Left Op Right". +type CompareNode struct { + Op Op + Left, Right ScalarValue +} + +// LikeNode is "Left LIKE Pattern", case-sensitive, with only % and _ special (no backslash escape). +// LIKE differs on databases; backends must add what's needed (e.g., Postgres ESCAPE), or return an error. +type LikeNode struct { + Left, Pattern ScalarValue +} + +// BetweenNode is "Inner BETWEEN Lo AND Hi". +type BetweenNode struct { + Inner, Lo, Hi ScalarValue +} + +// IsNullNode is "Inner IS NULL". +type IsNullNode struct{ Inner ScalarValue } + +// InNode is "Left IN (Elems...)". Elems must be non-empty. +type InNode struct { + Left ScalarValue + Elems []ScalarValue +} + +// QuantifiedNode is "Left Op ANY|ALL (Set)". An empty SetBindNode should render as a constant +// (ANY -> false, ALL -> true). +type QuantifiedNode struct { + Left ScalarValue + Op Op + Q Quantifier + Set SetValue +} + +// ExistsNode is "EXISTS (Stmt)". +type ExistsNode struct{ Stmt *Select } + +// LogicalNode is an AND or OR of Parts. Parts must be non-empty. +type LogicalNode struct { + Op LogicalOp + Parts []Predicate +} + +// NotNode negates Inner. +type NotNode struct{ Inner Predicate } + +// ConstPredNode is a constant true or false. +type ConstPredNode struct{ Value bool } + +// SubjectKindNode is true when the subject of the table with the given alias is one of Kinds. +// Empty Kinds is always false. +type SubjectKindNode struct { + Alias string + Kinds SubjectKinds +} + +// --- value nodes ------------------------------------------------------------------------ + +// CastNode casts Inner to Type. +type CastNode struct { + Inner ScalarValue + Type CastType +} + +// FuncNode is a scalar function call. +type FuncNode struct { + Fn ScalarFunc + Args []ScalarValue +} + +// JSONPairNode is one key/value pair of a JSONObjectNode. +type JSONPairNode struct { + Key, Value ScalarValue +} + +// JSONObjectNode builds a JSON object. Pairs must be non-empty. +type JSONObjectNode struct{ Pairs []JSONPairNode } + +// AggNode is an aggregate call. Filter is optional. A backend emulating Filter must map skipped +// rows to NULL so they are not counted. +type AggNode struct { + Fn AggFunc + Args []ScalarValue + Distinct bool + Filter Predicate +} + +// CaseSearchedNode is "CASE WHEN cond THEN ... [ELSE ...] END". Branches must be non-empty. +type CaseSearchedNode struct { + Branches []SearchedBranch + Else ScalarValue +} + +// SearchedBranch is one WHEN/THEN of a CaseSearchedNode. +type SearchedBranch struct { + When Predicate + Then ScalarValue +} + +// CaseSimpleNode is "CASE Base WHEN value THEN ... [ELSE ...] END". Branches must be non-empty. +type CaseSimpleNode struct { + Base ScalarValue + Branches []SimpleBranch + Else ScalarValue +} + +// SimpleBranch is one WHEN/THEN of a CaseSimpleNode. +type SimpleBranch struct { + When ScalarValue + Then ScalarValue +} + +// AliasNode names a result column. +type AliasNode struct { + Inner Projection + Alias string +} + +// SubqueryNode is a parenthesized subquery, usable as a value, a set, or a result column. +type SubqueryNode struct{ Stmt *Select } + +// --- statement -------------------------------------------------------------------------- + +// Select is a SELECT statement. Empty From means no table; empty Columns means all columns. +type Select struct { + Distinct bool + Columns []Projection + From []Table + Joins []JoinClause + Where Predicate + GroupBy []ScalarValue + Having Predicate + OrderBy []OrderTerm + Limit *uint64 + Offset *uint64 +} + +// Table is the tuple table under an alias. +type Table struct{ Alias string } + +// JoinClause is a join. On must be nil for JoinCross and non-nil otherwise. +type JoinClause struct { + Type JoinType + Table Table + On Predicate +} + +// OrderTerm is one ORDER BY term. +type OrderTerm struct { + Expr ScalarValue + Dir SortDirection +} + +// --- slot membership -------------------------------------------------------------------- + +func (CompareNode) isNode() {} +func (CompareNode) isPredicate() {} + +func (LikeNode) isNode() {} +func (LikeNode) isPredicate() {} + +func (BetweenNode) isNode() {} +func (BetweenNode) isPredicate() {} + +func (IsNullNode) isNode() {} +func (IsNullNode) isPredicate() {} + +func (InNode) isNode() {} +func (InNode) isPredicate() {} + +func (QuantifiedNode) isNode() {} +func (QuantifiedNode) isPredicate() {} + +func (ExistsNode) isNode() {} +func (ExistsNode) isPredicate() {} + +func (LogicalNode) isNode() {} +func (LogicalNode) isPredicate() {} + +func (NotNode) isNode() {} +func (NotNode) isPredicate() {} + +func (ConstPredNode) isNode() {} +func (ConstPredNode) isPredicate() {} + +func (SubjectKindNode) isNode() {} +func (SubjectKindNode) isPredicate() {} + +func (ColNode) isNode() {} +func (ColNode) isProjection() {} +func (ColNode) isScalarValue() {} + +func (BindNode) isNode() {} +func (BindNode) isProjection() {} +func (BindNode) isScalarValue() {} + +func (LitNode) isNode() {} +func (LitNode) isProjection() {} +func (LitNode) isScalarValue() {} + +func (CastNode) isNode() {} +func (CastNode) isProjection() {} +func (CastNode) isScalarValue() {} + +func (FuncNode) isNode() {} +func (FuncNode) isProjection() {} +func (FuncNode) isScalarValue() {} + +func (JSONObjectNode) isNode() {} +func (JSONObjectNode) isProjection() {} +func (JSONObjectNode) isScalarValue() {} + +func (CaseSearchedNode) isNode() {} +func (CaseSearchedNode) isProjection() {} +func (CaseSearchedNode) isScalarValue() {} + +func (CaseSimpleNode) isNode() {} +func (CaseSimpleNode) isProjection() {} +func (CaseSimpleNode) isScalarValue() {} + +func (AggNode) isNode() {} +func (AggNode) isProjection() {} +func (AggNode) isScalarValue() {} + +func (SetBindNode) isNode() {} +func (SetBindNode) isSetValue() {} + +func (SubqueryNode) isNode() {} +func (SubqueryNode) isProjection() {} +func (SubqueryNode) isScalarValue() {} +func (SubqueryNode) isSetValue() {} + +func (AliasNode) isNode() {} +func (AliasNode) isProjection() {} + +func (JSONPairNode) isNode() {} + +func (*Select) isNode() {} diff --git a/vendor/github.com/openfga/openfga/pkg/storage/adapter/ast/validate.go b/vendor/github.com/openfga/openfga/pkg/storage/adapter/ast/validate.go new file mode 100644 index 0000000000..882a95d659 --- /dev/null +++ b/vendor/github.com/openfga/openfga/pkg/storage/adapter/ast/validate.go @@ -0,0 +1,431 @@ +package ast + +import ( + "errors" + "fmt" + "reflect" + "strconv" +) + +var ( + ErrMissing = errors.New("required field is nil") + ErrArity = errors.New("wrong number of elements") + ErrEnum = errors.New("enum value out of range") + ErrCrossField = errors.New("invalid combination of fields") + ErrValue = errors.New("invalid value") + ErrAlias = errors.New("invalid alias") +) + +// --- helpers ---------------------------------------------------------------------------- + +// validator is used instead of Node so the helpers also accept clause items like OrderTerm. +type validator interface{ Validate() error } + +type enum interface{ ~int | ~uint8 } + +// at prefixes err with field, building the error path. +func at(field string, err error) error { + if err == nil { + return nil + } + return fmt.Errorf("%s: %w", field, err) +} + +// isNil also treats a typed nil pointer as nil, since calling a value-receiver Validate on it panics. +func isNil[T validator](x T) bool { + if any(x) == nil { + return true + } + v := reflect.ValueOf(any(x)) + return v.Kind() == reflect.Pointer && v.IsNil() +} + +func required[T validator](field string, x T) error { + if isNil(x) { + return fmt.Errorf("%s: %w", field, ErrMissing) + } + return at(field, x.Validate()) +} + +func optional[T validator](field string, x T) error { + if isNil(x) { + return nil + } + return at(field, x.Validate()) +} + +func stmt(field string, s *Select) error { + if s == nil { + return fmt.Errorf("%s: %w", field, ErrMissing) + } + return at(field, s.Validate()) +} + +func each[T validator](field string, xs []T) error { + for i, x := range xs { + if err := required(field+"["+strconv.Itoa(i)+"]", x); err != nil { + return err + } + } + return nil +} + +// fault exists so messages can start with a capitalized field name without tripping lint. +func fault(field string, sentinel error, msg string) error { + return fmt.Errorf("%s: %w: %s", field, sentinel, msg) +} + +func nonEmpty[T any](field string, xs []T) error { + if len(xs) == 0 { + return fmt.Errorf("%s: %w: empty, need at least one element", field, ErrArity) + } + return nil +} + +func arity(field string, have, lo, hi int) error { + if have < lo || have > hi { + if lo == hi { + return fmt.Errorf("%s: %w: have %d, need exactly %d", field, ErrArity, have, lo) + } + return fmt.Errorf("%s: %w: have %d, need %d to %d", field, ErrArity, have, lo, hi) + } + return nil +} + +func inRange[T enum](field string, v, lo, hi T) error { + if v < lo || v > hi { + return fmt.Errorf("%s: %w: %v", field, ErrEnum, v) + } + return nil +} + +func alias(s string) error { + if s == "" { + return fault("Alias", ErrAlias, "empty") + } + return nil +} + +// value checks Kind rather than type so named bools are rejected too. +func value(field string, v any) error { + if v == nil { + return nil // NULL + } + if _, ok := v.(Node); ok { + return fmt.Errorf("%s: %w: %T is an AST node, not a value", field, ErrValue, v) + } + if reflect.ValueOf(v).Kind() == reflect.Bool { + return fmt.Errorf("%s: %w: %T is a bool; truth values are the Predicate category, and a "+ + "constant one is ConstPredNode", field, ErrValue, v) + } + return nil +} + +// --- leaf nodes ------------------------------------------------------------------------- + +func (n ColNode) Validate() error { + if err := alias(n.Alias); err != nil { + return err + } + return inRange("Name", n.Name, ColObjectType, ColCount-1) +} + +func (n BindNode) Validate() error { return value("Value", n.Value) } + +func (n LitNode) Validate() error { return value("Value", n.Value) } + +func (n SetBindNode) Validate() error { + for i, e := range n.Elems { + if err := value("Elems["+strconv.Itoa(i)+"]", e); err != nil { + return err + } + } + return nil +} + +// --- predicate nodes -------------------------------------------------------------------- + +func (n CompareNode) Validate() error { + if err := inRange("Op", n.Op, OpEq, OpGte); err != nil { + return err + } + if err := required("Left", n.Left); err != nil { + return err + } + return required("Right", n.Right) +} + +func (n LikeNode) Validate() error { + if err := required("Left", n.Left); err != nil { + return err + } + return required("Pattern", n.Pattern) +} + +func (n BetweenNode) Validate() error { + if err := required("Inner", n.Inner); err != nil { + return err + } + if err := required("Lo", n.Lo); err != nil { + return err + } + return required("Hi", n.Hi) +} + +func (n IsNullNode) Validate() error { return required("Inner", n.Inner) } + +func (n InNode) Validate() error { + if err := nonEmpty("Elems", n.Elems); err != nil { + return err + } + if err := required("Left", n.Left); err != nil { + return err + } + return each("Elems", n.Elems) +} + +func (n QuantifiedNode) Validate() error { + if err := inRange("Op", n.Op, OpEq, OpGte); err != nil { + return err + } + if err := inRange("Q", n.Q, Any, All); err != nil { + return err + } + if err := required("Left", n.Left); err != nil { + return err + } + return required("Set", n.Set) +} + +func (n ExistsNode) Validate() error { return stmt("Stmt", n.Stmt) } + +func (n LogicalNode) Validate() error { + if err := inRange("Op", n.Op, And, Or); err != nil { + return err + } + if err := nonEmpty("Parts", n.Parts); err != nil { + return err + } + return each("Parts", n.Parts) +} + +func (n NotNode) Validate() error { return required("Inner", n.Inner) } + +func (ConstPredNode) Validate() error { return nil } + +func (n SubjectKindNode) Validate() error { + if err := alias(n.Alias); err != nil { + return err + } + if n.Kinds&^KindAll != 0 { + return fmt.Errorf("%s: %w: %#b", "Kinds", ErrEnum, n.Kinds) + } + return nil +} + +// --- value nodes ------------------------------------------------------------------------ + +func (n CastNode) Validate() error { + if err := inRange("Type", n.Type, TypeVarchar, TypeCount-1); err != nil { + return err + } + return required("Inner", n.Inner) +} + +// Validate checks Fn before arity, since arity depends on Fn. +func (n FuncNode) Validate() error { + if err := inRange("Fn", n.Fn, FuncCoalesce, FuncCount-1); err != nil { + return err + } + if err := n.argArity(); err != nil { + return err + } + return each("Args", n.Args) +} + +func (n FuncNode) argArity() error { + switch n.Fn { + case FuncCoalesce: + return nonEmpty("Args", n.Args) + case FuncLower, FuncUpper: + return arity("Args", len(n.Args), 1, 1) + case FuncJSONArray: + return nil + default: + return nil + } +} + +func (n JSONPairNode) Validate() error { + if err := required("Key", n.Key); err != nil { + return err + } + return required("Value", n.Value) +} + +func (n JSONObjectNode) Validate() error { + if err := nonEmpty("Pairs", n.Pairs); err != nil { + return err + } + return each("Pairs", n.Pairs) +} + +func (n AggNode) Validate() error { + if err := inRange("Fn", n.Fn, AggCount, AggCount_-1); err != nil { + return err + } + if err := n.argArity(); err != nil { + return err + } + if err := each("Args", n.Args); err != nil { + return err + } + return optional("Filter", n.Filter) +} + +func (n AggNode) argArity() error { + switch n.Fn { + case AggCount: + if err := arity("Args", len(n.Args), 0, 1); err != nil { + return err + } + if n.Distinct && len(n.Args) == 0 { + return fault("Distinct", ErrCrossField, + "COUNT(DISTINCT *) is not a construct; Distinct needs an argument") + } + return nil + default: + return nil + } +} + +func (n CaseSearchedNode) Validate() error { + if err := nonEmpty("Branches", n.Branches); err != nil { + return err + } + if err := each("Branches", n.Branches); err != nil { + return err + } + return optional("Else", n.Else) +} + +func (b SearchedBranch) Validate() error { + if err := required("When", b.When); err != nil { + return err + } + return required("Then", b.Then) +} + +func (n CaseSimpleNode) Validate() error { + if err := nonEmpty("Branches", n.Branches); err != nil { + return err + } + if err := required("Base", n.Base); err != nil { + return err + } + if err := each("Branches", n.Branches); err != nil { + return err + } + return optional("Else", n.Else) +} + +func (b SimpleBranch) Validate() error { + if err := required("When", b.When); err != nil { + return err + } + return required("Then", b.Then) +} + +func (n AliasNode) Validate() error { + if err := alias(n.Alias); err != nil { + return err + } + return required("Inner", n.Inner) +} + +func (n SubqueryNode) Validate() error { return stmt("Stmt", n.Stmt) } + +// --- statement and clause items --------------------------------------------------------- + +func (s *Select) Validate() error { + if s == nil { + return ErrMissing + } + if err := s.aliasErr(); err != nil { + return err + } + for _, check := range []func() error{ + func() error { return each("Columns", s.Columns) }, + func() error { return each("From", s.From) }, + func() error { return each("Joins", s.Joins) }, + func() error { return optional("Where", s.Where) }, + func() error { return each("GroupBy", s.GroupBy) }, + func() error { return optional("Having", s.Having) }, + func() error { return each("OrderBy", s.OrderBy) }, + } { + if err := check(); err != nil { + return err + } + } + return nil +} + +// aliasErr reports a table alias used twice. Empty aliases are left to Table.Validate. +func (s *Select) aliasErr() error { + seen := make(map[string]struct{}, len(s.From)+len(s.Joins)) + for _, a := range s.aliases() { + if a == "" { + continue + } + if _, dup := seen[a]; dup { + return fmt.Errorf("%w: table alias %q is used twice, which makes a column naming it "+ + "ambiguous", ErrCrossField, a) + } + seen[a] = struct{}{} + } + return nil +} + +func (s *Select) aliases() []string { + out := make([]string, 0, len(s.From)+len(s.Joins)) + for _, t := range s.From { + out = append(out, t.Alias) + } + for _, j := range s.Joins { + out = append(out, j.Table.Alias) + } + return out +} + +func (t Table) Validate() error { return alias(t.Alias) } + +func (j JoinClause) Validate() error { + if err := inRange("Type", j.Type, JoinInner, JoinCross); err != nil { + return err + } + if err := j.onErr(); err != nil { + return err + } + if err := at("Table", j.Table.Validate()); err != nil { + return err + } + return optional("On", j.On) +} + +func (j JoinClause) onErr() error { + switch cross := j.Type == JoinCross; { + case cross && !isNil(j.On): + return fault("On", ErrCrossField, "a cross join carries no condition") + case !cross && isNil(j.On): + return fault("On", ErrMissing, "only a cross join may omit it") + default: + return nil + } +} + +func (t OrderTerm) Validate() error { + if err := inRange("Dir", t.Dir, Ascending, Descending); err != nil { + return err + } + return required("Expr", t.Expr) +} diff --git a/vendor/github.com/openfga/openfga/pkg/storage/adapter/querier.go b/vendor/github.com/openfga/openfga/pkg/storage/adapter/querier.go new file mode 100644 index 0000000000..566aad9bb4 --- /dev/null +++ b/vendor/github.com/openfga/openfga/pkg/storage/adapter/querier.go @@ -0,0 +1,26 @@ +// Package adapter defines how datastores execute query.Statement values. +package adapter + +import ( + "context" + + "github.com/openfga/openfga/pkg/storage/adapter/query" +) + +// Querier executes a query.Statement. Implementations must support every statement, so Execute +// never returns an "unsupported" error. +type Querier interface { + Execute(ctx context.Context, stmt *query.Statement) (Rows, error) +} + +// Rows is a driver-agnostic result cursor mirroring *sql.Rows. +type Rows interface { + // Next returns false when rows are exhausted or on error; check Err. + Next() bool + // Scan copies the current row's columns into dest. + Scan(dest ...any) error + // Close releases the cursor's resources. + Close() error + // Err returns the error, if any, that stopped iteration. + Err() error +} diff --git a/vendor/github.com/openfga/openfga/pkg/storage/adapter/query/query.go b/vendor/github.com/openfga/openfga/pkg/storage/adapter/query/query.go new file mode 100644 index 0000000000..40c90f2f4b --- /dev/null +++ b/vendor/github.com/openfga/openfga/pkg/storage/adapter/query/query.go @@ -0,0 +1,530 @@ +// Package query is a type-safe builder for package ast. It does not produce SQL text. +package query + +import ( + "time" + + "github.com/openfga/openfga/pkg/storage/adapter/ast" +) + +// --- typed value wrappers --------------------------------------------------------------- + +// Expr is a SQL value of Go type T. +type Expr[T Scalar] struct{ n ast.ScalarValue } + +// Predicate is a true/false expression. It is not an Expr[bool] because some databases have no +// boolean type, so it cannot be a value or result column. +type Predicate struct{ n ast.Predicate } + +// BoundSet is a list of T values sent as one parameter, for use with Quantified. +type BoundSet[T Scalar] struct{ n ast.SetValue } + +// SetExpr is a multi-row subquery of T values. +type SetExpr[T Scalar] struct { + n interface { + ast.SetValue + ast.Projection + } +} + +// AnyExpr is an Expr of any T. +type AnyExpr interface { + value() ast.ScalarValue +} + +// AnySet is a BoundSet or SetExpr. Elem is never called; it only ties the set to T. +type AnySet[T Scalar] interface { + set() ast.SetValue + elem() T +} + +// Projection is anything that can go in a SELECT list. +type Projection interface { + projection() ast.Projection +} + +// Aliased is a named result column. +type Aliased struct{ n ast.Projection } + +func (e Expr[T]) value() ast.ScalarValue { return e.n } +func (e Expr[T]) projection() ast.Projection { return e.n } +func (e Expr[T]) countArg() []ast.ScalarValue { return []ast.ScalarValue{e.n} } +func (s BoundSet[T]) set() ast.SetValue { return s.n } +func (s BoundSet[T]) elem() (_ T) { return } +func (s SetExpr[T]) set() ast.SetValue { return s.n } +func (s SetExpr[T]) elem() (_ T) { return } +func (s SetExpr[T]) projection() ast.Projection { return s.n } +func (a Aliased) projection() ast.Projection { return a.n } + +// As names a result column. +func As(p Projection, alias string) Aliased { + return Aliased{n: ast.AliasNode{Inner: p.projection(), Alias: alias}} +} + +// --- constraints ------------------------------------------------------------------------ + +type ordinal interface { + ~string | ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64 +} + +type Ordered interface { + ordinal | time.Time +} + +// Literal excludes time.Time, whose literal syntax differs by database. +type Literal interface { + ordinal +} + +// Scalar follows database/sql/driver.Value, minus bool (use Predicate). Time.Time has no ~ +// because drivers reject named struct types. +type Scalar interface { + Ordered | ~[]byte +} + +// Comparable is Scalar without []byte. +type Comparable interface { + Scalar + comparable +} + +// --- re-exported enums ------------------------------------------------------------------ + +type ( + Op = ast.Op + Quantifier = ast.Quantifier + JoinType = ast.JoinType + SortDirection = ast.SortDirection + CastType = ast.CastType + SubjectKinds = ast.SubjectKinds +) + +const ( + OpEq = ast.OpEq + OpNe = ast.OpNe + OpLt = ast.OpLt + OpLte = ast.OpLte + OpGt = ast.OpGt + OpGte = ast.OpGte + + Any = ast.Any + All = ast.All + + JoinInner = ast.JoinInner + JoinLeftOuter = ast.JoinLeftOuter + JoinCross = ast.JoinCross + + Ascending = ast.Ascending + Descending = ast.Descending + + TypeVarchar = ast.TypeVarchar + TypeInteger = ast.TypeInteger + TypeBigint = ast.TypeBigint + TypeNumeric = ast.TypeNumeric + TypeVarbinary = ast.TypeVarbinary + + KindUser = ast.KindUser + KindUserset = ast.KindUserset + KindAll = ast.KindAll +) + +// --- leaves ----------------------------------------------------------------------------- + +// Bind sends v as a parameter. +func Bind[T Scalar](v T) Expr[T] { return Expr[T]{n: ast.BindNode{Value: v}} } + +// Lit inlines v into the SQL text. +func Lit[T Literal](v T) Expr[T] { return Expr[T]{n: ast.LitNode{Value: v}} } + +// BindAll sends vs as one list parameter. +func BindAll[T Scalar](vs []T) BoundSet[T] { + elems := make([]any, len(vs)) + for i, v := range vs { + elems[i] = v + } + return BoundSet[T]{n: ast.SetBindNode{Elems: elems}} +} + +func True() Predicate { return Predicate{n: ast.ConstPredNode{Value: true}} } +func False() Predicate { return Predicate{n: ast.ConstPredNode{Value: false}} } + +// --- comparison operators ------------------------------------------------------------- + +func Eq[T Comparable](a, b Expr[T]) Predicate { return compare(ast.OpEq, a, b) } +func Ne[T Comparable](a, b Expr[T]) Predicate { return compare(ast.OpNe, a, b) } +func Lt[T Ordered](a, b Expr[T]) Predicate { return compare(ast.OpLt, a, b) } +func Lte[T Ordered](a, b Expr[T]) Predicate { return compare(ast.OpLte, a, b) } +func Gt[T Ordered](a, b Expr[T]) Predicate { return compare(ast.OpGt, a, b) } +func Gte[T Ordered](a, b Expr[T]) Predicate { return compare(ast.OpGte, a, b) } +func Compare[T Ordered](op Op, a, b Expr[T]) Predicate { + return compare(op, a, b) +} + +func compare[T Scalar](op Op, a, b Expr[T]) Predicate { + return Predicate{n: ast.CompareNode{Op: op, Left: a.n, Right: b.n}} +} + +// Like is "a LIKE pattern". For case-insensitive matching, wrap both sides in Lower. +func Like(a, pattern Expr[string]) Predicate { + return Predicate{n: ast.LikeNode{Left: a.n, Pattern: pattern.n}} +} + +// Between is "a BETWEEN lo AND hi". +func Between[T Ordered](a, lo, hi Expr[T]) Predicate { + return Predicate{n: ast.BetweenNode{Inner: a.n, Lo: lo.n, Hi: hi.n}} +} + +// IsNull is "a IS NULL". +func IsNull[T Scalar](a Expr[T]) Predicate { + return Predicate{n: ast.IsNullNode{Inner: a.n}} +} + +// In is "a IN (vs...)". For a list parameter or subquery, use Quantified. +func In[T Comparable](a Expr[T], vs ...Expr[T]) Predicate { + elems := make([]ast.ScalarValue, len(vs)) + for i, v := range vs { + elems[i] = v.n + } + return Predicate{n: ast.InNode{Left: a.n, Elems: elems}} +} + +// Quantified is "a op ANY (set)" or "a op ALL (set)". +func Quantified[T Comparable](a Expr[T], op Op, q Quantifier, set AnySet[T]) Predicate { + return Predicate{n: ast.QuantifiedNode{Left: a.n, Op: op, Q: q, Set: set.set()}} +} + +// Exists is "EXISTS (stmt)". +func Exists(s *Statement) Predicate { + return Predicate{n: ast.ExistsNode{Stmt: &s.Select}} +} + +// --- logical connectives ---------------------------------------------------------------- + +// And and Or require at least one predicate; a single predicate is returned as-is. +func And(p Predicate, ps ...Predicate) Predicate { return combine(ast.And, p, ps) } +func Or(p Predicate, ps ...Predicate) Predicate { return combine(ast.Or, p, ps) } +func Not(p Predicate) Predicate { return Predicate{n: ast.NotNode{Inner: p.n}} } + +func combine(op ast.LogicalOp, first Predicate, rest []Predicate) Predicate { + if len(rest) == 0 { + return first + } + parts := make([]ast.Predicate, 0, len(rest)+1) + parts = append(parts, first.n) + for _, p := range rest { + parts = append(parts, p.n) + } + return Predicate{n: ast.LogicalNode{Op: op, Parts: parts}} +} + +// --- ordering --------------------------------------------------------------------------- + +// OrderTerm is one ORDER BY term. +type OrderTerm struct{ t ast.OrderTerm } + +func Order(e AnyExpr, dir SortDirection) OrderTerm { + return OrderTerm{t: ast.OrderTerm{Expr: e.value(), Dir: dir}} +} + +func Asc(e AnyExpr) OrderTerm { return Order(e, ast.Ascending) } +func Desc(e AnyExpr) OrderTerm { return Order(e, ast.Descending) } + +// --- scalar functions ------------------------------------------------------------------- + +func Coalesce[T Scalar](es ...Expr[T]) Expr[T] { + return Expr[T]{n: ast.FuncNode{Fn: ast.FuncCoalesce, Args: nodes(es)}} +} + +func Lower(e Expr[string]) Expr[string] { + return Expr[string]{n: ast.FuncNode{Fn: ast.FuncLower, Args: []ast.ScalarValue{e.n}}} +} + +func Upper(e Expr[string]) Expr[string] { + return Expr[string]{n: ast.FuncNode{Fn: ast.FuncUpper, Args: []ast.ScalarValue{e.n}}} +} + +// JSONPair is one key/value pair for JSONObject. +type JSONPair struct{ n ast.JSONPairNode } + +func Pair[T Scalar](key Expr[string], value Expr[T]) JSONPair { + return JSONPair{n: ast.JSONPairNode{Key: key.n, Value: value.n}} +} + +func JSONObject(pairs ...JSONPair) Expr[[]byte] { + ps := make([]ast.JSONPairNode, len(pairs)) + for i, p := range pairs { + ps[i] = p.n + } + return Expr[[]byte]{n: ast.JSONObjectNode{Pairs: ps}} +} + +func JSONArray(es ...AnyExpr) Expr[[]byte] { + return Expr[[]byte]{n: ast.FuncNode{Fn: ast.FuncJSONArray, Args: anyNodes(es)}} +} + +// --- aggregates ------------------------------------------------------------------------- + +// AggOption is AggDistinct or AggFilter. +type AggOption struct{ apply func(*aggMods) } + +type aggMods struct { + distinct bool + filter ast.Predicate +} + +// AggDistinct makes Count(x, AggDistinct) COUNT(DISTINCT x). +var AggDistinct = AggOption{apply: func(m *aggMods) { m.distinct = true }} + +// AggFilter is FILTER (WHERE cond). +func AggFilter(cond Predicate) AggOption { + return AggOption{apply: func(m *aggMods) { m.filter = cond.n }} +} + +func mods(opts []AggOption) aggMods { + var m aggMods + for _, o := range opts { + // zero-value AggOption + if o.apply != nil { + o.apply(&m) + } + } + return m +} + +// CountArg is any Expr, or Star. +type CountArg interface{ countArg() []ast.ScalarValue } + +type starArg struct{} + +func (starArg) countArg() []ast.ScalarValue { return nil } + +// Star makes Count(Star) COUNT(*). +var Star starArg + +func Count(e CountArg, opts ...AggOption) Expr[int64] { + m := mods(opts) + return Expr[int64]{n: ast.AggNode{ + Fn: ast.AggCount, + Args: e.countArg(), + Distinct: m.distinct, + Filter: m.filter, + }} +} + +// --- CASE ------------------------------------------------------------------------------- + +// CaseSearched builds "CASE WHEN cond THEN ... END". Start one with [Case]: +// +// query.Case[string](). +// When(query.Eq(t.ObjectType(), query.Lit("folder")), t.ObjectID()). +// Else(query.Lit("")). +// End() +type CaseSearched[T Scalar] struct{ n ast.CaseSearchedNode } + +func Case[T Scalar]() *CaseSearched[T] { return &CaseSearched[T]{} } + +func (c *CaseSearched[T]) When(cond Predicate, then Expr[T]) *CaseSearched[T] { + c.n.Branches = append(c.n.Branches, ast.SearchedBranch{When: cond.n, Then: then.n}) + return c +} + +// Else replaces any earlier Else. +func (c *CaseSearched[T]) Else(result Expr[T]) *CaseSearched[T] { + c.n.Else = result.n + return c +} + +// End panics if there are no branches. +func (c *CaseSearched[T]) End() Expr[T] { + if len(c.n.Branches) == 0 { + panic("query: CASE with no WHEN branches") + } + return Expr[T]{n: c.n} +} + +// CaseSimple builds "CASE base WHEN value THEN ... END". Start one with [CaseOf]: +// +// query.CaseOf[int64](t.ObjectType()). +// When(query.Lit("folder"), query.Lit[int64](1)). +// Else(query.Lit[int64](0)). +// End() +type CaseSimple[T Scalar, B Comparable] struct{ n ast.CaseSimpleNode } + +func CaseOf[T Scalar, B Comparable](base Expr[B]) *CaseSimple[T, B] { + return &CaseSimple[T, B]{n: ast.CaseSimpleNode{Base: base.n}} +} + +func (c *CaseSimple[T, B]) When(value Expr[B], then Expr[T]) *CaseSimple[T, B] { + c.n.Branches = append(c.n.Branches, ast.SimpleBranch{When: value.n, Then: then.n}) + return c +} + +// Else replaces any earlier Else. +func (c *CaseSimple[T, B]) Else(result Expr[T]) *CaseSimple[T, B] { + c.n.Else = result.n + return c +} + +// End panics if there are no branches. +func (c *CaseSimple[T, B]) End() Expr[T] { + if len(c.n.Branches) == 0 { + panic("query: CASE with no WHEN branches") + } + return Expr[T]{n: c.n} +} + +// --- tuple + typed columns -------------------------------------------------------------- + +// Tuple is the tuple table under an alias. Its methods return columns qualified by that alias. +type Tuple struct{ t ast.Table } + +func NewTuple(alias string) Tuple { return Tuple{t: ast.Table{Alias: alias}} } + +func (t Tuple) col(name ast.Column) ast.ScalarValue { + return ast.ColNode{Alias: t.t.Alias, Name: name} +} + +func (t Tuple) str(name ast.Column) Expr[string] { return Expr[string]{n: t.col(name)} } + +func (t Tuple) ObjectType() Expr[string] { return t.str(ast.ColObjectType) } +func (t Tuple) ObjectID() Expr[string] { return t.str(ast.ColObjectID) } + +func (t Tuple) ObjectRelation() Expr[string] { return t.str(ast.ColObjectRelation) } + +func (t Tuple) SubjectType() Expr[string] { return t.str(ast.ColSubjectType) } +func (t Tuple) SubjectID() Expr[string] { return t.str(ast.ColSubjectID) } + +// SubjectRelation is e.g. `member` in `group:eng#member`. It is also empty for wildcards like +// `user:*`, so empty does not imply a non-userset subject. +func (t Tuple) SubjectRelation() Expr[string] { return t.str(ast.ColSubjectRelation) } + +// SubjectKindIn is true when the subject is one of kinds. +func (t Tuple) SubjectKindIn(kinds SubjectKinds) Predicate { + return Predicate{n: ast.SubjectKindNode{Alias: t.t.Alias, Kinds: kinds}} +} + +func (t Tuple) Store() Expr[string] { return t.str(ast.ColStore) } + +func (t Tuple) Condition() Expr[string] { return t.str(ast.ColCondition) } + +// ConditionContext is a proto-encoded structpb.Struct. +func (t Tuple) ConditionContext() Expr[[]byte] { + return Expr[[]byte]{n: t.col(ast.ColConditionContext)} +} + +// --- SELECT builder --------------------------------------------------------------------- + +// Statement builds an ast.Select. Where, Having, Limit, and Offset replace earlier values; other +// methods append. +type Statement struct{ ast.Select } + +func Select(cols ...Projection) *Statement { + s := &Statement{} + return s.Columns(cols...) +} + +func (s *Statement) Columns(cols ...Projection) *Statement { + for _, c := range cols { + s.Select.Columns = append(s.Select.Columns, c.projection()) + } + return s +} + +func (s *Statement) Distinct() *Statement { + s.Select.Distinct = true + return s +} + +func (s *Statement) From(ts ...Tuple) *Statement { + for _, t := range ts { + s.Select.From = append(s.Select.From, t.t) + } + return s +} + +func (s *Statement) Join(t Tuple, on Predicate) *Statement { + return s.JoinOn(ast.JoinInner, t, on) +} + +func (s *Statement) JoinOn(jt JoinType, t Tuple, on Predicate) *Statement { + s.Joins = append(s.Joins, ast.JoinClause{Type: jt, Table: t.t, On: on.n}) + return s +} + +func (s *Statement) CrossJoin(t Tuple) *Statement { + s.Joins = append(s.Joins, ast.JoinClause{Type: ast.JoinCross, Table: t.t}) + return s +} + +func (s *Statement) Where(p Predicate) *Statement { + s.Select.Where = p.n + return s +} + +func (s *Statement) GroupBy(es ...AnyExpr) *Statement { + s.Select.GroupBy = append(s.Select.GroupBy, anyNodes(es)...) + return s +} + +func (s *Statement) Having(p Predicate) *Statement { + s.Select.Having = p.n + return s +} + +func (s *Statement) OrderBy(terms ...OrderTerm) *Statement { + s.Select.OrderBy = append(s.Select.OrderBy, orderTerms(terms)...) + return s +} + +func (s *Statement) Limit(n uint64) *Statement { + s.Select.Limit = &n + return s +} + +func (s *Statement) Offset(n uint64) *Statement { + s.Select.Offset = &n + return s +} + +// --- casts and subqueries --------------------------------------------------------------- + +func Cast[To Scalar](e AnyExpr, t CastType) Expr[To] { + return Expr[To]{n: ast.CastNode{Inner: e.value(), Type: t}} +} + +// ScalarExpr uses a single-value subquery as an Expr. +func ScalarExpr[T Scalar](s *Statement) Expr[T] { + return Expr[T]{n: ast.SubqueryNode{Stmt: &s.Select}} +} + +// SetSubExpr uses a multi-row subquery as a SetExpr. +func SetSubExpr[T Scalar](s *Statement) SetExpr[T] { + return SetExpr[T]{n: ast.SubqueryNode{Stmt: &s.Select}} +} + +// --- node plumbing ---------------------------------------------------------------------- + +func nodes[T Scalar](es []Expr[T]) []ast.ScalarValue { + out := make([]ast.ScalarValue, len(es)) + for i, e := range es { + out[i] = e.n + } + return out +} + +func anyNodes(es []AnyExpr) []ast.ScalarValue { + out := make([]ast.ScalarValue, len(es)) + for i, e := range es { + out[i] = e.value() + } + return out +} + +func orderTerms(ts []OrderTerm) []ast.OrderTerm { + out := make([]ast.OrderTerm, len(ts)) + for i, t := range ts { + out[i] = t.t + } + return out +} diff --git a/vendor/github.com/openfga/openfga/pkg/storage/postgres/postgres.go b/vendor/github.com/openfga/openfga/pkg/storage/postgres/postgres.go index 932818a247..da4fd617ed 100644 --- a/vendor/github.com/openfga/openfga/pkg/storage/postgres/postgres.go +++ b/vendor/github.com/openfga/openfga/pkg/storage/postgres/postgres.go @@ -34,6 +34,7 @@ import ( "github.com/openfga/openfga/pkg/logger" "github.com/openfga/openfga/pkg/storage" + "github.com/openfga/openfga/pkg/storage/adapter" "github.com/openfga/openfga/pkg/storage/sqlcommon" tupleUtils "github.com/openfga/openfga/pkg/tuple" ) @@ -317,6 +318,11 @@ func (s *Datastore) Close() { } } +// Querier see [storage.RelationshipTupleReader].Querier. +func (s *Datastore) Querier(_ openfgav1.ConsistencyPreference) adapter.Querier { + return nil +} + // getPgxPool returns the pgxpool.Pool based on consistency options. func (s *Datastore) getPgxPool(consistency openfgav1.ConsistencyPreference) *pgxpool.Pool { if consistency == openfgav1.ConsistencyPreference_HIGHER_CONSISTENCY { @@ -665,7 +671,7 @@ func (s *Datastore) ReadUserTuple(ctx context.Context, store string, filter stor Select( "object_type", "object_id", "relation", "_user", - "condition_name", "condition_context", + "condition_name", "condition_context", "inserted_at", ). From("tuple"). Where(sq.Eq{ @@ -694,6 +700,7 @@ func (s *Datastore) ReadUserTuple(ctx context.Context, store string, filter stor &record.User, &conditionName, &conditionContext, + &record.InsertedAt, ) if err != nil { @@ -934,11 +941,7 @@ func (s *Datastore) FindLatestAuthorizationModel(ctx context.Context, store stri defer span.End() db := s.getPgxPool(openfgav1.ConsistencyPreference_MINIMIZE_LATENCY) - stmt, args, err := sq.StatementBuilder.PlaceholderFormat(sq.Dollar). - Select("authorization_model_id", "schema_version", "type", "type_definition", "serialized_protobuf"). - From("authorization_model"). - Where(sq.Eq{"store": store}). - OrderBy("authorization_model_id desc").ToSql() + stmt, args, err := findLatestAuthorizationModelQuery(store) if err != nil { return nil, HandleSQLError(err) } @@ -955,6 +958,18 @@ func (s *Datastore) FindLatestAuthorizationModel(ctx context.Context, store stri return ret, nil } +// findLatestAuthorizationModelQuery reads only the rows of the store's latest model instead of its +// whole model history. A legacy model can span several rows with the same ID, so this filters on +// the ID rather than using LIMIT 1. +func findLatestAuthorizationModelQuery(store string) (string, []interface{}, error) { + return sq.StatementBuilder.PlaceholderFormat(sq.Dollar). + Select("authorization_model_id", "schema_version", "type", "type_definition", "serialized_protobuf"). + From("authorization_model"). + Where(sq.Eq{"store": store}). + Where(sq.Expr("authorization_model_id = (SELECT MAX(authorization_model_id) FROM authorization_model WHERE store = ?)", store)). + OrderBy("authorization_model_id desc").ToSql() +} + // MaxTypesPerAuthorizationModel see [storage.TypeDefinitionWriteBackend].MaxTypesPerAuthorizationModel. func (s *Datastore) MaxTypesPerAuthorizationModel() int { return s.maxTypesPerModelField diff --git a/vendor/github.com/openfga/openfga/pkg/storage/sqlcommon/sqlcommon.go b/vendor/github.com/openfga/openfga/pkg/storage/sqlcommon/sqlcommon.go index c52086fab5..7dbf8c2e45 100644 --- a/vendor/github.com/openfga/openfga/pkg/storage/sqlcommon/sqlcommon.go +++ b/vendor/github.com/openfga/openfga/pkg/storage/sqlcommon/sqlcommon.go @@ -1239,56 +1239,6 @@ func ConstructAuthorizationModelFromSQLRows(rows Rows) (*openfgav1.Authorization }, nil } -// FindLatestAuthorizationModel reads the latest authorization model corresponding to the store. -func FindLatestAuthorizationModel( - ctx context.Context, - dbInfo *DBInfo, - store string, -) (*openfgav1.AuthorizationModel, error) { - rows, err := dbInfo.stbl. - Select("authorization_model_id", "schema_version", "type", "type_definition", "serialized_protobuf"). - From("authorization_model"). - Where(sq.Eq{"store": store}). - OrderBy("authorization_model_id desc"). - QueryContext(ctx) - if err != nil { - return nil, dbInfo.HandleSQLError(err) - } - defer rows.Close() - ret, err := ConstructAuthorizationModelFromSQLRows(rows) - if err != nil { - return nil, dbInfo.HandleSQLError(err) - } - - return ret, nil -} - -// ReadAuthorizationModel reads the model corresponding to store and model ID. -func ReadAuthorizationModel( - ctx context.Context, - dbInfo *DBInfo, - store, modelID string, -) (*openfgav1.AuthorizationModel, error) { - rows, err := dbInfo.stbl. - Select("authorization_model_id", "schema_version", "type", "type_definition", "serialized_protobuf"). - From("authorization_model"). - Where(sq.Eq{ - "store": store, - "authorization_model_id": modelID, - }). - QueryContext(ctx) - if err != nil { - return nil, dbInfo.HandleSQLError(err) - } - defer rows.Close() - ret, err := ConstructAuthorizationModelFromSQLRows(rows) - if err != nil { - return nil, dbInfo.HandleSQLError(err) - } - - return ret, nil -} - // IsVersionReady checks if the database schema revision is at least the minimum supported revision. // The passed in context should have a timeout. func IsVersionReady(ctx context.Context, skipVersionCheck bool, db *sql.DB) (storage.ReadinessStatus, error) { diff --git a/vendor/github.com/openfga/openfga/pkg/storage/storage.go b/vendor/github.com/openfga/openfga/pkg/storage/storage.go index 2261de100f..c23addb052 100644 --- a/vendor/github.com/openfga/openfga/pkg/storage/storage.go +++ b/vendor/github.com/openfga/openfga/pkg/storage/storage.go @@ -1,10 +1,14 @@ package storage +//go:generate mockgen -source storage.go -destination ../../internal/mocks/mock_storage.go -package mocks OpenFGADatastore + import ( "context" "time" openfgav1 "github.com/openfga/api/proto/openfga/v1" + + "github.com/openfga/openfga/pkg/storage/adapter" ) type ctxKey string @@ -131,7 +135,9 @@ type ReadUsersetTuplesOptions struct { // ReadStartingWithUserOptions represents the options that can // be used with the ReadStartingWithUser method. type ReadStartingWithUserOptions struct { - Consistency ConsistencyOptions + Consistency ConsistencyOptions + // WithResultsSortedAscending orders the results by object ID. The same object can appear more than once, e.g. for a + // user and for the public wildcard, so callers that need unique objects must deduplicate after filtering. WithResultsSortedAscending bool } @@ -150,6 +156,11 @@ type TupleBackend interface { // RelationshipTupleReader is an interface that defines the set of // methods required to read relationship tuples from a data store. type RelationshipTupleReader interface { + // Querier returns an adapter.Querier bound to this backend for executing typed query.Statement + // values at the given consistency, or nil if the backend does not support the typed-AST query + // surface. A non-nil Querier must support the full surface. + Querier(consistency openfgav1.ConsistencyPreference) adapter.Querier + // Read the set of tuples associated with `store` and `tupleKey`, which may be nil or partially filled. If nil, // Read will return an iterator over all the tuples in the given `store`. If the `tupleKey` is partially filled, // it will return an iterator over those tuples which match the `tupleKey`. Note that at least one of `Object` diff --git a/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/bounded_datastore.go b/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/bounded_datastore.go index 8d8296ada0..fbcf056ce4 100644 --- a/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/bounded_datastore.go +++ b/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/bounded_datastore.go @@ -2,6 +2,7 @@ package storagewrappers import ( "context" + "sync" "sync/atomic" "time" @@ -14,6 +15,8 @@ import ( "github.com/openfga/openfga/internal/build" "github.com/openfga/openfga/pkg/storage" + "github.com/openfga/openfga/pkg/storage/adapter" + "github.com/openfga/openfga/pkg/storage/adapter/query" ) const timeWaitingAttribute = "datastore_time_waiting" @@ -47,6 +50,7 @@ var ( _ storage.RelationshipTupleReader = (*BoundedTupleReader)(nil) _ StorageInstrumentation = (*BoundedTupleReader)(nil) _ storage.TupleIterator = (*countingTupleIterator)(nil) + _ adapter.Rows = (*boundedRows)(nil) concurrentReadDelayMsHistogram = promauto.NewHistogramVec(prometheus.HistogramOpts{ Namespace: build.ProjectName, @@ -69,6 +73,47 @@ var ( }, []string{"operation", "method"}) ) +type boundedQuerier struct { + *BoundedTupleReader + adapter.Querier +} + +// Execute holds the concurrency slot until the returned Rows are drained or closed, since they +// retain the connection. +func (q *boundedQuerier) Execute(ctx context.Context, stmt *query.Statement) (adapter.Rows, error) { + if err := q.bound(ctx, "Querier"); err != nil { + return nil, err + } + rows, err := q.Querier.Execute(ctx, stmt) + if err != nil { + q.done() + return nil, err + } + return &boundedRows{Rows: rows, release: q.done, counter: &q.countItems}, nil +} + +type boundedRows struct { + adapter.Rows + release func() + once sync.Once + counter *atomic.Uint64 +} + +func (r *boundedRows) Next() bool { + ok := r.Rows.Next() + if !ok { + r.once.Do(r.release) + return false + } + r.counter.Add(1) + return true +} + +func (r *boundedRows) Close() error { + defer r.once.Do(r.release) + return r.Rows.Close() +} + type BoundedTupleReader struct { storage.RelationshipTupleReader limiter chan struct{} // bound concurrency @@ -83,8 +128,9 @@ type BoundedTupleReader struct { } // NewBoundedTupleReader returns a wrapper over a datastore that makes sure that there are, at most, -// "concurrency" concurrent calls to Read, ReadUserTuple and ReadUsersetTuples. +// op.Concurrency concurrent calls to Read, ReadUserTuple, ReadUsersetTuples, and Querier.Execute. // Consumers can then rest assured that one client will not hoard all the database connections available. +// If op.ThrottlingEnabled, calls beyond op.ThrottleThreshold additionally incur op.ThrottleDuration of latency. func NewBoundedTupleReader(wrapped storage.RelationshipTupleReader, op *Operation) *BoundedTupleReader { return &BoundedTupleReader{ RelationshipTupleReader: wrapped, @@ -106,6 +152,15 @@ func (b *BoundedTupleReader) GetMetadata() Metadata { } } +// Querier returns a concurrency-bounded Querier, or nil if the delegate's is nil. +func (b *BoundedTupleReader) Querier(consistency openfgav1.ConsistencyPreference) adapter.Querier { + inner := b.RelationshipTupleReader.Querier(consistency) + if inner == nil { + return nil + } + return &boundedQuerier{b, inner} +} + // ReadUserTuple tries to return one tuple that matches the provided key exactly. func (b *BoundedTupleReader) ReadUserTuple( ctx context.Context, diff --git a/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/cached_reader.go b/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/cached_reader.go index 7831f2c5c1..3506e10da5 100644 --- a/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/cached_reader.go +++ b/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/cached_reader.go @@ -13,6 +13,7 @@ import ( openfgav1 "github.com/openfga/api/proto/openfga/v1" "github.com/openfga/openfga/pkg/storage" + "github.com/openfga/openfga/pkg/storage/adapter" "github.com/openfga/openfga/pkg/storage/cache/keys" "github.com/openfga/openfga/pkg/tuple" ) @@ -90,6 +91,11 @@ func NewCachedTupleReader( return c } +// Querier see [storage.RelationshipTupleReader].Querier. +func (c *CachedTupleReader) Querier(consistency openfgav1.ConsistencyPreference) adapter.Querier { + return c.delegate.Querier(consistency) +} + // ReadUsersetTuples reads userset tuples with caching. func (c *CachedTupleReader) ReadUsersetTuples( ctx context.Context, diff --git a/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/combinedtuplereader.go b/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/combinedtuplereader.go index 667102bbc6..387aacc96a 100644 --- a/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/combinedtuplereader.go +++ b/vendor/github.com/openfga/openfga/pkg/storage/storagewrappers/combinedtuplereader.go @@ -8,6 +8,7 @@ import ( openfgav1 "github.com/openfga/api/proto/openfga/v1" "github.com/openfga/openfga/pkg/storage" + "github.com/openfga/openfga/pkg/storage/adapter" "github.com/openfga/openfga/pkg/tuple" ) @@ -42,6 +43,11 @@ type CombinedTupleReader struct { var _ storage.RelationshipTupleReader = (*CombinedTupleReader)(nil) +// Querier returns nil because the delegate's Querier would ignore contextual tuples. +func (c *CombinedTupleReader) Querier(openfgav1.ConsistencyPreference) adapter.Querier { + return nil +} + // filterTuples filters out the tuples in the provided slice by removing any tuples in the slice // that don't match the object, relation or user provided in the filterKey. // @@ -187,8 +193,26 @@ func (c *CombinedTupleReader) ReadStartingWithUser( } if options.WithResultsSortedAscending { + // A contextual tuple shadows a stored one for the same object and user, as ReadUserTuple does. Wildcards are not shadowed, + // and a user's and the wildcard's tuples must both be returned: each one's condition decides, and the caller evaluates it. + if len(filteredTuples) > 0 { // most requests have no contextual tuples: avoid the allocation + type objectUser struct{ object, user string } + shadowed := make(map[objectUser]struct{}, len(filteredTuples)) + for _, t := range filteredTuples { + if !tuple.IsTypedWildcard(t.GetKey().GetUser()) { + shadowed[objectUser{t.GetKey().GetObject(), t.GetKey().GetUser()}] = struct{}{} + } + } + if len(shadowed) > 0 { + iter2 = storage.NewKeepTupleIterator(iter2, func(t *openfgav1.Tuple) bool { + _, ok := shadowed[objectUser{t.GetKey().GetObject(), t.GetKey().GetUser()}] + return !ok + }) + } + } + // Note that both iter1 and iter2 return sorted by object ID - return storage.NewOrderedCombinedIterator(storage.ObjectMapper(), iter1, iter2), nil + return storage.NewOrderedMergeIterator(storage.ObjectMapper(), iter1, iter2), nil } return storage.NewCombinedIterator(iter1, iter2), nil diff --git a/vendor/github.com/openfga/openfga/pkg/storage/tuple_iterators.go b/vendor/github.com/openfga/openfga/pkg/storage/tuple_iterators.go index c70436ed0c..9478822b41 100644 --- a/vendor/github.com/openfga/openfga/pkg/storage/tuple_iterators.go +++ b/vendor/github.com/openfga/openfga/pkg/storage/tuple_iterators.go @@ -1,5 +1,7 @@ package storage +//go:generate mockgen -source tuple_iterators.go -destination ../../internal/mocks/mock_iterator.go -package mocks + import ( "context" "errors" @@ -8,6 +10,8 @@ import ( "sync" openfgav1 "github.com/openfga/api/proto/openfga/v1" + + interrors "github.com/openfga/openfga/internal/errors" ) var ErrIteratorDone = errors.New("iterator done") @@ -358,6 +362,10 @@ func (f *ConditionsFilteredTupleKeyIterator) Next(ctx context.Context) (*openfga valid, err := f.filter(tuple) if err != nil { + var fatal *interrors.FatalError + if errors.As(err, &fatal) { + return nil, err // propagate immediately; keep wrapper intact + } f.lastError = err continue } @@ -397,6 +405,10 @@ func (f *ConditionsFilteredTupleKeyIterator) Head(ctx context.Context) (*openfga valid, err := f.filter(tuple) if err != nil || !valid { if err != nil { + var fatal *interrors.FatalError + if errors.As(err, &fatal) { + return nil, err // propagate immediately; keep wrapper intact + } f.lastError = err } // Note that we don't care about the item returned by Next() as this is already via Head(). We call Next() solely @@ -429,6 +441,7 @@ func NewConditionsFilteredTupleKeyIterator(iter TupleKeyIterator, filter TupleKe } } +// OrderedCombinedIterator merges ordered iterators. Whether equal values are dropped depends on the constructor. type OrderedCombinedIterator struct { mu *sync.Mutex once *sync.Once @@ -437,6 +450,7 @@ type OrderedCombinedIterator struct { lastHead *openfgav1.Tuple // GUARDED_BY(mu) lastYielded *openfgav1.Tuple // GUARDED_BY(mu) ordered bool + dedupe bool } var _ TupleIterator = (*OrderedCombinedIterator)(nil) @@ -445,6 +459,16 @@ var _ TupleIterator = (*OrderedCombinedIterator)(nil) // All the input iterators must be individually ordered already according to mapper. // Iterators can yield the same value (as defined by mapper) multiple times, but it will only be returned once. func NewOrderedCombinedIterator(mapper TupleMapperFunc, sortedIters ...TupleIterator) *OrderedCombinedIterator { + return newOrderedIterator(true, mapper, sortedIters...) +} + +// NewOrderedMergeIterator is like NewOrderedCombinedIterator but keeps tuples that map to the same value, so callers can +// filter (e.g. by condition) before deduplicating. Ties go to the lowest index. +func NewOrderedMergeIterator(mapper TupleMapperFunc, sortedIters ...TupleIterator) *OrderedCombinedIterator { + return newOrderedIterator(false, mapper, sortedIters...) +} + +func newOrderedIterator(dedupe bool, mapper TupleMapperFunc, sortedIters ...TupleIterator) *OrderedCombinedIterator { pending := make([]TupleIterator, 0, len(sortedIters)) ordered := true for _, sortedIter := range sortedIters { @@ -455,7 +479,7 @@ func NewOrderedCombinedIterator(mapper TupleMapperFunc, sortedIters ...TupleIter } } } - return &OrderedCombinedIterator{pending: pending, once: &sync.Once{}, mu: &sync.Mutex{}, mapper: mapper, ordered: ordered} + return &OrderedCombinedIterator{pending: pending, once: &sync.Once{}, mu: &sync.Mutex{}, mapper: mapper, ordered: ordered, dedupe: dedupe} } func (c *OrderedCombinedIterator) Next(ctx context.Context) (*openfgav1.Tuple, error) { @@ -521,7 +545,7 @@ IterateOverPending: // We do this based on the previous Head() returned for performance reasons. // If on every call to Head() we discarded, we would need to iterate twice over pending: // one time to find the minIdx, and one time to move the corresponding iterators. - for c.mapper(head) == c.mapper(c.lastYielded) { + for c.dedupe && c.mapper(head) == c.mapper(c.lastYielded) { // We want to advance to the new tuple. However, notice the "Next"'s returned // tuple is still "old". Therefore, we will need to load it with "Head" in the // next step. @@ -578,6 +602,56 @@ func (c *OrderedCombinedIterator) Stop() { // produces sorted output only when every input is individually sorted. func (c *OrderedCombinedIterator) IsOrdered() bool { return c.ordered } +type keptTupleIterator struct { + iter TupleIterator + keep func(*openfgav1.Tuple) bool + once sync.Once +} + +var _ TupleIterator = (*keptTupleIterator)(nil) + +// Next see [Iterator.Next]. +func (k *keptTupleIterator) Next(ctx context.Context) (*openfgav1.Tuple, error) { + for { + t, err := k.iter.Next(ctx) + if err != nil { + return nil, err + } + if k.keep(t) { + return t, nil + } + } +} + +// Head see [Iterator.Head]. It advances past dropped tuples. +func (k *keptTupleIterator) Head(ctx context.Context) (*openfgav1.Tuple, error) { + for { + t, err := k.iter.Head(ctx) + if err != nil { + return nil, err + } + if k.keep(t) { + return t, nil + } + if _, err := k.iter.Next(ctx); err != nil { + return nil, err + } + } +} + +// Stop see [Iterator.Stop]. +func (k *keptTupleIterator) Stop() { + k.once.Do(k.iter.Stop) +} + +// IsOrdered forwards from the inner iterator. +func (k *keptTupleIterator) IsOrdered() bool { return k.iter.IsOrdered() } + +// NewKeepTupleIterator yields only tuples for which keep is true. It works on tuples so conditions survive, unlike NewFilteredTupleKeyIterator. +func NewKeepTupleIterator(iter TupleIterator, keep func(*openfgav1.Tuple) bool) TupleIterator { + return &keptTupleIterator{iter: iter, keep: keep} +} + // IterIsDoneOrCancelled is true if the error is due to done or cancelled or deadline exceeded. func IterIsDoneOrCancelled(err error) bool { return errors.Is(err, ErrIteratorDone) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) diff --git a/vendor/github.com/openfga/openfga/pkg/typesystem/typesystem.go b/vendor/github.com/openfga/openfga/pkg/typesystem/typesystem.go index a66d230a1e..d8a8f46558 100644 --- a/vendor/github.com/openfga/openfga/pkg/typesystem/typesystem.go +++ b/vendor/github.com/openfga/openfga/pkg/typesystem/typesystem.go @@ -1456,12 +1456,13 @@ func (t *TypeSystem) validateTypeRestrictions(objectType string, relationName st } } - if related.GetCondition() != "" { + if condName := related.GetCondition(); condName != "" && !condition.IsInlineExpression(condName) { // Validate the conditions referenced by the relations are included in the model. - if _, ok := t.conditions[related.GetCondition()]; !ok { + // $expression is a reserved inline condition and is not stored in the model's conditions map. + if _, ok := t.conditions[condName]; !ok { return &RelationConditionError{ Relation: relationName, - Condition: related.GetCondition(), + Condition: condName, Err: ErrNoConditionForRelation, } } diff --git a/vendor/github.com/pressly/goose/v3/CHANGELOG.md b/vendor/github.com/pressly/goose/v3/CHANGELOG.md index 315fe5acef..3afcdd5793 100644 --- a/vendor/github.com/pressly/goose/v3/CHANGELOG.md +++ b/vendor/github.com/pressly/goose/v3/CHANGELOG.md @@ -7,6 +7,47 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +## [v3.29.0] - 2026-10-11 + +### Added + +- Support [environ credentials](https://github.com/ydb-platform/ydb-go-sdk-auth-environ#auth-environment-variables) + for YDB using connection string parameter `use_env_credentials`. + +### Changed + +- Various dependency upgrades + +## [v3.28.0] - 2026-09-02 + +### Added + +- CLI: `azuresql` driver for Azure SQL with Microsoft Entra ID (Azure AD) authentication via + `fedauth` connection string parameters, e.g. + `goose azuresql "sqlserver://host?database=mydb&fedauth=ActiveDirectoryDefault" status`. + Excluded when building with the `no_mssql` or `no_azuresql` tags (#1109) +- MySQL/MariaDB table-based `Locker` via `lock.NewMySQLTableLocker`, the MySQL counterpart to the + Postgres table locker from #993, accepting the same `TableLockerOption` set (#1075) + +### Changed + +- **Minimum Go version is now 1.26** +- ClickHouse: new `goose_db_version` tables are created with `ORDER BY (version_id)` instead of + `ORDER BY (date)`. Existing tables are unchanged (#1085) +- MySQL/TiDB: the `tstamp` column is now `DATETIME` instead of `TIMESTAMP`, which is capped at + 2038-01-19 (#1053). Only newly created tables are affected; existing tables can be updated with: + + ```sql + ALTER TABLE goose_db_version MODIFY tstamp datetime NULL DEFAULT CURRENT_TIMESTAMP; + ``` + +- Various dependency upgrades + +### Fixed + +- `goose create` returns a clear "file exists" error, including the path, instead of `%!w()` + when the migration file already exists (#1104) + ## [v3.27.3] - 2026-07-22 ### Changed @@ -325,7 +366,9 @@ Here's a quick summary: - Add new `context.Context`-aware functions and methods, for both sql and go migrations. - Return error when no migration files found or dir is not a directory. -[Unreleased]: https://github.com/pressly/goose/compare/v3.27.3...HEAD +[Unreleased]: https://github.com/pressly/goose/compare/v3.29.0...HEAD +[v3.29.0]: https://github.com/pressly/goose/compare/v3.28.0...v3.29.0 +[v3.28.0]: https://github.com/pressly/goose/compare/v3.27.3...v3.28.0 [v3.27.3]: https://github.com/pressly/goose/compare/v3.27.2...v3.27.3 [v3.27.2]: https://github.com/pressly/goose/compare/v3.27.1...v3.27.2 [v3.27.1]: https://github.com/pressly/goose/compare/v3.27.0...v3.27.1 diff --git a/vendor/github.com/pressly/goose/v3/Makefile b/vendor/github.com/pressly/goose/v3/Makefile index 99c429ff19..0f0e63155a 100644 --- a/vendor/github.com/pressly/goose/v3/Makefile +++ b/vendor/github.com/pressly/goose/v3/Makefile @@ -89,6 +89,10 @@ test-clickhouse: add-gowork go test $(GO_TEST_FLAGS) ./internal/testing/integration -run='(TestClickhouse|TestClickhouseRemote)' |\ tparse --follow -sort=elapsed +test-mysql-long: add-gowork test-mysql + go test $(GO_TEST_FLAGS) ./internal/testing/integration/locking -run='TestMySQL' |\ + tparse --follow -sort=elapsed + test-mysql: add-gowork go test $(GO_TEST_FLAGS) ./internal/testing/integration -run='TestMySQL' | tparse --follow -sort=elapsed diff --git a/vendor/github.com/pressly/goose/v3/README.md b/vendor/github.com/pressly/goose/v3/README.md index a022d8c8d4..16a7fb05f3 100644 --- a/vendor/github.com/pressly/goose/v3/README.md +++ b/vendor/github.com/pressly/goose/v3/README.md @@ -39,8 +39,11 @@ Binary too big? Build a lite version by excluding the drivers you don't need: go build -tags='no_postgres no_mysql no_sqlite3 no_ydb' -o goose ./cmd/goose # Available build tags: -# no_clickhouse no_libsql no_mssql no_mysql -# no_postgres no_sqlite3 no_vertica no_ydb +# no_azuresql no_clickhouse no_libsql no_mssql +# no_mysql no_postgres no_sqlite3 no_vertica +# no_ydb +# +# Note: no_mssql also excludes the azuresql driver. ``` For macOS users `goose` is available as a [Homebrew @@ -75,6 +78,7 @@ Drivers: sqlite3 spanner mssql + azuresql redshift tidb clickhouse @@ -95,6 +99,7 @@ Examples: goose redshift "postgres://user:password@qwerty.us-east-1.redshift.amazonaws.com:5439/db" status goose tidb "user:password@/dbname?parseTime=true" status goose mssql "sqlserver://user:password@hostname:1433?database=master" status + goose azuresql "sqlserver://myserver.database.windows.net?database=mydb&fedauth=ActiveDirectoryDefault" status goose clickhouse "tcp://127.0.0.1:9000" status goose ydb "grpcs://localhost:2135/local?go_query_mode=scripting&go_fake_tx=scripting&go_query_bind=declare,numeric" status goose starrocks "user:password@/dbname?parseTime=true&interpolateParams=true" status @@ -143,12 +148,15 @@ Commands: status Dump the migration status for the current DB version Print the current version of the database create NAME [sql|go] Creates new migration file with the current timestamp + env Print the current Goose environment configuration fix Apply sequential ordering to migrations validate Check migration files without running them ``` +See [drivers](#drivers) for driver-specific details. + Commonly used commands: [create](#create) •  [up](#up) •  [up-to](#up-to) •  [down](#down) •  [down-to](#down-to) •  [status](#status) •  [version](#version) @@ -489,6 +497,15 @@ When you're ready to deploy your migrations in a production environment, we also ordering. We recommend running `fix` in the CI pipeline, and only when the migrations are ready for production. +# Drivers + +Some drivers have specific requirements or special behaviour. Make sure to read the documentation +for your database's driver before adopting and deploying Goose. + +* [ClickHouse](doc/dialect-clickhouse.md) only fully supports some clickhouse + deployment modes and requires careful configuration or work-arounds for + others. + ## Credit The gopher mascot was designed by [Renée French](https://reneefrench.blogspot.com/) / [CC diff --git a/vendor/github.com/pressly/goose/v3/create.go b/vendor/github.com/pressly/goose/v3/create.go index a26eae510c..538632fbf6 100644 --- a/vendor/github.com/pressly/goose/v3/create.go +++ b/vendor/github.com/pressly/goose/v3/create.go @@ -58,11 +58,7 @@ func CreateWithTemplate(db *sql.DB, dir string, tmpl *template.Template, name, m } path := filepath.Join(dir, filename) - if _, err := os.Stat(path); !os.IsNotExist(err) { - return fmt.Errorf("failed to create migration file: %w", err) - } - - f, err := os.Create(path) + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o666) if err != nil { return fmt.Errorf("failed to create migration file: %w", err) } diff --git a/vendor/github.com/pressly/goose/v3/down.go b/vendor/github.com/pressly/goose/v3/down.go index 29e7daaeeb..4b59fb0894 100644 --- a/vendor/github.com/pressly/goose/v3/down.go +++ b/vendor/github.com/pressly/goose/v3/down.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "fmt" + "slices" ) // Down rolls back a single migration from the current version. @@ -92,13 +93,13 @@ func DownToContext(ctx context.Context, db *sql.DB, dir string, version int64, o // target version. func downToNoVersioning(ctx context.Context, db *sql.DB, migrations Migrations, version int64) error { var finalVersion int64 - for i := len(migrations) - 1; i >= 0; i-- { - if version >= migrations[i].Version { - finalVersion = migrations[i].Version + for _, migration := range slices.Backward(migrations) { + if version >= migration.Version { + finalVersion = migration.Version break } - migrations[i].noVersioning = true - if err := migrations[i].DownContext(ctx, db); err != nil { + migration.noVersioning = true + if err := migration.DownContext(ctx, db); err != nil { return err } } diff --git a/vendor/github.com/pressly/goose/v3/internal/dialects/clickhouse.go b/vendor/github.com/pressly/goose/v3/internal/dialects/clickhouse.go index 7b676b9777..7b62d68e28 100644 --- a/vendor/github.com/pressly/goose/v3/internal/dialects/clickhouse.go +++ b/vendor/github.com/pressly/goose/v3/internal/dialects/clickhouse.go @@ -23,7 +23,7 @@ func (c *clickhouse) CreateTable(tableName string) string { tstamp DateTime default now() ) ENGINE = MergeTree() - ORDER BY (date)` + ORDER BY (version_id)` return fmt.Sprintf(q, tableName) } diff --git a/vendor/github.com/pressly/goose/v3/internal/dialects/mysql.go b/vendor/github.com/pressly/goose/v3/internal/dialects/mysql.go index 9341589523..4d1a2becbc 100644 --- a/vendor/github.com/pressly/goose/v3/internal/dialects/mysql.go +++ b/vendor/github.com/pressly/goose/v3/internal/dialects/mysql.go @@ -20,7 +20,7 @@ func (m *mysql) CreateTable(tableName string) string { id bigint(20) unsigned NOT NULL AUTO_INCREMENT, version_id bigint NOT NULL, is_applied boolean NOT NULL, - tstamp timestamp NULL default now(), + tstamp datetime NULL default CURRENT_TIMESTAMP, PRIMARY KEY(id) )` return fmt.Sprintf(q, tableName) diff --git a/vendor/github.com/pressly/goose/v3/internal/dialects/tidb.go b/vendor/github.com/pressly/goose/v3/internal/dialects/tidb.go index f5b58f2b7a..9978424b91 100644 --- a/vendor/github.com/pressly/goose/v3/internal/dialects/tidb.go +++ b/vendor/github.com/pressly/goose/v3/internal/dialects/tidb.go @@ -20,7 +20,7 @@ func (t *Tidb) CreateTable(tableName string) string { id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, version_id bigint NOT NULL, is_applied boolean NOT NULL, - tstamp timestamp NULL default now(), + tstamp datetime NULL default CURRENT_TIMESTAMP, PRIMARY KEY(id) )` return fmt.Sprintf(q, tableName) diff --git a/vendor/github.com/pressly/goose/v3/lock/internal/store/mysql.go b/vendor/github.com/pressly/goose/v3/lock/internal/store/mysql.go new file mode 100644 index 0000000000..ad213e8270 --- /dev/null +++ b/vendor/github.com/pressly/goose/v3/lock/internal/store/mysql.go @@ -0,0 +1,346 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" + + "go.uber.org/multierr" +) + +// NewMySQL creates a new MySQL-based [LockStore]. +func NewMySQL(tableName string) (LockStore, error) { + if tableName == "" { + return nil, errors.New("table name must not be empty") + } + return &mysqlStore{ + tableName: tableName, + }, nil +} + +var _ LockStore = (*mysqlStore)(nil) + +type mysqlStore struct { + tableName string +} + +func (s *mysqlStore) TableExists( + ctx context.Context, + db *sql.DB, +) (bool, error) { + schemaName, tableName := parseTableIdentifier(s.tableName) + + var query string + var args []any + if schemaName != "" { + query = `SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ? )` + args = []any{schemaName, tableName} + } else { + query = `SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ? )` + args = []any{tableName} + } + + var exists bool + if err := db.QueryRowContext(ctx, query, args...).Scan( + &exists, + ); err != nil { + return false, fmt.Errorf("table exists: %w", err) + } + return exists, nil +} + +func (s *mysqlStore) CreateLockTable( + ctx context.Context, + db *sql.DB, +) error { + exists, err := s.TableExists(ctx, db) + if err != nil { + return fmt.Errorf("check lock table existence: %w", err) + } + if exists { + return nil + } + + query := fmt.Sprintf(`CREATE TABLE %s ( + lock_id BIGINT NOT NULL PRIMARY KEY, + locked BOOLEAN NOT NULL DEFAULT 0, + locked_at DATETIME(6) NULL, + locked_by TEXT NULL, + lease_expires_at DATETIME(6) NULL, + updated_at DATETIME(6) NULL + )`, s.tableName) + if _, err := db.ExecContext(ctx, query); err != nil { + // Double-check if another process created it concurrently + if exists, checkErr := s.TableExists(ctx, db); checkErr == nil && exists { + // Another process created it, that's fine! + return nil + } + return fmt.Errorf("create lock table %q: %w", s.tableName, err) + } + return nil +} + +func (s *mysqlStore) AcquireLock( + ctx context.Context, + db *sql.DB, + lockID int64, + lockedBy string, + leaseDuration time.Duration, +) (_ *AcquireLockResult, retErr error) { + leaseSeconds := int(leaseDuration.Seconds()) + + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("acquire lock %d: begin tx: %w", lockID, err) + } + defer func() { + if retErr != nil { + retErr = multierr.Append(retErr, tx.Rollback()) + } + }() + + // First, try to insert a brand-new row. If a row already exists for this lock_id, + // INSERT IGNORE silently no-ops (RowsAffected == 0) and we fall through to the UPDATE. + insertQ := fmt.Sprintf(`INSERT IGNORE INTO %s (lock_id, locked, locked_at, locked_by, lease_expires_at, updated_at) + VALUES (?, true, now(6), ?, now(6) + INTERVAL ? SECOND, now(6))`, s.tableName) + insertRes, err := tx.ExecContext(ctx, insertQ, lockID, lockedBy, leaseSeconds) + if err != nil { + return nil, fmt.Errorf("acquire lock %d: %w", lockID, err) + } + inserted, err := insertRes.RowsAffected() + if err != nil { + return nil, fmt.Errorf("acquire lock %d: rows affected: %w", lockID, err) + } + + if inserted == 0 { + // Row exists: only steal if currently unlocked or lease has expired. + updateQ := fmt.Sprintf(`UPDATE %s SET + locked = true, + locked_at = now(6), + locked_by = ?, + lease_expires_at = now(6) + INTERVAL ? SECOND, + updated_at = now(6) + WHERE lock_id = ? AND (locked = false OR lease_expires_at < now(6))`, s.tableName) + updateRes, err := tx.ExecContext(ctx, updateQ, lockedBy, leaseSeconds, lockID) + if err != nil { + return nil, fmt.Errorf("acquire lock %d: %w", lockID, err) + } + affected, err := updateRes.RowsAffected() + if err != nil { + return nil, fmt.Errorf("acquire lock %d: rows affected: %w", lockID, err) + } + if affected == 0 { + // TODO(mf): should we return a special error type here? + return nil, fmt.Errorf("acquire lock %d: already held by another instance", lockID) + } + } + + // MySQL has no RETURNING clause; read the row back to learn the resulting lease. + selectQ := fmt.Sprintf(`SELECT locked_by, lease_expires_at FROM %s WHERE lock_id = ?`, s.tableName) + var returnedLockedBy string + var leaseExpiresAt time.Time + if err := tx.QueryRowContext(ctx, selectQ, lockID).Scan( + &returnedLockedBy, + &leaseExpiresAt, + ); err != nil { + return nil, fmt.Errorf("acquire lock %d: %w", lockID, err) + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("acquire lock %d: commit: %w", lockID, err) + } + + // Verify we got the lock by checking the returned locked_by matches our instance ID + if returnedLockedBy != lockedBy { + return nil, fmt.Errorf("acquire lock %d: acquired by %s instead of %s", lockID, returnedLockedBy, lockedBy) + } + + return &AcquireLockResult{ + LockedBy: returnedLockedBy, + LeaseExpiresAt: leaseExpiresAt, + }, nil +} + +func (s *mysqlStore) ReleaseLock( + ctx context.Context, + db *sql.DB, + lockID int64, + lockedBy string, +) (_ *ReleaseLockResult, retErr error) { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("release lock %d: begin tx: %w", lockID, err) + } + defer func() { + if retErr != nil { + retErr = multierr.Append(retErr, tx.Rollback()) + } + }() + + // Release lock only if it's held by the current instance + updateQ := fmt.Sprintf(`UPDATE %s SET + locked = false, + locked_at = NULL, + locked_by = NULL, + lease_expires_at = NULL, + updated_at = now(6) + WHERE lock_id = ? AND locked_by = ?`, s.tableName) + res, err := tx.ExecContext(ctx, updateQ, lockID, lockedBy) + if err != nil { + return nil, fmt.Errorf("release lock %d: %w", lockID, err) + } + affected, err := res.RowsAffected() + if err != nil { + return nil, fmt.Errorf("release lock %d: rows affected: %w", lockID, err) + } + if affected == 0 { + // TODO(mf): should we return a special error type here? + return nil, fmt.Errorf("release lock %d: not held by this instance", lockID) + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("release lock %d: commit: %w", lockID, err) + } + + return &ReleaseLockResult{ + LockID: lockID, + }, nil +} + +func (s *mysqlStore) UpdateLease( + ctx context.Context, + db *sql.DB, + lockID int64, + lockedBy string, + leaseDuration time.Duration, +) (_ *UpdateLeaseResult, retErr error) { + leaseSeconds := int(leaseDuration.Seconds()) + + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: begin tx: %w", lockID, err) + } + defer func() { + if retErr != nil { + retErr = multierr.Append(retErr, tx.Rollback()) + } + }() + + // Update lease expiration time for heartbeat, only if we own the lock + updateQ := fmt.Sprintf(`UPDATE %s SET + lease_expires_at = now(6) + INTERVAL ? SECOND, + updated_at = now(6) + WHERE lock_id = ? AND locked_by = ? AND locked = true`, s.tableName) + res, err := tx.ExecContext(ctx, updateQ, leaseSeconds, lockID, lockedBy) + if err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: %w", lockID, err) + } + affected, err := res.RowsAffected() + if err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: rows affected: %w", lockID, err) + } + if affected == 0 { + return nil, fmt.Errorf("failed to update lease for lock %d: not held by this instance", lockID) + } + + selectQ := fmt.Sprintf(`SELECT lease_expires_at FROM %s WHERE lock_id = ?`, s.tableName) + var leaseExpiresAt time.Time + if err := tx.QueryRowContext(ctx, selectQ, lockID).Scan(&leaseExpiresAt); err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: %w", lockID, err) + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: commit: %w", lockID, err) + } + + return &UpdateLeaseResult{ + LeaseExpiresAt: leaseExpiresAt, + }, nil +} + +func (s *mysqlStore) CheckLockStatus( + ctx context.Context, + db *sql.DB, + lockID int64, +) (*LockStatus, error) { + query := fmt.Sprintf(`SELECT locked, locked_by, lease_expires_at, updated_at FROM %s WHERE lock_id = ?`, s.tableName) + var status LockStatus + + err := db.QueryRowContext(ctx, query, + lockID, + ).Scan( + &status.Locked, + &status.LockedBy, + &status.LeaseExpiresAt, + &status.UpdatedAt, + ) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("lock %d not found", lockID) + } + return nil, fmt.Errorf("check lock status for %d: %w", lockID, err) + } + + return &status, nil +} + +func (s *mysqlStore) CleanupStaleLocks(ctx context.Context, db *sql.DB) (_ []int64, retErr error) { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("cleanup stale locks: begin tx: %w", err) + } + defer func() { + if retErr != nil { + retErr = multierr.Append(retErr, tx.Rollback()) + } + }() + + // MySQL has no RETURNING on UPDATE; lock rows for update, collect their IDs, then clear them. + selectQ := fmt.Sprintf(`SELECT lock_id FROM %s WHERE locked = true AND lease_expires_at < now(6) FOR UPDATE`, s.tableName) + rows, err := tx.QueryContext(ctx, selectQ) + if err != nil { + return nil, fmt.Errorf("cleanup stale locks: %w", err) + } + var cleanedLocks []int64 + for rows.Next() { + var lockID int64 + if err := rows.Scan(&lockID); err != nil { + return nil, multierr.Append(fmt.Errorf("scan cleaned lock ID: %w", err), rows.Close()) + } + cleanedLocks = append(cleanedLocks, lockID) + } + if err := rows.Err(); err != nil { + retErr = multierr.Append(retErr, rows.Close()) + return nil, fmt.Errorf("iterate over cleaned locks: %w", err) + } + if err := rows.Close(); err != nil { + return nil, fmt.Errorf("close cleaned locks rows: %w", err) + } + + if len(cleanedLocks) > 0 { + placeholders := strings.TrimSuffix(strings.Repeat("?,", len(cleanedLocks)), ",") + updateQ := fmt.Sprintf(`UPDATE %s SET + locked = false, + locked_at = NULL, + locked_by = NULL, + lease_expires_at = NULL, + updated_at = now(6) + WHERE lock_id IN (%s)`, s.tableName, placeholders) + args := make([]any, len(cleanedLocks)) + for i, id := range cleanedLocks { + args[i] = id + } + if _, err := tx.ExecContext(ctx, updateQ, args...); err != nil { + return nil, fmt.Errorf("cleanup stale locks: %w", err) + } + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("cleanup stale locks: commit: %w", err) + } + + return cleanedLocks, nil +} diff --git a/vendor/github.com/pressly/goose/v3/lock/mysql.go b/vendor/github.com/pressly/goose/v3/lock/mysql.go new file mode 100644 index 0000000000..731e1e9755 --- /dev/null +++ b/vendor/github.com/pressly/goose/v3/lock/mysql.go @@ -0,0 +1,54 @@ +package lock + +import ( + "fmt" + "time" + + "github.com/pressly/goose/v3/lock/internal/store" + "github.com/pressly/goose/v3/lock/internal/table" +) + +// NewMySQLTableLocker returns a Locker that uses MySQL table-based locking. It manages a single +// lock row and keeps the lock alive automatically. +// +// Default behavior: +// +// - Lease (30s): How long the lock is valid if heartbeat stops +// - Heartbeat (5s): How often the lock gets refreshed to keep it alive +// - If the process dies, others can take the lock after lease expires +// +// Defaults: +// +// Table: "goose_lock" +// Lock ID: 4097083626 (crc32 of "goose") +// Lock retry: 5s intervals, 5min timeout +// Unlock retry: 2s intervals, 1min timeout +// +// Lock and Unlock both retry on failure. Lock stays alive automatically until released. All +// defaults can be overridden with options. +func NewMySQLTableLocker(options ...TableLockerOption) (Locker, error) { + config := table.Config{ + TableName: DefaultLockTableName, + LockID: DefaultLockID, + LeaseDuration: 30 * time.Second, + HeartbeatInterval: 5 * time.Second, + LockTimeout: table.ProbeConfig{ + IntervalDuration: 5 * time.Second, + FailureThreshold: 60, // 5 minutes total + }, + UnlockTimeout: table.ProbeConfig{ + IntervalDuration: 2 * time.Second, + FailureThreshold: 30, // 1 minute total + }, + } + for _, opt := range options { + if err := opt.apply(&config); err != nil { + return nil, err + } + } + lockStore, err := store.NewMySQL(config.TableName) + if err != nil { + return nil, fmt.Errorf("create lock store: %w", err) + } + return table.New(lockStore, config), nil +} diff --git a/vendor/github.com/pressly/goose/v3/migrate.go b/vendor/github.com/pressly/goose/v3/migrate.go index b60c61ae77..fbf4098719 100644 --- a/vendor/github.com/pressly/goose/v3/migrate.go +++ b/vendor/github.com/pressly/goose/v3/migrate.go @@ -8,6 +8,7 @@ import ( "io/fs" "math" "path" + "slices" "sort" "strings" "time" @@ -63,9 +64,9 @@ func (ms Migrations) Next(current int64) (*Migration, error) { // Previous : Get the previous migration. func (ms Migrations) Previous(current int64) (*Migration, error) { - for i := len(ms) - 1; i >= 0; i-- { - if ms[i].Version < current { - return ms[i], nil + for _, m := range slices.Backward(ms) { + if m.Version < current { + return m, nil } } diff --git a/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go b/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go index 820bf436ab..2cd16f13a4 100644 --- a/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go +++ b/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go @@ -39,7 +39,7 @@ func init() { // token = 1* // qdtext = > - for c := 0; c < 256; c++ { + for c := range 256 { var t octetType isCtl := c <= 31 || c == 127 isChar := 0 <= c && c <= 127 diff --git a/vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go index 450189f35e..b80b964c9c 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go @@ -32,7 +32,8 @@ func NewBuildInfoCollector() Collector { "Build information about the main Go module.", nil, Labels{"path": path, "version": version, "checksum": sum}, ), - GaugeValue, 1)} + GaugeValue, 1, + )} c.init(c.self) return c } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go index d29ade654f..c5a5d50aa0 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go @@ -11,9 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build go1.17 -// +build go1.17 - package collectors import ( diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc.go b/vendor/github.com/prometheus/client_golang/prometheus/desc.go index a3c92e7a4c..881d91dee0 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/desc.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/desc.go @@ -21,7 +21,6 @@ import ( "github.com/cespare/xxhash/v2" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" - "google.golang.org/protobuf/proto" "github.com/prometheus/client_golang/prometheus/internal" ) @@ -181,8 +180,8 @@ func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, const d.constLabelPairs = make([]*dto.LabelPair, 0, len(constLabels)) for n, v := range constLabels { d.constLabelPairs = append(d.constLabelPairs, &dto.LabelPair{ - Name: proto.String(n), - Value: proto.String(v), + Name: new(n), + Value: new(v), }) } sort.Sort(internal.LabelPairSorter(d.constLabelPairs)) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/get_pid.go b/vendor/github.com/prometheus/client_golang/prometheus/get_pid.go index 614fd61be9..c7be2a0ca7 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/get_pid.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/get_pid.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build !js || wasm -// +build !js wasm package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go b/vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go index eaf8059ee1..0ddc8c6eed 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build js && !wasm -// +build js,!wasm package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go index 520cbd7d41..a4725849f4 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go @@ -211,23 +211,28 @@ func newBaseGoCollector() baseGoCollector { goroutinesDesc: NewDesc( "go_goroutines", "Number of goroutines that currently exist.", - nil, nil), + nil, nil, + ), threadsDesc: NewDesc( "go_threads", "Number of OS threads created.", - nil, nil), + nil, nil, + ), gcDesc: NewDesc( "go_gc_duration_seconds", "A summary of the wall-time pause (stop-the-world) duration in garbage collection cycles.", - nil, nil), + nil, nil, + ), gcLastTimeDesc: NewDesc( "go_memstats_last_gc_time_seconds", "Number of seconds since 1970 of last garbage collection.", - nil, nil), + nil, nil, + ), goInfoDesc: NewDesc( "go_info", "Information about the Go environment.", - nil, Labels{"version": runtime.Version()}), + nil, Labels{"version": runtime.Version()}, + ), } } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go index 1db1c4be09..23091e1774 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go @@ -11,9 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build go1.17 -// +build go1.17 - package prometheus import ( @@ -27,7 +24,6 @@ import ( "github.com/prometheus/client_golang/prometheus/internal" dto "github.com/prometheus/client_model/go" - "google.golang.org/protobuf/proto" ) const ( @@ -573,14 +569,14 @@ func (h *batchHistogram) Write(out *dto.Metric) error { // by obtaining the next float64 value down, in order. upperBound := math.Nextafter(h.buckets[i+1], h.buckets[i]) dtoBuckets = append(dtoBuckets, &dto.Bucket{ - CumulativeCount: proto.Uint64(totalCount), - UpperBound: proto.Float64(upperBound), + CumulativeCount: new(totalCount), + UpperBound: new(upperBound), }) } out.Histogram = &dto.Histogram{ Bucket: dtoBuckets, - SampleCount: proto.Uint64(totalCount), - SampleSum: proto.Float64(sum), + SampleCount: new(totalCount), + SampleSum: new(sum), } return nil } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go index 88bae3b32c..1d6ca1614f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go @@ -803,8 +803,8 @@ func (h *histogram) Write(out *dto.Metric) error { his := &dto.Histogram{ Bucket: make([]*dto.Bucket, len(h.upperBounds)), - SampleCount: proto.Uint64(count), - SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))), + SampleCount: new(count), + SampleSum: new(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))), CreatedTimestamp: timestamppb.New(h.lastResetTime), } out.Histogram = his @@ -814,8 +814,8 @@ func (h *histogram) Write(out *dto.Metric) error { for i, upperBound := range h.upperBounds { cumCount += atomic.LoadUint64(&coldCounts.buckets[i]) his.Bucket[i] = &dto.Bucket{ - CumulativeCount: proto.Uint64(cumCount), - UpperBound: proto.Float64(upperBound), + CumulativeCount: new(cumCount), + UpperBound: new(upperBound), } if e := h.exemplars[i].Load(); e != nil { his.Bucket[i].Exemplar = e.(*dto.Exemplar) @@ -824,15 +824,15 @@ func (h *histogram) Write(out *dto.Metric) error { // If there is an exemplar for the +Inf bucket, we have to add that bucket explicitly. if e := h.exemplars[len(h.upperBounds)].Load(); e != nil { b := &dto.Bucket{ - CumulativeCount: proto.Uint64(count), - UpperBound: proto.Float64(math.Inf(1)), + CumulativeCount: new(count), + UpperBound: new(math.Inf(1)), Exemplar: e.(*dto.Exemplar), } his.Bucket = append(his.Bucket, b) } if h.nativeHistogramSchema > math.MinInt32 { - his.ZeroThreshold = proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.nativeHistogramZeroThresholdBits))) - his.Schema = proto.Int32(atomic.LoadInt32(&coldCounts.nativeHistogramSchema)) + his.ZeroThreshold = new(math.Float64frombits(atomic.LoadUint64(&coldCounts.nativeHistogramZeroThresholdBits))) + his.Schema = new(atomic.LoadInt32(&coldCounts.nativeHistogramSchema)) zeroBucket := atomic.LoadUint64(&coldCounts.nativeHistogramZeroBucket) defer func() { @@ -840,7 +840,7 @@ func (h *histogram) Write(out *dto.Metric) error { coldCounts.nativeHistogramBucketsNegative.Range(addAndReset(&hotCounts.nativeHistogramBucketsNegative, &hotCounts.nativeHistogramBucketsNumber)) }() - his.ZeroCount = proto.Uint64(zeroBucket) + his.ZeroCount = new(zeroBucket) his.NegativeSpan, his.NegativeDelta = makeBuckets(&coldCounts.nativeHistogramBucketsNegative) his.PositiveSpan, his.PositiveDelta = makeBuckets(&coldCounts.nativeHistogramBucketsPositive) @@ -1331,12 +1331,12 @@ func (h *constHistogram) Write(out *dto.Metric) error { buckets := make([]*dto.Bucket, 0, len(h.buckets)) - his.SampleCount = proto.Uint64(h.count) - his.SampleSum = proto.Float64(h.sum) + his.SampleCount = new(h.count) + his.SampleSum = new(h.sum) for upperBound, count := range h.buckets { buckets = append(buckets, &dto.Bucket{ - CumulativeCount: proto.Uint64(count), - UpperBound: proto.Float64(upperBound), + CumulativeCount: new(count), + UpperBound: new(upperBound), }) } @@ -1481,7 +1481,7 @@ func pickSchema(bucketFactor float64) int32 { func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) { var ii []int - buckets.Range(func(k, v any) bool { + buckets.Range(func(k, _ any) bool { ii = append(ii, k.(int)) return true }) @@ -1518,13 +1518,13 @@ func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) { // at the very beginning, or because we have found a gap // of more than two buckets. spans = append(spans, &dto.BucketSpan{ - Offset: proto.Int32(iDelta), + Offset: new(iDelta), Length: proto.Uint32(0), }) } else { // We have found a small gap (or no gap at all). // Insert empty buckets as needed. - for j := int32(0); j < iDelta; j++ { + for range iDelta { appendDelta(0) } } @@ -1570,7 +1570,7 @@ func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v any) bool } func deleteSyncMap(m *sync.Map) { - m.Range(func(k, v any) bool { + m.Range(func(k, _ any) bool { m.Delete(k) return true }) @@ -1578,7 +1578,7 @@ func deleteSyncMap(m *sync.Map) { func findSmallestKey(m *sync.Map) int { result := math.MaxInt32 - m.Range(func(k, v any) bool { + m.Range(func(k, _ any) bool { key := k.(int) if key < result { result = key @@ -1956,7 +1956,7 @@ func NewConstNativeHistogram( PositiveSpan: PositiveSpan, PositiveDelta: PositiveDelta, - ZeroCount: proto.Uint64(zeroBucket), + ZeroCount: new(zeroBucket), }, labelPairs: MakeLabelPairs(desc, labelValues), } @@ -2044,13 +2044,13 @@ func makeBucketsFromMap(buckets map[int]int64) ([]*dto.BucketSpan, []int64) { // at the very beginning, or because we have found a gap // of more than two buckets. spans = append(spans, &dto.BucketSpan{ - Offset: proto.Int32(iDelta), + Offset: new(iDelta), Length: proto.Uint32(0), }) } else { // We have found a small gap (or no gap at all). // Insert empty buckets as needed. - for j := int32(0); j < iDelta; j++ { + for range iDelta { appendDelta(0) } } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go b/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go index d273b6640e..e38dfe0adc 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go @@ -11,9 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build go1.17 -// +build go1.17 - package internal import ( diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric.go b/vendor/github.com/prometheus/client_golang/prometheus/metric.go index c5cb90adf8..e4bbf3b8ec 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/metric.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/metric.go @@ -22,7 +22,6 @@ import ( dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" - "google.golang.org/protobuf/proto" ) var separatorByteSlice = []byte{model.SeparatorByte} // For convenient use with xxhash. @@ -153,7 +152,7 @@ type timestampedMetric struct { func (m timestampedMetric) Write(pb *dto.Metric) error { e := m.Metric.Write(pb) - pb.TimestampMs = proto.Int64(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000)) + pb.TimestampMs = new(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000)) return e } @@ -209,8 +208,8 @@ func (m *withExemplarsMetric) Write(pb *dto.Metric) error { } else { // The +Inf bucket should be explicitly added if there is an exemplar for it, similar to non-const histogram logic in https://github.com/prometheus/client_golang/blob/main/prometheus/histogram.go#L357-L365. b := &dto.Bucket{ - CumulativeCount: proto.Uint64(h.GetSampleCount()), - UpperBound: proto.Float64(math.Inf(1)), + CumulativeCount: new(h.GetSampleCount()), + UpperBound: new(math.Inf(1)), Exemplar: e, } h.Bucket = append(h.Bucket, b) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/num_threads.go b/vendor/github.com/prometheus/client_golang/prometheus/num_threads.go index 7c12b21087..7ffac21340 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/num_threads.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/num_threads.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build !js || wasm -// +build !js wasm package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go b/vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go index 7348df01df..65f4263f9f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build js && !wasm -// +build js,!wasm package prometheus 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 2b16298f40..46e7e45aab 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 @@ -54,21 +54,22 @@ func getOpenFileCount() (float64, error) { // benefits, however, include fewer system calls and not failing when at the // open file soft limit. - if dir, err := os.Open("/dev/fd"); err != nil { + dir, err := os.Open("/dev/fd") + if err != nil { return 0.0, err - } else { - defer dir.Close() + } + defer dir.Close() - // Avoid ReadDir(), as it calls stat(2) on each descriptor. Not only is - // that info not used, but KQUEUE descriptors fail stat(2), which causes - // the whole method to fail. - if names, err := dir.Readdirnames(0); err != nil { - return 0.0, err - } else { - // Subtract 1 to ignore the open /dev/fd descriptor above. - return float64(len(names) - 1), nil - } + // Avoid ReadDir(), as it calls stat(2) on each descriptor. Not only is + // that info not used, but KQUEUE descriptors fail stat(2), which causes + // the whole method to fail. + names, err := dir.Readdirnames(0) + if err != nil { + return 0.0, err } + + // Subtract 1 to ignore the open /dev/fd descriptor above. + return float64(len(names) - 1), nil } func (c *processCollector) processCollect(ch chan<- Metric) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go index 7732b7f376..8650b6f4a7 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build wasip1 || js || ios -// +build wasip1 js ios package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go index 8074f70f5d..56c97d62ef 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build !windows && !js && !wasip1 && !darwin -// +build !windows,!js,!wasip1,!darwin package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go index c28af5ce2b..0af3deebfe 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go @@ -51,10 +51,12 @@ import ( ) const ( + acceptHeader = "Accept" contentTypeHeader = "Content-Type" contentEncodingHeader = "Content-Encoding" acceptEncodingHeader = "Accept-Encoding" processStartTimeHeader = "Process-Start-Time-Unix" + varyHeader = "Vary" ) // Compression represents the content encodings handlers support for the HTTP @@ -70,9 +72,8 @@ const ( func defaultCompressionFormats() []Compression { if internal.NewZstdWriter != nil { return []Compression{Identity, Gzip, Zstd} - } else { - return []Compression{Identity, Gzip} } + return []Compression{Identity, Gzip} } var gzipPool = sync.Pool{ @@ -315,11 +316,20 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO } } - var contentType expfmt.Format - if opts.EnableOpenMetrics { - contentType = expfmt.NegotiateIncludingOpenMetrics(req.Header) - } else { - contentType = expfmt.Negotiate(req.Header) + var ( + contentType expfmt.Format + acceptedFormats = opts.AcceptedFormats + ) + if len(acceptedFormats) == 0 { + acceptedFormats = expfmt.DefaultAcceptedFormats() + if opts.EnableOpenMetrics { + acceptedFormats = expfmt.DefaultOpenMetricsAcceptedFormats() + } + } + contentType = expfmt.NegotiateAccept(req.Header, acceptedFormats...) + rsp.Header().Add(varyHeader, acceptHeader) + if len(compressions) > 0 { + rsp.Header().Add(varyHeader, acceptEncodingHeader) } rsp.Header().Set(contentTypeHeader, string(contentType)) @@ -598,6 +608,8 @@ type HandlerOpts struct { // a trailing ".0" if they would otherwise look like integer numbers // (which changes the identity of the resulting series on the Prometheus // server). + // + // Note that setting AcceptedFormats overrides this option. EnableOpenMetrics bool // EnableOpenMetricsTextCreatedSamples specifies if this handler should add, extra, synthetic // Created Timestamps for counters, histograms and summaries, which for the current @@ -622,6 +634,18 @@ type HandlerOpts struct { // NOTE: This feature is experimental and not covered by OpenMetrics or Prometheus // exposition format. ProcessStartTime time.Time + // AcceptedFormats allows customizing the formats the handler will negotiate + // with the client based on the request's Accept header. + // The client's Accept header and q-values take precedence, but the order of + // formats in AcceptedFormats specifies the server's preference order used as a + // tie-breaker (e.g. for wildcard "*/*" requests or equal q-values) and fallback. + // If empty, the default set is used (expfmt.DefaultAcceptedFormats()). + // If empty and EnableOpenMetrics is true, stable OpenMetrics formats are negotiated + // (expfmt.DefaultOpenMetricsAcceptedFormats()). + // This is useful for testing experimental formats (e.g. OpenMetrics 2.0) + // or restricting the formats you want to allow. + // Using EnableOpenMetrics with an empty AcceptedFormats is still the recommended option for the majority of cases. + AcceptedFormats []expfmt.Format } // httpError removes any content-encoding header and then calls http.Error with diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go index d4c0954f36..258a2a5b55 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go @@ -41,7 +41,7 @@ type options struct { func defaultOptions() *options { return &options{ - getExemplarFn: func(req *http.Request) prometheus.Labels { return nil }, + getExemplarFn: func(_ *http.Request) prometheus.Labels { return nil }, extraLabelsFromRequest: map[string]LabelValueFromRequest{}, } } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/push.go b/vendor/github.com/prometheus/client_golang/prometheus/push/push.go index c65b6a665a..d5e31d78b6 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/push/push.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/push/push.go @@ -290,7 +290,8 @@ func (p *Pusher) push(ctx context.Context, method string) error { if err := enc.Encode(mf); err != nil { return fmt.Errorf( "failed to encode metric family %s, error is %w", - mf.GetName(), err) + mf.GetName(), err, + ) } } req, err := http.NewRequestWithContext(ctx, method, p.fullURL(), buf) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry.go b/vendor/github.com/prometheus/client_golang/prometheus/registry.go index ed0681c8b4..4151b59c48 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/registry.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/registry.go @@ -17,6 +17,7 @@ import ( "bytes" "errors" "fmt" + "maps" "os" "path/filepath" "runtime" @@ -31,7 +32,6 @@ import ( "github.com/cespare/xxhash/v2" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" - "google.golang.org/protobuf/proto" ) const ( @@ -296,6 +296,7 @@ func (r *Registry) Register(c Collector) error { defer func() { // Drain channel in case of premature return to not leak a goroutine. for range descChan { + continue } r.mtx.Unlock() }() @@ -369,9 +370,7 @@ func (r *Registry) Register(c Collector) error { for hash := range newDescIDs { r.descIDs[hash] = struct{}{} } - for name, dimHash := range newDimHashesByName { - r.dimHashesByName[name] = dimHash - } + maps.Copy(r.dimHashesByName, newDimHashesByName) return nil } @@ -476,7 +475,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { for { select { case collector := <-checkedCollectors: - safeErrs.Append((safeCollect(collector, checkedMetricChan))) + safeErrs.Append(safeCollect(collector, checkedMetricChan)) case collector := <-uncheckedCollectors: safeErrs.Append(safeCollect(collector, uncheckedMetricChan)) default: @@ -502,10 +501,12 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { defer func() { if checkedMetricChan != nil { for range checkedMetricChan { + continue } } if uncheckedMetricChan != nil { for range uncheckedMetricChan { + continue } } }() @@ -727,10 +728,10 @@ func processMetric( } } else { // New name. metricFamily = &dto.MetricFamily{} - metricFamily.Name = proto.String(desc.fqName) - metricFamily.Help = proto.String(desc.help) + metricFamily.Name = new(desc.fqName) + metricFamily.Help = new(desc.help) if desc.unit != "" { - metricFamily.Unit = proto.String(desc.unit) + metricFamily.Unit = new(desc.unit) } // TODO(beorn7): Simplify switch once Desc has type. switch { @@ -956,7 +957,8 @@ func checkMetricConsistency( if !utf8.ValidString(labelPair.GetValue()) { return fmt.Errorf( "collected metric %q { %s} has a label named %q whose value is not utf8: %#v", - name, dtoMetric, labelName, labelPair.GetValue()) + name, dtoMetric, labelName, labelPair.GetValue(), + ) } previousLabelName = labelName } @@ -981,7 +983,7 @@ func checkMetricConsistency( h.Write(separatorByteSlice) } if dtoMetric.TimestampMs != nil { - h.WriteString(strconv.FormatInt(*(dtoMetric.TimestampMs), 10)) + h.WriteString(strconv.FormatInt(*dtoMetric.TimestampMs, 10)) h.Write(separatorByteSlice) } hSum := h.Sum64() @@ -1013,7 +1015,7 @@ func checkDescConsistency( copy(lpsFromDesc, desc.constLabelPairs) for _, l := range desc.variableLabels.names { lpsFromDesc = append(lpsFromDesc, &dto.LabelPair{ - Name: proto.String(l), + Name: new(l), }) } if len(lpsFromDesc) != len(dtoMetric.Label) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go index c12b8d13d4..d92850ca01 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/summary.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go @@ -25,7 +25,6 @@ import ( dto "github.com/prometheus/client_model/go" "github.com/beorn7/perks/quantile" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -337,8 +336,8 @@ func (s *summary) Write(out *dto.Metric) error { s.bufMtx.Unlock() s.flushColdBuf() - sum.SampleCount = proto.Uint64(s.cnt) - sum.SampleSum = proto.Float64(s.sum) + sum.SampleCount = new(s.cnt) + sum.SampleSum = new(s.sum) for _, rank := range s.sortedObjectives { var q float64 @@ -348,8 +347,8 @@ func (s *summary) Write(out *dto.Metric) error { q = s.headStream.Query(rank) } qs = append(qs, &dto.Quantile{ - Quantile: proto.Float64(rank), - Value: proto.Float64(q), + Quantile: new(rank), + Value: new(q), }) } @@ -512,8 +511,8 @@ func (s *noObjectivesSummary) Write(out *dto.Metric) error { } sum := &dto.Summary{ - SampleCount: proto.Uint64(count), - SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))), + SampleCount: new(count), + SampleSum: new(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))), CreatedTimestamp: s.createdTs, } @@ -718,13 +717,13 @@ func (s *constSummary) Write(out *dto.Metric) error { } qs := make([]*dto.Quantile, 0, len(s.quantiles)) - sum.SampleCount = proto.Uint64(s.count) - sum.SampleSum = proto.Float64(s.sum) + sum.SampleCount = new(s.count) + sum.SampleSum = new(s.sum) for rank, q := range s.quantiles { qs = append(qs, &dto.Quantile{ - Quantile: proto.Float64(rank), - Value: proto.Float64(q), + Quantile: new(rank), + Value: new(q), }) } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/value.go b/vendor/github.com/prometheus/client_golang/prometheus/value.go index cc23011fad..c856e4f336 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/value.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/value.go @@ -23,7 +23,6 @@ import ( "github.com/prometheus/client_golang/prometheus/internal" dto "github.com/prometheus/client_model/go" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -196,11 +195,11 @@ func populateMetric( m.Label = labelPairs switch t { case CounterValue: - m.Counter = &dto.Counter{Value: proto.Float64(v), Exemplar: e, CreatedTimestamp: ct} + m.Counter = &dto.Counter{Value: new(v), Exemplar: e, CreatedTimestamp: ct} case GaugeValue: - m.Gauge = &dto.Gauge{Value: proto.Float64(v)} + m.Gauge = &dto.Gauge{Value: new(v)} case UntypedValue: - m.Untyped = &dto.Untyped{Value: proto.Float64(v)} + m.Untyped = &dto.Untyped{Value: new(v)} default: return fmt.Errorf("encountered unknown type %v", t) } @@ -227,8 +226,8 @@ func MakeLabelPairs(desc *Desc, labelValues []string) []*dto.LabelPair { labelPairs := make([]*dto.LabelPair, 0, totalLen) for i, l := range desc.variableLabels.names { labelPairs = append(labelPairs, &dto.LabelPair{ - Name: proto.String(l), - Value: proto.String(labelValues[i]), + Name: new(l), + Value: new(labelValues[i]), }) } labelPairs = append(labelPairs, desc.constLabelPairs...) @@ -244,7 +243,7 @@ const ExemplarMaxRunes = 128 // number of runes in the label names and values exceeds ExemplarMaxRunes. func newExemplar(value float64, ts time.Time, l Labels) (*dto.Exemplar, error) { e := &dto.Exemplar{} - e.Value = proto.Float64(value) + e.Value = new(value) tsProto := timestamppb.New(ts) if err := tsProto.CheckValid(); err != nil { return nil, err @@ -262,8 +261,8 @@ func newExemplar(value float64, ts time.Time, l Labels) (*dto.Exemplar, error) { } runes += utf8.RuneCountInString(value) labelPairs = append(labelPairs, &dto.LabelPair{ - Name: proto.String(name), - Value: proto.String(value), + Name: new(name), + Value: new(value), }) } if runes > ExemplarMaxRunes { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/wrap.go b/vendor/github.com/prometheus/client_golang/prometheus/wrap.go index 697f55558b..cc9ae8f20b 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/wrap.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/wrap.go @@ -20,7 +20,6 @@ import ( "github.com/prometheus/client_golang/prometheus/internal" dto "github.com/prometheus/client_model/go" - "google.golang.org/protobuf/proto" ) // WrapRegistererWith returns a Registerer wrapping the provided @@ -212,8 +211,8 @@ func (m *wrappingMetric) Write(out *dto.Metric) error { } for ln, lv := range m.labels { out.Label = append(out.Label, &dto.LabelPair{ - Name: proto.String(ln), - Value: proto.String(lv), + Name: new(ln), + Value: new(lv), }) } sort.Sort(internal.LabelPairSorter(out.Label)) diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go index 8f8dc65d38..0339d8c1d0 100644 --- a/vendor/github.com/prometheus/common/expfmt/decode.go +++ b/vendor/github.com/prometheus/common/expfmt/decode.go @@ -72,13 +72,15 @@ func ResponseFormat(h http.Header) Format { // NewDecoder returns a new decoder based on the given input format. Metric // names are validated based on the provided Format -- if the format requires -// escaping, raditional Prometheues validity checking is used. Otherwise, names +// escaping, traditional Prometheus validity checking is used. Otherwise, names // are checked for UTF-8 validity. Supported formats include delimited protobuf -// and Prometheus text format. For historical reasons, this decoder fallbacks -// to classic text decoding for any other format. This decoder does not fully -// support OpenMetrics although it may often succeed due to the similarities -// between the formats. This decoder may not support the latest features of -// Prometheus text format and is not intended for high-performance applications. +// and Prometheus text format. For historical reasons, this decoder falls back +// to classic text decoding for other legacy formats, but returns an error for +// unsupported formats such as OpenMetrics 2.0. This decoder does not fully +// support OpenMetrics although it may often succeed for OpenMetrics 1.0 due to +// the similarities between the formats. This decoder may not support the latest +// features of Prometheus text format and is not intended for high-performance +// applications. // See: https://github.com/prometheus/common/issues/812 func NewDecoder(r io.Reader, format Format) Decoder { scheme := model.LegacyValidation @@ -90,6 +92,11 @@ func NewDecoder(r io.Reader, format Format) Decoder { return &protoDecoder{r: bufio.NewReader(r), s: scheme} case TypeProtoText, TypeProtoCompact: return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)} + case TypeOpenMetrics: + _, params, err := mime.ParseMediaType(string(format)) + if err == nil && params["version"] == OpenMetricsVersion_2_0_0 { + return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)} + } } return &textDecoder{r: r, s: scheme} } diff --git a/vendor/github.com/prometheus/common/expfmt/encode.go b/vendor/github.com/prometheus/common/expfmt/encode.go index 73c24dfbc9..651e69a2c8 100644 --- a/vendor/github.com/prometheus/common/expfmt/encode.go +++ b/vendor/github.com/prometheus/common/expfmt/encode.go @@ -16,7 +16,9 @@ package expfmt import ( "fmt" "io" + "mime" "net/http" + "slices" "github.com/munnerz/goautoneg" dto "github.com/prometheus/client_model/go" @@ -26,6 +28,55 @@ import ( "github.com/prometheus/common/model" ) +var formatToAccept = map[Format]goautoneg.Accept{} + +func init() { + for _, f := range []Format{ + FmtText, + FmtProtoDelim, + FmtProtoText, + FmtProtoCompact, + FmtOpenMetrics_1_0_0, + FmtOpenMetrics_2_0_0, + FmtOpenMetrics_0_0_1, + } { + if parsed := goautoneg.ParseAccept(string(f)); len(parsed) > 0 { + formatToAccept[f] = parsed[0] + } + } +} + +var ( + defaultAcceptedFormats = []Format{ + FmtProtoDelim, + FmtProtoText, + FmtProtoCompact, + FmtText, + } + + defaultOpenMetricsAcceptedFormats = []Format{ + FmtOpenMetrics_1_0_0, + FmtOpenMetrics_0_0_1, + FmtProtoDelim, + FmtProtoText, + FmtProtoCompact, + FmtText, + } +) + +// DefaultAcceptedFormats returns a copy of standard accepted formats for Negotiate, +// ordered by preference (delimited protobuf, protobuf text, compact protobuf text, +// and Prometheus text format). +func DefaultAcceptedFormats() []Format { + return slices.Clone(defaultAcceptedFormats) +} + +// DefaultOpenMetricsAcceptedFormats returns a copy of standard accepted formats including +// stable OpenMetrics formats, ordered by preference. +func DefaultOpenMetricsAcceptedFormats() []Format { + return slices.Clone(defaultOpenMetricsAcceptedFormats) +} + // Encoder types encode metric families into an underlying wire protocol. type Encoder interface { Encode(*dto.MetricFamily) error @@ -57,11 +108,30 @@ func (ec encoderCloser) Close() error { // Negotiate returns the Content-Type based on the given Accept header. If no // appropriate accepted type is found, FmtText is returned (which is the -// Prometheus text format). This function will never negotiate FmtOpenMetrics, -// as the support is still experimental. To include the option to negotiate -// FmtOpenMetrics, use NegotiateIncludingOpenMetrics. +// Prometheus text format). +// +// Deprecated: Use NegotiateAccept(h, DefaultAcceptedFormats()...) +// or specify only the formats supported by your server. func Negotiate(h http.Header) Format { - escapingScheme := Format(fmt.Sprintf("; escaping=%s", Format(model.NameEscapingScheme.String()))) + return NegotiateAccept(h, defaultAcceptedFormats...) +} + +// NegotiateIncludingOpenMetrics works like Negotiate but includes all stable +// FmtOpenMetrics formats as an option for the result. +// +// Deprecated: Use NegotiateAccept(h, DefaultOpenMetricsAcceptedFormats()...) +// or specify only the formats supported by your server. +func NegotiateIncludingOpenMetrics(h http.Header) Format { + return NegotiateAccept(h, defaultOpenMetricsAcceptedFormats...) +} + +// NegotiateAccept returns the Content-Type based on the given Accept header +// and the list of accepted Formats provided by the caller, in order of preference. +// If no accepted format matches the Accept header, it falls back to the text +// format if present in the accepted list, or the first accepted format (or FmtText +// if accepted is empty). +func NegotiateAccept(h http.Header, accepted ...Format) Format { + escapingScheme := Format("; escaping=" + model.NameEscapingScheme.String()) for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) { if escapeParam := ac.Params[model.EscapingKey]; escapeParam != "" { switch Format(escapeParam) { @@ -71,63 +141,66 @@ func Negotiate(h http.Header) Format { // If the escaping parameter is unknown, ignore it. } } - ver := ac.Params["version"] - if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol { - switch ac.Params["encoding"] { - case "delimited": - return FmtProtoDelim + escapingScheme - case "text": - return FmtProtoText + escapingScheme - case "compact-text": - return FmtProtoCompact + escapingScheme + + for _, f := range accepted { + if matchFormat(ac, f) { + return f + escapingScheme } } - if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") { - return FmtText + escapingScheme + } + for _, f := range accepted { + if f.FormatType() == TypeTextPlain { + return f + escapingScheme } } + if len(accepted) > 0 { + return accepted[0] + escapingScheme + } return FmtText + escapingScheme } -// NegotiateIncludingOpenMetrics works like Negotiate but includes -// FmtOpenMetrics as an option for the result. Note that this function is -// temporary and will disappear once FmtOpenMetrics is fully supported and as -// such may be negotiated by the normal Negotiate function. -func NegotiateIncludingOpenMetrics(h http.Header) Format { - escapingScheme := Format(fmt.Sprintf("; escaping=%s", Format(model.NameEscapingScheme.String()))) - for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) { - if escapeParam := ac.Params[model.EscapingKey]; escapeParam != "" { - switch Format(escapeParam) { - case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues: - escapingScheme = Format("; escaping=" + escapeParam) - default: - // If the escaping parameter is unknown, ignore it. - } +// matchFormat checks if a parsed accept clause matches a given Format. +func matchFormat(ac goautoneg.Accept, f Format) bool { + target, ok := formatToAccept[f] + if !ok { + parsed := goautoneg.ParseAccept(string(f)) + if len(parsed) == 0 { + return false } - ver := ac.Params["version"] - if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol { - switch ac.Params["encoding"] { - case "delimited": - return FmtProtoDelim + escapingScheme - case "text": - return FmtProtoText + escapingScheme - case "compact-text": - return FmtProtoCompact + escapingScheme - } + target = parsed[0] + } + + if ac.Type != "*" && ac.Type != target.Type { + return false + } + if ac.SubType != "*" && ac.SubType != target.SubType { + return false + } + + // Default OpenMetrics version to OpenMetricsVersion_0_0_1. + acVersion := ac.Params["version"] + if acVersion == "" && ac.Type+"/"+ac.SubType == OpenMetricsType { + acVersion = OpenMetricsVersion_0_0_1 + } + if acVersion == "" && ac.Type == "text" && ac.SubType == "plain" { + acVersion = TextVersion + } + + // General param matching. + for k, v := range target.Params { + if k == "charset" { + continue } - if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") { - return FmtText + escapingScheme + acVal := ac.Params[k] + if k == "version" { + acVal = acVersion } - if ac.Type+"/"+ac.SubType == OpenMetricsType && (ver == OpenMetricsVersion_0_0_1 || ver == OpenMetricsVersion_1_0_0 || ver == "") { - switch ver { - case OpenMetricsVersion_1_0_0: - return FmtOpenMetrics_1_0_0 + escapingScheme - default: - return FmtOpenMetrics_0_0_1 + escapingScheme - } + if acVal != v { + return false } } - return FmtText + escapingScheme + + return true } // NewEncoder returns a new encoder based on content type negotiation. All @@ -181,6 +254,19 @@ func NewEncoder(w io.Writer, format Format, options ...EncoderOption) Encoder { close: func() error { return nil }, } case TypeOpenMetrics: + _, params, err := mime.ParseMediaType(string(format)) + if err == nil && params["version"] == OpenMetricsVersion_2_0_0 { + return encoderCloser{ + encode: func(v *dto.MetricFamily) error { + _, err := MetricFamilyToOpenMetrics20(w, model.EscapeMetricFamily(v, escapingScheme), options...) + return err + }, + close: func() error { + _, err := FinalizeOpenMetrics(w) + return err + }, + } + } return encoderCloser{ encode: func(v *dto.MetricFamily) error { _, err := MetricFamilyToOpenMetrics(w, model.EscapeMetricFamily(v, escapingScheme), options...) diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go index 10bf35708c..ea9a0a2a04 100644 --- a/vendor/github.com/prometheus/common/expfmt/expfmt.go +++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go @@ -16,50 +16,48 @@ package expfmt import ( "errors" + "mime" "strings" "github.com/prometheus/common/model" ) -// Format specifies the HTTP content type of the different wire protocols. -type Format string - // Constants to assemble the Content-Type values for the different wire -// protocols. The Content-Type strings here are all for the legacy exposition -// formats, where valid characters for metric names and label names are limited. -// Support for arbitrary UTF-8 characters in those names is already partially -// implemented in this module (see model.ValidationScheme), but to actually use -// it on the wire, new content-type strings will have to be agreed upon and -// added here. +// protocols. const ( TextVersion = "0.0.4" ProtoType = `application/vnd.google.protobuf` ProtoProtocol = `io.prometheus.client.MetricFamily` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoCompact) instead. - ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";" + ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";" + OpenMetricsType = `application/openmetrics-text` //nolint:revive // Allow for underscores. OpenMetricsVersion_0_0_1 = "0.0.1" //nolint:revive // Allow for underscores. OpenMetricsVersion_1_0_0 = "1.0.0" + //nolint:revive // Allow for underscores. + OpenMetricsVersion_2_0_0 = "2.0.0" +) - // The Content-Type values for the different wire protocols. Do not do direct - // comparisons to these constants, instead use the comparison functions. - // - // Deprecated: Use expfmt.NewFormat(expfmt.TypeUnknown) instead. - FmtUnknown Format = `` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeTextPlain) instead. - FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoDelim) instead. - FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoText) instead. - FmtProtoText Format = ProtoFmt + ` encoding=text` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoCompact) instead. +// Format specifies the HTTP content type of the different wire protocols. +// The Content-Type values for the different wire protocols represent +// baseline Content-Types used for HTTP headers and content negotiation. +// +// Because Content-Types on the wire may include dynamic parameters +// (such as "; escaping=...") or whitespace variations, avoid comparing Format +// values using direct equality (==). +type Format string + +const ( + FmtUnknown Format = `` + FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8` + FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` + FmtProtoText Format = ProtoFmt + ` encoding=text` FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeOpenMetrics) instead. + //nolint:revive // Allow for underscores. + FmtOpenMetrics_2_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_2_0_0 + `; charset=utf-8` //nolint:revive // Allow for underscores. FmtOpenMetrics_1_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_1_0_0 + `; charset=utf-8` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeOpenMetrics) instead. //nolint:revive // Allow for underscores. FmtOpenMetrics_0_0_1 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_0_0_1 + `; charset=utf-8` ) @@ -86,7 +84,7 @@ const ( // NewFormat generates a new Format from the type provided. Mostly used for // tests, most Formats should be generated as part of content negotiation in -// encode.go. If a type has more than one version, the latest version will be +// encode.go. If a type has more than one version, the latest stable version will be // returned. func NewFormat(t FormatType) Format { switch t { @@ -107,6 +105,9 @@ func NewFormat(t FormatType) Format { // NewOpenMetricsFormat generates a new OpenMetrics format matching the // specified version number. +// +// Note: OpenMetrics version 2.0.0 is experimental and encode-only (supporting +// counter, gauge, summary, untyped, histogram, and gaugehistogram metric types). func NewOpenMetricsFormat(version string) (Format, error) { if version == OpenMetricsVersion_0_0_1 { return FmtOpenMetrics_0_0_1, nil @@ -114,30 +115,22 @@ func NewOpenMetricsFormat(version string) (Format, error) { if version == OpenMetricsVersion_1_0_0 { return FmtOpenMetrics_1_0_0, nil } + if version == OpenMetricsVersion_2_0_0 { + // OpenMetrics 2.0.0 is experimental and encode-only. + return FmtOpenMetrics_2_0_0, nil + } return FmtUnknown, errors.New("unknown open metrics version string") } -// WithEscapingScheme returns a copy of Format with the specified escaping -// scheme appended to the end. If an escaping scheme already exists it is -// removed. -func (f Format) WithEscapingScheme(s model.EscapingScheme) Format { - var terms []string - for p := range strings.SplitSeq(string(f), ";") { - toks := strings.Split(p, "=") - if len(toks) != 2 { - trimmed := strings.TrimSpace(p) - if len(trimmed) > 0 { - terms = append(terms, trimmed) - } - continue - } - key := strings.TrimSpace(toks[0]) - if key != model.EscapingKey { - terms = append(terms, strings.TrimSpace(p)) - } +// Version returns the version parameter without validating whether it is supported. +// It returns an empty string if the parameter is absent or the Content-Type +// cannot be parsed. +func (f Format) Version() string { + _, params, err := mime.ParseMediaType(string(f)) + if err != nil { + return "" } - terms = append(terms, model.EscapingKey+"="+s.String()) - return Format(strings.Join(terms, "; ")) + return params["version"] } // FormatType deduces an overall FormatType for the given format. @@ -189,8 +182,31 @@ func (f Format) FormatType() FormatType { } } -// ToEscapingScheme returns an EscapingScheme depending on the Format. Iff the -// Format contains a escaping=allow-utf-8 term, it will select NoEscaping. If a valid +// WithEscapingScheme returns a copy of Format with the specified escaping +// scheme appended to the end. If an escaping scheme already exists it is +// removed. +func (f Format) WithEscapingScheme(s model.EscapingScheme) Format { + var terms []string + for p := range strings.SplitSeq(string(f), ";") { + toks := strings.Split(p, "=") + if len(toks) != 2 { + trimmed := strings.TrimSpace(p) + if len(trimmed) > 0 { + terms = append(terms, trimmed) + } + continue + } + key := strings.TrimSpace(toks[0]) + if key != model.EscapingKey { + terms = append(terms, strings.TrimSpace(p)) + } + } + terms = append(terms, model.EscapingKey+"="+s.String()) + return Format(strings.Join(terms, "; ")) +} + +// ToEscapingScheme returns an EscapingScheme depending on the Format. IFF the +// Format contains an escaping=allow-utf-8 term, it will select NoEscaping. If a valid // "escaping" term exists, that will be used. Otherwise, the global default will // be returned. func (f Format) ToEscapingScheme() model.EscapingScheme { diff --git a/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go b/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go new file mode 100644 index 0000000000..600ac32f5c --- /dev/null +++ b/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go @@ -0,0 +1,1221 @@ +// Copyright 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 expfmt + +import ( + "bufio" + "errors" + "fmt" + "io" + "math" + "strconv" + "strings" + "unicode/utf8" + + dto "github.com/prometheus/client_model/go" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// MetricFamilyToOpenMetrics20 converts a MetricFamily proto message into the +// OpenMetrics text format version 2.0.0 and writes the resulting lines to 'out'. +// It returns the number of bytes written and any error encountered. +// +// NOTE: This method targets OpenMetrics 2.0.0 (currently aligned with 2.0-rc.0) which is experimental and +// encode-only. All metric types defined in client_model (counter, gauge, summary, untyped, histogram, +// and gaugehistogram) are supported; info and stateset are not supported as they are not present in +// client_model. Breaking changes might happen in the future. +// EncoderOptions are accepted for signature compatibility with +// MetricFamilyToOpenMetrics and are currently ignored. +// +// OpenMetrics 2.0 enforces stricter validation rules defined in the specification +// than Prometheus text or OpenMetrics 1.0 formats (such as requiring non-negative +// count and sum, and non-negative quantile values for summaries). Consequently, +// MetricFamilyToOpenMetrics20 may reject metric families that the other encoders accept. +func MetricFamilyToOpenMetrics20(out io.Writer, in *dto.MetricFamily, options ...EncoderOption) (written int, err error) { + // Options are accepted for signature compatibility and ignored. + _ = options + name := in.GetName() + if name == "" { + return 0, fmt.Errorf("MetricFamily has no name: %s", in) + } + if containsRawNewline(name) { + return 0, fmt.Errorf("MetricFamily name %q contains raw newlines", name) + } + if !utf8.ValidString(name) { + return 0, fmt.Errorf("MetricFamily name %q is not valid UTF-8", name) + } + if in.Help != nil { + if !utf8.ValidString(*in.Help) { + return 0, fmt.Errorf("MetricFamily help %q is not valid UTF-8", *in.Help) + } + // A carriage return may appear in HELP, but not at the end, where it + // would make the line end in "\r\n". + if strings.HasSuffix(*in.Help, "\r") { + return 0, fmt.Errorf("MetricFamily help %q ends with a carriage return", *in.Help) + } + } + if in.Unit != nil { + if containsRawNewline(*in.Unit) { + return 0, fmt.Errorf("MetricFamily unit %q contains raw newlines", *in.Unit) + } + if !utf8.ValidString(*in.Unit) { + return 0, fmt.Errorf("MetricFamily unit %q is not valid UTF-8", *in.Unit) + } + } + + // Try the interface upgrade. If it doesn't work, we'll use a + // bufio.Writer from the sync.Pool. + w, ok := out.(enhancedWriter) + if !ok { + b := bufPool.Get().(*bufio.Writer) + b.Reset(out) + w = b + defer func() { + bErr := b.Flush() + if err == nil { + err = bErr + } + bufPool.Put(b) + }() + } + + var ( + n int + metricType = in.GetType() + ) + + // Comments, first HELP, then TYPE. + if in.Help != nil { + n, err = w.WriteString("# HELP ") + written += n + if err != nil { + return written, err + } + n, err = writeName(w, name) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeEscapedString(w, *in.Help, true) + written += n + if err != nil { + return written, err + } + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + } + n, err = w.WriteString("# TYPE ") + written += n + if err != nil { + return written, err + } + n, err = writeName(w, name) + written += n + if err != nil { + return written, err + } + switch metricType { + case dto.MetricType_COUNTER: + n, err = w.WriteString(" counter\n") + case dto.MetricType_GAUGE: + n, err = w.WriteString(" gauge\n") + case dto.MetricType_SUMMARY: + n, err = w.WriteString(" summary\n") + case dto.MetricType_UNTYPED: + n, err = w.WriteString(" unknown\n") + case dto.MetricType_HISTOGRAM: + n, err = w.WriteString(" histogram\n") + case dto.MetricType_GAUGE_HISTOGRAM: + n, err = w.WriteString(" gaugehistogram\n") + default: + // TODO: Support Info and StateSet once they are supported in the + // Prometheus protobuf format. + return written, fmt.Errorf("unknown metric type %s", metricType.String()) + } + written += n + if err != nil { + return written, err + } + if in.Unit != nil { + n, err = w.WriteString("# UNIT ") + written += n + if err != nil { + return written, err + } + n, err = writeName(w, name) + written += n + if err != nil { + return written, err + } + + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeEscapedString(w, *in.Unit, true) + written += n + if err != nil { + return written, err + } + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + } + + // Finally the samples, one line for each. + for _, metric := range in.Metric { + if metric == nil { + return written, fmt.Errorf("expected non-nil metric in MetricFamily %s", name) + } + switch metricType { + case dto.MetricType_COUNTER: + if metric.Counter == nil { + return written, fmt.Errorf("expected counter in metric %s %s", name, metric) + } + val := metric.Counter.GetValue() + if math.IsNaN(val) { + return written, fmt.Errorf("counter value cannot be NaN in metric %s", name) + } + if val < 0 { + return written, fmt.Errorf("counter value cannot be negative (%g) in metric %s", val, name) + } + n, err = writeOpenMetrics20Sample(w, name, metric, val, 0, false, metric.Counter.CreatedTimestamp, metric.Counter.Exemplar) + case dto.MetricType_GAUGE: + if metric.Gauge == nil { + return written, fmt.Errorf("expected gauge in metric %s %s", name, metric) + } + n, err = writeOpenMetrics20Sample(w, name, metric, metric.Gauge.GetValue(), 0, false, nil, nil) + case dto.MetricType_UNTYPED: + if metric.Untyped == nil { + return written, fmt.Errorf("expected untyped in metric %s %s", name, metric) + } + n, err = writeOpenMetrics20Sample(w, name, metric, metric.Untyped.GetValue(), 0, false, nil, nil) + case dto.MetricType_SUMMARY: + if metric.Summary == nil { + return written, fmt.Errorf("expected summary in metric %s %s", name, metric) + } + n, err = writeCompositeSummary(w, name, metric) + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: + if metric.Histogram == nil { + return written, fmt.Errorf("expected histogram in metric %s %s", name, metric) + } + n, err = writeCompositeHistogram(w, name, metric, metricType == dto.MetricType_GAUGE_HISTOGRAM) + default: + return written, fmt.Errorf("unexpected type in metric %s %s", name, metric) + } + written += n + if err != nil { + return written, err + } + } + return written, nil +} + +// writeOpenMetrics20Sample writes a single sample for simple types (Counter, Gauge, Untyped). +func writeOpenMetrics20Sample(w enhancedWriter, name string, metric *dto.Metric, floatValue float64, intValue uint64, useIntValue bool, startTimestamp *timestamppb.Timestamp, exemplar *dto.Exemplar) (int, error) { + if err := validateLabels20(metric.Label); err != nil { + return 0, err + } + written := 0 + n, err := writeOpenMetricsNameAndLabelPairs(w, name, metric.Label, "", 0) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + + if useIntValue { + n, err = writeUint(w, intValue) + } else { + n, err = writeOpenMetricsFloat(w, floatValue) + } + written += n + if err != nil { + return written, err + } + + if metric.TimestampMs != nil { + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetrics20Timestamp(w, float64(*metric.TimestampMs)/1000) + written += n + if err != nil { + return written, err + } + } + + // Start Timestamp + if startTimestamp != nil { + if err := startTimestamp.CheckValid(); err != nil { + return written, fmt.Errorf("invalid created timestamp in metric %s: %w", name, err) + } + n, err = w.WriteString(" st@") + written += n + if err != nil { + return written, err + } + n, err = writeProtoTimestamp(w, startTimestamp) + written += n + if err != nil { + return written, err + } + } + + if exemplar != nil { + n, err = writeExemplar20(w, exemplar) + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + return written, nil +} + +// writeExemplar20 writes the provided exemplar in OpenMetrics 2.0 format to w. +// In OpenMetrics 2.0, invalid exemplars or exemplars without a timestamp are dropped. +func writeExemplar20(w enhancedWriter, e *dto.Exemplar) (int, error) { + if e == nil { + return 0, nil + } + // In OpenMetrics 2.0, invalid exemplars are dropped rather than failing the entire exposition. + if err := validateExemplar20(e); err != nil { + return 0, nil + } + written := 0 + n, err := w.WriteString(" # ") + written += n + if err != nil { + return written, err + } + if len(e.Label) == 0 { + n, err = w.WriteString("{}") + } else { + n, err = writeOpenMetricsNameAndLabelPairs(w, "", e.Label, "", 0) + } + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetricsFloat(w, e.GetValue()) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + ts := e.Timestamp + n, err = writeProtoTimestamp(w, ts) + written += n + if err != nil { + return written, err + } + return written, nil +} + +// writeOpenMetrics20Timestamp writes a float64 as a timestamp without scientific notation. +func writeOpenMetrics20Timestamp(w enhancedWriter, f float64) (int, error) { + bp := numBufPool.Get().(*[]byte) + *bp = strconv.AppendFloat((*bp)[:0], f, 'f', -1, 64) + written, err := w.Write(*bp) + numBufPool.Put(bp) + return written, err +} + +func writeCompositeSummary(w enhancedWriter, name string, metric *dto.Metric) (int, error) { + s := metric.Summary + if s == nil { + return 0, fmt.Errorf("expected summary in metric %s", name) + } + + if err := validateLabels20(metric.Label); err != nil { + return 0, err + } + for _, lp := range metric.Label { + if lp.GetName() == "quantile" { + return 0, fmt.Errorf("metric %s is a summary but label set contains %q label", name, "quantile") + } + } + + sum := s.GetSampleSum() + if math.IsNaN(sum) { + return 0, fmt.Errorf("summary sum cannot be NaN in metric %s", name) + } + if sum < 0 { + return 0, fmt.Errorf("summary sum cannot be negative (%g) in metric %s", sum, name) + } + + var prevQuantile float64 + for i, q := range s.Quantile { + if q == nil { + return 0, fmt.Errorf("expected non-nil quantile in metric %s", name) + } + qv := q.GetQuantile() + if math.IsNaN(qv) { + return 0, fmt.Errorf("summary quantile cannot be NaN in metric %s", name) + } + if qv < 0 || qv > 1 { + return 0, fmt.Errorf("summary quantile %g must be between 0 and 1 in metric %s", qv, name) + } + if i > 0 && qv <= prevQuantile { + return 0, fmt.Errorf("summary quantiles must be strictly increasing: %g <= %g in metric %s", qv, prevQuantile, name) + } + prevQuantile = qv + + v := q.GetValue() + if !math.IsNaN(v) && v < 0 { + return 0, fmt.Errorf("summary quantile value cannot be negative (%g) in metric %s", v, name) + } + } + + if s.CreatedTimestamp != nil { + if err := s.CreatedTimestamp.CheckValid(); err != nil { + return 0, fmt.Errorf("invalid created timestamp in metric %s: %w", name, err) + } + } + + written := 0 + n, err := writeOpenMetricsNameAndLabelPairs(w, name, metric.Label, "", 0) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(" {count:") + written += n + if err != nil { + return written, err + } + + n, err = writeUint(w, s.GetSampleCount()) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(",sum:") + written += n + if err != nil { + return written, err + } + + n, err = writeFloat(w, sum) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(",quantile:[") + written += n + if err != nil { + return written, err + } + + for i, q := range s.Quantile { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = writeFloat(w, q.GetQuantile()) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(':') + written++ + if err != nil { + return written, err + } + n, err = writeFloat(w, q.GetValue()) + written += n + if err != nil { + return written, err + } + } + + n, err = w.WriteString("]}") + written += n + if err != nil { + return written, err + } + + if metric.TimestampMs != nil { + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetrics20Timestamp(w, float64(*metric.TimestampMs)/1000) + written += n + if err != nil { + return written, err + } + } + + if s.CreatedTimestamp != nil { + n, err = w.WriteString(" st@") + written += n + if err != nil { + return written, err + } + n, err = writeProtoTimestamp(w, s.CreatedTimestamp) + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + + return written, nil +} + +func writeCompositeHistogram(w enhancedWriter, name string, metric *dto.Metric, isGauge bool) (int, error) { + h := metric.Histogram + if h == nil { + return 0, fmt.Errorf("expected histogram in metric %s", name) + } + + isNative := h.Schema != nil + hasClassicBuckets := len(h.Bucket) > 0 || !isNative + + if err := validateLabels20(metric.Label); err != nil { + return 0, err + } + if hasClassicBuckets { + for _, lp := range metric.Label { + if lp.GetName() == "le" { + return 0, fmt.Errorf("metric %s has classic buckets but label set contains %q label", name, "le") + } + } + } + + if h.SampleCountFloat != nil { + c := *h.SampleCountFloat + if math.IsNaN(c) { + if isGauge { + return 0, fmt.Errorf("gaugehistogram count cannot be NaN in metric %s", name) + } + return 0, fmt.Errorf("histogram count cannot be NaN in metric %s", name) + } + if !isGauge && c < 0 { + return 0, fmt.Errorf("histogram count cannot be negative (%g) in metric %s", c, name) + } + } + + var isFloatCount bool + var sampleCountFloat float64 + var sampleCountUint uint64 + switch { + case h.SampleCountFloat != nil && (*h.SampleCountFloat > 0 || h.SampleCount == nil || isGauge): + isFloatCount = true + sampleCountFloat = *h.SampleCountFloat + case h.SampleCount != nil: + sampleCountUint = *h.SampleCount + sampleCountFloat = float64(sampleCountUint) + } + + if isNative { + if err := validateNativeHistogram(name, h, isGauge); err != nil { + return 0, err + } + } + + if hasClassicBuckets { + if err := validateClassicBuckets(name, h, sampleCountFloat, sampleCountUint, isFloatCount, isGauge); err != nil { + return 0, err + } + } + + if !isGauge && h.CreatedTimestamp != nil { + if err := h.CreatedTimestamp.CheckValid(); err != nil { + return 0, fmt.Errorf("invalid created timestamp in metric %s: %w", name, err) + } + } + + written := 0 + n, err := writeOpenMetricsNameAndLabelPairs(w, name, metric.Label, "", 0) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(" {") + written += n + if err != nil { + return written, err + } + + if isGauge { + n, err = w.WriteString("gcount:") + } else { + n, err = w.WriteString("count:") + } + written += n + if err != nil { + return written, err + } + + if isFloatCount { + n, err = writeFloat(w, sampleCountFloat) + } else { + n, err = writeUint(w, sampleCountUint) + } + written += n + if err != nil { + return written, err + } + + if isGauge { + n, err = w.WriteString(",gsum:") + } else { + n, err = w.WriteString(",sum:") + } + written += n + if err != nil { + return written, err + } + n, err = writeFloat(w, h.GetSampleSum()) + written += n + if err != nil { + return written, err + } + + if isNative { + n, err = writeNativeBuckets(w, h, isGauge) + written += n + if err != nil { + return written, err + } + } + + var classicExemplars []*dto.Exemplar + if hasClassicBuckets { + n, err = writeClassicBuckets(w, h, sampleCountFloat, sampleCountUint, isFloatCount, isGauge, &classicExemplars) + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte('}') + written++ + if err != nil { + return written, err + } + + if metric.TimestampMs != nil { + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetrics20Timestamp(w, float64(*metric.TimestampMs)/1000) + written += n + if err != nil { + return written, err + } + } + + if !isGauge && h.CreatedTimestamp != nil { + ts := h.CreatedTimestamp + n, err = w.WriteString(" st@") + written += n + if err != nil { + return written, err + } + n, err = writeProtoTimestamp(w, ts) + written += n + if err != nil { + return written, err + } + } + + var exemplarsToEmit []*dto.Exemplar + if len(classicExemplars) > 0 { + // We follow the spec suggestion and prefer classic histogram + // exemplars in dual mode. + exemplarsToEmit = classicExemplars + } else if len(h.Exemplars) > 0 { + exemplarsToEmit = h.Exemplars + } + + for _, e := range exemplarsToEmit { + if e == nil || e.Timestamp == nil { + continue + } + n, err = writeExemplar20(w, e) + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + + return written, nil +} + +func validateNativeHistogram(name string, h *dto.Histogram, isGauge bool) error { + schema := *h.Schema + if schema < -4 || schema > 8 { + return fmt.Errorf("native histogram schema %d is out of range [-4, 8] in metric %s", schema, name) + } + + zeroThreshold := h.GetZeroThreshold() + if math.IsNaN(zeroThreshold) || math.IsInf(zeroThreshold, 0) || zeroThreshold < 0 { + return fmt.Errorf("native histogram zero_threshold %g must be a non-negative, finite number in metric %s", zeroThreshold, name) + } + + if h.ZeroCountFloat != nil { + c := *h.ZeroCountFloat + if math.IsNaN(c) { + return fmt.Errorf("native histogram zero_count cannot be NaN in metric %s", name) + } + if !isGauge && c < 0 { + return fmt.Errorf("native histogram zero_count cannot be negative (%g) in metric %s", c, name) + } + } + + if err := validateSpansAndBuckets(name, "negative", h.NegativeSpan, h.NegativeDelta, h.NegativeCount, isGauge); err != nil { + return err + } + return validateSpansAndBuckets(name, "positive", h.PositiveSpan, h.PositiveDelta, h.PositiveCount, isGauge) +} + +func validateSpansAndBuckets( + name string, + spanName string, + spans []*dto.BucketSpan, + deltas []int64, + floatCounts []float64, + isGauge bool, +) error { + isFloatBuckets := len(floatCounts) > 0 + var numBuckets int + if isFloatBuckets { + numBuckets = len(floatCounts) + } else { + numBuckets = len(deltas) + } + + var totalLength uint64 + for i, span := range spans { + if span == nil { + return errors.New("expected non-nil bucket span") + } + if i > 0 && span.GetOffset() < 0 { + return fmt.Errorf("subsequent %s span offset cannot be negative: %d in metric %s", spanName, span.GetOffset(), name) + } + totalLength += uint64(span.GetLength()) + } + + if numBuckets == 0 { + if totalLength == 0 { + return nil + } + return fmt.Errorf("sum of %s span lengths (%d) does not match bucket count (0) in metric %s", spanName, totalLength, name) + } + + if totalLength != uint64(numBuckets) { + return fmt.Errorf("sum of %s span lengths (%d) does not match bucket count (%d) in metric %s", spanName, totalLength, numBuckets, name) + } + + if isFloatBuckets { + for _, v := range floatCounts { + if math.IsNaN(v) { + return fmt.Errorf("%s bucket count cannot be NaN in metric %s", spanName, name) + } + if !isGauge && v < 0 { + return fmt.Errorf("%s bucket count cannot be negative (%g) in metric %s", spanName, v, name) + } + } + } else { + var current int64 + for _, d := range deltas { + current += d + if !isGauge && current < 0 { + return fmt.Errorf("%s bucket count cannot be negative (%d) in metric %s", spanName, current, name) + } + } + } + return nil +} + +func writeNativeBuckets(w enhancedWriter, h *dto.Histogram, isGauge bool) (int, error) { + schema := *h.Schema + zeroThreshold := h.GetZeroThreshold() + + var isFloatZeroCount bool + var zeroCountFloat float64 + var zeroCountUint uint64 + switch { + case h.ZeroCountFloat != nil && (*h.ZeroCountFloat > 0 || h.ZeroCount == nil || isGauge): + isFloatZeroCount = true + zeroCountFloat = *h.ZeroCountFloat + case h.ZeroCount != nil: + zeroCountUint = *h.ZeroCount + zeroCountFloat = float64(zeroCountUint) + } + + written := 0 + n, err := w.WriteString(",schema:") + written += n + if err != nil { + return written, err + } + n, err = writeInt(w, int64(schema)) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(",zero_threshold:") + written += n + if err != nil { + return written, err + } + n, err = writeFloat(w, zeroThreshold) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(",zero_count:") + written += n + if err != nil { + return written, err + } + if isFloatZeroCount { + n, err = writeFloat(w, zeroCountFloat) + } else { + n, err = writeUint(w, zeroCountUint) + } + written += n + if err != nil { + return written, err + } + + n, err = writeSpansAndBuckets(w, ",negative_spans:[", ",negative_buckets:[", h.NegativeSpan, h.NegativeDelta, h.NegativeCount) + written += n + if err != nil { + return written, err + } + + n, err = writeSpansAndBuckets(w, ",positive_spans:[", ",positive_buckets:[", h.PositiveSpan, h.PositiveDelta, h.PositiveCount) + written += n + if err != nil { + return written, err + } + + return written, nil +} + +func writeSpansAndBuckets( + w enhancedWriter, + spansPrefix string, + bucketsPrefix string, + spans []*dto.BucketSpan, + deltas []int64, + floatCounts []float64, +) (int, error) { + isFloatBuckets := len(floatCounts) > 0 + var numBuckets int + if isFloatBuckets { + numBuckets = len(floatCounts) + } else { + numBuckets = len(deltas) + } + + if numBuckets == 0 { + return 0, nil + } + + written := 0 + n, err := w.WriteString(spansPrefix) + written += n + if err != nil { + return written, err + } + for i, span := range spans { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = writeInt(w, int64(span.GetOffset())) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(':') + written++ + if err != nil { + return written, err + } + n, err = writeUint(w, uint64(span.GetLength())) + written += n + if err != nil { + return written, err + } + } + err = w.WriteByte(']') + written++ + if err != nil { + return written, err + } + + n, err = w.WriteString(bucketsPrefix) + written += n + if err != nil { + return written, err + } + if isFloatBuckets { + for i, v := range floatCounts { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = writeFloat(w, v) + written += n + if err != nil { + return written, err + } + } + } else { + var current int64 + for i, d := range deltas { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + current += d + n, err = writeInt(w, current) + written += n + if err != nil { + return written, err + } + } + } + err = w.WriteByte(']') + written++ + if err != nil { + return written, err + } + + return written, nil +} + +func validateClassicBuckets( + name string, + h *dto.Histogram, + sampleCount float64, + sampleCountUint uint64, + isFloatCount bool, + isGauge bool, +) error { + var infSeen bool + var prevBound float64 + var prevCount float64 + for i, b := range h.Bucket { + if b == nil { + return errors.New("expected non-nil bucket") + } + ub := b.GetUpperBound() + if math.IsNaN(ub) { + return fmt.Errorf("classic bucket upper bound cannot be NaN in metric %s", name) + } + if i > 0 && ub <= prevBound { + return fmt.Errorf("classic bucket upper bounds must be strictly increasing: %g <= %g in metric %s", ub, prevBound, name) + } + prevBound = ub + + if b.CumulativeCountFloat != nil { + c := *b.CumulativeCountFloat + if math.IsNaN(c) { + return fmt.Errorf("classic bucket count cannot be NaN in metric %s", name) + } + if !isGauge && c < 0 { + return fmt.Errorf("classic bucket count cannot be negative (%g) in metric %s", c, name) + } + } + + var bCount float64 + switch { + case b.CumulativeCountFloat != nil && (*b.CumulativeCountFloat > 0 || b.CumulativeCount == nil || isGauge): + bCount = *b.CumulativeCountFloat + case b.CumulativeCount != nil: + bCount = float64(*b.CumulativeCount) + } + + if !isGauge && i > 0 && bCount < prevCount { + return fmt.Errorf("classic bucket counts must be monotonically increasing: %g < %g in metric %s", bCount, prevCount, name) + } + prevCount = bCount + + if math.IsInf(ub, +1) { + if i != len(h.Bucket)-1 { + return fmt.Errorf("+Inf bucket must be the last bucket in metric %s", name) + } + infSeen = true + if isFloatCount { + if bCount != sampleCount { + return fmt.Errorf("classic bucket +Inf count (%g) does not match sample count (%g) in metric %s", bCount, sampleCount, name) + } + } else { + if b.CumulativeCount != nil { + if *b.CumulativeCount != sampleCountUint { + return fmt.Errorf("classic bucket +Inf count (%d) does not match sample count (%d) in metric %s", *b.CumulativeCount, sampleCountUint, name) + } + } else { + if bCount < 0 || bCount > math.MaxUint64 || uint64(bCount) != sampleCountUint || float64(uint64(bCount)) != bCount { + return fmt.Errorf("classic bucket +Inf count (%g) does not match sample count (%d) in metric %s", bCount, sampleCountUint, name) + } + } + } + } + } + + if !infSeen && len(h.Bucket) > 0 && !isGauge { + if sampleCount < prevCount { + return fmt.Errorf("sample count (%g) is less than highest bucket count (%g) in metric %s", sampleCount, prevCount, name) + } + } + return nil +} + +func writeClassicBuckets( + w enhancedWriter, + h *dto.Histogram, + sampleCount float64, + sampleCountUint uint64, + isFloatCount bool, + isGauge bool, + collectedExemplars *[]*dto.Exemplar, +) (int, error) { + var infSeen bool + written := 0 + n, err := w.WriteString(",bucket:[") + written += n + if err != nil { + return written, err + } + + for i, b := range h.Bucket { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = writeFloat(w, b.GetUpperBound()) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(':') + written++ + if err != nil { + return written, err + } + switch { + case b.CumulativeCountFloat != nil && (*b.CumulativeCountFloat > 0 || b.CumulativeCount == nil || isGauge): + n, err = writeFloat(w, *b.CumulativeCountFloat) + case b.CumulativeCount != nil: + n, err = writeUint(w, *b.CumulativeCount) + default: + n, err = writeUint(w, 0) + } + written += n + if err != nil { + return written, err + } + if math.IsInf(b.GetUpperBound(), +1) { + infSeen = true + } + if b.Exemplar != nil && b.Exemplar.Timestamp != nil { + *collectedExemplars = append(*collectedExemplars, b.Exemplar) + } + } + + if !infSeen { + if len(h.Bucket) > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = w.WriteString("+Inf:") + written += n + if err != nil { + return written, err + } + if isFloatCount { + n, err = writeFloat(w, sampleCount) + } else { + n, err = writeUint(w, sampleCountUint) + } + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte(']') + written++ + if err != nil { + return written, err + } + + return written, nil +} + +func validateLabels20(labels []*dto.LabelPair) error { + for _, lp := range labels { + if lp == nil { + return errors.New("expected non-nil label pair") + } + lname := lp.GetName() + if lname == "" { + return errors.New("label name cannot be empty") + } + if containsRawNewline(lname) { + return fmt.Errorf("label name %q contains raw newlines", lname) + } + } + return nil +} + +func containsRawNewline(s string) bool { + return strings.IndexByte(s, '\n') >= 0 || strings.IndexByte(s, '\r') >= 0 +} + +func validateExemplar20(e *dto.Exemplar) error { + if e.Timestamp == nil { + return errors.New("exemplar timestamp is required") + } + if err := e.Timestamp.CheckValid(); err != nil { + return err + } + return validateLabels20(e.Label) +} + +func writeProtoTimestamp(w enhancedWriter, ts *timestamppb.Timestamp) (int, error) { + if err := ts.CheckValid(); err != nil { + return 0, err + } + if ts.Nanos == 0 { + return writeInt(w, ts.Seconds) + } + sec := ts.Seconds + nanos := int64(ts.Nanos) + if sec < 0 { + sec++ + nanos = 1_000_000_000 - nanos + if sec == 0 { + n, err := w.WriteString("-0") + if err != nil { + return n, err + } + n2, err := writeNanos(w, nanos) + return n + n2, err + } + } + + n, err := writeInt(w, sec) + if err != nil { + return n, err + } + n2, err := writeNanos(w, nanos) + return n + n2, err +} + +func writeNanos(w enhancedWriter, nanos int64) (int, error) { + err := w.WriteByte('.') + if err != nil { + return 0, err + } + written := 1 + bp := numBufPool.Get().(*[]byte) + *bp = strconv.AppendInt((*bp)[:0], nanos, 10) + pad := 9 - len(*bp) + for range pad { + err = w.WriteByte('0') + written++ + if err != nil { + numBufPool.Put(bp) + return written, err + } + } + val := *bp + for len(val) > 0 && val[len(val)-1] == '0' { + val = val[:len(val)-1] + } + n2, err := w.Write(val) + written += n2 + numBufPool.Put(bp) + return written, err +} diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go index 4ce1f40b81..10529300f4 100644 --- a/vendor/github.com/prometheus/common/expfmt/text_parse.go +++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go @@ -194,6 +194,7 @@ func (p *TextParser) reset(in io.Reader) { // start of a line (or whitespace leading up to it). func (p *TextParser) startOfLine() stateFn { p.lineCount++ + p.currentMetric = nil p.currentMetricIsInsideBraces = false p.currentMetricInsideBracesIsPresent = false if p.skipBlankTab(); p.err != nil { @@ -339,12 +340,11 @@ func (p *TextParser) startLabelName() stateFn { return nil // Unexpected end of input. } if p.currentByte == '}' { - if p.currentMF == nil { + if p.currentMetric == nil { // The closing brace was reached before any metric name was read, // e.g. for the input "{}". There is no metric to attach labels to, // so this is a malformed exposition. This mirrors the guard in - // startLabelValue. currentMF (not currentMetric) is checked because - // reset only clears currentMF between parses. + // startLabelValue. currentMetric is cleared at the start of each line. p.parseError("invalid metric name") p.currentLabelPairs = nil return nil @@ -495,7 +495,7 @@ func (p *TextParser) startLabelValue() stateFn { return p.startLabelName case '}': - if p.currentMF == nil { + if p.currentMetric == nil { p.parseError("invalid metric name") return nil } diff --git a/vendor/github.com/prometheus/common/model/signature.go b/vendor/github.com/prometheus/common/model/signature.go index dc8a0026c4..b723e3bb2d 100644 --- a/vendor/github.com/prometheus/common/model/signature.go +++ b/vendor/github.com/prometheus/common/model/signature.go @@ -14,7 +14,7 @@ package model import ( - "sort" + "slices" ) // SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is @@ -37,7 +37,7 @@ func LabelsToSignature(labels map[string]string) uint64 { for labelName := range labels { labelNames = append(labelNames, labelName) } - sort.Strings(labelNames) + slices.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { @@ -60,7 +60,7 @@ func labelSetToFingerprint(ls LabelSet) Fingerprint { for labelName := range ls { labelNames = append(labelNames, labelName) } - sort.Sort(labelNames) + slices.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { @@ -100,7 +100,7 @@ func SignatureForLabels(m Metric, labels ...LabelName) uint64 { return emptyLabelSignature } - sort.Sort(LabelNames(labels)) + slices.Sort(labels) sum := hashNew() for _, label := range labels { @@ -129,7 +129,7 @@ func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64 { if len(labelNames) == 0 { return emptyLabelSignature } - sort.Sort(labelNames) + slices.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { diff --git a/vendor/github.com/prometheus/common/model/time.go b/vendor/github.com/prometheus/common/model/time.go index 0854753f4a..9860717422 100644 --- a/vendor/github.com/prometheus/common/model/time.go +++ b/vendor/github.com/prometheus/common/model/time.go @@ -164,6 +164,34 @@ func (t *Time) UnmarshalJSON(b []byte) error { // This type should not propagate beyond the scope of input/output processing. type Duration time.Duration +// Common durations. Day and Week are included because ParseDuration supports +// those units (unlike the standard time package). +// +// To count the number of units in a Duration, divide: +// +// second := model.Second +// fmt.Print(int64(second/model.Millisecond)) // prints 1000 +// +// To convert an integer number of units to a Duration, multiply: +// +// seconds := 10 +// fmt.Print(model.Duration(seconds)*model.Second) // prints 10s +const ( + Nanosecond Duration = 1 + Microsecond = 1000 * Nanosecond + Millisecond = 1000 * Microsecond + Second = 1000 * Millisecond + Minute = 60 * Second + Hour = 60 * Minute + Day = 24 * Hour + Week = 7 * Day +) + +// Milliseconds returns the duration as an integer millisecond count. +// Prometheus stores timestamps in milliseconds; time.Duration already +// covers the other units. +func (d Duration) Milliseconds() int64 { return time.Duration(d).Milliseconds() } + // Set implements pflag/flag.Value. func (d *Duration) Set(s string) error { var err error diff --git a/vendor/github.com/prometheus/common/model/value.go b/vendor/github.com/prometheus/common/model/value.go index 8dffd9c4a5..eed5c9ef3b 100644 --- a/vendor/github.com/prometheus/common/model/value.go +++ b/vendor/github.com/prometheus/common/model/value.go @@ -224,28 +224,6 @@ func (ss SampleStream) MarshalJSON() ([]byte, error) { } } -func (ss *SampleStream) UnmarshalJSON(b []byte) error { - v := struct { - Metric Metric `json:"metric"` - Values []SamplePair `json:"values"` - Histograms []SampleHistogramPair `json:"histograms"` - }{ - Metric: ss.Metric, - Values: ss.Values, - Histograms: ss.Histograms, - } - - if err := json.Unmarshal(b, &v); err != nil { - return err - } - - ss.Metric = v.Metric - ss.Values = v.Values - ss.Histograms = v.Histograms - - return nil -} - // Scalar is a scalar value evaluated at the set timestamp. type Scalar struct { Value SampleValue `json:"value"` diff --git a/vendor/github.com/prometheus/common/model/value_float127.go b/vendor/github.com/prometheus/common/model/value_float127.go new file mode 100644 index 0000000000..821cc1e725 --- /dev/null +++ b/vendor/github.com/prometheus/common/model/value_float127.go @@ -0,0 +1,70 @@ +// Copyright 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. + +//go:build go1.27 + +package model + +import ( + "bytes" + "encoding/json/jsontext" + "errors" +) + +var nullBytes = []byte("null") + +func (s *SamplePair) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() == jsontext.KindNull { + return nil + } else if t.Kind() != jsontext.KindBeginArray { + return errors.New("expected [") + } + + // Loop until we see the end of the array (tolerate arrays of any length). + for i := 0; dec.PeekKind() != jsontext.KindEndArray; i++ { + switch i { + case 0: + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Timestamp.UnmarshalJSON(v); err != nil { + return err + } + case 1: + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Value.UnmarshalJSON(v); err != nil { + return err + } + default: + // Skip any remaining array items to match UnmarshalJSON behavior. + if err := dec.SkipValue(); err != nil { + return err + } + } + } + + // Read the final end array token. + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindEndArray { + return errors.New("expected ]") + } + + return nil +} diff --git a/vendor/github.com/prometheus/common/model/value_histogram127.go b/vendor/github.com/prometheus/common/model/value_histogram127.go new file mode 100644 index 0000000000..fbcfb3f94f --- /dev/null +++ b/vendor/github.com/prometheus/common/model/value_histogram127.go @@ -0,0 +1,95 @@ +// Copyright 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. + +//go:build go1.27 + +package model + +import ( + "bytes" + "encoding/json/jsontext" + "encoding/json/v2" + "errors" +) + +func (s *SampleHistogramPair) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindBeginArray { + return errors.New("expected [") + } + + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Timestamp.UnmarshalJSON(v); err != nil { + return err + } + + if err := json.UnmarshalDecode(dec, &s.Histogram); err != nil { + return err + } else if s.Histogram == nil { + return errors.New("histogram is nil") + } + + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindEndArray { + return errors.New("expected ]") + } + return nil +} + +func (s *HistogramBucket) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindBeginArray { + return errors.New("expected [") + } + + if err := json.UnmarshalDecode(dec, &s.Boundaries); err != nil { + return err + } + + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Lower.UnmarshalJSON(v); err != nil { + return err + } + + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Upper.UnmarshalJSON(v); err != nil { + return err + } + + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Count.UnmarshalJSON(v); err != nil { + return err + } + + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindEndArray { + return errors.New("expected ]") + } + return nil +} diff --git a/vendor/github.com/prometheus/procfs/.golangci.yml b/vendor/github.com/prometheus/procfs/.golangci.yml index eac920ba80..23ecd4505b 100644 --- a/vendor/github.com/prometheus/procfs/.golangci.yml +++ b/vendor/github.com/prometheus/procfs/.golangci.yml @@ -34,14 +34,6 @@ linters: capital: true misspell: locale: US - revive: - rules: - - name: var-naming - # TODO(SuperQ): See: https://github.com/prometheus/prometheus/issues/17766 - arguments: - - [] - - [] - - - skip-package-name-checks: true exclusions: presets: - comments diff --git a/vendor/github.com/prometheus/procfs/CONTRIBUTING.md b/vendor/github.com/prometheus/procfs/CONTRIBUTING.md index 853eb9d49b..812a71bb97 100644 --- a/vendor/github.com/prometheus/procfs/CONTRIBUTING.md +++ b/vendor/github.com/prometheus/procfs/CONTRIBUTING.md @@ -96,7 +96,7 @@ The `proc` and `sys` filesystems are pseudo file systems and work a bit differen Many of the files are changing continuously and the data being read can in some cases change between subsequent reads in the same file. Also, most of the files are relatively small (less than a few KBs), and system calls to the `stat` function will often return the wrong size. Therefore, for most files it's recommended to read the -full file in a single operation using an internal utility function called `util.ReadFileNoStat`. +full file in a single operation using an internal utility function called `parsers.ReadFileNoStat`. This function is similar to `os.ReadFile`, but it avoids the system call to `stat` to get the current size of the file. @@ -104,7 +104,7 @@ Note that parsing the file's contents can still be performed one line at a time. the full file, and then using a scanner on the `[]byte` or `string` containing the data. ``` - data, err := util.ReadFileNoStat("/proc/cpuinfo") + data, err := parsers.ReadFileNoStat("/proc/cpuinfo") if err != nil { return err } @@ -113,9 +113,9 @@ the full file, and then using a scanner on the `[]byte` or `string` containing t ``` The `/sys` filesystem contains many very small files which contain only a single numeric or text value. These files -can be read using an internal function called `util.SysReadFile` which is similar to `os.ReadFile` but does +can be read using an internal function called `parsers.SysReadFile` which is similar to `os.ReadFile` but does not bother to check the size of the file before reading. ``` - data, err := util.SysReadFile("/sys/class/power_supply/BAT0/capacity") + data, err := parsers.SysReadFile("/sys/class/power_supply/BAT0/capacity") ``` diff --git a/vendor/github.com/prometheus/procfs/Makefile.common b/vendor/github.com/prometheus/procfs/Makefile.common index a7c5f553e1..cd54cb419c 100644 --- a/vendor/github.com/prometheus/procfs/Makefile.common +++ b/vendor/github.com/prometheus/procfs/Makefile.common @@ -61,7 +61,7 @@ PROMU_URL := https://github.com/prometheus/promu/releases/download/v$(PROMU_ SKIP_GOLANGCI_LINT := GOLANGCI_LINT := GOLANGCI_LINT_OPTS ?= -GOLANGCI_LINT_VERSION ?= v2.11.4 +GOLANGCI_LINT_VERSION ?= v2.12.2 GOLANGCI_FMT_OPTS ?= # golangci-lint only supports linux, darwin and windows platforms on i386/amd64/arm64. # windows isn't included here because of the path separator being different. @@ -165,8 +165,9 @@ common-deps: .PHONY: update-go-deps update-go-deps: @echo ">> updating Go dependencies" + # GOTOOLCHAIN prevents go get from pulling deps that require a newer Go version. @for m in $$($(GO) list -mod=readonly -m -f '{{ if and (not .Indirect) (not .Main)}}{{.Path}}{{end}}' all); do \ - $(GO) get $$m; \ + GOTOOLCHAIN=go$$($(GO) mod edit -json | jq -r .Go) $(GO) get $$m; \ done $(GO) mod tidy @@ -246,6 +247,7 @@ common-docker-repo-name: .PHONY: common-docker $(BUILD_DOCKER_ARCHS) common-docker: $(BUILD_DOCKER_ARCHS) +# DOCKER_ARCHS holds promu architecture names, which are not OCI platform strings. $(BUILD_DOCKER_ARCHS): common-docker-%: @for variant in $(DOCKERFILE_VARIANTS_WITH_NAMES); do \ dockerfile=$${variant#*:}; \ @@ -254,10 +256,16 @@ $(BUILD_DOCKER_ARCHS): common-docker-%: if [ "$*" = "armv7" ]; then \ distroless_arch="arm"; \ fi; \ + arch="$*"; \ + case "$$arch" in \ + armv*) docker_platform="linux/arm/v$${arch#armv}";; \ + *) docker_platform="linux/$$arch";; \ + esac; \ if [ "$$dockerfile" = "Dockerfile" ]; then \ echo "Building default variant ($$variant_name) for linux-$* using $$dockerfile"; \ docker build -t "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)" \ -f $$dockerfile \ + --platform "$$docker_platform" \ --build-arg ARCH="$*" \ --build-arg OS="linux" \ --build-arg DISTROLESS_ARCH="$$distroless_arch" \ @@ -271,6 +279,7 @@ $(BUILD_DOCKER_ARCHS): common-docker-%: echo "Building $$variant_name variant for linux-$* using $$dockerfile"; \ docker build -t "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name" \ -f $$dockerfile \ + --platform "$$docker_platform" \ --build-arg ARCH="$*" \ --build-arg OS="linux" \ --build-arg DISTROLESS_ARCH="$$distroless_arch" \ diff --git a/vendor/github.com/prometheus/procfs/cmdline.go b/vendor/github.com/prometheus/procfs/cmdline.go index 4f1cac1f0a..6a2e7bb0ec 100644 --- a/vendor/github.com/prometheus/procfs/cmdline.go +++ b/vendor/github.com/prometheus/procfs/cmdline.go @@ -16,12 +16,12 @@ package procfs import ( "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // CmdLine returns the command line of the kernel. func (fs FS) CmdLine() ([]string, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("cmdline")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("cmdline")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/cpuinfo.go b/vendor/github.com/prometheus/procfs/cpuinfo.go index 4b23d8d6b5..7a31a4555b 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo.go @@ -24,7 +24,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // CPUInfo contains general information about a system CPU found in /proc/cpuinfo. @@ -65,7 +65,7 @@ var ( // CPUInfo returns information about current system CPUs. // See https://www.kernel.org/doc/Documentation/filesystems/proc.txt func (fs FS) CPUInfo() ([]CPUInfo, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("cpuinfo")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("cpuinfo")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/crypto.go b/vendor/github.com/prometheus/procfs/crypto.go index d93b712e05..c4ba05b15a 100644 --- a/vendor/github.com/prometheus/procfs/crypto.go +++ b/vendor/github.com/prometheus/procfs/crypto.go @@ -20,7 +20,7 @@ import ( "io" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Crypto holds info parsed from /proc/crypto. @@ -55,7 +55,7 @@ var cryptoFile = "crypto" // https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html func (fs FS) Crypto() ([]Crypto, error) { path := fs.proc.Path(cryptoFile) - b, err := util.ReadFileNoStat(path) + b, err := parsers.ReadFileNoStat(path) if err != nil { return nil, fmt.Errorf("%w: Cannot read file %v: %w", ErrFileRead, b, err) @@ -112,7 +112,7 @@ func parseCrypto(r io.Reader) ([]Crypto, error) { // parseKV parses a key/value pair into the appropriate field of c. func (c *Crypto) parseKV(k, v string) error { - vp := util.NewValueParser(v) + vp := parsers.NewValueParser(v) switch k { case "async": diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go index 0bef25bdd9..fc16802dcb 100644 --- a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go +++ b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go @@ -15,8 +15,8 @@ package procfs -// isRealProc returns true on architectures that don't have a Type argument +// isRealProc returns false on architectures that don't have a Type argument // in their Statfs_t struct. func isRealProc(_ string) (bool, error) { - return true, nil + return false, nil } diff --git a/vendor/github.com/prometheus/procfs/fscache.go b/vendor/github.com/prometheus/procfs/fscache.go index 9dde857073..388295cb46 100644 --- a/vendor/github.com/prometheus/procfs/fscache.go +++ b/vendor/github.com/prometheus/procfs/fscache.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Fscacheinfo represents fscache statistics. @@ -229,7 +229,7 @@ type Fscacheinfo struct { // Fscacheinfo returns information about current fscache statistics. // See https://www.kernel.org/doc/Documentation/filesystems/caching/fscache.txt func (fs FS) Fscacheinfo() (Fscacheinfo, error) { - b, err := util.ReadFileNoStat(fs.proc.Path("fs/fscache/stats")) + b, err := parsers.ReadFileNoStat(fs.proc.Path("fs/fscache/stats")) if err != nil { return Fscacheinfo{}, err } diff --git a/vendor/github.com/prometheus/procfs/internal/fs/fs.go b/vendor/github.com/prometheus/procfs/internal/fs/fs.go index e7ccad66b2..bdd8010a48 100644 --- a/vendor/github.com/prometheus/procfs/internal/fs/fs.go +++ b/vendor/github.com/prometheus/procfs/internal/fs/fs.go @@ -31,6 +31,9 @@ const ( // DefaultSelinuxMountPoint is the common mount point of the selinuxfs. DefaultSelinuxMountPoint = "/sys/fs/selinux" + + // DefaultResctrlMountPoint is the common mount point of the resctrl filesystem. + DefaultResctrlMountPoint = "/sys/fs/resctrl" ) // FS represents a pseudo-filesystem, normally /proc or /sys, which provides an diff --git a/vendor/github.com/prometheus/procfs/internal/util/parse.go b/vendor/github.com/prometheus/procfs/internal/parsers/parse.go similarity index 99% rename from vendor/github.com/prometheus/procfs/internal/util/parse.go rename to vendor/github.com/prometheus/procfs/internal/parsers/parse.go index 30c5872019..5789ae5db0 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/parse.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/parse.go @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package util +package parsers import ( "errors" diff --git a/vendor/github.com/prometheus/procfs/internal/util/readfile.go b/vendor/github.com/prometheus/procfs/internal/parsers/readfile.go similarity index 98% rename from vendor/github.com/prometheus/procfs/internal/util/readfile.go rename to vendor/github.com/prometheus/procfs/internal/parsers/readfile.go index 0e41f71af1..c68d292153 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/readfile.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/readfile.go @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package util +package parsers import ( "io" diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go b/vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile.go similarity index 99% rename from vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go rename to vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile.go index f6a4a4de62..0f72f6021c 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile.go @@ -13,7 +13,7 @@ //go:build (linux || darwin) && !appengine -package util +package parsers import ( "bytes" diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go b/vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile_compat.go similarity index 98% rename from vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go rename to vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile_compat.go index c80e082cb9..6e19c45559 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile_compat.go @@ -13,7 +13,7 @@ //go:build (linux && appengine) || (!linux && !darwin) -package util +package parsers import ( "fmt" diff --git a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go b/vendor/github.com/prometheus/procfs/internal/parsers/valueparser.go similarity index 99% rename from vendor/github.com/prometheus/procfs/internal/util/valueparser.go rename to vendor/github.com/prometheus/procfs/internal/parsers/valueparser.go index e0ed671ea0..6289fd6704 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/valueparser.go @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package util +package parsers import ( "strconv" diff --git a/vendor/github.com/prometheus/procfs/ipvs.go b/vendor/github.com/prometheus/procfs/ipvs.go index 5374da9fa8..8a6f737478 100644 --- a/vendor/github.com/prometheus/procfs/ipvs.go +++ b/vendor/github.com/prometheus/procfs/ipvs.go @@ -25,7 +25,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // IPVSStats holds IPVS statistics, as exposed by the kernel in `/proc/net/ip_vs_stats`. @@ -66,7 +66,7 @@ type IPVSBackendStatus struct { // IPVSStats reads the IPVS statistics from the specified `proc` filesystem. func (fs FS) IPVSStats() (IPVSStats, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("net/ip_vs_stats")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("net/ip_vs_stats")) if err != nil { return IPVSStats{}, err } diff --git a/vendor/github.com/prometheus/procfs/kernel_random.go b/vendor/github.com/prometheus/procfs/kernel_random.go index e7c5b8cf2b..cbcd12b436 100644 --- a/vendor/github.com/prometheus/procfs/kernel_random.go +++ b/vendor/github.com/prometheus/procfs/kernel_random.go @@ -18,7 +18,7 @@ package procfs import ( "os" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // KernelRandom contains information about to the kernel's random number generator. @@ -48,7 +48,7 @@ func (fs FS) KernelRandom() (KernelRandom, error) { "write_wakeup_threshold": &random.WriteWakeupThreshold, "read_wakeup_threshold": &random.ReadWakeupThreshold, } { - val, err := util.ReadUintFromFile(fs.proc.Path("sys", "kernel", "random", file)) + val, err := parsers.ReadUintFromFile(fs.proc.Path("sys", "kernel", "random", file)) if os.IsNotExist(err) { continue } diff --git a/vendor/github.com/prometheus/procfs/kernel_tainted.go b/vendor/github.com/prometheus/procfs/kernel_tainted.go new file mode 100644 index 0000000000..9707f02808 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/kernel_tainted.go @@ -0,0 +1,95 @@ +// Copyright 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. + +//go:build linux + +package procfs + +import ( + "github.com/prometheus/procfs/internal/parsers" +) + +// KernelTaintBit represents a single kernel taint flag. +type KernelTaintBit struct { + // Index is the zero-based bit position in the tainted bitmask. + Index int + // Flag is the letter code identifying this taint (e.g. "L" for soft lockup). + // See https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html + Flag string + // Description is a human-readable explanation of what this taint means. + Description string + // Set indicates whether this taint flag is currently active. + Set bool +} + +// KernelTainted holds the kernel taint state read from /proc/sys/kernel/tainted. +type KernelTainted struct { + // Value is the raw integer from /proc/sys/kernel/tainted. + Value uint64 + // Bits contains each known taint flag and whether it is currently set. + // Flags are listed in bit-position order (bit 0 first). + Bits []KernelTaintBit +} + +// kernelTaintBitDefs lists all known kernel taint flags in bit-position order. +// Reference: https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html +var kernelTaintBitDefs = []struct { + flag string + description string +}{ + {"P", "Proprietary module was loaded."}, + {"F", "Module was force loaded."}, + {"S", "SMP kernel oops on an officially SMP incapable processor."}, + {"R", "Module was force unloaded."}, + {"M", "Processor reported a Machine Check Exception (MCE)."}, + {"B", "Bad page referenced or some unexpected page flags."}, + {"U", "Taint requested by userspace application."}, + {"D", "Kernel died recently, i.e. there was an OOPS or BUG."}, + {"A", "An ACPI table was overridden by user."}, + {"W", "Kernel issued warning."}, + {"C", "Staging driver was loaded."}, + {"I", "Workaround for bug in platform firmware applied."}, + {"O", "Externally-built (out-of-tree) module was loaded."}, + {"E", "Unsigned module was loaded."}, + {"L", "Soft lockup occurred."}, + {"K", "Kernel has been live patched."}, + {"X", "Auxiliary taint, defined and used by distros."}, + {"T", "The kernel was built with the struct randomization plugin."}, + {"N", "An in-kernel test such as a KUnit test has been run."}, + {"J", "Userspace used a mutating debug operation in fwctl."}, +} + +// KernelTainted reads /proc/sys/kernel/tainted and returns the raw taint value +// along with each known flag parsed into a KernelTainted struct. +// See https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html +func (fs FS) KernelTainted() (KernelTainted, error) { + value, err := parsers.SysReadUintFromFile(fs.proc.Path("sys", "kernel", "tainted")) + if err != nil { + return KernelTainted{}, err + } + return parseTainted(value), nil +} + +// parseTainted builds a KernelTainted from the raw taint bitmask value. +func parseTainted(value uint64) KernelTainted { + bits := make([]KernelTaintBit, len(kernelTaintBitDefs)) + for i, def := range kernelTaintBitDefs { + bits[i] = KernelTaintBit{ + Index: i, + Flag: def.flag, + Description: def.description, + Set: value&(1</environ`. func (p Proc) Environ() ([]string, error) { environments := make([]string, 0) - data, err := util.ReadFileNoStat(p.path("environ")) + data, err := parsers.ReadFileNoStat(p.path("environ")) if err != nil { return environments, err } diff --git a/vendor/github.com/prometheus/procfs/proc_fdinfo.go b/vendor/github.com/prometheus/procfs/proc_fdinfo.go index fa57761dbe..9e3e313e14 100644 --- a/vendor/github.com/prometheus/procfs/proc_fdinfo.go +++ b/vendor/github.com/prometheus/procfs/proc_fdinfo.go @@ -19,7 +19,7 @@ import ( "fmt" "regexp" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) var ( @@ -49,7 +49,7 @@ type ProcFDInfo struct { // FDInfo constructor. On kernels older than 3.8, InotifyInfos will always be empty. func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) { - data, err := util.ReadFileNoStat(p.path("fdinfo", fd)) + data, err := parsers.ReadFileNoStat(p.path("fdinfo", fd)) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/proc_interrupts.go b/vendor/github.com/prometheus/procfs/proc_interrupts.go index 643b500d5d..2a2412c4f8 100644 --- a/vendor/github.com/prometheus/procfs/proc_interrupts.go +++ b/vendor/github.com/prometheus/procfs/proc_interrupts.go @@ -22,7 +22,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Interrupt represents a single interrupt line. @@ -42,7 +42,7 @@ type Interrupts map[string]Interrupt // Interrupts creates a new instance from a given Proc instance. func (p Proc) Interrupts() (Interrupts, error) { - data, err := util.ReadFileNoStat(p.fs.proc.Path("interrupts")) + data, err := parsers.ReadFileNoStat(p.fs.proc.Path("interrupts")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/proc_io.go b/vendor/github.com/prometheus/procfs/proc_io.go index dd8086ba2e..ca221bb656 100644 --- a/vendor/github.com/prometheus/procfs/proc_io.go +++ b/vendor/github.com/prometheus/procfs/proc_io.go @@ -16,7 +16,7 @@ package procfs import ( "fmt" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcIO models the content of /proc//io. @@ -43,7 +43,7 @@ type ProcIO struct { func (p Proc) IO() (ProcIO, error) { pio := ProcIO{} - data, err := util.ReadFileNoStat(p.path("io")) + data, err := parsers.ReadFileNoStat(p.path("io")) if err != nil { return pio, err } diff --git a/vendor/github.com/prometheus/procfs/proc_netstat.go b/vendor/github.com/prometheus/procfs/proc_netstat.go index 7f94cc8914..6a118f58a7 100644 --- a/vendor/github.com/prometheus/procfs/proc_netstat.go +++ b/vendor/github.com/prometheus/procfs/proc_netstat.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcNetstat models the content of /proc//net/netstat. @@ -146,6 +146,20 @@ type TcpExt struct { // nolint:revive TCPMTUPFail *float64 TCPMTUPSuccess *float64 TCPWqueueTooBig *float64 + + // Legacy TcpExt counters dropped from recent kernels' TcpExt table; + // modeled so consumers retain metric parity with older kernels that + // still print them in /proc/net/netstat. + TCPLoss *float64 + PAWSPassive *float64 + TCPForwardRetrans *float64 + TCPSchedulerFailed *float64 + TCPPrequeued *float64 + TCPDirectCopyFromBacklog *float64 + TCPDirectCopyFromPrequeue *float64 + TCPPrequeueDropped *float64 + TCPFACKReorder *float64 + TCPHPHitsToUser *float64 } type IpExt struct { // nolint:revive @@ -171,7 +185,7 @@ type IpExt struct { // nolint:revive func (p Proc) Netstat() (ProcNetstat, error) { filename := p.path("net/netstat") - data, err := util.ReadFileNoStat(filename) + data, err := parsers.ReadFileNoStat(filename) if err != nil { return ProcNetstat{PID: p.PID}, err } @@ -396,6 +410,26 @@ func parseProcNetstat(r io.Reader, fileName string) (ProcNetstat, error) { procNetstat.TCPMTUPSuccess = &value case "TCPWqueueTooBig": procNetstat.TCPWqueueTooBig = &value + case "TCPLoss": + procNetstat.TCPLoss = &value + case "PAWSPassive": + procNetstat.PAWSPassive = &value + case "TCPForwardRetrans": + procNetstat.TCPForwardRetrans = &value + case "TCPSchedulerFailed": + procNetstat.TCPSchedulerFailed = &value + case "TCPPrequeued": + procNetstat.TCPPrequeued = &value + case "TCPDirectCopyFromBacklog": + procNetstat.TCPDirectCopyFromBacklog = &value + case "TCPDirectCopyFromPrequeue": + procNetstat.TCPDirectCopyFromPrequeue = &value + case "TCPPrequeueDropped": + procNetstat.TCPPrequeueDropped = &value + case "TCPFACKReorder": + procNetstat.TCPFACKReorder = &value + case "TCPHPHitsToUser": + procNetstat.TCPHPHitsToUser = &value } case "IpExt": switch key { diff --git a/vendor/github.com/prometheus/procfs/proc_psi.go b/vendor/github.com/prometheus/procfs/proc_psi.go index cc2c5de873..5f0fbdffb5 100644 --- a/vendor/github.com/prometheus/procfs/proc_psi.go +++ b/vendor/github.com/prometheus/procfs/proc_psi.go @@ -30,7 +30,7 @@ import ( "io" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) const lineFormat = "avg10=%f avg60=%f avg300=%f total=%d" @@ -59,7 +59,7 @@ type PSIStats struct { // resource from /proc/pressure/. At time of writing this can be // either "cpu", "memory" or "io". func (fs FS) PSIStatsForResource(resource string) (PSIStats, error) { - data, err := util.ReadFileNoStat(fs.proc.Path(fmt.Sprintf("%s/%s", "pressure", resource))) + data, err := parsers.ReadFileNoStat(fs.proc.Path(fmt.Sprintf("%s/%s", "pressure", resource))) if err != nil { return PSIStats{}, fmt.Errorf("%w: psi_stats: unavailable for %q: %w", ErrFileRead, resource, err) } diff --git a/vendor/github.com/prometheus/procfs/proc_smaps.go b/vendor/github.com/prometheus/procfs/proc_smaps.go index f637309b3d..dff5cfb885 100644 --- a/vendor/github.com/prometheus/procfs/proc_smaps.go +++ b/vendor/github.com/prometheus/procfs/proc_smaps.go @@ -23,7 +23,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) var ( @@ -60,7 +60,7 @@ type ProcSMapsRollup struct { // If smaps_rollup does not exists (require kernel >= 4.15), the content of /proc/pid/smaps will // we read and summed. func (p Proc) ProcSMapsRollup() (ProcSMapsRollup, error) { - data, err := util.ReadFileNoStat(p.path("smaps_rollup")) + data, err := parsers.ReadFileNoStat(p.path("smaps_rollup")) if err != nil && os.IsNotExist(err) { return p.procSMapsRollupManual() } diff --git a/vendor/github.com/prometheus/procfs/proc_snmp.go b/vendor/github.com/prometheus/procfs/proc_snmp.go index 8d9a9bcd67..531bc8371c 100644 --- a/vendor/github.com/prometheus/procfs/proc_snmp.go +++ b/vendor/github.com/prometheus/procfs/proc_snmp.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcSnmp models the content of /proc//net/snmp. @@ -135,7 +135,7 @@ type UdpLite struct { // nolint:revive func (p Proc) Snmp() (ProcSnmp, error) { filename := p.path("net/snmp") - data, err := util.ReadFileNoStat(filename) + data, err := parsers.ReadFileNoStat(filename) if err != nil { return ProcSnmp{PID: p.PID}, err } diff --git a/vendor/github.com/prometheus/procfs/proc_snmp6.go b/vendor/github.com/prometheus/procfs/proc_snmp6.go index 841fef4649..8296a4aed1 100644 --- a/vendor/github.com/prometheus/procfs/proc_snmp6.go +++ b/vendor/github.com/prometheus/procfs/proc_snmp6.go @@ -22,7 +22,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcSnmp6 models the content of /proc//net/snmp6. @@ -140,7 +140,7 @@ type UdpLite6 struct { // nolint:revive func (p Proc) Snmp6() (ProcSnmp6, error) { filename := p.path("net/snmp6") - data, err := util.ReadFileNoStat(filename) + data, err := parsers.ReadFileNoStat(filename) if err != nil { // On systems with IPv6 disabled, this file won't exist. // Do nothing. diff --git a/vendor/github.com/prometheus/procfs/proc_stat.go b/vendor/github.com/prometheus/procfs/proc_stat.go index 02e3f9e316..d9e544bcc8 100644 --- a/vendor/github.com/prometheus/procfs/proc_stat.go +++ b/vendor/github.com/prometheus/procfs/proc_stat.go @@ -18,7 +18,7 @@ import ( "fmt" "os" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Originally, this USER_HZ value was dynamically retrieved via a sysconf call @@ -134,7 +134,7 @@ func (p Proc) NewStat() (ProcStat, error) { // Stat returns the current status information of the process. func (p Proc) Stat() (ProcStat, error) { - data, err := util.ReadFileNoStat(p.path("stat")) + data, err := parsers.ReadFileNoStat(p.path("stat")) if err != nil { return ProcStat{}, err } diff --git a/vendor/github.com/prometheus/procfs/proc_statm.go b/vendor/github.com/prometheus/procfs/proc_statm.go index 6bcc97ec9c..5fbe27965f 100644 --- a/vendor/github.com/prometheus/procfs/proc_statm.go +++ b/vendor/github.com/prometheus/procfs/proc_statm.go @@ -18,7 +18,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // - https://man7.org/linux/man-pages/man5/proc_pid_statm.5.html @@ -53,7 +53,7 @@ func (p Proc) NewStatm() (ProcStatm, error) { // Statm returns the current memory usage information of the process. func (p Proc) Statm() (ProcStatm, error) { - data, err := util.ReadFileNoStat(p.path("statm")) + data, err := parsers.ReadFileNoStat(p.path("statm")) if err != nil { return ProcStatm{}, err } diff --git a/vendor/github.com/prometheus/procfs/proc_status.go b/vendor/github.com/prometheus/procfs/proc_status.go index 12d65581c8..8c1652e172 100644 --- a/vendor/github.com/prometheus/procfs/proc_status.go +++ b/vendor/github.com/prometheus/procfs/proc_status.go @@ -20,7 +20,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcStatus provides status information about the process, @@ -100,7 +100,7 @@ type ProcStatus struct { // NewStatus returns the current status information of the process. func (p Proc) NewStatus() (ProcStatus, error) { - data, err := util.ReadFileNoStat(p.path("status")) + data, err := parsers.ReadFileNoStat(p.path("status")) if err != nil { return ProcStatus{}, err } diff --git a/vendor/github.com/prometheus/procfs/proc_sys.go b/vendor/github.com/prometheus/procfs/proc_sys.go index 52658a4d52..c465b6be02 100644 --- a/vendor/github.com/prometheus/procfs/proc_sys.go +++ b/vendor/github.com/prometheus/procfs/proc_sys.go @@ -17,7 +17,7 @@ import ( "fmt" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) func sysctlToPath(sysctl string) string { @@ -25,7 +25,7 @@ func sysctlToPath(sysctl string) string { } func (fs FS) SysctlStrings(sysctl string) ([]string, error) { - value, err := util.SysReadFile(fs.proc.Path("sys", sysctlToPath(sysctl))) + value, err := parsers.SysReadFile(fs.proc.Path("sys", sysctlToPath(sysctl))) if err != nil { return nil, err } @@ -41,7 +41,7 @@ func (fs FS) SysctlInts(sysctl string) ([]int, error) { values := make([]int, len(fields)) for i, f := range fields { - vp := util.NewValueParser(f) + vp := parsers.NewValueParser(f) values[i] = vp.Int() if err := vp.Err(); err != nil { return nil, fmt.Errorf("%w: field %d in sysctl %s is not a valid int: %w", ErrFileParse, i, sysctl, err) diff --git a/vendor/github.com/prometheus/procfs/slab.go b/vendor/github.com/prometheus/procfs/slab.go index 32a04678ad..b78bac6344 100644 --- a/vendor/github.com/prometheus/procfs/slab.go +++ b/vendor/github.com/prometheus/procfs/slab.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) var ( @@ -142,7 +142,7 @@ func (fs FS) SlabInfo() (SlabInfo, error) { // TODO: Consider passing options to allow for parsing different // slabinfo versions. However, slabinfo 2.1 has been stable since // kernel 2.6.10 and later. - data, err := util.ReadFileNoStat(fs.proc.Path("slabinfo")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("slabinfo")) if err != nil { return SlabInfo{}, err } diff --git a/vendor/github.com/prometheus/procfs/softirqs.go b/vendor/github.com/prometheus/procfs/softirqs.go index 47b73a7297..dcd5859335 100644 --- a/vendor/github.com/prometheus/procfs/softirqs.go +++ b/vendor/github.com/prometheus/procfs/softirqs.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Softirqs represents the softirq statistics. @@ -40,7 +40,7 @@ type Softirqs struct { func (fs FS) Softirqs() (Softirqs, error) { fileName := fs.proc.Path("softirqs") - data, err := util.ReadFileNoStat(fileName) + data, err := parsers.ReadFileNoStat(fileName) if err != nil { return Softirqs{}, err } diff --git a/vendor/github.com/prometheus/procfs/stat.go b/vendor/github.com/prometheus/procfs/stat.go index 593ad0f62f..781bd28ada 100644 --- a/vendor/github.com/prometheus/procfs/stat.go +++ b/vendor/github.com/prometheus/procfs/stat.go @@ -23,7 +23,7 @@ import ( "strings" "github.com/prometheus/procfs/internal/fs" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // CPUStat shows how much time the cpu spend in various stages. @@ -167,7 +167,7 @@ func (fs FS) NewStat() (Stat, error) { // See: https://www.kernel.org/doc/Documentation/filesystems/proc.txt func (fs FS) Stat() (Stat, error) { fileName := fs.proc.Path("stat") - data, err := util.ReadFileNoStat(fileName) + data, err := parsers.ReadFileNoStat(fileName) if err != nil { return Stat{}, err } diff --git a/vendor/github.com/prometheus/procfs/swaps.go b/vendor/github.com/prometheus/procfs/swaps.go index ee17bf4888..8f9bbfb5c4 100644 --- a/vendor/github.com/prometheus/procfs/swaps.go +++ b/vendor/github.com/prometheus/procfs/swaps.go @@ -20,7 +20,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Swap represents an entry in /proc/swaps. @@ -34,7 +34,7 @@ type Swap struct { // Swaps returns a slice of all configured swap devices on the system. func (fs FS) Swaps() ([]*Swap, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("swaps")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("swaps")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/vm.go b/vendor/github.com/prometheus/procfs/vm.go index 52180c03e2..62725b4207 100644 --- a/vendor/github.com/prometheus/procfs/vm.go +++ b/vendor/github.com/prometheus/procfs/vm.go @@ -21,7 +21,7 @@ import ( "path/filepath" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // The VM interface is described at @@ -102,11 +102,11 @@ func (fs FS) VM() (*VM, error) { name := filepath.Join(path, f.Name()) // ignore errors on read, as there are some write only // in /proc/sys/vm - value, err := util.SysReadFile(name) + value, err := parsers.SysReadFile(name) if err != nil { continue } - vp := util.NewValueParser(value) + vp := parsers.NewValueParser(value) switch f.Name() { case "admin_reserve_kbytes": @@ -143,7 +143,7 @@ func (fs FS) VM() (*VM, error) { stringSlice := strings.Fields(value) pint64Slice := make([]*int64, 0, len(stringSlice)) for _, value := range stringSlice { - vp := util.NewValueParser(value) + vp := parsers.NewValueParser(value) pint64Slice = append(pint64Slice, vp.PInt64()) } vm.LowmemReserveRatio = pint64Slice diff --git a/vendor/github.com/prometheus/procfs/zoneinfo.go b/vendor/github.com/prometheus/procfs/zoneinfo.go index 63d1898bc8..71b3c2b653 100644 --- a/vendor/github.com/prometheus/procfs/zoneinfo.go +++ b/vendor/github.com/prometheus/procfs/zoneinfo.go @@ -22,7 +22,7 @@ import ( "regexp" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Zoneinfo holds info parsed from /proc/zoneinfo. @@ -103,7 +103,7 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) { if len(parts) < 2 { continue } - vp := util.NewValueParser(parts[1]) + vp := parsers.NewValueParser(parts[1]) switch parts[0] { case "nr_free_pages": zoneinfoElement.NrFreePages = vp.PInt64() @@ -179,7 +179,7 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) { protectionValues = strings.Replace(protectionValues, ")", "", 1) protectionValues = strings.TrimSpace(protectionValues) protectionStringMap := strings.Split(protectionValues, ", ") - val, err := util.ParsePInt64s(protectionStringMap) + val, err := parsers.ParsePInt64s(protectionStringMap) if err == nil { zoneinfoElement.Protection = val } diff --git a/vendor/github.com/sethvargo/go-retry/README.md b/vendor/github.com/sethvargo/go-retry/README.md index 3464965a8b..531b6a1904 100644 --- a/vendor/github.com/sethvargo/go-retry/README.md +++ b/vendor/github.com/sethvargo/go-retry/README.md @@ -94,7 +94,7 @@ NewExponential(1 * time.Second) The Fibonacci backoff uses the Fibonacci sequence to calculate the backoff. The next value is the sum of the current value and the previous value. This means -retires happen quickly at first, but then gradually take slower, ideal for +retries happen quickly at first, but then gradually slow down, ideal for network-type issues. Here is an example: ```text diff --git a/vendor/github.com/sethvargo/go-retry/backoff.go b/vendor/github.com/sethvargo/go-retry/backoff.go index 47f747536f..c0614a041c 100644 --- a/vendor/github.com/sethvargo/go-retry/backoff.go +++ b/vendor/github.com/sethvargo/go-retry/backoff.go @@ -1,6 +1,7 @@ package retry import ( + "math" "math/rand/v2" "sync" "time" @@ -25,7 +26,7 @@ func (b BackoffFunc) Next() (time.Duration, bool) { // WithJitter wraps a backoff function and adds the specified jitter. j can be // interpreted as "+/- j". For example, if j were 5 seconds and the backoff // returned 20s, the value could be between 15 and 25 seconds. The value can -// never be less than 0. +// never be less than 0 or greater than the maximum time.Duration. func WithJitter(j time.Duration, next Backoff) Backoff { return BackoffFunc(func() (time.Duration, bool) { val, stop := next.Next() @@ -37,17 +38,30 @@ func WithJitter(j time.Duration, next Backoff) Backoff { return val, false } - diff := time.Duration(rand.Int64N(int64(j)*2) - int64(j)) - val = max(val+diff, 0) - return val, false + // The unsigned bound fits even when twice j exceeds MaxInt64. + diff := time.Duration(rand.Uint64N(uint64(j)*2) - uint64(j)) + return addClamp(val, diff), false }) } +func addClamp(a, b time.Duration) time.Duration { + if b > 0 && a > math.MaxInt64-b { + return math.MaxInt64 + } + if b < 0 && a < math.MinInt64-b { + return 0 + } + return max(a+b, 0) +} + // WithJitterPercent wraps a backoff function and adds the specified jitter // percentage. j can be interpreted as "+/- j%". For example, if j were 5 and // the backoff returned 20s, the value could be between 19 and 21 seconds. The // value can never be less than 0 or greater than 100. func WithJitterPercent(j uint64, next Backoff) Backoff { + // Above 100 the computed percentage goes negative and int64(j)*2 overflows. + j = min(j, 100) + return BackoffFunc(func() (time.Duration, bool) { val, stop := next.Next() if stop { @@ -62,11 +76,20 @@ func WithJitterPercent(j uint64, next Backoff) Backoff { top := rand.Int64N(int64(j)*2) - int64(j) pct := 1 - float64(top)/100.0 - val = max(time.Duration(float64(val)*pct), 0) - return val, false + return durationFromFloat(float64(val) * pct), false }) } +func durationFromFloat(f float64) time.Duration { + if f >= math.MaxInt64 { + return math.MaxInt64 + } + if f <= 0 { + return 0 + } + return time.Duration(f) +} + // WithFullJitter wraps a backoff function and returns a random value between // zero (inclusive) and the wrapped backoff's returned value (exclusive). For // example, if the backoff returned 20s, the value could be anywhere in [0, 20s). @@ -124,7 +147,7 @@ func WithCappedDuration(cap time.Duration, next Backoff) Backoff { return 0, true } - if val <= 0 || val > cap { + if val > cap { val = cap } return val, false @@ -148,7 +171,7 @@ func WithMaxDuration(timeout time.Duration, next Backoff) Backoff { return 0, true } - if val <= 0 || val > diff { + if val > diff { val = diff } return val, false diff --git a/vendor/github.com/sirupsen/logrus/.golangci.yml b/vendor/github.com/sirupsen/logrus/.golangci.yml index 792db36181..c9a840e0d7 100644 --- a/vendor/github.com/sirupsen/logrus/.golangci.yml +++ b/vendor/github.com/sirupsen/logrus/.golangci.yml @@ -1,12 +1,9 @@ version: "2" -run: - tests: false linters: enable: - asasalint - asciicheck - bidichk - - bodyclose - contextcheck - durationcheck - errchkjson @@ -22,46 +19,21 @@ linters: - nilerr - nilnesserr - noctx - - protogetter - reassign - recvcheck - - rowserrcheck - - spancheck - - sqlclosecheck - testifylint - unparam - - zerologlint - disable: - - prealloc - settings: - errcheck: - check-type-assertions: false - check-blank: false - lll: - line-length: 100 - tab-width: 4 - prealloc: - simple: false - range-loops: false - for-loops: false - whitespace: - multi-if: false - multi-func: false exclusions: - generated: lax presets: - - comments - - common-false-positives - legacy - std-error-handling - paths: - - third_party$ - - builtin$ - - examples$ -formatters: - exclusions: - generated: lax - paths: - - third_party$ - - builtin$ - - examples$ + rules: + # Exclude some linters from running on tests files. + - path: _test\.go + linters: + - gosec + - musttag + - noctx # TODO: enable once we switch to Go 1.24+. + - linters: # TODO: remove once golangci-lint is updated with https://github.com/golangci/golangci-lint/pull/6584 + - gocheckcompilerdirectives + text: 'compiler directive unrecognized: //go:fix' diff --git a/vendor/github.com/sirupsen/logrus/.travis.yml b/vendor/github.com/sirupsen/logrus/.travis.yml deleted file mode 100644 index c1dbd5a3a3..0000000000 --- a/vendor/github.com/sirupsen/logrus/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go -go_import_path: github.com/sirupsen/logrus -git: - depth: 1 -env: - - GO111MODULE=on -go: 1.15.x -os: linux -install: - - ./travis/install.sh -script: - - cd ci - - go run mage.go -v -w ../ crossBuild - - go run mage.go -v -w ../ lint - - go run mage.go -v -w ../ test diff --git a/vendor/github.com/sirupsen/logrus/CHANGELOG.md b/vendor/github.com/sirupsen/logrus/CHANGELOG.md index 098608ff4b..683cec9088 100644 --- a/vendor/github.com/sirupsen/logrus/CHANGELOG.md +++ b/vendor/github.com/sirupsen/logrus/CHANGELOG.md @@ -1,90 +1,253 @@ -# 1.8.1 +# Changelog + +All notable changes to this project will be documented in this file. + +## 1.10.2 + +Changed: + + * Update `github.com/stretchr/testify` to v1.12.1, removing the legacy + `gopkg.in/yaml.v3` dependency. + +## 1.10.1 + +Fixes: + + * Fix a regression introduced in v1.10.0 where `TextFormatter` could panic + when formatting nil or panicking `error` and `fmt.Stringer` values. + * Allow function-backed implementations of `error` as field values. + +## 1.10.0 + +Fixes: + + * Fix reentrant logging deadlocks in formatter paths. + * Fix race conditions in formatter and entry handling. + * Fix generic `Log`, `Logf`, `Logln`, and `LogFn` methods unexpectedly + panicking when called with `PanicLevel`. Use the corresponding `Panic` + methods when panic behavior is desired. + * Improve concurrency safety around formatter and hook access. + +Features: + + * Add `slog` hook for forwarding Logrus entries to `log/slog`. + * Add `slog.Handler` for forwarding `log/slog` records to a Logrus logger, + including levels, fields, groups, context, time, and optional caller + reporting. The hook and handler can also be combined to help migrate + between Logrus and `log/slog`. + * Add minimal, composable logging interfaces for each log level. This enables + consumers to depend on narrower interfaces, making it easier to substitute + or adapt logging implementations. + * Allow `Entry.Caller` to be set explicitly and preserve it across derived + entries, enabling custom caller detection without Logrus overwriting + caller information when `ReportCaller` is enabled. + +Changed: + + * Raise minimum supported Go version to 1.23. + * TextFormatter now renders `[]byte` values as raw/quoted strings instead of slice-of-ints. + * TextFormatter now uses distinct dimmed colors for debug and trace output. + * TextFormatter now automatically enables colors on Windows terminals with ANSI support, + matching the behavior on other platforms. + * `Entry.HasCaller` is now deprecated in favor of checking `Entry.Caller` directly. + * Deprecated `MutexWrap`, which was unintentionally exposed as public API. + It remains available as an alias for compatibility but should not be used + directly. + +Performance: + + * Significantly improve TextFormatter performance and reduce allocations. + * Optimize common Entry and Logger hot paths. + * Reduce allocations in caller reporting. + * ~17% lower geomean runtime and ~27% higher formatter throughput overall. + * Common enabled logging paths are ~30–44% faster. + * TextFormatter paths are up to ~40% faster, with allocation counts reduced + by 25–74% across the measured formatter cases. + + +## 1.9.4 + +Fixes: + + * Remove uses of deprecated `ioutil` package + +Features: + + * Add GNU/Hurd support + * Add WASI wasip1 support + +Code quality: + + * Update minimum supported Go version to 1.17 + * Documentation updates + + +## 1.9.3 + +Fixes: + + * Re-apply fix for potential denial of service in logrus.Writer() when logging >64KB single-line payloads without newlines (#1376) + * Fix panic in Writer + + +## 1.9.2 + +Fixes: + + * Revert Writer DoS fix (#1376) due to regression + + +## 1.9.1 + +Fixes: + + * Fix potential denial of service in logrus.Writer() when logging >64KB single-line payloads without newlines (#1376) + + +## 1.9.0 + +Fixes: + + * Multiple concurrency and race condition fixes + * Improve Windows terminal and ANSI handling + Code quality: + + * Internal cleanups and modernization + + +## 1.8.3 + +Fixes: + + * Fix potential denial of service in logrus.Writer() when logging >64KB single-line payloads without newlines (#1376) + + +## 1.8.2 + +Features: + + * Add support for the logger private buffer pool (#1253) + +Fixes: + + * Fix race condition for SetFormatter and SetReportCaller + * Fix data race in hooks test package + +## 1.8.1 + +Code quality: + * move magefile in its own subdir/submodule to remove magefile dependency on logrus consumer * improve timestamp format documentation Fixes: + * fix race condition on logger hooks -# 1.8.0 +## 1.8.0 Correct versioning number replacing v1.7.1. -# 1.7.1 +## 1.7.1 Beware this release has introduced a new public API and its semver is therefore incorrect. Code quality: + * use go 1.15 in travis * use magefile as task runner Fixes: + * small fixes about new go 1.13 error formatting system * Fix for long time race condiction with mutating data hooks Features: + * build support for zos -# 1.7.0 +## 1.7.0 + Fixes: + * the dependency toward a windows terminal library has been removed Features: + * a new buffer pool management API has been added * a set of `Fn()` functions have been added -# 1.6.0 +## 1.6.0 + Fixes: + * end of line cleanup * revert the entry concurrency bug fix which leads to deadlock under some circumstances * update dependency on go-windows-terminal-sequences to fix a crash with go 1.14 Features: + * add an option to the `TextFormatter` to completely disable fields quoting -# 1.5.0 +## 1.5.0 + Code quality: + * add golangci linter run on travis Fixes: + * add mutex for hooks concurrent access on `Entry` data * caller function field for go1.14 * fix build issue for gopherjs target Feature: + * add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level * add a `DisableHTMLEscape` option in the `JSONFormatter` * add `ForceQuote` and `PadLevelText` options in the `TextFormatter` -# 1.4.2 +## 1.4.2 + * Fixes build break for plan9, nacl, solaris -# 1.4.1 + +## 1.4.1 + This new release introduces: + * Enhance TextFormatter to not print caller information when they are empty (#944) * Remove dependency on golang.org/x/crypto (#932, #943) Fixes: + * Fix Entry.WithContext method to return a copy of the initial entry (#941) -# 1.4.0 +## 1.4.0 + This new release introduces: + * Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848). * Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911) * Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919). Fixes: + * Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893). * Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903) * Fix infinite recursion on unknown `Level.String()` (#907) * Fix race condition in `getCaller` (#916). -# 1.3.0 +## 1.3.0 + This new release introduces: + * Log, Logf, Logln functions for Logger and Entry that take a Level Fixes: + * Building prometheus node_exporter on AIX (#840) * Race condition in TextFormatter (#468) * Travis CI import path (#868) @@ -92,20 +255,26 @@ Fixes: * Pointer to func as field in JSONFormatter (#870) * Properly marshal Levels (#873) -# 1.2.0 +## 1.2.0 + This new release introduces: + * A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued * A new trace level named `Trace` whose level is below `Debug` * A configurable exit function to be called upon a Fatal trace * The `Level` object now implements `encoding.TextUnmarshaler` interface -# 1.1.1 +## 1.1.1 + This is a bug fix release. + * fix the build break on Solaris * don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized -# 1.1.0 +## 1.1.0 + This new release introduces: + * several fixes: * a fix for a race condition on entry formatting * proper cleanup of previously used entries before putting them back in the pool @@ -122,9 +291,10 @@ This new release introduces: * the field sort function is now configurable for text formatter * the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater -# 1.0.6 +## 1.0.6 This new release introduces: + * a new api WithTime which allows to easily force the time of the log entry which is mostly useful for logger wrapper * a fix reverting the immutability of the entry given as parameter to the hooks @@ -134,71 +304,71 @@ This new release introduces: * a new configuration of the textformatter to configure the name of the default keys * a new configuration of the text formatter to disable the level truncation -# 1.0.5 +## 1.0.5 * Fix hooks race (#707) * Fix panic deadlock (#695) -# 1.0.4 +## 1.0.4 * Fix race when adding hooks (#612) * Fix terminal check in AppEngine (#635) -# 1.0.3 +## 1.0.3 * Replace example files with testable examples -# 1.0.2 +## 1.0.2 * bug: quote non-string values in text formatter (#583) * Make (*Logger) SetLevel a public method -# 1.0.1 +## 1.0.1 * bug: fix escaping in text formatter (#575) -# 1.0.0 +## 1.0.0 * Officially changed name to lower-case * bug: colors on Windows 10 (#541) * bug: fix race in accessing level (#512) -# 0.11.5 +## 0.11.5 * feature: add writer and writerlevel to entry (#372) -# 0.11.4 +## 0.11.4 * bug: fix undefined variable on solaris (#493) -# 0.11.3 +## 0.11.3 * formatter: configure quoting of empty values (#484) * formatter: configure quoting character (default is `"`) (#484) * bug: fix not importing io correctly in non-linux environments (#481) -# 0.11.2 +## 0.11.2 * bug: fix windows terminal detection (#476) -# 0.11.1 +## 0.11.1 * bug: fix tty detection with custom out (#471) -# 0.11.0 +## 0.11.0 * performance: Use bufferpool to allocate (#370) * terminal: terminal detection for app-engine (#343) * feature: exit handler (#375) -# 0.10.0 +## 0.10.0 * feature: Add a test hook (#180) * feature: `ParseLevel` is now case-insensitive (#326) * feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308) * performance: avoid re-allocations on `WithFields` (#335) -# 0.9.0 +## 0.9.0 * logrus/text_formatter: don't emit empty msg * logrus/hooks/airbrake: move out of main repository @@ -210,25 +380,25 @@ This new release introduces: * logrus/core: support `WithError` on logger * logrus/core: Solaris support -# 0.8.7 +## 0.8.7 * logrus/core: fix possible race (#216) * logrus/doc: small typo fixes and doc improvements -# 0.8.6 +## 0.8.6 * hooks/raven: allow passing an initialized client -# 0.8.5 +## 0.8.5 * logrus/core: revert #208 -# 0.8.4 +## 0.8.4 * formatter/text: fix data race (#218) -# 0.8.3 +## 0.8.3 * logrus/core: fix entry log level (#208) * logrus/core: improve performance of text formatter by 40% @@ -236,24 +406,24 @@ This new release introduces: * logrus/core: add support for DragonflyBSD and NetBSD * formatter/text: print structs more verbosely -# 0.8.2 +## 0.8.2 * logrus: fix more Fatal family functions -# 0.8.1 +## 0.8.1 * logrus: fix not exiting on `Fatalf` and `Fatalln` -# 0.8.0 +## 0.8.0 * logrus: defaults to stderr instead of stdout * hooks/sentry: add special field for `*http.Request` * formatter/text: ignore Windows for colors -# 0.7.3 +## 0.7.3 * formatter/\*: allow configuration of timestamp layout -# 0.7.2 +## 0.7.2 * formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/sirupsen/logrus/README.md b/vendor/github.com/sirupsen/logrus/README.md index cc5dab7eb7..b2ff7affca 100644 --- a/vendor/github.com/sirupsen/logrus/README.md +++ b/vendor/github.com/sirupsen/logrus/README.md @@ -3,13 +3,10 @@ Logrus is a structured logger for Go (golang), completely API compatible with the standard library logger. -**Logrus is in maintenance-mode.** We will not be introducing new features. It's -simply too hard to do in a way that won't break many people's projects, which is -the last thing you want from your Logging library (again...). - -This does not mean Logrus is dead. Logrus will continue to be maintained for -security, (backwards compatible) bug fixes, and performance (where we are -limited by the interface). +**Logrus is in maintenance mode.** The project focuses on security, bug fixes, +and performance improvements. New features are not planned, aside from changes +required to provide interoperability with other logging ecosystems (e.g., Go's +[log/slog](https://pkg.go.dev/log/slog)). I believe Logrus' biggest contribution is to have played a part in today's widespread use of structured logging in Golang. There doesn't seem to be a @@ -23,18 +20,6 @@ about structured logging in Go today. Check out, for example, [zap]: https://github.com/uber-go/zap [apex]: https://github.com/apex/log -**Seeing weird case-sensitive problems?** It's in the past been possible to -import Logrus as both upper- and lower-case. Due to the Go package environment, -this caused issues in the community and we needed a standard. Some environments -experienced problems with the upper-case variant, so the lower-case was decided. -Everything using `logrus` will need to use the lower-case: -`github.com/sirupsen/logrus`. Any package that isn't, should be changed. - -To fix Glide, see [these -comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). -For an in-depth explanation of the casing issue, see [this -comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). - Nicely color-coded in development (when a TTY is attached, otherwise just plain text): @@ -43,35 +28,27 @@ plain text): With `logrus.SetFormatter(&logrus.JSONFormatter{})`, for easy parsing by logstash or Splunk: -```text -{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the -ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} - -{"level":"warning","msg":"The group's number increased tremendously!", -"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"A giant walrus appears!", -"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", -"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} - -{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, -"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} +```json lines +{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} +{"level":"warning","msg":"The group's number increased tremendously!","number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} +{"animal":"walrus","level":"info","msg":"A giant walrus appears!","size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} +{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.","size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} +{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} ``` With the default `logrus.SetFormatter(&logrus.TextFormatter{})` when a TTY is not attached, the output is compatible with the [logfmt](https://pkg.go.dev/github.com/kr/logfmt) format: -```text +```bash time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 -time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true +time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" animal=orca err="It's over 9000!" number=100 omg=true size=9009 ``` + To ensure this behaviour even if a TTY is attached, set your formatter as follows: ```go @@ -88,29 +65,32 @@ If you wish to add the calling method as a field, instruct the logger via: ```go logrus.SetReportCaller(true) ``` + This adds the caller as 'method' like so: ```json -{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by", -"time":"2014-03-10 19:57:38.562543129 -0400 EDT"} +{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by","time":"2014-03-10 19:57:38.562543129 -0400 EDT"} ``` -```text +```bash time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin ``` + Note that this does add measurable overhead - the cost will depend on the version of Go, but is between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your environment via benchmarks: ```bash -go test -bench=.*CallerTracing +go test -bench=ReportCaller ``` #### Case-sensitivity -The organization's name was changed to lower-case--and this will not be changed -back. If you are getting import conflicts due to case sensitivity, please use -the lower-case import: `github.com/sirupsen/logrus`. +The organization's name was [changed to lower-case][1]. If you are getting import +conflicts due to case sensitivity, please use the lower-case import: +`github.com/sirupsen/logrus`. + +[1]: https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276 #### Example @@ -289,6 +269,7 @@ func init() { } } ``` + Note: Syslog hooks also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) @@ -367,18 +348,21 @@ Splunk or Logstash. The built-in logging formatters are: -* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise - without colors. - * *Note:* to force colored output when there is no TTY, set the `ForceColors` +* [`logrus.TextFormatter`](https://pkg.go.dev/github.com/sirupsen/logrus#TextFormatter) + logs the event in colors if the logger output is a TTY, otherwise without colors. + * To force colored output when there is no TTY, set the `ForceColors` field to `true`. To force no colored output even if there is a TTY set the - `DisableColors` field to `true`. For Windows, see - [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). + `DisableColors` field to `true`. + * On modern Windows terminals with ANSI (Virtual Terminal) support, TextFormatter + automatically enables colored output. + * If your environment does not support ANSI escape sequences, wrap the logger output + using [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable) + and set `ForceColors` (or `CLICOLOR_FORCE=1`) to enable colors through the wrapper. * When colors are enabled, levels are truncated to 4 characters by default. To disable truncation set the `DisableLevelTruncation` field to `true`. * When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text. - * All options are listed in the [generated docs](https://pkg.go.dev/github.com/sirupsen/logrus#TextFormatter). -* `logrus.JSONFormatter`. Logs fields as JSON. - * All options are listed in the [generated docs](https://pkg.go.dev/github.com/sirupsen/logrus#JSONFormatter). +* [`logrus.JSONFormatter`](https://pkg.go.dev/github.com/sirupsen/logrus#JSONFormatter) + logs fields as JSON. Third-party logging formatters: @@ -390,10 +374,12 @@ Third-party logging formatters: * [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure. * [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Save log to files. * [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added. +* [`easy-logrus-formatter`](https://github.com/WeiZhixiong/easy-logrus-formatter). Provide a user-friendly formatter for logrus. +* [`redactrus`](https://github.com/ibreakthecloud/redactrus). Redacts sensitive information like password, apikeys, email, etc. from logs. You can define your formatter by implementing the `Formatter` interface, requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a -`Fields` type (`map[string]interface{}`) with all your fields as well as the +`Fields` type (`map[string]any`) with all your fields as well as the default ones (see Entries section above): ```go @@ -516,4 +502,4 @@ Situations when locking is not needed include: 2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing) - (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) + (Refer to ) diff --git a/vendor/github.com/sirupsen/logrus/alt_exit.go b/vendor/github.com/sirupsen/logrus/alt_exit.go index 8fd189e1cc..1c35cf81c4 100644 --- a/vendor/github.com/sirupsen/logrus/alt_exit.go +++ b/vendor/github.com/sirupsen/logrus/alt_exit.go @@ -57,7 +57,7 @@ func Exit(code int) { // // This method is useful when a caller wishes to use logrus to log a fatal // message but also needs to gracefully shutdown. An example usecase could be -// closing database connections, or sending a alert that the application is +// closing database connections, or sending an alert that the application is // closing. func RegisterExitHandler(handler func()) { handlers = append(handlers, handler) @@ -69,7 +69,7 @@ func RegisterExitHandler(handler func()) { // // This method is useful when a caller wishes to use logrus to log a fatal // message but also needs to gracefully shutdown. An example usecase could be -// closing database connections, or sending a alert that the application is +// closing database connections, or sending an alert that the application is // closing. func DeferExitHandler(handler func()) { handlers = append([]func(){handler}, handlers...) diff --git a/vendor/github.com/sirupsen/logrus/buffer_pool.go b/vendor/github.com/sirupsen/logrus/buffer_pool.go index c7787f77cb..6b562d8703 100644 --- a/vendor/github.com/sirupsen/logrus/buffer_pool.go +++ b/vendor/github.com/sirupsen/logrus/buffer_pool.go @@ -5,9 +5,13 @@ import ( "sync" ) -var ( - bufferPool BufferPool -) +var bufferPool BufferPool = &defaultPool{ + pool: &sync.Pool{ + New: func() any { + return new(bytes.Buffer) + }, + }, +} type BufferPool interface { Put(*bytes.Buffer) @@ -27,17 +31,7 @@ func (p *defaultPool) Get() *bytes.Buffer { } // SetBufferPool allows to replace the default logrus buffer pool -// to better meets the specific needs of an application. +// to better meet the specific needs of an application. func SetBufferPool(bp BufferPool) { bufferPool = bp } - -func init() { - SetBufferPool(&defaultPool{ - pool: &sync.Pool{ - New: func() interface{} { - return new(bytes.Buffer) - }, - }, - }) -} diff --git a/vendor/github.com/sirupsen/logrus/doc.go b/vendor/github.com/sirupsen/logrus/doc.go index da67aba06d..75186dc2d2 100644 --- a/vendor/github.com/sirupsen/logrus/doc.go +++ b/vendor/github.com/sirupsen/logrus/doc.go @@ -1,25 +1,25 @@ /* Package logrus is a structured logger for Go, completely API compatible with the standard library logger. - The simplest way to use Logrus is simply the package-level exported logger: - package main + package main - import ( - log "github.com/sirupsen/logrus" - ) + import ( + log "github.com/sirupsen/logrus" + ) - func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "number": 1, - "size": 10, - }).Info("A walrus appears") - } + func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "number": 1, + "size": 10, + }).Info("A walrus appears") + } Output: - time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 + + time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 For a full guide visit https://github.com/sirupsen/logrus */ diff --git a/vendor/github.com/sirupsen/logrus/entry.go b/vendor/github.com/sirupsen/logrus/entry.go index 71d796d0b1..82de41f9f8 100644 --- a/vendor/github.com/sirupsen/logrus/entry.go +++ b/vendor/github.com/sirupsen/logrus/entry.go @@ -4,9 +4,11 @@ import ( "bytes" "context" "fmt" + "maps" "os" "reflect" "runtime" + "strconv" "strings" "sync" "time" @@ -17,8 +19,10 @@ var ( // qualified package name, cached at first use logrusPackage string - // Positions in the call stack when tracing to report the calling method - minimumCallerDepth int + // Positions in the call stack when tracing to report the calling method. + // + // Start at the bottom of the stack before the package-name cache is primed. + minimumCallerDepth = 1 // Used for caller information initialisation callerInitOnce sync.Once @@ -29,68 +33,116 @@ const ( knownLogrusFrames int = 4 ) -func init() { - // start at the bottom of the stack before the package-name cache is primed - minimumCallerDepth = 1 -} - // ErrorKey defines the key when adding errors using [WithError], [Logger.WithError]. var ErrorKey = "error" -// Entry is the final or intermediate Logrus logging entry. It contains all -// the fields passed with WithField{,s}. It's finally logged when Trace, Debug, -// Info, Warn, Error, Fatal or Panic is called on it. These objects can be -// reused and passed around as much as you wish to avoid field duplication. +// Entry represents a single log event. It may be either an intermediate +// entry (created via WithField(s), WithContext, etc.) or a final entry +// that is emitted when one of the level methods (Trace, Debug, Info, +// Warn, Error, Fatal, Panic) is called. // -//nolint:recvcheck // the methods of "Entry" use pointer receiver and non-pointer receiver. +// An Entry always belongs to a Logger. A nil Logger is invalid and will +// cause a panic when the entry is logged. Use [NewEntry] or Logger methods +// to construct entries. +// +// Entries are safe to reuse for adding fields and may be passed around +// to avoid field duplication. Each log operation operates on a copy +// of the Entry’s data to avoid mutation during formatting. +// +//nolint:recvcheck // Entry methods intentionally use both pointer and value receivers. type Entry struct { + // Logger is the Logger that owns this entry and is responsible for + // formatting, hooks, and output. It must not be nil. An Entry without + // a Logger is invalid and will panic when logged. Logger *Logger - // Contains all the fields set by the user. + // Data contains all user-defined fields attached to this entry. Data Fields - // Time at which the log entry was created + // Time is the timestamp for the log event. If zero when the entry is + // logged, it defaults to the current time. Time time.Time - // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic - // This field will be set on entry firing and the value will be equal to the one in Logger struct field. + // Level is the severity of the log entry. It is set when the entry + // is fired and reflects the level used for that log call. Level Level - // Calling method, with package name + // Caller contains the calling method information. + // + // When [Logger.ReportCaller] is enabled, Caller is populated automatically at + // log time if it is nil. Hooks and formatters may inspect Caller. + // + // Applications generally should not modify Caller unless they intentionally + // want to provide custom caller information. Caller *runtime.Frame - // Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic + // Message is the log message supplied to one of the logging methods + // (Trace, Debug, Info, Warn, Error, Fatal, or Panic). It is set when + // the entry is logged. Message string - // When formatter is called in entry.log(), a Buffer may be set to entry + // Buffer is a reusable buffer provided to the formatter. It is set + // before formatting in the normal log path; when nil, formatters + // allocate their own. Buffer *bytes.Buffer - // Contains the context set by the user. Useful for hook processing etc. + // Context carries user-provided context for hooks and formatters. Context context.Context - // err may contain a field formatting error + // err contains internal field-formatting errors. err string } +// NewEntry creates a new [Entry] associated with the provided Logger. +// The logger must not be nil. Passing a nil logger results in a +// panic when a logging method (e.g., [Entry.Info], [Entry.Error], etc.) +// is called. func NewEntry(logger *Logger) *Entry { return &Entry{ Logger: logger, - // Default is three fields, plus one optional. Give a little extra room. - Data: make(Fields, 6), + // Reserve default predefined fields and a little extra room. + Data: make(Fields, defaultFields+3), } } +// Dup creates a copy of the entry for further modification. +// +// Data is cloned to avoid mutating the original entry. Other fields +// (Logger, Time, Context, etc.) are copied by value. func (entry *Entry) Dup() *Entry { - data := make(Fields, len(entry.Data)) - for k, v := range entry.Data { - data[k] = v + dup := entry.dup() + dup.Data = maps.Clone(entry.Data) + return dup +} + +// dup copies the entry fields shared by derived entries except Data, which +// callers must copy or initialize as appropriate for their use. +func (entry *Entry) dup() *Entry { + return &Entry{ + Logger: entry.Logger, + Time: entry.Time, + Caller: entry.Caller, + Context: entry.Context, + err: entry.err, } - return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, Context: entry.Context, err: entry.err} } // Bytes returns the bytes representation of this entry from the formatter. func (entry *Entry) Bytes() ([]byte, error) { - return entry.Logger.Formatter.Format(entry) + // Snapshot the formatter under the lock to protect against concurrent + // SetFormatter calls, then release the lock before formatting. + // This avoids a data race and prevents a deadlock if Format() triggers + // reentrant logging (e.g., a field's MarshalJSON calls logrus). + // + // See: + // + // - https://github.com/sirupsen/logrus/issues/1440 + // - https://github.com/sirupsen/logrus/issues/1448 + entry.Logger.mu.Lock() + formatter := entry.Logger.Formatter + entry.Logger.mu.Unlock() + + return formatter.Format(entry) } // String returns the string representation from the reader and ultimately the @@ -112,58 +164,61 @@ func (entry *Entry) WithError(err error) *Entry { // WithContext adds a context to the Entry. func (entry *Entry) WithContext(ctx context.Context) *Entry { - dataCopy := make(Fields, len(entry.Data)) - for k, v := range entry.Data { - dataCopy[k] = v - } - return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx} + dup := entry.dup() + dup.Data = maps.Clone(entry.Data) + dup.Context = ctx + return dup } // WithField adds a single field to the Entry. -func (entry *Entry) WithField(key string, value interface{}) *Entry { - return entry.WithFields(Fields{key: value}) +func (entry *Entry) WithField(key string, value any) *Entry { + dup := entry.dup() + dup.Data = maps.Clone(entry.Data) + dup.addField(key, value) + return dup } // WithFields adds a map of fields to the Entry. func (entry *Entry) WithFields(fields Fields) *Entry { - data := make(Fields, len(entry.Data)+len(fields)) - for k, v := range entry.Data { - data[k] = v + dup := entry.dup() + dup.Data = make(Fields, len(entry.Data)+len(fields)) + maps.Copy(dup.Data, entry.Data) + + for key, value := range fields { + dup.addField(key, value) } - fieldErr := entry.err - for k, v := range fields { - isErrField := false - if t := reflect.TypeOf(v); t != nil { - switch { - case t.Kind() == reflect.Func, t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Func: - isErrField = true - } - } - if isErrField { - tmp := fmt.Sprintf("can not add field %q", k) - if fieldErr != "" { - fieldErr = entry.err + ", " + tmp + return dup +} + +// WithTime overrides the time of the Entry. +func (entry *Entry) WithTime(t time.Time) *Entry { + dup := entry.dup() + dup.Data = maps.Clone(entry.Data) + dup.Time = t + return dup +} + +func (entry *Entry) addField(key string, value any) { + if _, ok := value.(error); !ok { + t := reflect.TypeOf(value) + if t != nil && (t.Kind() == reflect.Func || t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.Func) { + if entry.err != "" { + entry.err += ", skipping unsupported field " + strconv.Quote(key) } else { - fieldErr = tmp + entry.err = "skipping unsupported field " + strconv.Quote(key) } - } else { - data[k] = v + return } } - return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context} -} -// WithTime overrides the time of the Entry. -func (entry *Entry) WithTime(t time.Time) *Entry { - dataCopy := make(Fields, len(entry.Data)) - for k, v := range entry.Data { - dataCopy[k] = v + if entry.Data == nil { + entry.Data = make(Fields, 1) } - return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context} + entry.Data[key] = value } // getPackageName reduces a fully qualified function name to the package name -// There really ought to be to be a better way... +// There really ought to be a better way... func getPackageName(f string) string { for { lastPeriod := strings.LastIndex(f, ".") @@ -186,7 +241,7 @@ func getCaller() *runtime.Frame { _ = runtime.Callers(0, pcs) // dynamic get the package name and the minimum caller depth - for i := 0; i < maximumCallerDepth; i++ { + for i := range maximumCallerDepth { funcName := runtime.FuncForPC(pcs[i]).Name() if strings.Contains(funcName, "getCaller") { logrusPackage = getPackageName(funcName) @@ -215,16 +270,47 @@ func getCaller() *runtime.Frame { return nil } -func (entry Entry) HasCaller() (has bool) { - return entry.Logger != nil && - entry.Logger.ReportCaller && - entry.Caller != nil +// HasCaller reports whether this Entry contains caller information. +// +// Caller may be set explicitly, or populated at log time when +// [Logger.ReportCaller] is enabled. +// +// Deprecated: use [Entry.Caller] != nil instead. +// +//go:fix inline +func (entry Entry) HasCaller() bool { + return entry.Caller != nil } -func (entry *Entry) log(level Level, msg string) { - var buffer *bytes.Buffer +func (entry *Entry) logArgs(level Level, panicAfter bool, args ...any) { + entry.log(level, panicAfter, sprint(args...)) +} - newEntry := entry.Dup() +func (entry *Entry) logf(level Level, panicAfter bool, format string, args ...any) { + entry.log(level, panicAfter, fmt.Sprintf(format, args...)) +} + +// logln uses Sprintln for multiple arguments to preserve Println-style +// spacing between args, then trims the trailing newline. +func (entry *Entry) logln(level Level, panicAfter bool, args ...any) { + if len(args) <= 1 { + entry.log(level, panicAfter, sprint(args...)) + return + } + msg := fmt.Sprintln(args...) + msg = msg[:len(msg)-1] // Trim the newline added by Sprintln; logging adds its own. + entry.log(level, panicAfter, msg) +} + +// log writes msg at level. If panicAfter is true, it panics with the fully +// populated entry after hooks and output have completed. +// +// The explicit flag keeps panic behavior limited to Panic, Panicf, and +// Panicln while avoiding a return value used only as the panic value. +// See #1283 and commits f96066e and 5f8c666. +func (entry *Entry) log(level Level, panicAfter bool, msg string) { + newEntry := entry.dup() + newEntry.Data = maps.Clone(entry.Data) if newEntry.Time.IsZero() { newEntry.Time = time.Now() @@ -233,17 +319,24 @@ func (entry *Entry) log(level Level, msg string) { newEntry.Level = level newEntry.Message = msg - newEntry.Logger.mu.Lock() - reportCaller := newEntry.Logger.ReportCaller + logger := newEntry.Logger + logger.mu.Lock() + reportCaller := logger.ReportCaller bufPool := newEntry.getBufferPool() - newEntry.Logger.mu.Unlock() + logger.mu.Unlock() - if reportCaller { + // Preserve explicitly set caller information. + if reportCaller && newEntry.Caller == nil { newEntry.Caller = getCaller() } - newEntry.fireHooks() - buffer = bufPool.Get() + // Select hooks based on the level for this log call. Hooks receive the + // Entry and may mutate it, but that does not affect which hooks are + // fired for this event. + hooks := logger.hooksForLevel(level) + newEntry.fireHooks(hooks) + + buffer := bufPool.Get() defer func() { newEntry.Buffer = nil buffer.Reset() @@ -251,15 +344,12 @@ func (entry *Entry) log(level Level, msg string) { }() buffer.Reset() newEntry.Buffer = buffer - newEntry.write() - newEntry.Buffer = nil - // To avoid Entry#log() returning a value that only would make sense for - // panic() to use in Entry#Panic(), we avoid the allocation by checking - // directly here. - if level <= PanicLevel { + // Panic here so the panic value contains the fully populated entry without + // requiring log to return it to the caller. + if panicAfter { panic(newEntry) } } @@ -271,175 +361,207 @@ func (entry *Entry) getBufferPool() (pool BufferPool) { return bufferPool } -func (entry *Entry) fireHooks() { - var tmpHooks LevelHooks - entry.Logger.mu.Lock() - tmpHooks = make(LevelHooks, len(entry.Logger.Hooks)) - for k, v := range entry.Logger.Hooks { - tmpHooks[k] = v - } - entry.Logger.mu.Unlock() - - err := tmpHooks.Fire(entry.Level, entry) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) +func (entry *Entry) fireHooks(hooks []Hook) { + for _, hook := range hooks { + if err := hook.Fire(entry); err != nil { + _, _ = fmt.Fprintln(os.Stderr, "Failed to fire hook:", err) + return + } } } func (entry *Entry) write() { + // Snapshot the formatter under the lock to protect against concurrent + // SetFormatter calls, then release the lock before formatting. + // This avoids a deadlock when Format() triggers reentrant logging (e.g., + // a field's MarshalJSON calls logrus). See #1448, #1440. entry.Logger.mu.Lock() - defer entry.Logger.mu.Unlock() - serialized, err := entry.Logger.Formatter.Format(entry) + formatter := entry.Logger.Formatter + entry.Logger.mu.Unlock() + + serialized, err := formatter.Format(entry) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) + _, _ = fmt.Fprintln(os.Stderr, "Failed to format entry:", err) return } + + // Re-acquire the lock to serialize writes to the underlying io.Writer. + entry.Logger.mu.Lock() + defer entry.Logger.mu.Unlock() if _, err := entry.Logger.Out.Write(serialized); err != nil { - fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) + _, _ = fmt.Fprintln(os.Stderr, "Failed to write to log:", err) } } -// Log will log a message at the level given as parameter. -// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. -// For this behaviour Entry.Panic or Entry.Fatal should be used instead. -func (entry *Entry) Log(level Level, args ...interface{}) { +// Log logs a message at the specified level. +// +// Using Log with [PanicLevel] or [FatalLevel] intentionally does not +// trigger a panic or exit. Log treats the level as logging severity only; +// use [Entry.Panic] or [Entry.Fatal] when those side effects are desired. +func (entry *Entry) Log(level Level, args ...any) { + const panicAfter = false if entry.Logger.IsLevelEnabled(level) { - entry.log(level, fmt.Sprint(args...)) + entry.logArgs(level, panicAfter, args...) } } -func (entry *Entry) Trace(args ...interface{}) { +func (entry *Entry) Trace(args ...any) { entry.Log(TraceLevel, args...) } -func (entry *Entry) Debug(args ...interface{}) { +func (entry *Entry) Debug(args ...any) { entry.Log(DebugLevel, args...) } -func (entry *Entry) Print(args ...interface{}) { +func (entry *Entry) Print(args ...any) { entry.Info(args...) } -func (entry *Entry) Info(args ...interface{}) { +func (entry *Entry) Info(args ...any) { entry.Log(InfoLevel, args...) } -func (entry *Entry) Warn(args ...interface{}) { +func (entry *Entry) Warn(args ...any) { entry.Log(WarnLevel, args...) } -func (entry *Entry) Warning(args ...interface{}) { +func (entry *Entry) Warning(args ...any) { entry.Warn(args...) } -func (entry *Entry) Error(args ...interface{}) { +func (entry *Entry) Error(args ...any) { entry.Log(ErrorLevel, args...) } -func (entry *Entry) Fatal(args ...interface{}) { +func (entry *Entry) Fatal(args ...any) { entry.Log(FatalLevel, args...) entry.Logger.Exit(1) } -func (entry *Entry) Panic(args ...interface{}) { - entry.Log(PanicLevel, args...) +func (entry *Entry) Panic(args ...any) { + const panicAfter = true + if entry.Logger.IsLevelEnabled(PanicLevel) { + entry.logArgs(PanicLevel, panicAfter, args...) + } } // Entry Printf family functions -func (entry *Entry) Logf(level Level, format string, args ...interface{}) { +// Logf logs a formatted message at the specified level. +// +// Using Logf with [PanicLevel] or [FatalLevel] intentionally does not +// trigger a panic or exit. Logf treats the level as logging severity only; +// use [Entry.Panicf] or [Entry.Fatalf] when those side effects are desired. +func (entry *Entry) Logf(level Level, format string, args ...any) { + const panicAfter = false if entry.Logger.IsLevelEnabled(level) { - entry.Log(level, fmt.Sprintf(format, args...)) + entry.logf(level, panicAfter, format, args...) } } -func (entry *Entry) Tracef(format string, args ...interface{}) { +func (entry *Entry) Tracef(format string, args ...any) { entry.Logf(TraceLevel, format, args...) } -func (entry *Entry) Debugf(format string, args ...interface{}) { +func (entry *Entry) Debugf(format string, args ...any) { entry.Logf(DebugLevel, format, args...) } -func (entry *Entry) Infof(format string, args ...interface{}) { +func (entry *Entry) Infof(format string, args ...any) { entry.Logf(InfoLevel, format, args...) } -func (entry *Entry) Printf(format string, args ...interface{}) { +func (entry *Entry) Printf(format string, args ...any) { entry.Infof(format, args...) } -func (entry *Entry) Warnf(format string, args ...interface{}) { +func (entry *Entry) Warnf(format string, args ...any) { entry.Logf(WarnLevel, format, args...) } -func (entry *Entry) Warningf(format string, args ...interface{}) { +func (entry *Entry) Warningf(format string, args ...any) { entry.Warnf(format, args...) } -func (entry *Entry) Errorf(format string, args ...interface{}) { +func (entry *Entry) Errorf(format string, args ...any) { entry.Logf(ErrorLevel, format, args...) } -func (entry *Entry) Fatalf(format string, args ...interface{}) { +func (entry *Entry) Fatalf(format string, args ...any) { entry.Logf(FatalLevel, format, args...) entry.Logger.Exit(1) } -func (entry *Entry) Panicf(format string, args ...interface{}) { - entry.Logf(PanicLevel, format, args...) +func (entry *Entry) Panicf(format string, args ...any) { + const panicAfter = true + if entry.Logger.IsLevelEnabled(PanicLevel) { + entry.logf(PanicLevel, panicAfter, format, args...) + } } // Entry Println family functions -func (entry *Entry) Logln(level Level, args ...interface{}) { +// Logln logs a message at the specified level with Println-style spacing. +// +// Using Logln with [PanicLevel] or [FatalLevel] intentionally does not +// trigger a panic or exit. Logln treats the level as logging severity only; +// use [Entry.Panicln] or [Entry.Fatalln] when those side effects are desired. +func (entry *Entry) Logln(level Level, args ...any) { + const panicAfter = false if entry.Logger.IsLevelEnabled(level) { - entry.Log(level, entry.sprintlnn(args...)) + entry.logln(level, panicAfter, args...) } } -func (entry *Entry) Traceln(args ...interface{}) { +func (entry *Entry) Traceln(args ...any) { entry.Logln(TraceLevel, args...) } -func (entry *Entry) Debugln(args ...interface{}) { +func (entry *Entry) Debugln(args ...any) { entry.Logln(DebugLevel, args...) } -func (entry *Entry) Infoln(args ...interface{}) { +func (entry *Entry) Infoln(args ...any) { entry.Logln(InfoLevel, args...) } -func (entry *Entry) Println(args ...interface{}) { +func (entry *Entry) Println(args ...any) { entry.Infoln(args...) } -func (entry *Entry) Warnln(args ...interface{}) { +func (entry *Entry) Warnln(args ...any) { entry.Logln(WarnLevel, args...) } -func (entry *Entry) Warningln(args ...interface{}) { +func (entry *Entry) Warningln(args ...any) { entry.Warnln(args...) } -func (entry *Entry) Errorln(args ...interface{}) { +func (entry *Entry) Errorln(args ...any) { entry.Logln(ErrorLevel, args...) } -func (entry *Entry) Fatalln(args ...interface{}) { +func (entry *Entry) Fatalln(args ...any) { entry.Logln(FatalLevel, args...) entry.Logger.Exit(1) } -func (entry *Entry) Panicln(args ...interface{}) { - entry.Logln(PanicLevel, args...) +func (entry *Entry) Panicln(args ...any) { + const panicAfter = true + if entry.Logger.IsLevelEnabled(PanicLevel) { + entry.logln(PanicLevel, panicAfter, args...) + } } -// sprintlnn => Sprint no newline. This is to get the behavior of how -// fmt.Sprintln where spaces are always added between operands, regardless of -// their type. Instead of vendoring the Sprintln implementation to spare a -// string allocation, we do the simplest thing. -func (entry *Entry) sprintlnn(args ...interface{}) string { - msg := fmt.Sprintln(args...) - return msg[:len(msg)-1] +// sprint is fmt.Sprint with fast paths for zero or one string argument. +func sprint(args ...any) string { + switch len(args) { + case 0: + return "" + case 1: + if msg, ok := args[0].(string); ok { + return msg + } + } + return fmt.Sprint(args...) } diff --git a/vendor/github.com/sirupsen/logrus/exported.go b/vendor/github.com/sirupsen/logrus/exported.go index 017c30ce67..8b261c124d 100644 --- a/vendor/github.com/sirupsen/logrus/exported.go +++ b/vendor/github.com/sirupsen/logrus/exported.go @@ -6,11 +6,12 @@ import ( "time" ) -var ( - // std is the name of the standard logger in stdlib `log` - std = New() -) +// std is the package-level standard logger, similar to the default logger +// in the stdlib [log] package. +var std = New() +// StandardLogger returns the package-level standard logger used by +// the top-level logging functions. func StandardLogger() *Logger { return std } @@ -41,7 +42,7 @@ func GetLevel() Level { return std.GetLevel() } -// IsLevelEnabled checks if the log level of the standard logger is greater than the level param +// IsLevelEnabled checks if logging for the given level is enabled for the standard logger. func IsLevelEnabled(level Level) bool { return std.IsLevelEnabled(level) } @@ -51,9 +52,10 @@ func AddHook(hook Hook) { std.AddHook(hook) } -// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. +// WithError creates an entry from the standard logger and adds an error to it, +// using the value defined in [ErrorKey] as key. func WithError(err error) *Entry { - return std.WithField(ErrorKey, err) + return std.WithError(err) } // WithContext creates an entry from the standard logger and adds a context to it. @@ -61,210 +63,203 @@ func WithContext(ctx context.Context) *Entry { return std.WithContext(ctx) } -// WithField creates an entry from the standard logger and adds a field to -// it. If you want multiple fields, use `WithFields`. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithField(key string, value interface{}) *Entry { +// WithField creates an entry from the standard logger and adds a single field. +// For multiple fields, prefer [WithFields] over chaining WithField calls. +func WithField(key string, value any) *Entry { return std.WithField(key, value) } -// WithFields creates an entry from the standard logger and adds multiple -// fields to it. This is simply a helper for `WithField`, invoking it -// once for each field. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. +// WithFields creates an entry from the standard logger and adds the fields to it. func WithFields(fields Fields) *Entry { return std.WithFields(fields) } -// WithTime creates an entry from the standard logger and overrides the time of -// logs generated with it. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. +// WithTime creates an entry from the standard logger and overrides the time +// used for logs generated with it. func WithTime(t time.Time) *Entry { return std.WithTime(t) } -// Trace logs a message at level Trace on the standard logger. -func Trace(args ...interface{}) { +// Trace logs a message at level [TraceLevel] on the standard logger. +func Trace(args ...any) { std.Trace(args...) } -// Debug logs a message at level Debug on the standard logger. -func Debug(args ...interface{}) { +// Debug logs a message at level [DebugLevel] on the standard logger. +func Debug(args ...any) { std.Debug(args...) } -// Print logs a message at level Info on the standard logger. -func Print(args ...interface{}) { +// Print logs a message at level [InfoLevel] on the standard logger. +func Print(args ...any) { std.Print(args...) } -// Info logs a message at level Info on the standard logger. -func Info(args ...interface{}) { +// Info logs a message at level [InfoLevel] on the standard logger. +func Info(args ...any) { std.Info(args...) } -// Warn logs a message at level Warn on the standard logger. -func Warn(args ...interface{}) { +// Warn logs a message at level [WarnLevel] on the standard logger. +func Warn(args ...any) { std.Warn(args...) } -// Warning logs a message at level Warn on the standard logger. -func Warning(args ...interface{}) { +// Warning logs a message at level [WarnLevel] on the standard logger. +func Warning(args ...any) { std.Warning(args...) } -// Error logs a message at level Error on the standard logger. -func Error(args ...interface{}) { +// Error logs a message at level [ErrorLevel] on the standard logger. +func Error(args ...any) { std.Error(args...) } -// Panic logs a message at level Panic on the standard logger. -func Panic(args ...interface{}) { +// Panic logs a message at level [PanicLevel] on the standard logger. +func Panic(args ...any) { std.Panic(args...) } -// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1. -func Fatal(args ...interface{}) { +// Fatal logs a message at level [FatalLevel] on the standard logger, +// then exits the process with status 1. +func Fatal(args ...any) { std.Fatal(args...) } -// TraceFn logs a message from a func at level Trace on the standard logger. +// TraceFn logs a message from a func at level [TraceLevel] on the standard logger. func TraceFn(fn LogFunction) { std.TraceFn(fn) } -// DebugFn logs a message from a func at level Debug on the standard logger. +// DebugFn logs a message from a func at level [DebugLevel] on the standard logger. func DebugFn(fn LogFunction) { std.DebugFn(fn) } -// PrintFn logs a message from a func at level Info on the standard logger. +// PrintFn logs a message from a func at level [InfoLevel] on the standard logger. func PrintFn(fn LogFunction) { std.PrintFn(fn) } -// InfoFn logs a message from a func at level Info on the standard logger. +// InfoFn logs a message from a func at level [InfoLevel] on the standard logger. func InfoFn(fn LogFunction) { std.InfoFn(fn) } -// WarnFn logs a message from a func at level Warn on the standard logger. +// WarnFn logs a message from a func at level [WarnLevel] on the standard logger. func WarnFn(fn LogFunction) { std.WarnFn(fn) } -// WarningFn logs a message from a func at level Warn on the standard logger. +// WarningFn logs a message from a func at level [WarnLevel] on the standard logger. func WarningFn(fn LogFunction) { std.WarningFn(fn) } -// ErrorFn logs a message from a func at level Error on the standard logger. +// ErrorFn logs a message from a func at level [ErrorLevel] on the standard logger. func ErrorFn(fn LogFunction) { std.ErrorFn(fn) } -// PanicFn logs a message from a func at level Panic on the standard logger. +// PanicFn logs a message from a func at level [PanicLevel] on the standard logger. func PanicFn(fn LogFunction) { std.PanicFn(fn) } -// FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1. +// FatalFn logs a message from a func at level [FatalLevel] on the standard logger, +// then exits the process with status 1. func FatalFn(fn LogFunction) { std.FatalFn(fn) } -// Tracef logs a message at level Trace on the standard logger. -func Tracef(format string, args ...interface{}) { +// Tracef logs a message at level [TraceLevel] on the standard logger. +func Tracef(format string, args ...any) { std.Tracef(format, args...) } -// Debugf logs a message at level Debug on the standard logger. -func Debugf(format string, args ...interface{}) { +// Debugf logs a message at level [DebugLevel] on the standard logger. +func Debugf(format string, args ...any) { std.Debugf(format, args...) } -// Printf logs a message at level Info on the standard logger. -func Printf(format string, args ...interface{}) { +// Printf logs a message at level [InfoLevel] on the standard logger. +func Printf(format string, args ...any) { std.Printf(format, args...) } -// Infof logs a message at level Info on the standard logger. -func Infof(format string, args ...interface{}) { +// Infof logs a message at level [InfoLevel] on the standard logger. +func Infof(format string, args ...any) { std.Infof(format, args...) } -// Warnf logs a message at level Warn on the standard logger. -func Warnf(format string, args ...interface{}) { +// Warnf logs a message at level [WarnLevel] on the standard logger. +func Warnf(format string, args ...any) { std.Warnf(format, args...) } -// Warningf logs a message at level Warn on the standard logger. -func Warningf(format string, args ...interface{}) { +// Warningf logs a message at level [WarnLevel] on the standard logger. +func Warningf(format string, args ...any) { std.Warningf(format, args...) } -// Errorf logs a message at level Error on the standard logger. -func Errorf(format string, args ...interface{}) { +// Errorf logs a message at level [ErrorLevel] on the standard logger. +func Errorf(format string, args ...any) { std.Errorf(format, args...) } -// Panicf logs a message at level Panic on the standard logger. -func Panicf(format string, args ...interface{}) { +// Panicf logs a message at level [PanicLevel] on the standard logger. +func Panicf(format string, args ...any) { std.Panicf(format, args...) } -// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1. -func Fatalf(format string, args ...interface{}) { +// Fatalf logs a message at level [FatalLevel] on the standard logger, +// then exits the process with status 1. +func Fatalf(format string, args ...any) { std.Fatalf(format, args...) } -// Traceln logs a message at level Trace on the standard logger. -func Traceln(args ...interface{}) { +// Traceln logs a message at level [TraceLevel] on the standard logger. +func Traceln(args ...any) { std.Traceln(args...) } -// Debugln logs a message at level Debug on the standard logger. -func Debugln(args ...interface{}) { +// Debugln logs a message at level [DebugLevel] on the standard logger. +func Debugln(args ...any) { std.Debugln(args...) } -// Println logs a message at level Info on the standard logger. -func Println(args ...interface{}) { +// Println logs a message at level [InfoLevel] on the standard logger. +func Println(args ...any) { std.Println(args...) } -// Infoln logs a message at level Info on the standard logger. -func Infoln(args ...interface{}) { +// Infoln logs a message at level [InfoLevel] on the standard logger. +func Infoln(args ...any) { std.Infoln(args...) } -// Warnln logs a message at level Warn on the standard logger. -func Warnln(args ...interface{}) { +// Warnln logs a message at level [WarnLevel] on the standard logger. +func Warnln(args ...any) { std.Warnln(args...) } -// Warningln logs a message at level Warn on the standard logger. -func Warningln(args ...interface{}) { +// Warningln logs a message at level [WarnLevel] on the standard logger. +func Warningln(args ...any) { std.Warningln(args...) } -// Errorln logs a message at level Error on the standard logger. -func Errorln(args ...interface{}) { +// Errorln logs a message at level [ErrorLevel] on the standard logger. +func Errorln(args ...any) { std.Errorln(args...) } -// Panicln logs a message at level Panic on the standard logger. -func Panicln(args ...interface{}) { +// Panicln logs a message at level [PanicLevel] on the standard logger. +func Panicln(args ...any) { std.Panicln(args...) } -// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1. -func Fatalln(args ...interface{}) { +// Fatalln logs a message at level [FatalLevel] on the standard logger, +// then exits the process with status 1. +func Fatalln(args ...any) { std.Fatalln(args...) } diff --git a/vendor/github.com/sirupsen/logrus/formatter.go b/vendor/github.com/sirupsen/logrus/formatter.go index 408883773e..16f2e0e0fc 100644 --- a/vendor/github.com/sirupsen/logrus/formatter.go +++ b/vendor/github.com/sirupsen/logrus/formatter.go @@ -2,27 +2,40 @@ package logrus import "time" -// Default key names for the default fields const ( + // defaultTimestampFormat is the layout used to format entry timestamps + // when a formatter has not specified a custom TimestampFormat. + // It follows time.RFC3339 and is applied unless timestamps are disabled. defaultTimestampFormat = time.RFC3339 - FieldKeyMsg = "msg" - FieldKeyLevel = "level" - FieldKeyTime = "time" - FieldKeyLogrusError = "logrus_error" - FieldKeyFunc = "func" - FieldKeyFile = "file" + + // defaultFields is the number of commonly included predefined log entry fields + // (msg, level, time). It is used as a capacity hint when constructing + // intermediate collections during formatting (for example, the fixed key list). + // + // It does not include the optional "logrus_error", "func", or "file" fields. + defaultFields = 3 +) + +// Default key names for the default fields +const ( + FieldKeyMsg = "msg" + FieldKeyLevel = "level" + FieldKeyTime = "time" + FieldKeyLogrusError = "logrus_error" + FieldKeyFunc = "func" + FieldKeyFile = "file" ) -// The Formatter interface is used to implement a custom Formatter. It takes an -// `Entry`. It exposes all the fields, including the default ones: +// Formatter is implemented by types that format log entries. It receives an +// [*Entry], which contains: // -// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. -// * `entry.Data["time"]`. The timestamp. -// * `entry.Data["level"]. The level the entry was logged at. +// - entry.Message: the message passed to logging methods such as [Info], [Warn], [Error] +// - entry.Time: the timestamp +// - entry.Level: the log level // -// Any additional fields added with `WithField` or `WithFields` are also in -// `entry.Data`. Format is expected to return an array of bytes which are then -// logged to `logger.Out`. +// Additional fields added with [WithField] or [WithFields] are available in +// [Entry.Data]. Format should return the formatted log entry as a byte slice, +// which is written to [Logger.Out]. type Formatter interface { Format(*Entry) ([]byte, error) } @@ -30,12 +43,12 @@ type Formatter interface { // This is to not silently overwrite `time`, `msg`, `func` and `level` fields when // dumping it. If this code wasn't there doing: // -// logrus.WithField("level", 1).Info("hello") +// logrus.WithField("level", 1).Info("hello") // // Would just silently drop the user provided level. Instead with this code // it'll logged as: // -// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} +// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} // // It's not exported because it's still using Data in an opinionated way. It's to // avoid code duplication between the two default formatters. diff --git a/vendor/github.com/sirupsen/logrus/json_formatter.go b/vendor/github.com/sirupsen/logrus/json_formatter.go index c96dc5636b..fac7695e9e 100644 --- a/vendor/github.com/sirupsen/logrus/json_formatter.go +++ b/vendor/github.com/sirupsen/logrus/json_formatter.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "runtime" + "strconv" ) type fieldKey string @@ -20,7 +21,13 @@ func (f FieldMap) resolve(key fieldKey) string { return string(key) } -// JSONFormatter formats logs into parsable json +// JSONFormatter formats logs into parsable JSON. +// +// Fields from [Entry.Data] are included in the JSON object together with the +// standard fields derived from the entry. If a field conflicts with a standard +// field, it is prefixed with "fields.". Standard field names can be customized +// through FieldMap. When DataKey is set, fields from [Entry.Data] are nested +// under that key instead. type JSONFormatter struct { // TimestampFormat sets the format used for marshaling timestamps. // The format to use is the same than for time.Format or time.Parse from the standard @@ -61,7 +68,8 @@ type JSONFormatter struct { // Format renders a single log entry func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { - data := make(Fields, len(entry.Data)+4) + caller := entry.Caller + data := make(Fields, len(entry.Data)+defaultFields) for k, v := range entry.Data { switch v := v.(type) { case error: @@ -73,13 +81,14 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { } } - if f.DataKey != "" { - newData := make(Fields, 4) + if f.DataKey != "" && len(entry.Data) > 0 { + newData := make(Fields, defaultFields+1) newData[f.DataKey] = data data = newData } - prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) + hasCaller := caller != nil + prefixFieldClashes(data, f.FieldMap, hasCaller) timestampFormat := f.TimestampFormat if timestampFormat == "" { @@ -94,11 +103,13 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { } data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() - if entry.HasCaller() { - funcVal := entry.Caller.Function - fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) + if caller != nil { + var funcVal, fileVal string if f.CallerPrettyfier != nil { - funcVal, fileVal = f.CallerPrettyfier(entry.Caller) + funcVal, fileVal = f.CallerPrettyfier(caller) + } else { + funcVal = caller.Function + fileVal = caller.File + ":" + strconv.FormatInt(int64(caller.Line), 10) } if funcVal != "" { data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal @@ -108,11 +119,9 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { } } - var b *bytes.Buffer - if entry.Buffer != nil { - b = entry.Buffer - } else { - b = &bytes.Buffer{} + b := entry.Buffer + if b == nil { + b = new(bytes.Buffer) } encoder := json.NewEncoder(b) diff --git a/vendor/github.com/sirupsen/logrus/level.go b/vendor/github.com/sirupsen/logrus/level.go new file mode 100644 index 0000000000..7bd4255d3c --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/level.go @@ -0,0 +1,101 @@ +package logrus + +import ( + "strings" + "sync" +) + +const ( + ansiReset = "\x1b[0m" // reset attributes + ansiRed = "\x1b[31m" // red + ansiYellow = "\x1b[33m" // yellow + ansiCyan = "\x1b[36m" // cyan + ansiDimCyan = "\x1b[2;36m" // dim cyan + ansiDimWhite = "\x1b[2;37m" // dim white (light gray) +) + +type lvlPrefix struct { + full string + truncated string + padded string +} + +func colorize(level Level, s string) string { + color := ansiCyan + switch level { + case TraceLevel: + color = ansiDimWhite + case DebugLevel: + color = ansiDimCyan + case WarnLevel: + color = ansiYellow + case ErrorLevel, FatalLevel, PanicLevel: + color = ansiRed + case InfoLevel: + color = ansiCyan + } + return color + s + ansiReset +} + +func formatLevel(level Level, disableTrunc, pad bool, maxLen int) string { + upper := strings.ToUpper(level.String()) + + if pad && maxLen > len(upper) { + upper += strings.Repeat(" ", maxLen-len(upper)) + } + + if !pad && !disableTrunc && len(upper) > 4 { + upper = upper[:4] + } + + return colorize(level, upper) +} + +var levelPrefixOnce = sync.OnceValues(func() (map[Level]lvlPrefix, lvlPrefix) { + var maxLevel Level + maxLen := 0 + for _, lvl := range AllLevels { + if lvl > maxLevel { + maxLevel = lvl + } + if l := len(lvl.String()); l > maxLen { + maxLen = l + } + } + + prefix := make(map[Level]lvlPrefix, len(AllLevels)) + for _, lvl := range AllLevels { + prefix[lvl] = lvlPrefix{ + full: formatLevel(lvl, true, false, maxLen), + truncated: formatLevel(lvl, false, false, maxLen), + padded: formatLevel(lvl, true, true, maxLen), + } + } + + unknownLevel := maxLevel + 1 + unknown := lvlPrefix{ + full: formatLevel(unknownLevel, true, false, maxLen), + truncated: formatLevel(unknownLevel, false, false, maxLen), + padded: formatLevel(unknownLevel, true, true, maxLen), + } + + return prefix, unknown +}) + +func levelPrefix(level Level, disableTrunc, pad bool) string { + prefix, unknown := levelPrefixOnce() + + p, ok := prefix[level] + if !ok { + p = unknown + } + + switch { + case pad: + return p.padded + case !disableTrunc: + return p.truncated + default: + return p.full + } +} diff --git a/vendor/github.com/sirupsen/logrus/logger.go b/vendor/github.com/sirupsen/logrus/logger.go index f5b8c439ee..17a46e6a65 100644 --- a/vendor/github.com/sirupsen/logrus/logger.go +++ b/vendor/github.com/sirupsen/logrus/logger.go @@ -12,17 +12,19 @@ import ( // LogFunction For big messages, it can be more efficient to pass a function // and only call it if the log level is actually enables rather than // generating the log message and then checking if the level is enabled -type LogFunction func() []interface{} +type LogFunction func() []any type Logger struct { // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a // file, or leave it default which is `os.Stderr`. You can also set this to // something more adventurous, such as logging to Kafka. Out io.Writer + // Hooks for the logger instance. These allow firing events based on logging // levels and log entries. For example, to send errors to an error tracking // service, log to StatsD or dump the core on fatal errors. Hooks LevelHooks + // All log entries pass through the formatter before logged to Out. The // included formatters are `TextFormatter` and `JSONFormatter` for which // TextFormatter is the default. In development (when a TTY is attached) it @@ -38,37 +40,44 @@ type Logger struct { // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be // logged. Level Level + // Used to sync writing to the log. Locking is enabled by Default - mu MutexWrap + mu mutexWrap + // Reusable empty entry entryPool sync.Pool + // Function to exit the application, defaults to `os.Exit()` - ExitFunc exitFunc + ExitFunc func(int) + // The buffer pool used to format the log. If it is nil, the default global // buffer pool will be used. BufferPool BufferPool } -type exitFunc func(int) +// MutexWrap is the mutex implementation used by [Logger]. +// +// Deprecated: MutexWrap is an implementation detail of Logger and should not be used directly. +type MutexWrap = mutexWrap -type MutexWrap struct { +type mutexWrap struct { lock sync.Mutex disabled bool } -func (mw *MutexWrap) Lock() { +func (mw *mutexWrap) Lock() { if !mw.disabled { mw.lock.Lock() } } -func (mw *MutexWrap) Unlock() { +func (mw *mutexWrap) Unlock() { if !mw.disabled { mw.lock.Unlock() } } -func (mw *MutexWrap) Disable() { +func (mw *mutexWrap) Disable() { mw.disabled = true } @@ -104,7 +113,7 @@ func (logger *Logger) newEntry() *Entry { } func (logger *Logger) releaseEntry(entry *Entry) { - entry.Data = map[string]interface{}{} + entry.Data = map[string]any{} logger.entryPool.Put(entry) } @@ -112,7 +121,7 @@ func (logger *Logger) releaseEntry(entry *Entry) { // Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to // this new returned entry. // If you want multiple fields, use `WithFields`. -func (logger *Logger) WithField(key string, value interface{}) *Entry { +func (logger *Logger) WithField(key string, value any) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) return entry.WithField(key, value) @@ -148,7 +157,12 @@ func (logger *Logger) WithTime(t time.Time) *Entry { return entry.WithTime(t) } -func (logger *Logger) Logf(level Level, format string, args ...interface{}) { +// Logf logs a formatted message at the specified level. +// +// Using Logf with [PanicLevel] or [FatalLevel] intentionally does not +// trigger a panic or exit. Logf treats the level as logging severity only; +// use [Logger.Panicf] or [Logger.Fatalf] when those side effects are desired. +func (logger *Logger) Logf(level Level, format string, args ...any) { if logger.IsLevelEnabled(level) { entry := logger.newEntry() entry.Logf(level, format, args...) @@ -156,49 +170,55 @@ func (logger *Logger) Logf(level Level, format string, args ...interface{}) { } } -func (logger *Logger) Tracef(format string, args ...interface{}) { +func (logger *Logger) Tracef(format string, args ...any) { logger.Logf(TraceLevel, format, args...) } -func (logger *Logger) Debugf(format string, args ...interface{}) { +func (logger *Logger) Debugf(format string, args ...any) { logger.Logf(DebugLevel, format, args...) } -func (logger *Logger) Infof(format string, args ...interface{}) { +func (logger *Logger) Infof(format string, args ...any) { logger.Logf(InfoLevel, format, args...) } -func (logger *Logger) Printf(format string, args ...interface{}) { +func (logger *Logger) Printf(format string, args ...any) { entry := logger.newEntry() entry.Printf(format, args...) logger.releaseEntry(entry) } -func (logger *Logger) Warnf(format string, args ...interface{}) { +func (logger *Logger) Warnf(format string, args ...any) { logger.Logf(WarnLevel, format, args...) } -func (logger *Logger) Warningf(format string, args ...interface{}) { +func (logger *Logger) Warningf(format string, args ...any) { logger.Warnf(format, args...) } -func (logger *Logger) Errorf(format string, args ...interface{}) { +func (logger *Logger) Errorf(format string, args ...any) { logger.Logf(ErrorLevel, format, args...) } -func (logger *Logger) Fatalf(format string, args ...interface{}) { +func (logger *Logger) Fatalf(format string, args ...any) { logger.Logf(FatalLevel, format, args...) logger.Exit(1) } -func (logger *Logger) Panicf(format string, args ...interface{}) { - logger.Logf(PanicLevel, format, args...) +func (logger *Logger) Panicf(format string, args ...any) { + if logger.IsLevelEnabled(PanicLevel) { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + entry.Panicf(format, args...) + } } -// Log will log a message at the level given as parameter. -// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. -// For this behaviour Logger.Panic or Logger.Fatal should be used instead. -func (logger *Logger) Log(level Level, args ...interface{}) { +// Log logs a message at the specified level. +// +// Using Log with [PanicLevel] or [FatalLevel] intentionally does not +// trigger a panic or exit. Log treats the level as logging severity only; +// use [Logger.Panic] or [Logger.Fatal] when those side effects are desired. +func (logger *Logger) Log(level Level, args ...any) { if logger.IsLevelEnabled(level) { entry := logger.newEntry() entry.Log(level, args...) @@ -206,6 +226,11 @@ func (logger *Logger) Log(level Level, args ...interface{}) { } } +// LogFn logs a message returned by fn at the specified level. +// +// Using LogFn with [PanicLevel] or [FatalLevel] intentionally does not +// trigger a panic or exit. LogFn treats the level as logging severity only; +// use [Logger.PanicFn] or [Logger.FatalFn] when those side effects are desired. func (logger *Logger) LogFn(level Level, fn LogFunction) { if logger.IsLevelEnabled(level) { entry := logger.newEntry() @@ -214,43 +239,47 @@ func (logger *Logger) LogFn(level Level, fn LogFunction) { } } -func (logger *Logger) Trace(args ...interface{}) { +func (logger *Logger) Trace(args ...any) { logger.Log(TraceLevel, args...) } -func (logger *Logger) Debug(args ...interface{}) { +func (logger *Logger) Debug(args ...any) { logger.Log(DebugLevel, args...) } -func (logger *Logger) Info(args ...interface{}) { +func (logger *Logger) Info(args ...any) { logger.Log(InfoLevel, args...) } -func (logger *Logger) Print(args ...interface{}) { +func (logger *Logger) Print(args ...any) { entry := logger.newEntry() entry.Print(args...) logger.releaseEntry(entry) } -func (logger *Logger) Warn(args ...interface{}) { +func (logger *Logger) Warn(args ...any) { logger.Log(WarnLevel, args...) } -func (logger *Logger) Warning(args ...interface{}) { +func (logger *Logger) Warning(args ...any) { logger.Warn(args...) } -func (logger *Logger) Error(args ...interface{}) { +func (logger *Logger) Error(args ...any) { logger.Log(ErrorLevel, args...) } -func (logger *Logger) Fatal(args ...interface{}) { +func (logger *Logger) Fatal(args ...any) { logger.Log(FatalLevel, args...) logger.Exit(1) } -func (logger *Logger) Panic(args ...interface{}) { - logger.Log(PanicLevel, args...) +func (logger *Logger) Panic(args ...any) { + if logger.IsLevelEnabled(PanicLevel) { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + entry.Panic(args...) + } } func (logger *Logger) TraceFn(fn LogFunction) { @@ -289,10 +318,19 @@ func (logger *Logger) FatalFn(fn LogFunction) { } func (logger *Logger) PanicFn(fn LogFunction) { - logger.LogFn(PanicLevel, fn) + if logger.IsLevelEnabled(PanicLevel) { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + entry.Panic(fn()...) + } } -func (logger *Logger) Logln(level Level, args ...interface{}) { +// Logln logs a message at the specified level with Println-style spacing. +// +// Using Logln with [PanicLevel] or [FatalLevel] intentionally does not +// trigger a panic or exit. Logln treats the level as logging severity only; +// use [Logger.Panicln] or [Logger.Fatalln] when those side effects are desired. +func (logger *Logger) Logln(level Level, args ...any) { if logger.IsLevelEnabled(level) { entry := logger.newEntry() entry.Logln(level, args...) @@ -300,43 +338,47 @@ func (logger *Logger) Logln(level Level, args ...interface{}) { } } -func (logger *Logger) Traceln(args ...interface{}) { +func (logger *Logger) Traceln(args ...any) { logger.Logln(TraceLevel, args...) } -func (logger *Logger) Debugln(args ...interface{}) { +func (logger *Logger) Debugln(args ...any) { logger.Logln(DebugLevel, args...) } -func (logger *Logger) Infoln(args ...interface{}) { +func (logger *Logger) Infoln(args ...any) { logger.Logln(InfoLevel, args...) } -func (logger *Logger) Println(args ...interface{}) { +func (logger *Logger) Println(args ...any) { entry := logger.newEntry() entry.Println(args...) logger.releaseEntry(entry) } -func (logger *Logger) Warnln(args ...interface{}) { +func (logger *Logger) Warnln(args ...any) { logger.Logln(WarnLevel, args...) } -func (logger *Logger) Warningln(args ...interface{}) { +func (logger *Logger) Warningln(args ...any) { logger.Warnln(args...) } -func (logger *Logger) Errorln(args ...interface{}) { +func (logger *Logger) Errorln(args ...any) { logger.Logln(ErrorLevel, args...) } -func (logger *Logger) Fatalln(args ...interface{}) { +func (logger *Logger) Fatalln(args ...any) { logger.Logln(FatalLevel, args...) logger.Exit(1) } -func (logger *Logger) Panicln(args ...interface{}) { - logger.Logln(PanicLevel, args...) +func (logger *Logger) Panicln(args ...any) { + if logger.IsLevelEnabled(PanicLevel) { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + entry.Panicln(args...) + } } func (logger *Logger) Exit(code int) { @@ -375,7 +417,22 @@ func (logger *Logger) AddHook(hook Hook) { logger.Hooks.Add(hook) } -// IsLevelEnabled checks if the log level of the logger is greater than the level param +// hooksForLevel returns a snapshot of the hooks registered for the given level. +// The returned slice is a shallow copy and may be used without holding logger.mu. +func (logger *Logger) hooksForLevel(level Level) []Hook { + logger.mu.Lock() + hooks := logger.Hooks[level] + if len(hooks) == 0 { + logger.mu.Unlock() + return nil + } + out := make([]Hook, len(hooks)) + copy(out, hooks) + logger.mu.Unlock() + return out +} + +// IsLevelEnabled checks if logging for the given level is enabled. func (logger *Logger) IsLevelEnabled(level Level) bool { return logger.level() >= level } @@ -394,6 +451,7 @@ func (logger *Logger) SetOutput(output io.Writer) { logger.Out = output } +// SetReportCaller sets whether the caller stack frame must be logged. func (logger *Logger) SetReportCaller(reportCaller bool) { logger.mu.Lock() defer logger.mu.Unlock() @@ -403,9 +461,9 @@ func (logger *Logger) SetReportCaller(reportCaller bool) { // ReplaceHooks replaces the logger hooks and returns the old ones func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks { logger.mu.Lock() + defer logger.mu.Unlock() oldHooks := logger.Hooks logger.Hooks = hooks - logger.mu.Unlock() return oldHooks } diff --git a/vendor/github.com/sirupsen/logrus/logrus.go b/vendor/github.com/sirupsen/logrus/logrus.go index 37fc4fef85..d52b4ba73d 100644 --- a/vendor/github.com/sirupsen/logrus/logrus.go +++ b/vendor/github.com/sirupsen/logrus/logrus.go @@ -1,13 +1,13 @@ package logrus import ( + "bytes" "fmt" "log" - "strings" ) // Fields type, used to pass to [WithFields]. -type Fields map[string]interface{} +type Fields map[string]any // Level type // @@ -16,39 +16,56 @@ type Level uint32 // Convert the Level to a string. E.g. [PanicLevel] becomes "panic". func (level Level) String() string { - if b, err := level.MarshalText(); err == nil { - return string(b) - } else { + switch level { + case TraceLevel: + return "trace" + case DebugLevel: + return "debug" + case InfoLevel: + return "info" + case WarnLevel: + return "warning" + case ErrorLevel: + return "error" + case FatalLevel: + return "fatal" + case PanicLevel: + return "panic" + default: return "unknown" } } // ParseLevel takes a string level and returns the Logrus log level constant. func ParseLevel(lvl string) (Level, error) { - switch strings.ToLower(lvl) { - case "panic": + return parseLevel([]byte(lvl)) +} + +func parseLevel(b []byte) (Level, error) { + switch { + case bytes.EqualFold(b, []byte("panic")): return PanicLevel, nil - case "fatal": + case bytes.EqualFold(b, []byte("fatal")): return FatalLevel, nil - case "error": + case bytes.EqualFold(b, []byte("error")): return ErrorLevel, nil - case "warn", "warning": + case bytes.EqualFold(b, []byte("warn")), + bytes.EqualFold(b, []byte("warning")): return WarnLevel, nil - case "info": + case bytes.EqualFold(b, []byte("info")): return InfoLevel, nil - case "debug": + case bytes.EqualFold(b, []byte("debug")): return DebugLevel, nil - case "trace": + case bytes.EqualFold(b, []byte("trace")): return TraceLevel, nil + default: + return 0, fmt.Errorf("not a valid logrus Level: %q", b) } - - var l Level - return l, fmt.Errorf("not a valid logrus Level: %q", lvl) } // UnmarshalText implements encoding.TextUnmarshaler. func (level *Level) UnmarshalText(text []byte) error { - l, err := ParseLevel(string(text)) + l, err := parseLevel(text) if err != nil { return err } @@ -60,23 +77,11 @@ func (level *Level) UnmarshalText(text []byte) error { func (level Level) MarshalText() ([]byte, error) { switch level { - case TraceLevel: - return []byte("trace"), nil - case DebugLevel: - return []byte("debug"), nil - case InfoLevel: - return []byte("info"), nil - case WarnLevel: - return []byte("warning"), nil - case ErrorLevel: - return []byte("error"), nil - case FatalLevel: - return []byte("fatal"), nil - case PanicLevel: - return []byte("panic"), nil + case TraceLevel, DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel, PanicLevel: + return []byte(level.String()), nil + default: + return nil, fmt.Errorf("not a valid logrus level %d", level) } - - return nil, fmt.Errorf("not a valid logrus level %d", level) } // AllLevels exposing all logging levels. @@ -91,7 +96,7 @@ var AllLevels = []Level{ } // These are the different logging levels. You can set the logging level to log -// on your instance of logger, obtained with `logrus.New()`. +// on your instance of logger, obtained with [logrus.New]. const ( // PanicLevel level, highest level of severity. Logs and then calls panic with the // message passed to Debug, Info, ... @@ -113,78 +118,110 @@ const ( TraceLevel ) -// Won't compile if StdLogger can't be realized by a log.Logger +// Compile-time interface assertions. var ( - _ StdLogger = &log.Logger{} - _ StdLogger = &Entry{} - _ StdLogger = &Logger{} + _ StdLogger = (*log.Logger)(nil) + _ StdLogger = (*Entry)(nil) + _ StdLogger = (*Logger)(nil) + + _ FieldLogger = (*Logger)(nil) + _ FieldLogger = (*Entry)(nil) + _ FieldLogger = Ext1FieldLogger(nil) + + _ DebugLogger = (*Logger)(nil) + _ InfoLogger = (*Logger)(nil) + _ WarnLogger = (*Logger)(nil) + _ ErrorLogger = (*Logger)(nil) + _ TraceLogger = (*Logger)(nil) + + _ DebugLogger = (*Entry)(nil) + _ InfoLogger = (*Entry)(nil) + _ WarnLogger = (*Entry)(nil) + _ ErrorLogger = (*Entry)(nil) + _ TraceLogger = (*Entry)(nil) + + _ Ext1FieldLogger = (*Logger)(nil) + _ Ext1FieldLogger = (*Entry)(nil) ) // StdLogger is what your logrus-enabled library should take, that way // it'll accept a stdlib logger ([log.Logger]) and a logrus logger. // There's no standard interface, so this is the closest we get, unfortunately. type StdLogger interface { - Print(...interface{}) - Printf(string, ...interface{}) - Println(...interface{}) + Print(args ...any) + Printf(format string, args ...any) + Println(args ...any) - Fatal(...interface{}) - Fatalf(string, ...interface{}) - Fatalln(...interface{}) + Fatal(args ...any) + Fatalf(format string, args ...any) + Fatalln(args ...any) - Panic(...interface{}) - Panicf(string, ...interface{}) - Panicln(...interface{}) + Panic(args ...any) + Panicf(format string, args ...any) + Panicln(args ...any) } // FieldLogger extends the [StdLogger] interface, generalizing // the [Entry] and [Logger] types. type FieldLogger interface { - WithField(key string, value interface{}) *Entry + WithField(key string, value any) *Entry WithFields(fields Fields) *Entry WithError(err error) *Entry - Debugf(format string, args ...interface{}) - Infof(format string, args ...interface{}) - Printf(format string, args ...interface{}) - Warnf(format string, args ...interface{}) - Warningf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) - Fatalf(format string, args ...interface{}) - Panicf(format string, args ...interface{}) - - Debug(args ...interface{}) - Info(args ...interface{}) - Print(args ...interface{}) - Warn(args ...interface{}) - Warning(args ...interface{}) - Error(args ...interface{}) - Fatal(args ...interface{}) - Panic(args ...interface{}) - - Debugln(args ...interface{}) - Infoln(args ...interface{}) - Println(args ...interface{}) - Warnln(args ...interface{}) - Warningln(args ...interface{}) - Errorln(args ...interface{}) - Fatalln(args ...interface{}) - Panicln(args ...interface{}) - - // IsDebugEnabled() bool - // IsInfoEnabled() bool - // IsWarnEnabled() bool - // IsErrorEnabled() bool - // IsFatalEnabled() bool - // IsPanicEnabled() bool + StdLogger + DebugLogger + InfoLogger + WarnLogger + ErrorLogger + + // Legacy warning aliases. These are kept on FieldLogger for backwards + // compatibility, but are intentionally omitted from [WarnLogger]. + + Warning(args ...any) + Warningf(format string, args ...any) + Warningln(args ...any) +} + +// DebugLogger provides convenience functions to log messages at level [DebugLevel]. +type DebugLogger interface { + Debug(args ...any) + Debugf(format string, args ...any) + Debugln(args ...any) +} + +// InfoLogger provides convenience functions to log messages at level [InfoLevel]. +type InfoLogger interface { + Info(args ...any) + Infof(format string, args ...any) + Infoln(args ...any) +} + +// WarnLogger provides convenience functions to log messages at level [WarnLevel]. +type WarnLogger interface { + Warn(args ...any) + Warnf(format string, args ...any) + Warnln(args ...any) +} + +// ErrorLogger provides convenience functions to log messages at level [ErrorLevel]. +type ErrorLogger interface { + Error(args ...any) + Errorf(format string, args ...any) + Errorln(args ...any) +} + +// TraceLogger provides convenience functions to log messages at level [TraceLevel]. +type TraceLogger interface { + Trace(args ...any) + Tracef(format string, args ...any) + Traceln(args ...any) } -// Ext1FieldLogger (the first extension to [FieldLogger]) is superfluous, it is -// here for consistency. Do not use. Use [FieldLogger], [Logger] or [Entry] -// instead. +// Ext1FieldLogger is FieldLogger extended with Trace-level methods. +// +// New code should prefer the smallest applicable interface, such as +// [FieldLogger] or [TraceLogger], or use [Logger] or [Entry] directly. type Ext1FieldLogger interface { FieldLogger - Tracef(format string, args ...interface{}) - Trace(args ...interface{}) - Traceln(args ...interface{}) + TraceLogger } diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go index 2403de9819..1c6202b8c4 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go @@ -1,11 +1,7 @@ -// +build appengine +//go:build appengine package logrus -import ( - "io" -) - -func checkIfTerminal(w io.Writer) bool { +func checkIfTerminal(_ any) bool { return true } diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go index 69956b425a..ff9531ac44 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go @@ -1,5 +1,4 @@ -// +build darwin dragonfly freebsd netbsd openbsd hurd -// +build !js +//go:build (darwin || dragonfly || freebsd || netbsd || openbsd || hurd) && !tinygo package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_js.go b/vendor/github.com/sirupsen/logrus/terminal_check_js.go deleted file mode 100644 index ebdae3ec62..0000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_js.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build js - -package logrus - -func isTerminal(fd int) bool { - return false -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go index 97af92c68e..17ae9f04fb 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go @@ -1,11 +1,7 @@ -// +build js nacl plan9 +//go:build js || nacl || plan9 || wasi || wasip1 || tinygo package logrus -import ( - "io" -) - -func checkIfTerminal(w io.Writer) bool { +func checkIfTerminal(_ any) bool { return false } diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go index 3293fb3caa..780a42a57f 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go @@ -1,4 +1,4 @@ -// +build !appengine,!js,!windows,!nacl,!plan9 +//go:build !appengine && !js && !windows && !nacl && !plan9 && !wasi && !wasip1 && !tinygo package logrus @@ -10,7 +10,11 @@ import ( func checkIfTerminal(w io.Writer) bool { switch v := w.(type) { case *os.File: - return isTerminal(int(v.Fd())) + fd := v.Fd() + if fd > uintptr(^uint(0)>>1) { + return false + } + return isTerminal(int(fd)) default: return false } diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go b/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go index f6710b3bd0..8d9b26fcad 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go @@ -1,3 +1,5 @@ +//go:build solaris && !tinygo + package logrus import ( diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go index c9aed267a4..b161506d3f 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go @@ -1,7 +1,4 @@ -//go:build (linux || aix || zos) && !js && !wasi -// +build linux aix zos -// +build !js -// +build !wasi +//go:build (linux || aix || zos) && !tinygo package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_wasi.go b/vendor/github.com/sirupsen/logrus/terminal_check_wasi.go deleted file mode 100644 index 2822b212fb..0000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_wasi.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build wasi -// +build wasi - -package logrus - -func isTerminal(fd int) bool { - return false -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_wasip1.go b/vendor/github.com/sirupsen/logrus/terminal_check_wasip1.go deleted file mode 100644 index 108a6be12b..0000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_wasip1.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build wasip1 -// +build wasip1 - -package logrus - -func isTerminal(fd int) bool { - return false -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go index 2879eb50ea..5fd3c43139 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go @@ -1,4 +1,4 @@ -// +build !appengine,!js,windows +//go:build windows && !appengine package logrus diff --git a/vendor/github.com/sirupsen/logrus/text_formatter.go b/vendor/github.com/sirupsen/logrus/text_formatter.go index 6dfeb18b10..82c1f3da24 100644 --- a/vendor/github.com/sirupsen/logrus/text_formatter.go +++ b/vendor/github.com/sirupsen/logrus/text_formatter.go @@ -3,30 +3,32 @@ package logrus import ( "bytes" "fmt" + "maps" "os" + "reflect" "runtime" - "sort" + "slices" "strconv" "strings" "sync" "time" - "unicode/utf8" ) -const ( - red = 31 - yellow = 33 - blue = 36 - gray = 37 -) - -var baseTimestamp time.Time - -func init() { - baseTimestamp = time.Now() -} - -// TextFormatter formats logs into text +var baseTimestamp = time.Now() + +// TextFormatter formats logs into text. +// +// Output is logfmt-like: key=value pairs separated by spaces. Fields from +// [Entry.Data] are included together with the standard fields derived from the +// entry. If a field conflicts with a standard field, it is prefixed with +// "fields.". Standard field names can be customized through FieldMap. +// +// Field keys are written as-is (unquoted and unescaped) in the plain +// (non-colored) format; only field values may be quoted depending on +// DisableQuote, ForceQuote, QuoteEmptyFields, and the value content. +// +// When colors are enabled, ANSI escape sequences may be added for presentation. +// For fully escaped structured output (including safe keys), use JSONFormatter. type TextFormatter struct { // Set to true to bypass checking for a TTY before outputting colors. ForceColors bool @@ -64,7 +66,7 @@ type TextFormatter struct { // be desired. DisableSorting bool - // The keys sorting function, when uninitialized it uses sort.Strings. + // The keys sorting function, when uninitialized it uses slices.Sort. SortingFunc func([]string) // Disables the truncation of the level text to 4 characters. @@ -77,16 +79,22 @@ type TextFormatter struct { // QuoteEmptyFields will wrap empty fields in quotes if true QuoteEmptyFields bool - // Whether the logger's out is to a terminal - isTerminal bool + // Whether the logger's out is to a terminal. Don't use this field + // directly; use TextFormatter.isTerminal instead. + terminal bool // FieldMap allows users to customize the names of keys for default fields. + // Mapped keys are written as-is, so they should be safe for plain-text output. + // // As an example: + // // formatter := &TextFormatter{ - // FieldMap: FieldMap{ - // FieldKeyTime: "@timestamp", - // FieldKeyLevel: "@level", - // FieldKeyMsg: "@message"}} + // FieldMap: FieldMap{ + // FieldKeyTime: "@timestamp", + // FieldKeyLevel: "@level", + // FieldKeyMsg: "@message", + // }, + // } FieldMap FieldMap // CallerPrettyfier can be set by the user to modify the content @@ -96,54 +104,78 @@ type TextFormatter struct { CallerPrettyfier func(*runtime.Frame) (function string, file string) terminalInitOnce sync.Once - - // The max length of the level text, generated dynamically on init - levelTextMaxLength int } -func (f *TextFormatter) init(entry *Entry) { - if entry.Logger != nil { - f.isTerminal = checkIfTerminal(entry.Logger.Out) - } - // Get the max length of the level text - for _, level := range AllLevels { - levelTextLength := utf8.RuneCount([]byte(level.String())) - if levelTextLength > f.levelTextMaxLength { - f.levelTextMaxLength = levelTextLength - } +func (f *TextFormatter) isTerminal(entry *Entry) bool { + if entry == nil || entry.Logger == nil { + // Don't run the terminalInitOnce without a logger, otherwise we'd + // cache the default (false) forever even if a logger is attached + // later. + return false } -} -func (f *TextFormatter) isColored() bool { - isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows")) + f.terminalInitOnce.Do(func() { + entry.Logger.mu.Lock() + out := entry.Logger.Out + entry.Logger.mu.Unlock() - if f.EnvironmentOverrideColors { - switch force, ok := os.LookupEnv("CLICOLOR_FORCE"); { - case ok && force != "0": - isColored = true - case ok && force == "0", os.Getenv("CLICOLOR") == "0": - isColored = false - } + f.terminal = checkIfTerminal(out) + }) + + return f.terminal +} + +func (f *TextFormatter) isColored(isTerminal bool) bool { + if f.DisableColors { + return false } - return isColored && !f.DisableColors + colored := f.ForceColors || isTerminal + if !f.EnvironmentOverrideColors { + return colored + } + if force, ok := os.LookupEnv("CLICOLOR_FORCE"); ok { + return force != "0" + } + if os.Getenv("CLICOLOR") == "0" { + return false + } + return colored } // Format renders a single log entry func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { - data := make(Fields) - for k, v := range entry.Data { - data[k] = v - } - prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) + data := make(Fields, len(entry.Data)) + maps.Copy(data, entry.Data) + isColored := f.isColored(f.isTerminal(entry)) + + caller := entry.Caller + hasCaller := caller != nil + prefixFieldClashes(data, f.FieldMap, hasCaller) keys := make([]string, 0, len(data)) for k := range data { keys = append(keys, k) } - var funcVal, fileVal string + b := entry.Buffer + if b == nil { + b = new(bytes.Buffer) + } + + if isColored { + f.printColored(b, entry, keys, data) + } else { + f.printPlain(b, entry, keys, data) + } + + return b.Bytes(), nil +} + +func (f *TextFormatter) printPlain(b *bytes.Buffer, entry *Entry, keys []string, data Fields) { + caller := entry.Caller + hasCaller := caller != nil - fixedKeys := make([]string, 0, 4+len(data)) + fixedKeys := make([]string, 0, len(keys)+defaultFields) if !f.DisableTimestamp { fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime)) } @@ -154,12 +186,14 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { if entry.err != "" { fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError)) } - if entry.HasCaller() { + + var funcVal, fileVal string + if caller != nil { if f.CallerPrettyfier != nil { - funcVal, fileVal = f.CallerPrettyfier(entry.Caller) + funcVal, fileVal = f.CallerPrettyfier(caller) } else { - funcVal = entry.Caller.Function - fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) + funcVal = caller.Function + fileVal = caller.File + ":" + strconv.FormatInt(int64(caller.Line), 10) } if funcVal != "" { @@ -172,169 +206,278 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { if !f.DisableSorting { if f.SortingFunc == nil { - sort.Strings(keys) + // Default sorting does not sort the "fixed keys"; + // see https://github.com/sirupsen/logrus/commit/73bc94e60c753099e8bae902f81fbd6e7dd95f26 + slices.Sort(keys) fixedKeys = append(fixedKeys, keys...) } else { - if !f.isColored() { - fixedKeys = append(fixedKeys, keys...) - f.SortingFunc(fixedKeys) - } else { - f.SortingFunc(keys) - } + fixedKeys = append(fixedKeys, keys...) + f.SortingFunc(fixedKeys) } } else { fixedKeys = append(fixedKeys, keys...) } - var b *bytes.Buffer - if entry.Buffer != nil { - b = entry.Buffer - } else { - b = &bytes.Buffer{} - } - - f.terminalInitOnce.Do(func() { f.init(entry) }) - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = defaultTimestampFormat - } - if f.isColored() { - f.printColored(b, entry, keys, data, timestampFormat) - } else { - - for _, key := range fixedKeys { - var value interface{} - switch { - case key == f.FieldMap.resolve(FieldKeyTime): - value = entry.Time.Format(timestampFormat) - case key == f.FieldMap.resolve(FieldKeyLevel): - value = entry.Level.String() - case key == f.FieldMap.resolve(FieldKeyMsg): - value = entry.Message - case key == f.FieldMap.resolve(FieldKeyLogrusError): - value = entry.err - case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller(): - value = funcVal - case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller(): - value = fileVal - default: - value = data[key] + for _, key := range fixedKeys { + var value any + switch { + case key == f.FieldMap.resolve(FieldKeyTime): + if f.TimestampFormat == "" { + value = entry.Time.Format(defaultTimestampFormat) + } else { + value = entry.Time.Format(f.TimestampFormat) } - f.appendKeyValue(b, key, value) + case key == f.FieldMap.resolve(FieldKeyLevel): + value = entry.Level.String() + case key == f.FieldMap.resolve(FieldKeyMsg): + value = entry.Message + case key == f.FieldMap.resolve(FieldKeyLogrusError): + value = entry.err + case key == f.FieldMap.resolve(FieldKeyFunc) && hasCaller: + value = funcVal + case key == f.FieldMap.resolve(FieldKeyFile) && hasCaller: + value = fileVal + default: + value = data[key] } + f.appendKeyValue(b, key, value) } b.WriteByte('\n') - return b.Bytes(), nil } -func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) { - var levelColor int - switch entry.Level { - case DebugLevel, TraceLevel: - levelColor = gray - case WarnLevel: - levelColor = yellow - case ErrorLevel, FatalLevel, PanicLevel: - levelColor = red - case InfoLevel: - levelColor = blue - default: - levelColor = blue - } - - levelText := strings.ToUpper(entry.Level.String()) - if !f.DisableLevelTruncation && !f.PadLevelText { - levelText = levelText[0:4] - } - if f.PadLevelText { - // Generates the format string used in the next line, for example "%-6s" or "%-7s". - // Based on the max level text length. - formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s" - // Formats the level text by appending spaces up to the max length, for example: - // - "INFO " - // - "WARNING" - levelText = fmt.Sprintf(formatString, levelText) - } - +func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields) { // Remove a single newline if it already exists in the message to keep // the behavior of logrus text_formatter the same as the stdlib log package entry.Message = strings.TrimSuffix(entry.Message, "\n") - caller := "" - if entry.HasCaller() { - funcVal := fmt.Sprintf("%s()", entry.Caller.Function) - fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) - + var callerText string + if caller := entry.Caller; caller != nil { + var funcVal, fileVal string if f.CallerPrettyfier != nil { - funcVal, fileVal = f.CallerPrettyfier(entry.Caller) + funcVal, fileVal = f.CallerPrettyfier(caller) + } else { + if caller.Function != "" { + funcVal = caller.Function + "()" + } + fileVal = caller.File + ":" + strconv.FormatInt(int64(caller.Line), 10) } if fileVal == "" { - caller = funcVal + callerText = funcVal } else if funcVal == "" { - caller = fileVal + callerText = fileVal } else { - caller = fileVal + " " + funcVal + callerText = fileVal + " " + funcVal } } + levelText := levelPrefix(entry.Level, f.DisableLevelTruncation, f.PadLevelText) switch { case f.DisableTimestamp: - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message) + _, _ = fmt.Fprintf(b, "%s%s %-44s ", levelText, callerText, entry.Message) case !f.FullTimestamp: - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message) + _, _ = fmt.Fprintf(b, "%s[%04d]%s %-44s ", levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), callerText, entry.Message) default: - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message) + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = defaultTimestampFormat + } + _, _ = fmt.Fprintf(b, "%s[%s]%s %-44s ", levelText, entry.Time.Format(timestampFormat), callerText, entry.Message) + } + + if !f.DisableSorting { + if f.SortingFunc == nil { + slices.Sort(keys) + } else { + f.SortingFunc(keys) + } } + + // Keys use the same color as the level-prefix. for _, k := range keys { - v := data[k] - fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) - f.appendValue(b, v) + b.WriteByte(' ') + b.WriteString(colorize(entry.Level, k)) + b.WriteByte('=') + f.appendValue(b, data[k]) } + + b.WriteByte('\n') } -func (f *TextFormatter) needsQuoting(text string) bool { - if f.ForceQuote { - return true +// appendKeyValue writes key=value. Keys are written verbatim (unquoted/unescaped); +// values are subject to quoting/escaping. +func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value any) { + if b.Len() > 0 { + b.WriteByte(' ') } - if f.QuoteEmptyFields && len(text) == 0 { - return true + b.WriteString(key) + b.WriteByte('=') + f.appendValue(b, value) +} + +func (f *TextFormatter) appendValue(b *bytes.Buffer, value any) { + // Fast paths. + switch v := value.(type) { + case string: + f.appendString(b, v) + return + case []byte: + f.appendBytes(b, v) + return + case bool: + var raw [8]byte + f.appendBytes(b, strconv.AppendBool(raw[:0], v)) + return + case error: + f.appendError(b, v) + return + case fmt.Stringer: + f.appendStringer(b, v) + return } - if f.DisableQuote { - return false + + // Handle common primitives. + var raw [64]byte + var num []byte + + switch v := value.(type) { + case int: + num = strconv.AppendInt(raw[:0], int64(v), 10) + case int8: + num = strconv.AppendInt(raw[:0], int64(v), 10) + case int16: + num = strconv.AppendInt(raw[:0], int64(v), 10) + case int32: + num = strconv.AppendInt(raw[:0], int64(v), 10) + case int64: + num = strconv.AppendInt(raw[:0], v, 10) + + case uint: + num = strconv.AppendUint(raw[:0], uint64(v), 10) + case uint8: + num = strconv.AppendUint(raw[:0], uint64(v), 10) + case uint16: + num = strconv.AppendUint(raw[:0], uint64(v), 10) + case uint32: + num = strconv.AppendUint(raw[:0], uint64(v), 10) + case uint64: + num = strconv.AppendUint(raw[:0], v, 10) + case uintptr: + num = strconv.AppendUint(raw[:0], uint64(v), 10) + + case float32: + num = strconv.AppendFloat(raw[:0], float64(v), 'g', -1, 32) + case float64: + num = strconv.AppendFloat(raw[:0], v, 'g', -1, 64) + + default: + f.appendString(b, fmt.Sprint(value)) + return + } + + f.appendNumeric(b, num) +} + +func (f *TextFormatter) appendString(b *bytes.Buffer, s string) { + quote := f.ForceQuote || (f.QuoteEmptyFields && len(s) == 0) || (!f.DisableQuote && needsQuoting(s)) + if !quote { + b.WriteString(s) + return + } + if len(s) == 0 { + b.WriteString(`""`) + return + } + + var tmp [128]byte + b.Write(strconv.AppendQuote(tmp[:0], s)) +} + +func (f *TextFormatter) appendBytes(b *bytes.Buffer, bs []byte) { + quote := f.ForceQuote || (f.QuoteEmptyFields && len(bs) == 0) || (!f.DisableQuote && needsQuotingBytes(bs)) + if !quote { + b.Write(bs) + return + } + if len(bs) == 0 { + b.WriteString(`""`) + return + } + + var tmp [128]byte + b.Write(strconv.AppendQuote(tmp[:0], string(bs))) +} + +func (f *TextFormatter) appendNumeric(b *bytes.Buffer, out []byte) { + if f.ForceQuote { + var tmp [128]byte + b.Write(strconv.AppendQuote(tmp[:0], string(out))) + return } - for _, ch := range text { - //nolint:staticcheck // QF1001: could apply De Morgan's law - if !((ch >= 'a' && ch <= 'z') || - (ch >= 'A' && ch <= 'Z') || - (ch >= '0' && ch <= '9') || - ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') { + b.Write(out) +} + +func (f *TextFormatter) appendError(b *bytes.Buffer, v error) { + defer f.recoverValue(b, v, "Error") + + f.appendString(b, v.Error()) +} + +func (f *TextFormatter) appendStringer(b *bytes.Buffer, v fmt.Stringer) { + defer f.recoverValue(b, v, "String") + + f.appendString(b, v.String()) +} + +func (f *TextFormatter) recoverValue(b *bytes.Buffer, v any, method string) { + if r := recover(); r != nil { + rv := reflect.ValueOf(v) + if rv.Kind() == reflect.Pointer && rv.IsNil() { + f.appendString(b, "") + } else { + f.appendString(b, fmt.Sprintf("%%!v(PANIC=%s method: %v)", method, r)) + } + } +} + +// needsQuoting returns true if the string contains any byte that +// requires quoting. It returns false when every byte is "safe" according +// to isSafeByte. +func needsQuoting(s string) bool { + // use an index loop (avoid rune decoding). + for i := range len(s) { + c := s[i] + if !isSafeByte(c) { return true } } return false } -func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { - if b.Len() > 0 { - b.WriteByte(' ') +// needsQuotingBytes returns true if the byte slice contains any byte that +// requires quoting. It returns false when every byte is "safe" according +// to isSafeByte. +func needsQuotingBytes(bs []byte) bool { + for _, c := range bs { + if !isSafeByte(c) { + return true + } } - b.WriteString(key) - b.WriteByte('=') - f.appendValue(b, value) + return false } -func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { - stringVal, ok := value.(string) - if !ok { - stringVal = fmt.Sprint(value) +// isSafeByte returns true if the byte is allowed unquoted (ASCII and in the allowlist). +// It purposely uses byte arithmetic (no runes) for performance. +func isSafeByte(ch byte) bool { + ok := ch < 0x80 && ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) + if ok { + return true } - - if !f.needsQuoting(stringVal) { - b.WriteString(stringVal) - } else { - fmt.Fprintf(b, "%q", stringVal) + switch ch { + case '-', '.', '_', '/', '@', '^', '+': + return true + default: + return false } } diff --git a/vendor/github.com/sirupsen/logrus/writer.go b/vendor/github.com/sirupsen/logrus/writer.go index 074fd4b8bd..30e34cda72 100644 --- a/vendor/github.com/sirupsen/logrus/writer.go +++ b/vendor/github.com/sirupsen/logrus/writer.go @@ -30,7 +30,7 @@ func (entry *Entry) Writer() *io.PipeWriter { func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { reader, writer := io.Pipe() - var printFunc func(args ...interface{}) + printFunc := entry.Print // Determine which log function to use based on the specified log level switch level { @@ -48,8 +48,6 @@ func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { printFunc = entry.Fatal case PanicLevel: printFunc = entry.Panic - default: - printFunc = entry.Print } // Start a new goroutine to scan the input and write it to the logger using the specified print function. @@ -63,7 +61,7 @@ func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { } // writerScanner scans the input from the reader and writes it to the logger -func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { +func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...any)) { scanner := bufio.NewScanner(reader) // Set the buffer size to the maximum token size to avoid buffer overflows diff --git a/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/bundle.go b/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/bundle.go index 78cdaddfca..06ce6374c8 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/bundle.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/bundle.go @@ -154,7 +154,7 @@ func (b *Bundle) Marshal() ([]byte, error) { b.mtx.RLock() defer b.mtx.RUnlock() - jwks := jose.JSONWebKeySet{} + jwks := jose.JSONWebKeySet{Keys: make([]jose.JSONWebKey, 0, len(b.jwtAuthorities))} for keyID, jwtAuthority := range b.jwtAuthorities { jwks.Keys = append(jwks.Keys, jose.JSONWebKey{ Key: jwtAuthority, diff --git a/vendor/github.com/spiffe/go-spiffe/v2/exp/bundle/witbundle/bundle.go b/vendor/github.com/spiffe/go-spiffe/v2/exp/bundle/witbundle/bundle.go index dbf8cf3cd9..95598c5629 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/exp/bundle/witbundle/bundle.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/exp/bundle/witbundle/bundle.go @@ -16,6 +16,8 @@ import ( "github.com/spiffe/go-spiffe/v2/spiffeid" ) +const witSVIDUse = "wit-svid" + // Bundle is a collection of trusted WIT authorities for a trust domain. type Bundle struct { trustDomain spiffeid.TrustDomain @@ -160,11 +162,12 @@ func (b *Bundle) Marshal() ([]byte, error) { b.mtx.RLock() defer b.mtx.RUnlock() - jwks := jose.JSONWebKeySet{} + jwks := jose.JSONWebKeySet{Keys: make([]jose.JSONWebKey, 0, len(b.witAuthorities))} for keyID, witAuthority := range b.witAuthorities { jwks.Keys = append(jwks.Keys, jose.JSONWebKey{ Key: witAuthority, KeyID: keyID, + Use: witSVIDUse, }) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/stats_handler.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/stats_handler.go index 1d0fc06226..3b3a2afc60 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/stats_handler.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/stats_handler.go @@ -407,22 +407,38 @@ func (*config) handleRPC( // Don't use gctx.metricAttrSet here, because it requires passing // multiple RecordOptions, which would call metric.mergeSets and // allocate a new set for each Record call. - metricAttrs = make([]attribute.KeyValue, 0, len(gctx.metricAttrs)+1) + metricAttrs = make([]attribute.KeyValue, 0, len(gctx.metricAttrs)+2) metricAttrs = append(metricAttrs, gctx.metricAttrs...) } metricAttrs = append(metricAttrs, rpcStatusAttr) - // Allocate vararg slice once. - recordOpts := []metric.RecordOption{metric.WithAttributeSet(attribute.NewSet(metricAttrs...))} + + // error.type is Conditionally Required on the stable rpc.*.call.duration + // metrics when the RPC failed, and SHOULD be set to the returned status + // code. The failure classification is role-specific: clients treat every + // non-OK status as an error, while servers only classify Unknown, + // DeadlineExceeded, Unimplemented, Internal, Unavailable and DataLoss + // as errors. Use recordStatus so the client and server rules are applied + // independently (e.g. a client cancellation is not a server error). + // The legacy v1.37 rpc.*.duration conventions did not define error.type, + // so the compatibility instruments keep the unmodified attribute set. + // Build each record option only in its enabled branch: single-mode + // configurations (rpc, rpc/old) must not allocate the other set, and + // error.type is only appended after the legacy instruments recorded. // Use floating point division here for higher precision (instead of Millisecond method). // Measure right before calling Record() to capture as much elapsed time as possible. elapsedTime := float64(rs.EndTime.Sub(rs.BeginTime)) / float64(time.Second) - if durationEnabled { - duration.Record(ctx, elapsedTime, recordOpts...) - } if oldDurationEnabled { - oldDuration.Record(ctx, elapsedTime*1000.0, recordOpts...) + oldDuration.Record(ctx, elapsedTime*1000.0, metric.WithAttributeSet(attribute.NewSet(metricAttrs...))) + } + if durationEnabled { + if s != nil { + if c, _ := recordStatus(s); c == codes.Error { + metricAttrs = append(metricAttrs, semconv.ErrorTypeKey.String(canonicalString(s.Code()))) + } + } + duration.Record(ctx, elapsedTime, metric.WithAttributeSet(attribute.NewSet(metricAttrs...))) } } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go index 23fda6f503..bef4014dc3 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go @@ -4,4 +4,4 @@ package otelgrpc // Version is the current release version of the gRPC instrumentation. -const Version = "0.70.0" +const Version = "0.72.0" diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go index 733b75dca7..b32f99a934 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go @@ -10,12 +10,31 @@ import ( "go.opentelemetry.io/otel/trace" ) -// Attribute keys that can be added to a span. +// Legacy HTTP attribute keys retained for compatibility. const ( - ReadBytesKey = attribute.Key("http.read_bytes") // if anything was read from the request body, the total number of bytes read - ReadErrorKey = attribute.Key("http.read_error") // If an error occurred while reading a request, the string of the error (io.EOF is not recorded) - WroteBytesKey = attribute.Key("http.wrote_bytes") // if anything was written to the response writer, the total number of bytes written - WriteErrorKey = attribute.Key("http.write_error") // if an error occurred while writing a reply, the string of the error (io.EOF is not recorded) + // ReadBytesKey is the attribute key for the number of bytes returned by an + // individual read from an HTTP request body. + // + // Deprecated: there is no direct semantic-convention replacement. + ReadBytesKey = attribute.Key("http.read_bytes") + + // ReadErrorKey is the attribute key for the string form of a non-EOF error + // returned while reading an HTTP request body. + // + // Deprecated: there is no direct semantic-convention replacement. + ReadErrorKey = attribute.Key("http.read_error") + + // WroteBytesKey is the attribute key for the number of bytes returned by an + // individual write to an HTTP response body. + // + // Deprecated: there is no direct semantic-convention replacement. + WroteBytesKey = attribute.Key("http.wrote_bytes") + + // WriteErrorKey is the attribute key for the string form of a non-EOF error + // returned while writing an HTTP response body. + // + // Deprecated: there is no direct semantic-convention replacement. + WriteErrorKey = attribute.Key("http.write_error") ) // Filter is a predicate used to determine whether a given http.request should diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go index 08ba0778f6..45d4ee1611 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go @@ -143,14 +143,15 @@ const ( ) // WithMessageEvents configures the Handler to record the specified events -// (span.AddEvent) on spans. By default only summary attributes are added at the -// end of the request. +// (span.AddEvent) on spans. By default, no read or write events are recorded. // // Valid events are: -// - ReadEvents: Record the number of bytes read after every http.Request.Body.Read -// using the ReadBytesKey -// - WriteEvents: Record the number of bytes written after every http.ResponeWriter.Write -// using the WriteBytesKey +// - ReadEvents: Record a "read" span event after every http.Request.Body.Read. +// - WriteEvents: Record a "write" span event after every http.ResponseWriter.Write. +// +// The events do not include per-call byte-count attributes. Total request and +// response body sizes are recorded on the span according to HTTP semantic +// conventions. func WithMessageEvents(events ...Event) Option { return optionFunc(func(c *config) { for _, e := range events { diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go index 844363a090..d42f4f8708 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go @@ -129,8 +129,8 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http readRecordFunc := func(int64) {} if h.readEvent { - readRecordFunc = func(n int64) { - span.AddEvent("read", trace.WithAttributes(ReadBytesKey.Int64(n))) + readRecordFunc = func(int64) { + span.AddEvent("read") } } @@ -150,8 +150,8 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http writeRecordFunc := func(int64) {} if h.writeEvent { - writeRecordFunc = func(n int64) { - span.AddEvent("write", trace.WithAttributes(WroteBytesKey.Int64(n))) + writeRecordFunc = func(int64) { + span.AddEvent("write") } } @@ -180,12 +180,21 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http if !found { ctx = ContextWithLabeler(ctx, labeler) } + rCtx := r.WithContext(ctx) + defer func() { + // Copy MultipartForm back to the original request so net/http can + // find and remove any temp files ParseMultipartForm created on the + // copy. Deferred so the copy-back also runs during panic unwinding, + // letting net/http cleanup paths that still run (HTTP/2 handler + // recovery, outer recovery middleware) find the form. + if rCtx.MultipartForm != nil { + r.MultipartForm = rCtx.MultipartForm + } + }() + next.ServeHTTP(w, rCtx) - r = r.WithContext(ctx) - next.ServeHTTP(w, r) - - if r.Pattern != "" { - span.SetName(h.spanNameFormatter(h.operation, r)) + if rCtx.Pattern != "" { + span.SetName(h.spanNameFormatter(h.operation, rCtx)) } statusCode := rww.StatusCode() @@ -204,9 +213,9 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http ServerName: h.server, ResponseSize: bytesWritten, MetricAttributes: semconv.MetricAttributes{ - Req: r, + Req: rCtx, StatusCode: statusCode, - AdditionalAttributes: append(labeler.Get(), h.metricAttributesFromRequest(r)...), + AdditionalAttributes: append(labeler.Get(), h.metricAttributesFromRequest(rCtx)...), }, MetricData: semconv.MetricData{ RequestSize: bytesRead, diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go index 0de0bd83c4..1ec064b1d7 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go @@ -38,11 +38,9 @@ func SplitHostPort(hostport string) (host string, port int) { host = hostport[1:addrEnd] return host, port } - } else { - if i := strings.LastIndexByte(hostport, ':'); i < 0 { - host = hostport - return host, port - } + } else if !strings.Contains(hostport, ":") { + host = hostport + return host, port } host, pStr, err := net.SplitHostPort(hostport) diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/labeler.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/labeler.go index 8362b82468..3c0fa99a25 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/labeler.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/labeler.go @@ -56,3 +56,27 @@ func LabelerFromContext(ctx context.Context) (*Labeler, bool) { } return l, ok } + +// clientLabelerContextKey is a separate context key for the client-side Labeler. +// This prevents server-side Labeler attributes (e.g., http.route) from leaking +// into client-side metrics when a server handler propagates its request context +// into an outbound HTTP client request. +const clientLabelerContextKey labelerContextKeyType = 1 + +// ContextWithClientLabeler returns a new context with the provided Labeler instance +// for use with client-side HTTP instrumentation (otelhttp.Transport). +// Attributes added to this labeler will be attached to client-side metrics. +func ContextWithClientLabeler(parent context.Context, l *Labeler) context.Context { + return context.WithValue(parent, clientLabelerContextKey, l) +} + +// ClientLabelerFromContext retrieves a Labeler instance from the provided context +// for use with client-side HTTP instrumentation. If no Labeler was found, a new, +// empty Labeler is returned and the second return value is false. +func ClientLabelerFromContext(ctx context.Context) (*Labeler, bool) { + l, ok := ctx.Value(clientLabelerContextKey).(*Labeler) + if !ok { + l = &Labeler{} + } + return l, ok +} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go index 82501eab32..22bbcc737f 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go @@ -9,6 +9,7 @@ import ( "io" "net/http" "net/http/httptrace" + "sync" "sync/atomic" "time" @@ -19,7 +20,6 @@ import ( otelsemconv "go.opentelemetry.io/otel/semconv/v1.43.0" "go.opentelemetry.io/otel/trace" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" ) @@ -82,6 +82,142 @@ func defaultTransportFormatter(_ string, r *http.Request) string { return "HTTP " + r.Method } +// requestTracker tracks the request body lifecycle of a single RoundTrip and +// records the client metrics exactly once, after the request body reaches a +// final state. +// +// A single tracker is allocated per request with a body, replacing the +// body-wrapper allocation of the untracked implementation: the first request +// body is wrapped by the embedded first field, and the lifecycle state is +// held in explicit fields with methods instead of escaping closures. Only +// GetBody retries allocate an additional trackedRequestBody. +type requestTracker struct { + transport *Transport + first trackedRequestBody + + originalGetBody func() (io.ReadCloser, error) + + // mu protects body, published, and recorded. Body close callbacks may + // fire on a different goroutine (e.g. during transport retries or + // asynchronous closes) while the main goroutine publishes the metric + // data after RoundTrip returns. + mu sync.Mutex + body *trackedRequestBody // Last wrapped request body; nil records no data. + published bool + recorded bool + + // Metric data published when RoundTrip returns; immutable afterwards. + ctx context.Context + duration time.Duration + opts semconv.MetricOpts +} + +func newRequestTracker(t *Transport, r *http.Request) *requestTracker { + rt := &requestTracker{transport: t} + rt.first = trackedRequestBody{body: r.Body, tracker: rt} + rt.body = &rt.first + r.Body = &rt.first + if r.GetBody != nil { + rt.originalGetBody = r.GetBody + r.GetBody = rt.getBody + } + return rt +} + +func (rt *requestTracker) getBody() (io.ReadCloser, error) { + b, err := rt.originalGetBody() + if err != nil { + // The underlying transport will fail to make a retry request, + // hence, record no data. + rt.setBody(nil) + return nil, err + } + if b == nil || b == http.NoBody { + return b, nil + } + tb := &trackedRequestBody{body: b, tracker: rt} + rt.setBody(tb) + return tb, nil +} + +func (rt *requestTracker) setBody(b *trackedRequestBody) { + rt.mu.Lock() + rt.body = b + rt.mu.Unlock() +} + +// publish stores the metric data gathered when RoundTrip returns and records +// the metrics if the request body already reached a final state. +func (rt *requestTracker) publish(ctx context.Context, d time.Duration, opts semconv.MetricOpts) { + rt.mu.Lock() + rt.ctx = ctx + rt.duration = d + rt.opts = opts + rt.published = true + rt.mu.Unlock() + rt.maybeRecord() +} + +// maybeRecord records the client metrics once the metric data has been +// published and the request body has reached a final state. Close is the +// only authoritative completion signal for a non-nil body: a body may yield +// more bytes than its declared ContentLength, so a read count is never proof +// of completion. +func (rt *requestTracker) maybeRecord() { + rt.mu.Lock() + body := rt.body + record := rt.published && !rt.recorded && (body == nil || body.closed.Load()) + if record { + rt.recorded = true + } + rt.mu.Unlock() + if !record { + return + } + + // The winning caller evaluates the request size here so the recorded + // value reflects the latest byte count. + var requestSize int64 + if body != nil { + requestSize = body.read.Load() + } + rt.transport.semconv.RecordMetrics( + rt.ctx, + semconv.MetricData{ + RequestSize: requestSize, + RequestDuration: rt.duration, + }, + rt.opts, + ) +} + +// trackedRequestBody wraps a request body to count read bytes and signal the +// tracker when the body is closed. +type trackedRequestBody struct { + body io.ReadCloser + tracker *requestTracker + + read atomic.Int64 + closed atomic.Bool +} + +var _ io.ReadCloser = (*trackedRequestBody)(nil) + +func (b *trackedRequestBody) Read(p []byte) (int, error) { + n, err := b.body.Read(p) + b.read.Add(int64(n)) + return n, err +} + +func (b *trackedRequestBody) Close() error { + // Finalize telemetry before delegating to the underlying Close, which + // may block (mirroring wrappedBody.Close). Otherwise a blocking close + // could suppress client metrics indefinitely. + b.closed.Store(true) + b.tracker.maybeRecord() + return b.body.Close() +} + // RoundTrip creates a Span and propagates its context via the provided request's headers // before handing the request to the configured base RoundTripper. The created span will // end when the response body is closed or when a read from the body returns io.EOF. @@ -110,33 +246,20 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { ctx = httptrace.WithClientTrace(ctx, t.clientTrace(ctx)) } - labeler, found := LabelerFromContext(ctx) + labeler, found := ClientLabelerFromContext(ctx) if !found { - ctx = ContextWithLabeler(ctx, labeler) + ctx = ContextWithClientLabeler(ctx, labeler) } r = r.Clone(ctx) // According to RoundTripper spec, we shouldn't modify the origin request. - var lastBW *request.BodyWrapper // Records the last body wrapper. Can be nil. - maybeWrapBody := func(body io.ReadCloser) io.ReadCloser { - if body == nil || body == http.NoBody { - return body - } - bw := request.NewBodyWrapper(body, func(int64) {}) - lastBW = bw - return bw - } - r.Body = maybeWrapBody(r.Body) - if r.GetBody != nil { - originalGetBody := r.GetBody - r.GetBody = func() (io.ReadCloser, error) { - b, err := originalGetBody() - if err != nil { - lastBW = nil // The underlying transport will fail to make a retry request, hence, record no data. - return nil, err - } - return maybeWrapBody(b), nil - } + // Track the request body lifecycle so metrics report the final read + // size even when the transport keeps reading the body after RoundTrip + // returns. Bodyless requests allocate no tracker and record + // synchronously below. + var tracker *requestTracker + if r.Body != nil && r.Body != http.NoBody { + tracker = newRequestTracker(t, r) } span.SetAttributes(t.semconv.RequestTraceAttrs(r)...) @@ -147,29 +270,32 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { res, err = ensureResponseBody(t.rt, r, res) } - // Record the metrics on error or no error. + requestDuration := time.Since(requestStartTime) statusCode := 0 if err == nil { statusCode = res.StatusCode } - var requestSize int64 - if lastBW != nil { - requestSize = lastBW.BytesRead() + metricOpts := t.semconv.MetricOptions(semconv.MetricAttributes{ + Req: r, + Resp: res, + StatusCode: statusCode, + Err: err, + AdditionalAttributes: append(labeler.Get(), t.metricAttributesFromRequest(r)...), + }) + + if tracker != nil { + // Delay metric recording until the request body reaches a final + // state. The transport can continue reading the body after + // RoundTrip returns, including on errors, since RoundTrippers may + // close the request body asynchronously. + tracker.publish(ctx, requestDuration, metricOpts) + } else { + t.semconv.RecordMetrics( + ctx, + semconv.MetricData{RequestDuration: requestDuration}, + metricOpts, + ) } - t.semconv.RecordMetrics( - ctx, - semconv.MetricData{ - RequestSize: requestSize, - RequestDuration: time.Since(requestStartTime), - }, - t.semconv.MetricOptions(semconv.MetricAttributes{ - Req: r, - Resp: res, - StatusCode: statusCode, - Err: err, - AdditionalAttributes: append(labeler.Get(), t.metricAttributesFromRequest(r)...), - }), - ) if err != nil { span.SetAttributes(otelsemconv.ErrorType(err)) @@ -263,8 +389,7 @@ func (wb *wrappedBody) Read(b []byte) (int, error) { case nil: // nothing to do here but fall through to the return case io.EOF: - wb.recordBytesRead() - wb.span.End() + wb.recordMetricsOnce() default: wb.span.SetAttributes(otelsemconv.ErrorType(err)) wb.span.SetStatus(codes.Error, err.Error()) @@ -272,21 +397,24 @@ func (wb *wrappedBody) Read(b []byte) (int, error) { return n, err } -// recordBytesRead is a function that ensures the number of bytes read is recorded once and only once. -func (wb *wrappedBody) recordBytesRead() { - // note: it is more performant (and equally correct) to use atomic.Bool over sync.Once here. In the event that - // two goroutines are racing to call this method, the number of bytes read will no longer increase. Using - // CompareAndSwap allows later goroutines to return quickly and not block waiting for the race winner to finish - // calling wb.record(wb.read.Load()). +// recordMetricsOnce ensures the final number of bytes read is recorded once. +func (wb *wrappedBody) recordMetricsOnce() { + // note: it is more performant (and equally correct) to use atomic.Bool + // over sync.Once here. In the event that two goroutines are racing to + // call this method, the number of bytes read will no longer increase. + // Using CompareAndSwap allows later goroutines to return quickly and not + // block waiting for the race winner to finish calling + // wb.record(wb.read.Load()). if wb.recorded.CompareAndSwap(false, true) { - // Record the total number of bytes read wb.record(wb.read.Load()) + wb.span.End() } } func (wb *wrappedBody) Close() error { - wb.recordBytesRead() - wb.span.End() + // Finalize telemetry before delegating to the underlying Close, which + // may block (e.g. upgraded streams or custom RoundTripper bodies). + wb.recordMetricsOnce() if wb.body != nil { return wb.body.Close() } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go index b757d6e9d0..05267f2fd2 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go @@ -4,4 +4,4 @@ package otelhttp // Version is the current release version of the otelhttp instrumentation. -const Version = "0.70.0" +const Version = "0.72.0" diff --git a/vendor/go.opentelemetry.io/otel/.golangci.yml b/vendor/go.opentelemetry.io/otel/.golangci.yml index 8a7f1ec5d9..1fef8520b3 100644 --- a/vendor/go.opentelemetry.io/otel/.golangci.yml +++ b/vendor/go.opentelemetry.io/otel/.golangci.yml @@ -143,8 +143,7 @@ linters: - name: constant-logical-expr - name: context-as-argument arguments: - - allow-types-before: '*testing.T' - disabled: true + - allow-types-before: '*testing.T,*testing.B' - name: context-keys-type - name: deep-exit - name: defer @@ -231,13 +230,6 @@ linters: - revive path: schema/v.*/types/.* text: avoid meaningless package names - # TODO: Having appropriate comments for exported objects helps development, - # even for objects in internal packages. Appropriate comments for all - # exported objects should be added and this exclusion removed. - - linters: - - revive - path: .*internal/.* - text: exported (method|function|type|const) (.+) should have comment or be unexported # Yes, they are, but it's okay in a test. - linters: - revive @@ -273,7 +265,10 @@ formatters: - golines settings: gofumpt: - extra-rules: true + extra: + group-params: true + clothe-returns: true + balance-calls: true goimports: local-prefixes: - go.opentelemetry.io/otel diff --git a/vendor/go.opentelemetry.io/otel/CHANGELOG.md b/vendor/go.opentelemetry.io/otel/CHANGELOG.md index 2db588ea27..18903c889b 100644 --- a/vendor/go.opentelemetry.io/otel/CHANGELOG.md +++ b/vendor/go.opentelemetry.io/otel/CHANGELOG.md @@ -11,6 +11,121 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm +## [1.47.0/0.69.0/0.23.0/0.1.0] - 2026-10-02 + +This release contains the first stable release of the OpenTelemetry Go Logs API and SDK. +Our project stability guarantees now apply to the following modules: + +- `go.opentelemetry.io/otel/log` +- `go.opentelemetry.io/otel/sdk/log` + +See our [versioning policy](VERSIONING.md) for more information about these stability guarantees. + +### Added + +- Add `String` method for `KeyValue` type in `go.opentelemetry.io/otel/attribute`. (#8205) +- Add `String` method for `Set` type in `go.opentelemetry.io/otel/attribute`. (#8347) +- Add `WithMaxExportBatchSize` to `go.opentelemetry.io/otel/sdk/metric` to configure the maximum export batch size for `PeriodicReader`. (#8960) +- Add `WithAttributeValueDepthLimit`, `DefaultAttributeValueDepthLimit`, and `SpanLimits.AttributeValueDepthLimit` in `go.opentelemetry.io/otel/sdk/trace` to configure the maximum depth of span, event, link, and instrumentation scope attribute values. (#8938) +- Add `WithAttributeValueDepthLimit` in `go.opentelemetry.io/otel/sdk/log` to configure the maximum depth of log record and instrumentation scope attribute values. (#8938) +- Add `WithMaxResponseSize` to `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`, + `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`, and + `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#8941) +- Add experimental `ProbabilitySampler` in `go.opentelemetry.io/otel/sdk/trace/x` that conforms to the [OpenTelemetry specification's threshold-based sampling algorithm](https://opentelemetry.io/docs/specs/otel/trace/sdk/#probabilitysampler). (#8123) +- Add experimental `*Binder` extension interfaces in `go.opentelemetry.io/otel/metric/x` for instruments that support binding attributes ahead of time. (#8760) +- Add the experimental `Finisher` synchronous metric instrument extension interface to `go.opentelemetry.io/otel/metric/x`. (#8906) + +### Changed + +- Use the [OpenTelemetry Attribute Collection representation for non-OTLP protocols](https://opentelemetry.io/docs/specs/otel/common/#attribute-collection-representation-for-non-otlp) for metric data diffs in `go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest`. (#8993) +- Apply a maximum depth of 64 by default to span, event, link, log record, and instrumentation scope attribute values in `go.opentelemetry.io/otel/sdk/trace` and `go.opentelemetry.io/otel/sdk/log`. (#8938) +- Reduce allocations when applying attribute value length limits in `go.opentelemetry.io/otel/sdk/trace` and `go.opentelemetry.io/otel/sdk/log` by rebuilding composite values only when truncation is needed. (#8912) +- Decode `traceparent` using a hex lookup table in `go.opentelemetry.io/otel/propagation`, which rejects the specification-disallowed upper-case characters without a separate scan of the header. (#8739) +- Decode all characters at constant indices in `TraceIDFromHex` and `SpanIDFromHex` in `go.opentelemetry.io/otel/trace` to eliminate bounds checks. (#8740) + +### Fixed + +- Count valid U+FFFD replacement characters toward attribute value length limits in `go.opentelemetry.io/otel/trace`, `go.opentelemetry.io/otel/sdk/trace`, and `go.opentelemetry.io/otel/sdk/log`. +- Truncate string attribute values to empty strings when the configured length limit is zero, including malformed UTF-8, in `go.opentelemetry.io/otel/trace`, `go.opentelemetry.io/otel/sdk/trace`, and `go.opentelemetry.io/otel/sdk/log`. (#9054) +- Fix a data race in `NewPeriodicReader` where `r.inst` was assigned after the background goroutine was launched in `go.opentelemetry.io/otel/sdk/metric`. (#9028) +- Prevent precision loss for large `int64` values in `Sum`, `Histogram`, and `ExponentialHistogram` aggregations in `go.opentelemetry.io/otel/sdk/metric`. (#8981) +- Ensure `grpc.DialOption` values passed via `WithDialOption` take precedence over conflicting internally-computed defaults in + `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc`, + `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc`, and + `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`. (#8805, #8834, #8836) +- Treat overflowing `OTEL_METRIC_EXPORT_INTERVAL` and `OTEL_METRIC_EXPORT_TIMEOUT` values as invalid in `go.opentelemetry.io/otel/sdk/metric`. (#8800) +- Prevent a panic in `NewFixedSizeReservoir` and `FixedSizeReservoirProvider` when given a negative size in `go.opentelemetry.io/otel/sdk/metric/exemplar`; negative sizes are now clamped to zero, consistent with a size of zero. (#8832) +- Preserve exponential histogram `ZeroThreshold` during OTLP metric export in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric`. (#8801) +- Ensure metric helpers in `go.opentelemetry.io/otel/semconv/v1.32.0`, `go.opentelemetry.io/otel/semconv/v1.33.0`, and `go.opentelemetry.io/otel/semconv/v1.34.0` record measurements only once when no attributes are provided. (#8849) +- Treat empty `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG` values as unset in `go.opentelemetry.io/otel/sdk/trace`. (#8873) +- Normalize global `OTEL_EXPORTER_OTLP_ENDPOINT` path joining in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp` so trailing-slash base URLs do not produce double-slash log export paths. (#8864) +- Prevent a deadlock when formatting an error passed to `RecordError` calls back into the span in `go.opentelemetry.io/otel/sdk/trace`. (#8815) +- Prevent `SimpleSpanProcessor.Shutdown` from panicking when constructed with a nil exporter in `go.opentelemetry.io/otel/sdk/trace`. (#8844) +- Propagate invalid exponential histogram scale errors to Prometheus exporter self-observability metrics in `go.opentelemetry.io/otel/exporters/prometheus`. (#8839) +- Retain instrument advisory attributes configured with `go.opentelemetry.io/otel/metric/x.WithDefaultAttributes` when a matching View in `go.opentelemetry.io/otel/sdk/metric` does not specify an attribute filter. (#8859) +- Ignore HTTP URL paths when building OTLP/gRPC metric exporter targets from `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, while preserving `unix://` and `unix-abstract://` targets; treat `unix-abstract://` endpoints as insecure in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc` and `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`. (#8862) +- Ignore HTTP(S) paths when deriving gRPC trace exporter endpoints from `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`. (#8852) +- Bound memory used while parsing dense W3C property metadata by storing it compactly and materializing `Property` values on demand in `go.opentelemetry.io/otel/baggage` and `go.opentelemetry.io/otel/propagation`. + +### Removed + +- Remove the experimental `OTEL_GO_X_METRIC_EXPORT_BATCH_SIZE` environment variable in `go.opentelemetry.io/otel/sdk/metric`. + Use the `WithMaxExportBatchSize` option instead. (#8960) + +## [1.47.0-rc.1] - 2026-08-28 + +This is a release candidate for the v1.47.0 release. +That release is expected to include the `v1` release of the OpenTelemetry Go Logs API and SDK and will provide stability guarantees for the following modules: + +- `go.opentelemetry.io/otel/log` +- `go.opentelemetry.io/otel/sdk/log` + +See our [versioning policy](VERSIONING.md) for more information about these stability guarantees. + +### Added + +- Add `Logger`, `GetLoggerProvider`, and `SetLoggerProvider` to `go.opentelemetry.io/otel`. (#8874) + +### Deprecated + +- Deprecate `go.opentelemetry.io/otel/log/global`; use the equivalent APIs in `go.opentelemetry.io/otel`. (#8874) + +### Fixed + +- Ignore attempts to unregister unknown span processors in `go.opentelemetry.io/otel/sdk/trace`. (#8840) + +### Removed + +- Drop support for [Go 1.25]. (#8876) + +## [1.46.0/0.68.0/0.22.0/0.0.19] - 2026-08-25 + +This release is the last to support [Go 1.25]. +The next release will require at least [Go 1.26]. + +### Added + +- Support testing of [Go 1.27]. (#8811) +- Support `http/json` protocol in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`. (#8273, #8775, #8831) +- Add `Hasher` struct and methods in `go.opentelemetry.io/otel/attribute` to compute authoritative `Distinct` hashes incrementally for attribute filtering and deduplication. (#8598) + +### Changed + +- Lazily evaluate filtered and dropped attributes on measurement hot paths in `go.opentelemetry.io/otel/sdk/metric` to avoid unnecessary attribute set allocations. (#8598) +- Add `ErrExporterShutdown` to `go.opentelemetry.io/otel/sdk/log` and return it from the `go.opentelemetry.io/otel/exporters/stdout/stdoutlog`, `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc`, and `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp` exporters when `Export` is called after `Shutdown`. (#8773) +- Clarify in `go.opentelemetry.io/otel/log` that calling `Logger.Enabled` is optional and that cached results can become stale. (#8764) + +### Fixed + +- Export dropped attribute counts in OTLP log records from `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc` and `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#8829) +- Name span events created from OpenTracing logs after the `event` log field, falling back to `log`, instead of always using an empty name in `go.opentelemetry.io/otel/bridge/opentracing`. (#8648) +- Count exception attributes omitted due to the attribute count limit as dropped in `go.opentelemetry.io/otel/sdk/log`. (#8796) +- Prevent log record and instrumentation scope attributes with empty keys from reaching processors and exporters in `go.opentelemetry.io/otel/sdk/log`. (#8797) +- Fix a data race when span attributes are read concurrently in `go.opentelemetry.io/otel/sdk/trace`. (#8706) +- Prevent a panic in `(*Set).Filter` when called on a nil receiver in `go.opentelemetry.io/otel/attribute`. (#8792) +- The simple span and log processors record `otel.sdk.processor.{span,log}.processed` when the record is submitted to the exporter instead of after the export completes, and no longer set `error.type` from the export outcome, in `go.opentelemetry.io/otel/sdk/trace` and `go.opentelemetry.io/otel/sdk/log`. (#8705) +- Prevent `Resource.MarshalLog` from panicking on nil resources in `go.opentelemetry.io/otel/sdk/resource`. (#8758) + ## [1.45.0/0.67.0/0.21.0/0.0.18] - 2026-08-03 ### Added @@ -3782,7 +3897,10 @@ It contains api and sdk for trace and meter. - CircleCI build CI manifest files. - CODEOWNERS file to track owners of this project. -[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.45.0...HEAD +[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.47.0...HEAD +[1.47.0/0.69.0/0.23.0/0.1.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.47.0 +[1.47.0-rc.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.47.0-rc.1 +[1.46.0/0.68.0/0.22.0/0.0.19]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.46.0 [1.45.0/0.67.0/0.21.0/0.0.18]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.45.0 [1.44.0/0.66.0/0.20.0/0.0.17]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.44.0 [1.43.0/0.65.0/0.19.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.43.0 @@ -3887,6 +4005,7 @@ It contains api and sdk for trace and meter. +[Go 1.27]: https://go.dev/doc/go1.27 [Go 1.26]: https://go.dev/doc/go1.26 [Go 1.25]: https://go.dev/doc/go1.25 [Go 1.24]: https://go.dev/doc/go1.24 diff --git a/vendor/go.opentelemetry.io/otel/CLAUDE.md b/vendor/go.opentelemetry.io/otel/CLAUDE.md deleted file mode 100644 index dd3c4594fc..0000000000 --- a/vendor/go.opentelemetry.io/otel/CLAUDE.md +++ /dev/null @@ -1,3 +0,0 @@ -# Instructions for Claude Code - -@AGENTS.md diff --git a/vendor/go.opentelemetry.io/otel/CODEOWNERS b/vendor/go.opentelemetry.io/otel/CODEOWNERS index 26a03aed1d..41937a3895 100644 --- a/vendor/go.opentelemetry.io/otel/CODEOWNERS +++ b/vendor/go.opentelemetry.io/otel/CODEOWNERS @@ -12,6 +12,6 @@ # https://help.github.com/en/articles/about-code-owners # -* @MrAlias @XSAM @dashpole @pellared @dmathieu @flc1125 +* @MrAlias @XSAM @dashpole @pellared @dmathieu @flc1125 @ps-mir CODEOWNERS @MrAlias @pellared @dashpole @XSAM @dmathieu diff --git a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md index 2aba71e196..958a698db7 100644 --- a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md +++ b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md @@ -779,7 +779,7 @@ func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } - + meter := otel.GetMeterProvider().Meter( "", metric.WithInstrumentationVersion(sdk.Version()), @@ -949,7 +949,7 @@ func BenchmarkExportSpans(b *testing.B) { {"ObsDisabled", false}, {"ObsEnabled", true}, } - + for _, scenario := range scenarios { b.Run(scenario.name, func(b *testing.B) { b.Setenv( @@ -980,7 +980,7 @@ func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } - + m := otel.GetMeterProvider().Meter(/* initialize meter */) counter, err := otelconv.NewSDKComponentCounter(m) // Use the partially initialized counter if available. @@ -996,7 +996,7 @@ func newInstrumentation() *instrumentation { if !x.Observability.Enabled() { return nil, nil } - + m := otel.GetMeterProvider().Meter(/* initialize meter */) counter, err := otelconv.NewSDKComponentCounter(m) if err != nil { @@ -1023,7 +1023,7 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) if e.inst.Enabled(ctx) { e.inst.recordSpanExportStarted(ctx, len(spans)) } - + err := e.doExport(ctx, spans) if e.inst.Enabled(ctx) { @@ -1043,11 +1043,11 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error { // ❌ Do not break the context propagation. e.inst.recordSpanExportStarted(context.Background(), len(spans)) - + err := e.doExport(ctx, spans) /* ... */ - + return err } ``` @@ -1118,7 +1118,7 @@ func TestObservability(t *testing.T) { // Reset component ID counter to ensure deterministic component names. componentIDCounter.Store(0) - + /* ... test code ... */ } ``` @@ -1203,18 +1203,20 @@ For more information about the maintainer role, see the [community repository](h ### Approvers - [Flc](https://github.com/flc1125), Independent +- [Puneet Singh](https://github.com/ps-mir), Independent For more information about the approver role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#approver). ### Triagers -- [Alex Kats](https://github.com/akats7), Capital One +- [Marc Schäfer](https://github.com/marcschaeferger), T&A SYSTEME GmbH For more information about the triager role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#triager). ### Emeritus - [Aaron Clawson](https://github.com/MadVikingGod) +- [Alex Kats](https://github.com/akats7) - [Anthony Mirabella](https://github.com/Aneurysm9) - [Cheng-Zhen Yang](https://github.com/scorpionknifes) - [Chester Cheung](https://github.com/hanyuancheung) diff --git a/vendor/go.opentelemetry.io/otel/Makefile b/vendor/go.opentelemetry.io/otel/Makefile index d4711257df..c674ef8a17 100644 --- a/vendor/go.opentelemetry.io/otel/Makefile +++ b/vendor/go.opentelemetry.io/otel/Makefile @@ -69,8 +69,13 @@ $(GORELEASE): PACKAGE=golang.org/x/exp/cmd/gorelease GOVULNCHECK = $(TOOLS)/govulncheck $(TOOLS)/govulncheck: PACKAGE=golang.org/x/vuln/cmd/govulncheck +AFFECTEDMODS = $(TOOLS)/affectedmods +AFFECTEDMODS_FILES := $(sort $(shell find $(TOOLS_MOD_DIR)/affectedmods -type f)) +$(TOOLS)/affectedmods: PACKAGE=go.opentelemetry.io/otel/$(TOOLS_MOD_DIR)/affectedmods +$(TOOLS)/affectedmods: $(AFFECTEDMODS_FILES) + .PHONY: tools -tools: $(CROSSLINK) $(GOLANGCI_LINT) $(MISSPELL) $(GOCOVMERGE) $(STRINGER) $(VERIFYREADMES) $(MULTIMOD) $(SEMCONVKIT) $(GOTMPL) $(GORELEASE) +tools: $(CROSSLINK) $(GOLANGCI_LINT) $(MISSPELL) $(GOCOVMERGE) $(STRINGER) $(VERIFYREADMES) $(MULTIMOD) $(SEMCONVKIT) $(GOTMPL) $(GORELEASE) $(AFFECTEDMODS) # Virtualized python tools via docker @@ -125,9 +130,11 @@ go-work: $(CROSSLINK) # Build -.PHONY: build +.PHONY: build cross-build build: $(OTEL_GO_MOD_DIRS:%=build/%) $(OTEL_GO_MOD_DIRS:%=build-tests/%) +# Cross-platform builds cannot execute the binaries produced by build-tests (go test), so use a compile-only target. +cross-build: $(OTEL_GO_MOD_DIRS:%=build/%) build/%: DIR=$* build/%: @echo "$(GO) build $(DIR)/..." \ @@ -163,6 +170,9 @@ test/%: | grep -v third_party \ | xargs $(GO) test -timeout $(TIMEOUT)s $(ARGS) +.PHONY: test-tools +test-tools: test/$(TOOLS_MOD_DIR) + COVERAGE_MODE = atomic COVERAGE_PROFILE = coverage.out .PHONY: test-coverage @@ -187,15 +197,23 @@ benchmark/%: # sdk/metric is split into two shards to work around CodSpeed limitations. # See https://github.com/CodSpeedHQ/codspeed-go/issues/56 -BENCHMARK_SHARDS := $(filter-out ./sdk/metric,$(OTEL_GO_MOD_DIRS)) ./sdk/metric/root ./sdk/metric/internal -benchmark/./sdk/metric/root: +BENCHMARK_SHARDS := $(filter-out ./sdk/metric,$(OTEL_GO_MOD_DIRS)) ./sdk/metric/. ./sdk/metric/internal +benchmark/./sdk/metric/.: cd ./sdk/metric && $(GO) test -run='^$$' -bench=. $(ARGS) . ./exemplar/... -benchmark/./sdk/metric/internal: - cd ./sdk/metric && $(GO) test -run='^$$' -bench=. $(ARGS) ./internal/... print-sharded-benchmarks: @echo $(BENCHMARK_SHARDS) | jq -cR 'split(" ")' +# Print the JSON list of benchmark shards whose code changed since +# BASE_REF (default: main). Filters print-sharded-benchmarks +# down to shards whose underlying module contains a changed *.go file. +# Non-Go changes (docs, workflows, Makefile, go.mod/go.sum, tooling) emit []. +# Override the diff base via BASE_REF, or pass ARGS=-all to emit the full list. +BASE_REF ?= main +.PHONY: print-affected-benchmarks +print-affected-benchmarks: + @$(MAKE) -s print-sharded-benchmarks | $(GO) -C $(TOOLS_MOD_DIR) run ./affectedmods $(if $(strip $(BASE_REF)),-base=$(BASE_REF),) $(ARGS) + .PHONY: golangci-lint golangci-lint-fix golangci-lint-fix: ARGS=--fix golangci-lint-fix: golangci-lint diff --git a/vendor/go.opentelemetry.io/otel/README.md b/vendor/go.opentelemetry.io/otel/README.md index ce97e9a251..bcdb73e017 100644 --- a/vendor/go.opentelemetry.io/otel/README.md +++ b/vendor/go.opentelemetry.io/otel/README.md @@ -3,12 +3,11 @@ [![ci](https://github.com/open-telemetry/opentelemetry-go/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/open-telemetry/opentelemetry-go/actions/workflows/ci.yml) [![codecov.io](https://codecov.io/gh/open-telemetry/opentelemetry-go/coverage.svg?branch=main)](https://app.codecov.io/gh/open-telemetry/opentelemetry-go?branch=main) [![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel)](https://pkg.go.dev/go.opentelemetry.io/otel) -[![Go Report Card](https://goreportcard.com/badge/go.opentelemetry.io/otel)](https://goreportcard.com/report/go.opentelemetry.io/otel) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/open-telemetry/opentelemetry-go/badge)](https://scorecard.dev/viewer/?uri=github.com/open-telemetry/opentelemetry-go) [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/9996/badge)](https://www.bestpractices.dev/projects/9996) [![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/opentelemetry-go.svg)](https://issues.oss-fuzz.com/issues?q=project:opentelemetry-go) [![FOSSA Status](https://app.fossa.com/api/projects/custom%2B162%2Fgithub.com%2Fopen-telemetry%2Fopentelemetry-go.svg?type=shield&issueType=license)](https://app.fossa.com/projects/custom%2B162%2Fgithub.com%2Fopen-telemetry%2Fopentelemetry-go?ref=badge_shield&issueType=license) -[![Slack](https://img.shields.io/badge/slack-@cncf/otel--go-brightgreen.svg?logo=slack)](https://cloud-native.slack.com/archives/C01NPAXACKT) +[![Slack](https://img.shields.io/badge/slack-@cncf/otel--go-brightgreen.svg?logo=slack)](https://slack.cncf.io/) OpenTelemetry-Go is the [Go](https://golang.org/) implementation of [OpenTelemetry](https://opentelemetry.io/). It provides a set of APIs to directly measure performance and behavior of your software and send this data to observability platforms. @@ -19,7 +18,7 @@ It provides a set of APIs to directly measure performance and behavior of your s |---------|--------------------| | Traces | Stable | | Metrics | Stable | -| Logs | Beta[^1] | +| Logs | Stable | Progress and status specific to this repository is tracked in our [project boards](https://github.com/open-telemetry/opentelemetry-go/projects) @@ -29,8 +28,6 @@ and Project versioning information and stability guarantees can be found in the [versioning documentation](VERSIONING.md). -[^1]: https://github.com/orgs/open-telemetry/projects/43 - ### Compatibility OpenTelemetry-Go ensures compatibility with the current supported versions of @@ -53,20 +50,20 @@ Currently, this project supports the following environments. | OS | Go Version | Architecture | |----------|------------|--------------| +| Ubuntu | 1.27 | amd64 | | Ubuntu | 1.26 | amd64 | -| Ubuntu | 1.25 | amd64 | +| Ubuntu | 1.27 | 386 | | Ubuntu | 1.26 | 386 | -| Ubuntu | 1.25 | 386 | +| Ubuntu | 1.27 | arm64 | | Ubuntu | 1.26 | arm64 | -| Ubuntu | 1.25 | arm64 | +| macOS | 1.27 | amd64 | | macOS | 1.26 | amd64 | -| macOS | 1.25 | amd64 | +| macOS | 1.27 | arm64 | | macOS | 1.26 | arm64 | -| macOS | 1.25 | arm64 | +| Windows | 1.27 | amd64 | | Windows | 1.26 | amd64 | -| Windows | 1.25 | amd64 | +| Windows | 1.27 | 386 | | Windows | 1.26 | 386 | -| Windows | 1.25 | 386 | While this project should work for other systems, no compatibility guarantees are made for those systems currently. @@ -113,10 +110,3 @@ All officially supported exporters for the OpenTelemetry project are contained i ## Contributing See the [contributing documentation](CONTRIBUTING.md). - -### Emeritus - -- [Alex Kats](https://github.com/akats7), Triager - -For more information about the emeritus role, see the -[community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#emeritus-maintainerapprovertriager). diff --git a/vendor/go.opentelemetry.io/otel/VERSIONING.md b/vendor/go.opentelemetry.io/otel/VERSIONING.md index b27c9e84f5..56eaa7d220 100644 --- a/vendor/go.opentelemetry.io/otel/VERSIONING.md +++ b/vendor/go.opentelemetry.io/otel/VERSIONING.md @@ -12,6 +12,12 @@ is designed so the following goals can be achieved. * [Semantic import versioning](https://github.com/golang/go/wiki/Modules#semantic-import-versioning) will be used. + * Stable module compatibility is understood in terms of the [Go 1 + compatibility guidelines](https://go.dev/doc/go1compat). Code that + compiled against an older version of a package should continue to compile + against newer versions of that package, subject to the exceptions in the + Go 1 compatibility guidelines and any additional exceptions documented + below. * Versions will comply with [semver 2.0](https://semver.org/spec/v2.0.0.html) with the following exceptions. * New methods may be added to exported API interfaces. All exported diff --git a/vendor/go.opentelemetry.io/otel/attribute/hash.go b/vendor/go.opentelemetry.io/otel/attribute/hash.go index f651eb13d9..54c26e67a0 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/hash.go +++ b/vendor/go.opentelemetry.io/otel/attribute/hash.go @@ -33,19 +33,71 @@ const ( emptyID uint64 = 7305809155345288421 // "__empty_" (little endian) ) +// Hasher computes a Distinct value from KeyValue attributes supplied with +// Write. +// +// A Hasher must be obtained from [NewHasher]. The zero value is not usable and +// its methods will panic. +type Hasher struct { + h xxhash.Hash +} + +// NewHasher returns a new Hasher. +func NewHasher() *Hasher { + return &Hasher{h: xxhash.New()} +} + +// Reset resets h to its initial state so it can be reused. +func (h *Hasher) Reset() { + h.h.Reset() +} + +// Write adds kv to the hash. +// +// Write requires attributes to be supplied in ascending key order with no +// duplicate keys. To produce the same Distinct as Set.Equivalent, write +// attributes in ascending key order, with no more than one value for each key. +// If the source contains duplicate keys, retain the last value for each key +// before calling Write. +func (h *Hasher) Write(kv KeyValue) { + // hashKV mutates the digest h.h refers to in place and returns the same + // Hash value it was passed. Discarding the result keeps the digest pointer + // from flowing back into h, which would force the digest to be heap + // allocated for every Hasher. Keeping Write this small also keeps it within + // the inlining budget, which matters because hashKVs calls it per attribute. + _ = hashKV(h.h, kv) +} + +// Distinct returns the identifier for the attributes written to h. When Write +// is called as described above, it returns the same value as [Set.Equivalent]. +func (h *Hasher) Distinct() Distinct { + // No count of written attributes is needed to detect the empty case. The + // sum of a digest with nothing written to it is emptyHash, which is + // non-zero (0xef46db3751d8e999), so it passes through remapZeroHash + // unchanged and matches emptySet.Equivalent. + return Distinct{hash: remapZeroHash(h.h.Sum64())} +} + +// remapZeroHash remaps a 0 sum to a non-zero value, because hash == 0 is a +// reserved sentinel (treated as empty/invalid). +func remapZeroHash(sum uint64) uint64 { + if sum == 0 { + return 1 + } + return sum +} + // hashKVs returns a new xxHash64 hash of kvs. +// +// This routes through [Hasher] so that Set hashing and Hasher cannot disagree: +// there is exactly one implementation of how attributes are mixed and how the +// final sum is framed. func hashKVs(kvs []KeyValue) uint64 { - h := xxhash.New() + h := NewHasher() for _, kv := range kvs { - h = hashKV(h, kv) + h.Write(kv) } - sum := h.Sum64() - // Remap 0 to a non-zero value for non-empty input because hash == 0 is a reserved sentinel (treated as empty/invalid). - const remappedZeroHash uint64 = 1 - if sum == 0 && len(kvs) > 0 { - return remappedZeroHash - } - return sum + return h.Distinct().hash } // hashKV returns the xxHash64 hash of kv with h as the base. diff --git a/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go b/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go index c851179cca..499aa3318f 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go +++ b/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go @@ -21,6 +21,7 @@ func New() Hash { return Hash{d: xxhash.New()} } +// Uint64 hashes val into h, returning the updated Hash. func (h Hash) Uint64(val uint64) Hash { var buf [8]byte binary.LittleEndian.PutUint64(buf[:], val) @@ -40,10 +41,12 @@ func (h Hash) Bool(val bool) Hash { // nolint:revive // This is a hashing functi return h.Uint64(0) } +// Float64 hashes val into h, returning the updated Hash. func (h Hash) Float64(val float64) Hash { return h.Uint64(math.Float64bits(val)) } +// Int64 hashes val into h, returning the updated Hash. func (h Hash) Int64(val int64) Hash { return h.Uint64(uint64(val)) // nolint:gosec // Overflow doesn't matter since we are hashing. } @@ -62,3 +65,8 @@ func (h Hash) String(val string) Hash { func (h Hash) Sum64() uint64 { return h.d.Sum64() } + +// Reset resets the hash to its initial state. +func (h Hash) Reset() { + h.d.Reset() +} diff --git a/vendor/go.opentelemetry.io/otel/attribute/kv.go b/vendor/go.opentelemetry.io/otel/attribute/kv.go index c4f0dd9281..60d49739a3 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/kv.go +++ b/vendor/go.opentelemetry.io/otel/attribute/kv.go @@ -13,6 +13,16 @@ type KeyValue struct { Value Value } +// String returns a string representation of KeyValue using the +// [OpenTelemetry Attribute representation for non-OTLP protocols] rules. +// +// The KeyValue is encoded as a JSON object containing a single key-value pair. +// +// [OpenTelemetry Attribute representation for non-OTLP protocols]: https://opentelemetry.io/docs/specs/otel/common/#attribute-representation-for-non-otlp +func (kv KeyValue) String() string { + return formatMap([]KeyValue{kv}) +} + // Valid reports whether kv is a valid OpenTelemetry attribute. func (kv KeyValue) Valid() bool { return kv.Key.Defined() diff --git a/vendor/go.opentelemetry.io/otel/attribute/set.go b/vendor/go.opentelemetry.io/otel/attribute/set.go index 87d6f96200..d3b2e240ba 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/set.go +++ b/vendor/go.opentelemetry.io/otel/attribute/set.go @@ -313,6 +313,9 @@ func filteredToFront(slice []KeyValue, keep Filter) int { // Filter returns a filtered copy of this Set. See the documentation for // NewSetWithSortableFiltered for more details. func (l *Set) Filter(re Filter) (Set, []KeyValue) { + if l == nil { + return emptySet, nil + } if re == nil { return *l, nil } @@ -406,6 +409,21 @@ func computeDataReflect(kvs []KeyValue) any { return at.Interface() } +// String returns a string representation of the Set using the +// [OpenTelemetry Attribute Collection representation for non-OTLP protocols] +// rules. +// +// The Set is encoded as a JSON object. A nil or empty Set is encoded as an +// empty JSON object. +// +// [OpenTelemetry Attribute Collection representation for non-OTLP protocols]: https://opentelemetry.io/docs/specs/otel/common/#attribute-collection-representation-for-non-otlp +func (l *Set) String() string { + if l == nil || l.hash == 0 { + return "{}" + } + return formatMapValue(l.data) +} + // MarshalJSON returns the JSON encoding of the Set. func (l *Set) MarshalJSON() ([]byte, error) { return json.Marshal(l.data) diff --git a/vendor/go.opentelemetry.io/otel/baggage/baggage.go b/vendor/go.opentelemetry.io/otel/baggage/baggage.go index 25c739d082..72a58c1b61 100644 --- a/vendor/go.opentelemetry.io/otel/baggage/baggage.go +++ b/vendor/go.opentelemetry.io/otel/baggage/baggage.go @@ -247,10 +247,78 @@ func (p properties) String() string { return strings.Join(props, propertyDelimiter) } +// validateMetadata validates non-empty W3C property elements without decoding +// or materializing Property values. Empty elements are accepted to preserve +// existing parsing behavior. +func validateMetadata(raw string) (string, bool) { + start := 0 + for end := 0; end <= len(raw); end++ { + if end != len(raw) && raw[end] != propertyDelimiter[0] { + continue + } + + if start != end { + if _, ok := parsePropertyFields(raw[start:end]); !ok { + return raw[start:end], false + } + } + start = end + 1 + } + return "", true +} + +// normalizeMetadata removes empty property elements while preserving the raw +// representation of all non-empty elements. +func normalizeMetadata(metadata string) string { + if metadata == "" || + (metadata[0] != propertyDelimiter[0] && + metadata[len(metadata)-1] != propertyDelimiter[0] && + !strings.Contains(metadata, propertyDelimiter+propertyDelimiter)) { + return metadata + } + + var normalized strings.Builder + normalized.Grow(len(metadata)) + for property := range strings.SplitSeq(metadata, propertyDelimiter) { + if property == "" { + continue + } + if normalized.Len() > 0 { + _, _ = normalized.WriteString(propertyDelimiter) + } + _, _ = normalized.WriteString(property) + } + return normalized.String() +} + +func propertiesFromMetadata(metadata string) properties { + if metadata == "" { + return nil + } + + props := make(properties, 0, strings.Count(metadata, propertyDelimiter)+1) + for pStr := range strings.SplitSeq(metadata, propertyDelimiter) { + if pStr == "" { + continue + } + p, err := parseProperty(pStr) + if err != nil { + return nil + } + props = append(props, p) + } + return props +} + // Member is a list-member of a baggage-string as defined by the W3C Baggage // specification. type Member struct { key, value string + + // metadata contains the opaque W3C property suffix extracted from the wire + // without the leading semicolon. properties contains API-created + // properties. The fields are mutually exclusive. + metadata string properties properties // hasData indicates whether the created property contains data or not. @@ -307,21 +375,16 @@ func newInvalidMember() Member { return Member{} } -// parseMember attempts to decode a Member from the passed string. It returns -// an error if the input is invalid according to the W3C Baggage -// specification. +// parseMember attempts to decode a Member from the passed string. Property +// metadata grammar is validated without decoding or materializing properties. func parseMember(member string) (Member, error) { - var props properties - keyValue, properties, found := strings.Cut(member, propertyDelimiter) + var metadata string + keyValue, rawMetadata, found := strings.Cut(member, propertyDelimiter) if found { - // Parse the member properties. - for pStr := range strings.SplitSeq(properties, propertyDelimiter) { - p, err := parseProperty(pStr) - if err != nil { - return newInvalidMember(), err - } - props = append(props, p) + if invalid, ok := validateMetadata(rawMetadata); !ok { + return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidProperty, invalid) } + metadata = normalizeMetadata(rawMetadata) } // Parse the member key/value pair. @@ -349,7 +412,7 @@ func parseMember(member string) (Member, error) { } value := replaceInvalidUTF8Sequences(len(rawVal), unescapeVal) - return Member{key: key, value: value, properties: props, hasData: true}, nil + return Member{key: key, value: value, metadata: metadata, hasData: true}, nil } // replaceInvalidUTF8Sequences replaces invalid UTF-8 sequences with '�'. @@ -399,10 +462,14 @@ func (m Member) Key() string { return m.key } func (m Member) Value() string { return m.value } // Properties returns a copy of the Member properties. -func (m Member) Properties() []Property { return m.properties.Copy() } +func (m Member) Properties() []Property { + if m.metadata != "" { + return propertiesFromMetadata(m.metadata) + } + return m.properties.Copy() +} -// String encodes Member into a header string compliant with the W3C Baggage -// specification. +// String encodes Member into a baggage header string. // It would return empty string if the key is invalid with the W3C Baggage // specification. This could happen for a UTF-8 key, as it may contain // invalid characters. @@ -413,12 +480,31 @@ func (m Member) String() string { } s := m.key + keyValueDelimiter + valueEscape(m.value) - if len(m.properties) > 0 { + if m.metadata != "" { + s += propertyDelimiter + m.metadata + } else if len(m.properties) > 0 { s += propertyDelimiter + m.properties.String() } return s } +func memberFromItem(key string, item baggage.Item) Member { + return Member{ + key: key, + value: item.Value(), + metadata: item.Metadata(), + properties: fromInternalProperties(item.Properties()), + hasData: true, + } +} + +func itemFromMember(member Member) baggage.Item { + if member.metadata != "" { + return baggage.NewItemWithMetadata(member.value, member.metadata) + } + return baggage.NewItemWithProperties(member.value, member.properties.asInternal()) +} + // Baggage is a list of baggage members representing the baggage-string as // defined by the W3C Baggage specification. type Baggage struct { //nolint:golint @@ -444,10 +530,7 @@ func New(members ...Member) (Baggage, error) { return Baggage{}, errInvalidMember } // OpenTelemetry resolves duplicates by last-one-wins. - b[m.key] = baggage.Item{ - Value: m.value, - Properties: m.properties.asInternal(), - } + b[m.key] = itemFromMember(m) } var truncateErr error @@ -467,11 +550,7 @@ func New(members ...Member) (Baggage, error) { totalBytes := 0 first := true for k := range b { - m := Member{ - key: k, - value: b[k].Value, - properties: fromInternalProperties(b[k].Properties), - } + m := memberFromItem(k, b[k]) memberSize := len(m.String()) if !first { memberSize++ // comma separator @@ -563,10 +642,7 @@ func Parse(bStr string) (Baggage, error) { } // OpenTelemetry resolves duplicates by last-one-wins. - b[m.key] = baggage.Item{ - Value: m.value, - Properties: m.properties.asInternal(), - } + b[m.key] = itemFromMember(m) sizes[m.key] = memberBytes totalBytes = newTotalBytes } @@ -597,12 +673,7 @@ func (b Baggage) Member(key string) Member { return newInvalidMember() } - return Member{ - key: key, - value: v.Value, - properties: fromInternalProperties(v.Properties), - hasData: true, - } + return memberFromItem(key, v) } // Members returns all the baggage list-members. @@ -617,12 +688,7 @@ func (b Baggage) Members() []Member { members := make([]Member, 0, len(b.list)) for k, v := range b.list { - members = append(members, Member{ - key: k, - value: v.Value, - properties: fromInternalProperties(v.Properties), - hasData: true, - }) + members = append(members, memberFromItem(k, v)) } return members } @@ -652,10 +718,7 @@ func (b Baggage) SetMember(member Member) (Baggage, error) { list[k] = v } - list[member.key] = baggage.Item{ - Value: member.value, - Properties: member.properties.asInternal(), - } + list[member.key] = itemFromMember(member) return Baggage{list: list}, nil } @@ -692,11 +755,7 @@ func (b Baggage) Len() int { func (b Baggage) String() string { members := make([]string, 0, len(b.list)) for k, v := range b.list { - s := Member{ - key: k, - value: v.Value, - properties: fromInternalProperties(v.Properties), - }.String() + s := memberFromItem(k, v).String() // Ignored empty members. if s != "" { @@ -706,9 +765,14 @@ func (b Baggage) String() string { return strings.Join(members, listDelimiter) } -// parsePropertyInternal attempts to decode a Property from the passed string. -// It follows the spec at https://www.w3.org/TR/baggage/#definition. -func parsePropertyInternal(s string) (p Property, ok bool) { +type propertyFields struct { + key, rawValue string + hasValue bool +} + +// parsePropertyFields validates and locates a property's fields without +// decoding or allocating them. +func parsePropertyFields(s string) (fields propertyFields, ok bool) { // For the entire function we will use " key = value " as an example. // Attempting to parse the key. // First skip spaces at the beginning "< >key = value " (they could be empty). @@ -727,7 +791,7 @@ func parsePropertyInternal(s string) (p Property, ok bool) { // If we couldn't find any valid key character, // it means the key is either empty or invalid. if keyStart == keyEnd { - return p, ok + return fields, ok } // Skip spaces after the key: " key< >= value ". @@ -735,15 +799,14 @@ func parsePropertyInternal(s string) (p Property, ok bool) { if index == len(s) { // A key can have no value, like: " key ". - ok = true - p.key = s[keyStart:keyEnd] - return p, ok + fields.key = s[keyStart:keyEnd] + return fields, true } // If we have not reached the end and we can't find the '=' delimiter, // it means the property is invalid. if s[index] != keyValueDelimiter[0] { - return p, ok + return fields, ok } // Attempting to parse the value. @@ -769,23 +832,59 @@ func parsePropertyInternal(s string) (p Property, ok bool) { // we have not reached the end, it means the property is // invalid, something like: " key = value value1". if index != len(s) { - return p, ok + return fields, ok + } + rawVal := s[valueStart:valueEnd] + if !validPercentEncoding(rawVal) { + return fields, ok + } + + fields.key = s[keyStart:keyEnd] + fields.rawValue = rawVal + fields.hasValue = true + return fields, true +} + +func validPercentEncoding(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] != '%' { + continue + } + if i+2 >= len(s) || !isHex(s[i+1]) || !isHex(s[i+2]) { + return false + } + i += 2 + } + return true +} + +func isHex(c byte) bool { + return '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' +} + +// parsePropertyInternal attempts to decode a Property from the passed string. +// It follows the spec at https://www.w3.org/TR/baggage/#definition. +func parsePropertyInternal(s string) (p Property, ok bool) { + fields, ok := parsePropertyFields(s) + if !ok { + return p, false + } + if !fields.hasValue { + p.key = fields.key + return p, true } // Decode a percent-encoded value. - rawVal := s[valueStart:valueEnd] - unescapeVal, err := url.PathUnescape(rawVal) + unescapeVal, err := url.PathUnescape(fields.rawValue) if err != nil { - return p, ok + return p, false } - value := replaceInvalidUTF8Sequences(len(rawVal), unescapeVal) + value := replaceInvalidUTF8Sequences(len(fields.rawValue), unescapeVal) - ok = true - p.key = s[keyStart:keyEnd] + p.key = fields.key p.hasValue = true - p.value = value - return p, ok + return p, true } func skipSpace(s string, offset int) int { diff --git a/vendor/go.opentelemetry.io/otel/codes/codes.go b/vendor/go.opentelemetry.io/otel/codes/codes.go index 9355545a8c..1502de3500 100644 --- a/vendor/go.opentelemetry.io/otel/codes/codes.go +++ b/vendor/go.opentelemetry.io/otel/codes/codes.go @@ -32,7 +32,7 @@ const ( maxCode = 3 ) -// Code is an 32-bit representation of a status state. +// Code is a 32-bit representation of a status state. type Code uint32 var codeToStr = map[Code]string{ diff --git a/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile b/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile index 20eecba40d..82653bca91 100644 --- a/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile +++ b/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile @@ -1,4 +1,4 @@ # This is a renovate-friendly source of Docker images. FROM python:3.13.6-slim-bullseye@sha256:e98b521460ee75bca92175c16247bdf7275637a8faaeb2bcfa19d879ae5c4b9a AS python -FROM otel/weaver:v0.25.1@sha256:9ad46ca9cd4fa5974b121f886aa3e9946a8ef8ea905001a96c018d21f9db87ca AS weaver +FROM otel/weaver:v0.26.1@sha256:9094862c0ab261bdbcb079bb981f9a573b3659b130a6d2ab8616eca6ba37aaec AS weaver FROM avtodev/markdown-lint:v1@sha256:6aeedc2f49138ce7a1cd0adffc1b1c0321b841dc2102408967d9301c031949ee AS markdown diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go index 078a9db0ab..1754a7fcb6 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go @@ -9,6 +9,8 @@ import ( "go.opentelemetry.io/otel/sdk/instrumentation" ) +// InstrumentationScope transforms il into an OTLP InstrumentationScope, +// returning nil if il is the zero value. func InstrumentationScope(il instrumentation.Scope) *commonpb.InstrumentationScope { if il == (instrumentation.Scope{}) { return nil diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/doc.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/doc.go index b01358fc83..3dbc842754 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/doc.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/doc.go @@ -12,8 +12,9 @@ The environment variables described below can be used for configuration. OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT (default: "https://localhost:4317") - target to which the exporter sends telemetry. The target syntax is defined in https://github.com/grpc/grpc/blob/master/doc/naming.md. -The value must contain a scheme ("http" or "https") and host. -The value may additionally contain a port, and a path. +If the value uses the "http" or "https" scheme, the host and optional port are +used as the gRPC target and any path is ignored. +Values with other schemes are passed to gRPC as-is. The value should not contain a query string or fragment. OTEL_EXPORTER_OTLP_TRACES_ENDPOINT takes precedence over OTEL_EXPORTER_OTLP_ENDPOINT. The configuration can be overridden by [WithEndpoint], [WithEndpointURL], [WithInsecure], and [WithGRPCConn] options. diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/gen.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/gen.go index ec16d01457..26066e3368 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/gen.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/gen.go @@ -14,8 +14,8 @@ package internal //go:generate gotmpl --body=../../../../../internal/shared/otlp/envconfig/envconfig_test.go.tmpl "--data={}" --out=envconfig/envconfig_test.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/envconfig.go.tmpl "--data={\"envconfigImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig\"}" --out=otlpconfig/envconfig.go -//go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/options.go.tmpl "--data={\"retryImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry\"}" --out=otlpconfig/options.go -//go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/options_test.go.tmpl "--data={\"envconfigImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig\"}" --out=otlpconfig/options_test.go +//go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/options.go.tmpl "--data={\"isHTTP\": false, \"retryImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry\"}" --out=otlpconfig/options.go +//go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/options_test.go.tmpl "--data={\"isHTTP\": false, \"envconfigImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig\"}" --out=otlpconfig/options_test.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/optiontypes.go.tmpl "--data={}" --out=otlpconfig/optiontypes.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/tls.go.tmpl "--data={}" --out=otlpconfig/tls.go diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/target.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/target.go index 4d06658941..3bd3798829 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/target.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/target.go @@ -21,13 +21,13 @@ const ( ) // ParseCanonicalTarget parses a target string and returns the extracted host -// (domain address or IP), the target port, or an error. +// (domain name or IP address), the target port, or an error. // // If no port is specified, -1 is returned. // // If no host is specified, an empty string is returned. // -// The target string is expected to always have the form +// The target string must have the form // "://[authority]/". For example: // - "dns:///example.com:42" // - "dns://8.8.8.8/example.com:42" @@ -35,8 +35,8 @@ const ( // - "unix-abstract:///socket-name" // - "passthrough:///192.34.2.1:42" // -// The target is expected to come from the CanonicalTarget method of a gRPC -// Client. +// The target is expected to be returned by gRPC's ClientConn.CanonicalTarget +// method. func ParseCanonicalTarget(target string) (string, int, error) { const sep = "://" @@ -60,7 +60,7 @@ func ParseCanonicalTarget(target string) (string, int, error) { return parseEndpoint(endpoint) } -// parseUnix parses unix socket targets. +// parseUnix parses Unix socket targets. func parseUnix(endpoint string) (string, int, error) { // Format: unix[-abstract]://path // @@ -70,8 +70,8 @@ func parseUnix(endpoint string) (string, int, error) { return endpoint, -1, nil } - // If there's no leading slash, it means there might be an authority - // Check for authority case (should error): "authority/path" + // If there is no leading slash, an authority might be present, which is + // invalid. Check for this case: "authority/path". if slashIdx := strings.Index(endpoint, "/"); slashIdx > 0 { return "", -1, fmt.Errorf("invalid (non-empty) authority: %s", endpoint[:slashIdx]) } @@ -97,8 +97,8 @@ func parseUnix(endpoint string) (string, int, error) { // - "[ipv6]:port" // - "[ipv6%zone]:port" // -// It returns the host or host%zone (domain address or IP), the port (or -1 if -// not specified), or an error if the input is not a valid. +// It returns the host or host%zone (domain name or IP address), the port (or +// -1 if not specified), or an error if the input is invalid. func parseEndpoint(endpoint string) (string, int, error) { // First check if the endpoint is just an IP address. if ip := parseIP(endpoint); ip != "" { diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/envconfig.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/envconfig.go index 8b3f729fde..ce41a22ebf 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/envconfig.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/envconfig.go @@ -100,6 +100,8 @@ func getOptionsFromEnv() []GenericOption { envconfig.WithHeaders("TRACES_HEADERS", func(h map[string]string) { opts = append(opts, WithHeaders(h)) }), WithEnvCompression("COMPRESSION", func(c Compression) { opts = append(opts, WithCompression(c)) }), WithEnvCompression("TRACES_COMPRESSION", func(c Compression) { opts = append(opts, WithCompression(c)) }), + WithEnvProtocol("PROTOCOL", func(p Protocol) { opts = append(opts, WithProtocol(p)) }), + WithEnvProtocol("TRACES_PROTOCOL", func(p Protocol) { opts = append(opts, WithProtocol(p)) }), envconfig.WithDuration("TIMEOUT", func(d time.Duration) { opts = append(opts, WithTimeout(d)) }), envconfig.WithDuration("TRACES_TIMEOUT", func(d time.Duration) { opts = append(opts, WithTimeout(d)) }), ) @@ -117,10 +119,20 @@ func withEndpointScheme(u *url.URL) GenericOption { } func withEndpointForGRPC(u *url.URL) func(cfg Config) Config { + target := u.String() + switch strings.ToLower(u.Scheme) { + case "http", "https": + target = u.Host + case "": + if u.Host != "" { + target = path.Join(u.Host, u.Path) + } + } + return func(cfg Config) Config { // For OTLP/gRPC endpoints, this is the target to which the // exporter is going to send telemetry. - cfg.Traces.Endpoint = path.Join(u.Host, u.Path) + cfg.Traces.Endpoint = target return cfg } } @@ -139,6 +151,25 @@ func WithEnvCompression(n string, fn func(Compression)) func(e *envconfig.EnvOpt } } +// WithEnvProtocol retrieves the specified config and passes it to ConfigFn as a Protocol. +func WithEnvProtocol(n string, fn func(Protocol)) func(e *envconfig.EnvOptionsReader) { + return func(e *envconfig.EnvOptionsReader) { + if v, ok := e.GetEnvValue(n); ok { + protocol := ProtocolHTTPProtobuf + switch v { + case "grpc": + protocol = ProtocolGRPC + case "http/protobuf": + protocol = ProtocolHTTPProtobuf + case "http/json": + protocol = ProtocolHTTPJSON + } + + fn(protocol) + } + } +} + // revive:disable-next-line:flag-parameter func withInsecure(b bool) GenericOption { if b { diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/options.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/options.go index 36cf1e267c..b990dd3f77 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/options.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/options.go @@ -44,12 +44,14 @@ type ( // This type is compatible with `http.Transport.Proxy` and can be used to set a custom proxy function to the OTLP HTTP client. HTTPTransportProxyFunc func(*http.Request) (*url.URL, error) + // SignalConfig holds the configuration for exporting a single signal. SignalConfig struct { Endpoint string Insecure bool TLSCfg *tls.Config Headers map[string]string Compression Compression + Protocol Protocol MaxRequestSize int Timeout time.Duration URLPath string @@ -62,6 +64,7 @@ type ( HTTPClient *http.Client } + // Config holds the configuration for an otlptrace exporter. Config struct { // Signal specific configurations Traces SignalConfig @@ -84,6 +87,7 @@ func NewHTTPConfig(opts ...HTTPOption) Config { Endpoint: fmt.Sprintf("%s:%d", DefaultCollectorHost, DefaultCollectorHTTPPort), URLPath: DefaultTracesPath, Compression: NoCompression, + Protocol: ProtocolHTTPProtobuf, MaxRequestSize: DefaultMaxRequestSize, Timeout: DefaultTimeout, }, @@ -119,41 +123,47 @@ func NewGRPCConfig(opts ...GRPCOption) Config { Endpoint: fmt.Sprintf("%s:%d", DefaultCollectorHost, DefaultCollectorGRPCPort), URLPath: DefaultTracesPath, Compression: NoCompression, + Protocol: ProtocolGRPC, MaxRequestSize: DefaultMaxRequestSize, Timeout: DefaultTimeout, }, RetryConfig: retry.DefaultConfig, - DialOptions: []grpc.DialOption{grpc.WithUserAgent(userAgent)}, } cfg = ApplyGRPCEnvConfigs(cfg) for _, opt := range opts { cfg = opt.ApplyGRPCOption(cfg) } + // dialOptsPrefix holds the internally computed defaults. It is prepended + // to cfg.DialOptions so that a raw grpc.DialOption supplied via WithDialOption + // always takes precedence: grpc.DialOption values are opaque closures, so this code has no way to + // detect a conflicting user-supplied option and defer to it instead. + dialOptsPrefix := []grpc.DialOption{grpc.WithUserAgent(userAgent)} if cfg.ServiceConfig != "" { - cfg.DialOptions = append(cfg.DialOptions, grpc.WithDefaultServiceConfig(cfg.ServiceConfig)) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithDefaultServiceConfig(cfg.ServiceConfig)) } // Prioritize GRPCCredentials over Insecure (passing both is an error). if cfg.Traces.GRPCCredentials != nil { //nolint:gocritic // if-else is clearer than switch - cfg.DialOptions = append(cfg.DialOptions, grpc.WithTransportCredentials(cfg.Traces.GRPCCredentials)) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithTransportCredentials(cfg.Traces.GRPCCredentials)) } else if cfg.Traces.Insecure { - cfg.DialOptions = append(cfg.DialOptions, grpc.WithTransportCredentials(insecure.NewCredentials())) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithTransportCredentials(insecure.NewCredentials())) } else { // Default to using the host's root CA. creds := credentials.NewTLS(nil) cfg.Traces.GRPCCredentials = creds - cfg.DialOptions = append(cfg.DialOptions, grpc.WithTransportCredentials(creds)) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithTransportCredentials(creds)) } if cfg.Traces.Compression == GzipCompression { - cfg.DialOptions = append(cfg.DialOptions, grpc.WithDefaultCallOptions(grpc.UseCompressor(gzip.Name))) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithDefaultCallOptions(grpc.UseCompressor(gzip.Name))) } if cfg.ReconnectionPeriod != 0 { p := grpc.ConnectParams{ Backoff: backoff.DefaultConfig, MinConnectTimeout: cfg.ReconnectionPeriod, } - cfg.DialOptions = append(cfg.DialOptions, grpc.WithConnectParams(p)) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithConnectParams(p)) } + cfg.DialOptions = append(dialOptsPrefix, cfg.DialOptions...) return cfg } @@ -243,6 +253,7 @@ func (h *httpOption) ApplyHTTPOption(cfg Config) Config { func (httpOption) private() {} +// NewHTTPOption creates an option that is only applied to the HTTP driver. func NewHTTPOption(fn func(cfg Config) Config) HTTPOption { return &httpOption{fn: fn} } @@ -258,6 +269,7 @@ func (h *grpcOption) ApplyGRPCOption(cfg Config) Config { func (grpcOption) private() {} +// NewGRPCOption creates an option that is only applied to the gRPC driver. func NewGRPCOption(fn func(cfg Config) Config) GRPCOption { return &grpcOption{fn: fn} } @@ -297,6 +309,7 @@ func WithEndpointURL(v string) GenericOption { }) } +// WithCompression configures the compression used for exports. func WithCompression(compression Compression) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Compression = compression @@ -304,6 +317,7 @@ func WithCompression(compression Compression) GenericOption { }) } +// WithURLPath configures the URL path the exporter sends requests to. func WithURLPath(urlPath string) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.URLPath = urlPath @@ -311,6 +325,7 @@ func WithURLPath(urlPath string) GenericOption { }) } +// WithRetry configures the retry policy used on failed exports. func WithRetry(rc retry.Config) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.RetryConfig = rc @@ -318,6 +333,8 @@ func WithRetry(rc retry.Config) GenericOption { }) } +// WithTLSClientConfig configures the TLS configuration used by the +// exporter's client. func WithTLSClientConfig(tlsCfg *tls.Config) GenericOption { return newSplitOption(func(cfg Config) Config { cfg.Traces.TLSCfg = tlsCfg.Clone() @@ -328,6 +345,8 @@ func WithTLSClientConfig(tlsCfg *tls.Config) GenericOption { }) } +// WithInsecure disables client transport security for the exporter's +// connection. func WithInsecure() GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Insecure = true @@ -335,6 +354,8 @@ func WithInsecure() GenericOption { }) } +// WithSecure enables client transport security for the exporter's +// connection. func WithSecure() GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Insecure = false @@ -342,6 +363,7 @@ func WithSecure() GenericOption { }) } +// WithHeaders configures headers sent with every export request. func WithHeaders(headers map[string]string) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Headers = headers @@ -349,6 +371,8 @@ func WithHeaders(headers map[string]string) GenericOption { }) } +// WithTimeout configures the max waiting time for the backend to process +// each export batch. func WithTimeout(duration time.Duration) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Timeout = duration @@ -356,6 +380,8 @@ func WithTimeout(duration time.Duration) GenericOption { }) } +// WithMaxRequestSize configures the maximum size, in bytes, of a serialized +// export request, before compression. func WithMaxRequestSize(size int) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.MaxRequestSize = size @@ -363,6 +389,8 @@ func WithMaxRequestSize(size int) GenericOption { }) } +// WithProxy configures the proxy function used by the exporter's HTTP +// client. func WithProxy(pf HTTPTransportProxyFunc) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Proxy = pf @@ -370,9 +398,33 @@ func WithProxy(pf HTTPTransportProxyFunc) GenericOption { }) } +// WithHTTPClient configures the HTTP client used to make requests. func WithHTTPClient(c *http.Client) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.HTTPClient = c return cfg }) } + +// WithProtocol configures the protocol used to encode and send telemetry. +func WithProtocol(protocol Protocol) GenericOption { + return newSplitOption( + // For OTLP/HTTP endpoints, this is the encoding format of the payloads sent to the collector. + func(cfg Config) Config { + if protocol == ProtocolGRPC { + global.Warn("grpc is not a valid protocol for OTLP/HTTP, defaulting to http/protobuf") + protocol = ProtocolHTTPProtobuf + } + cfg.Traces.Protocol = protocol + return cfg + }, + // For OTLP/gRPC endpoints, it's always "grpc". + func(cfg Config) Config { + if protocol != ProtocolGRPC { + global.Debug("protocol option is ignored for OTLP/gRPC and is set to grpc") + } + cfg.Traces.Protocol = ProtocolGRPC + return cfg + }, + ) +} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/optiontypes.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/optiontypes.go index 213c3605f2..4f2da74275 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/optiontypes.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/optiontypes.go @@ -38,3 +38,15 @@ const ( // MarshalJSON tells the driver to send using json format. MarshalJSON ) + +// Protocol describes the transport protocol used to send data to the collector. +type Protocol int + +const ( + // ProtocolGRPC describes the "grpc" protocol. + ProtocolGRPC Protocol = iota + // ProtocolHTTPProtobuf describes the "http/protobuf" protocol. + ProtocolHTTPProtobuf + // ProtocolHTTPJSON describes the "http/json" protocol. + ProtocolHTTPJSON +) diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go index 1883d0600a..468c7c8eb9 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go @@ -17,7 +17,7 @@ import ( "github.com/cenkalti/backoff/v5" ) -// DefaultConfig are the recommended defaults to use. +// DefaultConfig is the recommended default configuration. var DefaultConfig = Config{ Enabled: true, InitialInterval: 5 * time.Second, @@ -25,42 +25,40 @@ var DefaultConfig = Config{ MaxElapsedTime: time.Minute, } -// Config defines configuration for retrying batches in case of export failure -// using an exponential backoff. +// Config defines configuration for retrying batches after an export failure +// using exponential backoff. type Config struct { - // Enabled indicates whether to not retry sending batches in case of - // export failure. + // Enabled indicates whether to retry sending batches after an export + // failure. Enabled bool - // InitialInterval the time to wait after the first failure before + // InitialInterval is the time to wait after the first failure before // retrying. InitialInterval time.Duration - // MaxInterval is the upper bound on backoff interval. Once this value is - // reached the delay between consecutive retries will always be - // `MaxInterval`. + // MaxInterval is the upper bound on the backoff interval before + // randomization. Once this value is reached, the base interval remains at + // MaxInterval. MaxInterval time.Duration // MaxElapsedTime is the maximum amount of time (including retries) spent - // trying to send a request/batch. Once this value is reached, the data - // is discarded. + // trying to send a request/batch. Once this value is reached, retrying stops. MaxElapsedTime time.Duration } // RequestFunc wraps a request with retry logic. type RequestFunc func(context.Context, func(context.Context) error) error -// EvaluateFunc returns if an error is retry-able and if an explicit throttle -// duration should be honored that was included in the error. +// EvaluateFunc reports whether an error is retryable and returns any explicit +// throttle duration to honor. // -// The function must return true if the error argument is retry-able, -// otherwise it must return false for the first return parameter. +// The function must return true as its first return value if the error +// argument is retryable; otherwise, it must return false. // -// The function must return a non-zero time.Duration if the error contains -// explicit throttle duration that should be honored, otherwise it must return -// a zero valued time.Duration. +// The function must return a nonzero time.Duration if the error contains an +// explicit throttle duration that should be honored; otherwise, it must return +// the zero value for time.Duration. type EvaluateFunc func(error) (bool, time.Duration) -// RequestFunc returns a RequestFunc using the evaluate function to determine -// if requests can be retried and based on the exponential backoff -// configuration of c. +// RequestFunc returns a RequestFunc that uses evaluate to determine whether +// requests can be retried and uses c to configure exponential backoff. func (c Config) RequestFunc(evaluate EvaluateFunc) RequestFunc { if !c.Enabled { return func(ctx context.Context, fn func(context.Context) error) error { @@ -96,7 +94,7 @@ func (c Config) RequestFunc(evaluate EvaluateFunc) RequestFunc { // Check if context is canceled before attempting to wait and retry. if ctx.Err() != nil { - return fmt.Errorf("%w: %w", ctx.Err(), err) + return fmt.Errorf("%w: %w", context.Cause(ctx), err) } if maxElapsedTime != 0 && time.Since(startTime) > maxElapsedTime { @@ -119,12 +117,12 @@ func (c Config) RequestFunc(evaluate EvaluateFunc) RequestFunc { } } -// Allow override for testing. +// waitFunc can be overridden for testing. var waitFunc = wait -// wait takes the caller's context, and the amount of time to wait. It will -// return nil if the timer fires before or at the same time as the context's -// deadline. This indicates that the call can be retried. +// wait blocks until delay elapses or ctx is done. If both happen +// simultaneously, wait favors the elapsed delay and returns nil to indicate +// that the call can be retried. func wait(ctx context.Context, delay time.Duration) error { timer := time.NewTimer(delay) defer timer.Stop() diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/version.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/version.go index 942d37af7c..badf29557a 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/version.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/version.go @@ -5,4 +5,4 @@ package internal // Version is the current release version of the OpenTelemetry OTLP gRPC trace // exporter in use. -const Version = "1.45.0" +const Version = "1.47.0" diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/x.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/x.go index 69ce31eef3..71011358c2 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/x.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/x.go @@ -34,9 +34,9 @@ func newFeature[T any](suffix []string, parse func(string) (T, bool)) Feature[T] // feature. func (f Feature[T]) Keys() []string { return f.keys } -// Lookup returns the user configured value for the feature and true if the +// Lookup returns the user-configured value for the feature and true if the // user has enabled the feature. Otherwise, if the feature is not enabled, a -// zero-value and false are returned. +// zero value and false are returned. func (f Feature[T]) Lookup() (v T, ok bool) { // https://github.com/open-telemetry/opentelemetry-specification/blob/62effed618589a0bec416a87e559c0a9d96289bb/specification/configuration/sdk-environment-variables.md#parsing-empty-value // diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go index ea20363c05..516113b786 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go @@ -74,9 +74,10 @@ func WithEndpoint(endpoint string) Option { return wrappedOption{otlpconfig.WithEndpoint(endpoint)} } -// WithEndpointURL sets the target endpoint URL (scheme, host, port, path) -// the Exporter will connect to. The provided endpoint URL should resemble -// "https://example.com:4318/v1/traces". +// WithEndpointURL sets the target endpoint URL (scheme, host, port) the +// Exporter will connect to. The provided endpoint URL should resemble +// "https://example.com:4317". If the URL contains a path, it is ignored by +// the gRPC client. // // If the OTEL_EXPORTER_OTLP_ENDPOINT or OTEL_EXPORTER_OTLP_TRACES_ENDPOINT // environment variable is set, and this option is not passed, that variable @@ -90,7 +91,7 @@ func WithEndpoint(endpoint string) Option { // If an invalid URL is provided, the default value will be kept. // // By default, if an environment variable is not set, and this option is not -// passed, "https://localhost:4317/v1/traces" will be used. +// passed, "https://localhost:4317" will be used. // // This option has no effect if WithGRPCConn is used. func WithEndpointURL(u string) Option { diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go index da70f3f540..78e4f8e614 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go @@ -5,5 +5,5 @@ package otlptrace // Version is the current release version of the OpenTelemetry OTLP trace exporter in use. func Version() string { - return "1.45.0" + return "1.47.0" } diff --git a/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go b/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go index cbeb14fcd8..d682f8c811 100644 --- a/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go +++ b/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go @@ -16,12 +16,35 @@ package baggage // but OpenTelemetry does not, therefore, this is represented as a map. type List map[string]Item -// Item is the value and metadata properties part of a list-member. +// Item is the value and metadata or properties part of a list-member. +// Metadata and properties are mutually exclusive representations. type Item struct { - Value string - Properties []Property + value string + metadata string + properties []Property } +// NewItemWithMetadata returns an Item with opaque W3C metadata. +func NewItemWithMetadata(value, metadata string) Item { + return Item{value: value, metadata: metadata} +} + +// NewItemWithProperties returns an Item with materialized properties. +func NewItemWithProperties(value string, properties []Property) Item { + return Item{value: value, properties: properties} +} + +// Value returns the value of i. +func (i Item) Value() string { return i.value } + +// Metadata returns the opaque W3C metadata of i. It is empty for an Item +// created with properties. +func (i Item) Metadata() string { return i.metadata } + +// Properties returns the materialized properties of i. It is nil for an Item +// created with metadata. +func (i Item) Properties() []Property { return i.properties } + // Property is a metadata entry for a list-member. type Property struct { Key, Value string diff --git a/vendor/go.opentelemetry.io/otel/internal/errorhandler/errorhandler.go b/vendor/go.opentelemetry.io/otel/internal/errorhandler/errorhandler.go index de294461c7..1234ead63c 100644 --- a/vendor/go.opentelemetry.io/otel/internal/errorhandler/errorhandler.go +++ b/vendor/go.opentelemetry.io/otel/internal/errorhandler/errorhandler.go @@ -21,6 +21,9 @@ type ErrorHandler interface { Handle(error) } +// ErrDelegator is an ErrorHandler that forwards errors to a delegate +// ErrorHandler set with setDelegate. Before a delegate is set, it logs +// errors to STDERR. type ErrDelegator struct { delegate atomic.Pointer[ErrorHandler] } @@ -28,6 +31,8 @@ type ErrDelegator struct { // Compile-time check that delegator implements ErrorHandler. var _ ErrorHandler = (*ErrDelegator)(nil) +// Handle handles err by forwarding it to the configured delegate, or +// logging it to STDERR if no delegate is set. func (d *ErrDelegator) Handle(err error) { if eh := d.delegate.Load(); eh != nil { (*eh).Handle(err) diff --git a/vendor/go.opentelemetry.io/otel/log/internal/global/log.go b/vendor/go.opentelemetry.io/otel/internal/global/logger.go similarity index 70% rename from vendor/go.opentelemetry.io/otel/log/internal/global/log.go rename to vendor/go.opentelemetry.io/otel/internal/global/logger.go index 14eadf2e3a..e4328daa91 100644 --- a/vendor/go.opentelemetry.io/otel/log/internal/global/log.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/logger.go @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -// Package global is the internal implementation of the OpenTelemetry global -// Logs API. package global import ( @@ -10,30 +8,19 @@ import ( "sync" "sync/atomic" - "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/log" "go.opentelemetry.io/otel/log/embedded" ) -// instLib defines the instrumentation library a logger is created for. -// -// Do not use sdk/instrumentation (API cannot depend on the SDK). -type instLib struct { - name string - version string - schemaURL string - attrs attribute.Set -} - type loggerProvider struct { embedded.LoggerProvider mu sync.Mutex - loggers map[instLib]*logger + loggers map[il]*logger delegate log.LoggerProvider } -// Compile-time guarantee loggerProvider implements LoggerProvider. +// This is a compile-time guarantee that loggerProvider implements LoggerProvider. var _ log.LoggerProvider = (*loggerProvider)(nil) func (p *loggerProvider) Logger(name string, options ...log.LoggerOption) log.Logger { @@ -45,16 +32,16 @@ func (p *loggerProvider) Logger(name string, options ...log.LoggerOption) log.Lo } cfg := log.NewLoggerConfig(options...) - key := instLib{ - name: name, - version: cfg.InstrumentationVersion(), - schemaURL: cfg.SchemaURL(), - attrs: cfg.InstrumentationAttributes(), + key := il{ + name: name, + version: cfg.InstrumentationVersion(), + schema: cfg.SchemaURL(), + attrs: cfg.InstrumentationAttributes(), } if p.loggers == nil { l := &logger{name: name, options: options} - p.loggers = map[instLib]*logger{key: l} + p.loggers = map[il]*logger{key: l} return l } @@ -87,7 +74,7 @@ type logger struct { delegate atomic.Value // log.Logger } -// Compile-time guarantee logger implements Logger. +// This is a compile-time guarantee that logger implements Logger. var _ log.Logger = (*logger)(nil) func (l *logger) Emit(ctx context.Context, r log.Record) { diff --git a/vendor/go.opentelemetry.io/otel/internal/global/state.go b/vendor/go.opentelemetry.io/otel/internal/global/state.go index f8fcb82bcb..bd388d8341 100644 --- a/vendor/go.opentelemetry.io/otel/internal/global/state.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/state.go @@ -9,6 +9,7 @@ import ( "sync/atomic" "go.opentelemetry.io/otel/internal/errorhandler" + "go.opentelemetry.io/otel/log" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" @@ -26,16 +27,22 @@ type ( meterProviderHolder struct { mp metric.MeterProvider } + + loggerProviderHolder struct { + provider log.LoggerProvider + } ) var ( - globalTracer = defaultTracerValue() - globalPropagators = defaultPropagatorsValue() - globalMeterProvider = defaultMeterProvider() + globalTracer = defaultTracerValue() + globalPropagators = defaultPropagatorsValue() + globalMeterProvider = defaultMeterProvider() + globalLoggerProvider = defaultLoggerProvider() delegateTraceOnce sync.Once delegateTextMapPropagatorOnce sync.Once delegateMeterOnce sync.Once + delegateLoggerOnce sync.Once ) // GetErrorHandler returns the global ErrorHandler instance. @@ -150,6 +157,32 @@ func SetMeterProvider(mp metric.MeterProvider) { globalMeterProvider.Store(meterProviderHolder{mp: mp}) } +// LoggerProvider is the internal implementation for global.LoggerProvider. +func LoggerProvider() log.LoggerProvider { + return globalLoggerProvider.Load().(loggerProviderHolder).provider +} + +// SetLoggerProvider is the internal implementation for global.SetLoggerProvider. +func SetLoggerProvider(provider log.LoggerProvider) { + current := LoggerProvider() + if _, cOk := current.(*loggerProvider); cOk { + if _, lpOk := provider.(*loggerProvider); lpOk && current == provider { + Error( + errors.New("no delegate configured in logger provider"), + "Setting logger provider to its current value. No delegate will be configured", + ) + return + } + } + + delegateLoggerOnce.Do(func() { + if def, ok := current.(*loggerProvider); ok { + def.setDelegate(provider) + } + }) + globalLoggerProvider.Store(loggerProviderHolder{provider: provider}) +} + func defaultTracerValue() *atomic.Value { v := &atomic.Value{} v.Store(tracerProviderHolder{tp: &tracerProvider{}}) @@ -167,3 +200,9 @@ func defaultMeterProvider() *atomic.Value { v.Store(meterProviderHolder{mp: &meterProvider{}}) return v } + +func defaultLoggerProvider() *atomic.Value { + v := &atomic.Value{} + v.Store(loggerProviderHolder{provider: &loggerProvider{}}) + return v +} diff --git a/vendor/go.opentelemetry.io/otel/log.go b/vendor/go.opentelemetry.io/otel/log.go new file mode 100644 index 0000000000..1758913fa2 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log.go @@ -0,0 +1,41 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package otel + +import ( + "go.opentelemetry.io/otel/internal/global" + "go.opentelemetry.io/otel/log" +) + +// Logger returns a [log.Logger] configured with the provided name and options +// from the globally configured [log.LoggerProvider]. +// +// If this is called before a global LoggerProvider is configured, the returned +// Logger will be a No-Op implementation of a Logger. When a global +// LoggerProvider is registered for the first time, the returned Logger is +// updated in place to report to this new LoggerProvider. There is no need to +// call this function again for an updated instance. +// +// This is a convenience function. It is equivalent to: +// +// GetLoggerProvider().Logger(name, options...) +func Logger(name string, options ...log.LoggerOption) log.Logger { + return GetLoggerProvider().Logger(name, options...) +} + +// GetLoggerProvider returns the globally configured [log.LoggerProvider]. +// +// If a global LoggerProvider has not been configured with [SetLoggerProvider], +// the returned LoggerProvider will be a No-Op implementation. When +// a global LoggerProvider is registered for the first time, the returned +// LoggerProvider and all Loggers it has created are updated in place. There is +// no need to call this function again for an updated instance. +func GetLoggerProvider() log.LoggerProvider { + return global.LoggerProvider() +} + +// SetLoggerProvider configures provider as the global [log.LoggerProvider]. +func SetLoggerProvider(provider log.LoggerProvider) { + global.SetLoggerProvider(provider) +} diff --git a/vendor/go.opentelemetry.io/otel/log/doc.go b/vendor/go.opentelemetry.io/otel/log/doc.go index c6f9562699..211de35f58 100644 --- a/vendor/go.opentelemetry.io/otel/log/doc.go +++ b/vendor/go.opentelemetry.io/otel/log/doc.go @@ -4,8 +4,8 @@ /* Package log provides the OpenTelemetry Logs API. -This API is separate from its implementation so the instrumentation built from -it is reusable. See [go.opentelemetry.io/otel/sdk/log] for the official +This API is separate from its implementation, so the instrumentation built +from it is reusable. See [go.opentelemetry.io/otel/sdk/log] for the official OpenTelemetry implementation of this API. The log package provides the OpenTelemetry Logs API, which serves as a standard @@ -15,16 +15,16 @@ that can be easily integrated with observability tools. It ensures that log data in a way that is consistent with OpenTelemetry's data model. This package can be used to create bridges between existing logging libraries and OpenTelemetry. -Log bridges allow integrating the existing logging setups with OpenTelemetry. +Log bridges allow existing logging setups to be integrated with OpenTelemetry. Log bridges can be found in the [registry]. # API Implementations -This package does not conform to the standard Go versioning policy, all of its +This package does not conform to the standard Go versioning policy; all of its interfaces may have methods added to them without a package major version bump. This non-standard API evolution could surprise an uninformed implementation author. They could unknowingly build their implementation in a way that would -result in a runtime panic for their users that update to the new API. +result in a runtime panic for their users who update to the new API. The API is designed to help inform an instrumentation author about this non-standard API evolution. It requires them to choose a default behavior for @@ -38,7 +38,7 @@ make: All interfaces in this API embed a corresponding interface from [go.opentelemetry.io/otel/log/embedded]. If an author wants the default behavior of their implementations to be a compilation failure, signaling to -their users they need to update to the latest version of that implementation, +their users that they need to update to the latest version of that implementation, they need to embed the corresponding interface from [go.opentelemetry.io/otel/log/embedded] in their implementation. For example, @@ -49,7 +49,7 @@ they need to embed the corresponding interface from // ... } -If an author wants the default behavior of their implementations to a panic, +If an author wants the default behavior of their implementations to panic, they need to embed the API interface directly. import "go.opentelemetry.io/otel/log" @@ -60,7 +60,7 @@ they need to embed the API interface directly. } This is not a recommended behavior as it could lead to publishing packages that -contain runtime panics when users update other package that use newer versions +contain runtime panics when users update other packages that use newer versions of [go.opentelemetry.io/otel/log]. Finally, an author can embed another implementation in theirs. The embedded diff --git a/vendor/go.opentelemetry.io/otel/log/embedded/embedded.go b/vendor/go.opentelemetry.io/otel/log/embedded/embedded.go index 70bab2312d..3b97fcddcf 100644 --- a/vendor/go.opentelemetry.io/otel/log/embedded/embedded.go +++ b/vendor/go.opentelemetry.io/otel/log/embedded/embedded.go @@ -16,21 +16,21 @@ package embedded // LoggerProvider is embedded in the [Logs API LoggerProvider]. // // Embed this interface in your implementation of the [Logs API -// LoggerProvider] if you want users to experience a compilation error, -// signaling they need to update to your latest implementation, when the [Logs -// Bridge API LoggerProvider] interface is extended (which is something that -// can happen without a major version bump of the API package). +// LoggerProvider] if you want users to experience a compilation error when the +// [Logs Bridge API LoggerProvider] interface is extended (which is something +// that can happen without a major version bump of the API package). This error +// signals that they need to update to your latest implementation. // // [Logs API LoggerProvider]: https://pkg.go.dev/go.opentelemetry.io/otel/log#LoggerProvider type LoggerProvider interface{ loggerProvider() } -// Logger is embedded in [Logs API Logger]. +// Logger is embedded in the [Logs API Logger]. // // Embed this interface in your implementation of the [Logs API Logger] -// if you want users to experience a compilation error, signaling they need to -// update to your latest implementation, when the [Logs API Logger] -// interface is extended (which is something that can happen without a major -// version bump of the API package). +// if you want users to experience a compilation error when the [Logs API +// Logger] interface is extended (which is something that can happen without a +// major version bump of the API package). This error signals that they need to +// update to your latest implementation. // // [Logs API Logger]: https://pkg.go.dev/go.opentelemetry.io/otel/log#Logger type Logger interface{ logger() } diff --git a/vendor/go.opentelemetry.io/otel/log/global/README.md b/vendor/go.opentelemetry.io/otel/log/global/README.md index 11e5afefc0..729455472e 100644 --- a/vendor/go.opentelemetry.io/otel/log/global/README.md +++ b/vendor/go.opentelemetry.io/otel/log/global/README.md @@ -1,3 +1,5 @@ # Log Global +> Deprecated: Use the equivalent APIs in [go.opentelemetry.io/otel](https://pkg.go.dev/go.opentelemetry.io/otel). + [![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel/log/global)](https://pkg.go.dev/go.opentelemetry.io/otel/log/global) diff --git a/vendor/go.opentelemetry.io/otel/log/global/log.go b/vendor/go.opentelemetry.io/otel/log/global/log.go index ac9957c3f5..4f7ce80536 100644 --- a/vendor/go.opentelemetry.io/otel/log/global/log.go +++ b/vendor/go.opentelemetry.io/otel/log/global/log.go @@ -5,15 +5,13 @@ Package global provides access to a global implementation of the OpenTelemetry Logs API. -This package is experimental. It will be deprecated and removed when the [log] -package becomes stable. Its functionality will be migrated to -go.opentelemetry.io/otel. +Deprecated: Use the equivalent APIs in [go.opentelemetry.io/otel]. */ package global import ( + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/log" - "go.opentelemetry.io/otel/log/internal/global" ) // Logger returns a [log.Logger] configured with the provided name and options @@ -22,28 +20,34 @@ import ( // If this is called before a global LoggerProvider is configured, the returned // Logger will be a No-Op implementation of a Logger. When a global // LoggerProvider is registered for the first time, the returned Logger is -// updated in-place to report to this new LoggerProvider. There is no need to +// updated in place to report to this new LoggerProvider. There is no need to // call this function again for an updated instance. // // This is a convenience function. It is equivalent to: // // GetLoggerProvider().Logger(name, options...) +// +// Deprecated: Use [otel.Logger] instead. func Logger(name string, options ...log.LoggerOption) log.Logger { - return GetLoggerProvider().Logger(name, options...) + return otel.Logger(name, options...) } // GetLoggerProvider returns the globally configured [log.LoggerProvider]. // // If a global LoggerProvider has not been configured with [SetLoggerProvider], -// the returned Logger will be a No-Op implementation of a LoggerProvider. When +// the returned LoggerProvider will be a No-Op implementation. When // a global LoggerProvider is registered for the first time, the returned -// LoggerProvider and all of its created Loggers are updated in-place. There is +// LoggerProvider and all Loggers it has created are updated in place. There is // no need to call this function again for an updated instance. +// +// Deprecated: Use [otel.GetLoggerProvider] instead. func GetLoggerProvider() log.LoggerProvider { - return global.GetLoggerProvider() + return otel.GetLoggerProvider() } // SetLoggerProvider configures provider as the global [log.LoggerProvider]. +// +// Deprecated: Use [otel.SetLoggerProvider] instead. func SetLoggerProvider(provider log.LoggerProvider) { - global.SetLoggerProvider(provider) + otel.SetLoggerProvider(provider) } diff --git a/vendor/go.opentelemetry.io/otel/log/internal/global/state.go b/vendor/go.opentelemetry.io/otel/log/internal/global/state.go deleted file mode 100644 index e872cc2a87..0000000000 --- a/vendor/go.opentelemetry.io/otel/log/internal/global/state.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package global - -import ( - "errors" - "sync" - "sync/atomic" - - "go.opentelemetry.io/otel/internal/global" - "go.opentelemetry.io/otel/log" -) - -var ( - globalLoggerProvider = defaultLoggerProvider() - - delegateLoggerOnce sync.Once -) - -func defaultLoggerProvider() *atomic.Value { - v := &atomic.Value{} - v.Store(loggerProviderHolder{provider: &loggerProvider{}}) - return v -} - -type loggerProviderHolder struct { - provider log.LoggerProvider -} - -// GetLoggerProvider returns the global LoggerProvider. -func GetLoggerProvider() log.LoggerProvider { - return globalLoggerProvider.Load().(loggerProviderHolder).provider -} - -// SetLoggerProvider sets the global LoggerProvider. -func SetLoggerProvider(provider log.LoggerProvider) { - current := GetLoggerProvider() - if _, cOk := current.(*loggerProvider); cOk { - if _, mpOk := provider.(*loggerProvider); mpOk && current == provider { - err := errors.New("invalid delegation: LoggerProvider self-delegation") - global.Error(err, "No delegate will be configured") - return - } - } - - delegateLoggerOnce.Do(func() { - if def, ok := current.(*loggerProvider); ok { - def.setDelegate(provider) - } - }) - globalLoggerProvider.Store(loggerProviderHolder{provider: provider}) -} diff --git a/vendor/go.opentelemetry.io/otel/log/logger.go b/vendor/go.opentelemetry.io/otel/log/logger.go index 178e6be268..c0e4ca7ae2 100644 --- a/vendor/go.opentelemetry.io/otel/log/logger.go +++ b/vendor/go.opentelemetry.io/otel/log/logger.go @@ -15,7 +15,7 @@ import ( // // Warning: Methods may be added to this interface in minor releases. See // package documentation on API implementation for information on how to set -// default behavior for unimplemented methods. +// the default behavior for unimplemented methods. type Logger interface { // Users of the interface can ignore this. This embedded type is only used // by implementations of this interface. See the "API Implementations" @@ -25,7 +25,7 @@ type Logger interface { // Emit emits a log record. // // The record may be held by the implementation. Callers should not mutate - // the record after passed. + // the record after it is passed. // // Implementations of this method need to be safe for a user to call // concurrently. @@ -34,22 +34,28 @@ type Logger interface { // Enabled reports whether the Logger emits for the given context and // param. // - // This is useful for users that want to know if a [Record] - // will be processed or dropped before they perform complex operations to - // construct the [Record]. Callers should invoke Enabled before each call - // to [Logger.Emit] because the enabled state may change over time. + // Calling Enabled is optional. It is not required before calling + // [Logger.Emit]. // - // The passed param is likely to be a partial record information being - // provided (e.g a param with only the Severity set). + // Enabled is useful when constructing a [Record] is expensive. A caller can + // call Enabled first and skip record construction when it returns false. + // When constructing the Record is inexpensive, a caller can emit it + // directly. + // + // The returned value is not static and may change over time. A cached value + // can become stale. + // + // The passed param is likely to contain only partial information about a + // record (e.g., a param with only the Severity set). // If a Logger needs more information than is provided, it // is said to be in an indeterminate state (see below). // - // The returned value will be true when the Logger will emit for the - // provided context and param, and will be false if the Logger will not - // emit. The returned value may be true or false in an indeterminate state. + // The returned value is true if the Logger emits for the provided context + // and param, and false if the Logger does not emit. The returned value may be + // true or false in an indeterminate state. // An implementation should default to returning true for an indeterminate - // state, but may return false if valid reasons in particular circumstances - // exist (e.g. performance, correctness). + // state, but may return false if there are valid reasons to do so in + // particular circumstances (e.g., performance or correctness). // // The param should not be held by the implementation. A copy should be // made if the param needs to be held after the call returns. @@ -61,7 +67,7 @@ type Logger interface { // LoggerOption applies configuration options to a [Logger]. type LoggerOption interface { - // applyLogger is used to set a LoggerOption value of a LoggerConfig. + // applyLogger applies a LoggerOption to a LoggerConfig. applyLogger(LoggerConfig) LoggerConfig } @@ -123,8 +129,8 @@ func WithInstrumentationVersion(version string) LoggerOption { }) } -// mergeSets returns the union of keys between a and b. Any duplicate keys will -// use the value associated with b. +// mergeSets returns the union of the keys in a and b. For duplicate keys, the +// value associated with b is used. func mergeSets(a, b attribute.Set) attribute.Set { // NewMergeIterator uses the first value for any duplicates. iter := attribute.NewMergeIterator(&b, &a) @@ -144,18 +150,20 @@ func mergeSets(a, b attribute.Set) attribute.Set { // // If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet] // options are passed, the attributes will be merged together in the order -// they are passed. Attributes with duplicate keys will use the last value passed. +// they are passed. For attributes with duplicate keys, the last value passed +// will be used. func WithInstrumentationAttributes(attr ...attribute.KeyValue) LoggerOption { set := attribute.NewSet(slices.Clone(attr)...) return WithInstrumentationAttributeSet(set) } -// WithInstrumentationAttributeSet returns a [LoggerOption] that adds the -// instrumentation attributes of a [Logger]. +// WithInstrumentationAttributeSet returns a [LoggerOption] that adds +// instrumentation attributes to a [Logger]. // // If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet] // options are passed, the attributes will be merged together in the order -// they are passed. Attributes with duplicate keys will use the last value passed. +// they are passed. For attributes with duplicate keys, the last value passed +// will be used. func WithInstrumentationAttributeSet(set attribute.Set) LoggerOption { if set.Len() == 0 { return loggerOptionFunc(func(config LoggerConfig) LoggerConfig { @@ -182,7 +190,7 @@ func WithSchemaURL(schemaURL string) LoggerOption { }) } -// EnabledParameters represents payload for [Logger]'s Enabled method. +// EnabledParameters represents the payload for [Logger.Enabled]. type EnabledParameters struct { Severity Severity EventName string diff --git a/vendor/go.opentelemetry.io/otel/log/noop/noop.go b/vendor/go.opentelemetry.io/otel/log/noop/noop.go index 082eb887b0..0bb1de4abf 100644 --- a/vendor/go.opentelemetry.io/otel/log/noop/noop.go +++ b/vendor/go.opentelemetry.io/otel/log/noop/noop.go @@ -2,14 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 // Package noop provides an implementation of the [OpenTelemetry Logs Bridge -// API] that produces no telemetry and minimizes used computation resources. +// API] that produces no telemetry and minimizes computational resource usage. // // Using this package to implement the [OpenTelemetry Logs API] will // effectively disable OpenTelemetry. // // This implementation can be embedded in other implementations of the -// [OpenTelemetry Logs API]. Doing so will mean the implementation -// defaults to no operation for methods it does not implement. +// [OpenTelemetry Logs API]. Doing so means that the implementation defaults to +// performing no operation for methods it does not implement. // // [OpenTelemetry Logs API]: https://pkg.go.dev/go.opentelemetry.io/otel/log package noop @@ -22,7 +22,8 @@ import ( ) var ( - // Compile-time check this implements the OpenTelemetry API. + // These compile-time checks ensure that the implementations satisfy the + // OpenTelemetry API. _ log.LoggerProvider = LoggerProvider{} _ log.Logger = Logger{} ) diff --git a/vendor/go.opentelemetry.io/otel/log/provider.go b/vendor/go.opentelemetry.io/otel/log/provider.go index 62b7d73fc2..10969b4155 100644 --- a/vendor/go.opentelemetry.io/otel/log/provider.go +++ b/vendor/go.opentelemetry.io/otel/log/provider.go @@ -9,7 +9,7 @@ import "go.opentelemetry.io/otel/log/embedded" // // Warning: Methods may be added to this interface in minor releases. See // package documentation on API implementation for information on how to set -// default behavior for unimplemented methods. +// the default behavior for unimplemented methods. type LoggerProvider interface { // Users of the interface can ignore this. This embedded type is only used // by implementations of this interface. See the "API Implementations" @@ -19,7 +19,7 @@ type LoggerProvider interface { // Logger returns a new [Logger] with the provided name and configuration. // // The name needs to uniquely identify the source of logged code. It is - // recommended that name is the Go package name of the library using a log + // recommended that name be the Go package name of the library using a log // bridge (note: this is not the name of the bridge package). Most // commonly, this means a bridge will need to accept this value from its // users. @@ -27,7 +27,7 @@ type LoggerProvider interface { // An empty name is invalid. Implementations should retain the empty value as the // instrumentation scope name, return a working Logger, and report the invalid value. // - // The version of the packages using a bridge can be critical information + // The version of the package using a bridge can be critical information // to include when logging. The bridge should accept this version // information and use the [WithInstrumentationVersion] option to configure // the Logger appropriately. diff --git a/vendor/go.opentelemetry.io/otel/log/record.go b/vendor/go.opentelemetry.io/otel/log/record.go index 9e4e4d80bf..351657e953 100644 --- a/vendor/go.opentelemetry.io/otel/log/record.go +++ b/vendor/go.opentelemetry.io/otel/log/record.go @@ -11,13 +11,13 @@ import ( ) // attributesInlineCount is the number of attributes that are efficiently -// stored in an array within a Record. This value is borrowed from slog which -// performed a quantitative survey of log library use and found this value to -// cover 95% of all use-cases (https://go.dev/blog/slog#performance). +// stored in an array within a Record. This value is borrowed from slog, which +// performed a quantitative survey of log library use and found that this value +// covers 95% of all use cases (https://go.dev/blog/slog#performance). const attributesInlineCount = 5 // Record represents a log record. -// A log record with non-empty event name is interpreted as an event record. +// A log record with a non-empty event name is interpreted as an event record. type Record struct { // Ensure forward compatibility by explicitly making this not comparable. noCmp [0]func() //nolint: unused // This is indeed used. @@ -45,19 +45,20 @@ type Record struct { // The list of attributes except for those in front. // Invariants: // - len(back) > 0 if nFront == len(front) - // - Unused array elements are zero-ed. Used to detect mistakes. + // - Unused array elements are zeroed to detect mistakes. back []attribute.KeyValue } // EventName returns the event name. -// A log record with non-empty event name is interpreted as an event record. +// A log record with a non-empty event name is interpreted as an event record. func (r *Record) EventName() string { return r.eventName } // SetEventName sets the event name. -// A log record with non-empty event name is interpreted as an event record. -// Event names should uniquely identify the event's attribute and body structure. +// A log record with a non-empty event name is interpreted as an event record. +// Event names should uniquely identify the structure of the event's attributes +// and body. func (r *Record) SetEventName(s string) { r.eventName = s } @@ -92,14 +93,14 @@ func (r *Record) SetSeverity(level Severity) { r.severity = level } -// SeverityText returns severity (also known as log level) text. This is the -// original string representation of the severity as it is known at the source. +// SeverityText returns the text of the severity (also known as the log level) +// as originally known at the source. func (r *Record) SeverityText() string { return r.severityText } -// SetSeverityText sets severity (also known as log level) text. This is the -// original string representation of the severity as it is known at the source. +// SetSeverityText sets the text of the severity (also known as the log level) +// as originally known at the source. func (r *Record) SetSeverityText(text string) { r.severityText = text } @@ -124,8 +125,8 @@ func (r *Record) SetErr(err error) { r.err = err } -// WalkAttributes walks all attributes the log record holds by calling f for -// each on each [attribute.KeyValue] in the [Record]. Iteration stops if f returns false. +// WalkAttributes walks all attributes in the log record by calling f for each +// [attribute.KeyValue] in the [Record]. Iteration stops if f returns false. func (r *Record) WalkAttributes(f func(attribute.KeyValue) bool) { for i := 0; i < r.nFront; i++ { if !f(r.front[i]) { @@ -158,7 +159,8 @@ func (r *Record) AttributesLen() int { } // Clone returns a copy of the record with no shared state. -// The original record and the clone can both be modified without interfering with each other. +// The original record and the clone can both be modified without interfering +// with each other. func (r *Record) Clone() Record { res := *r res.back = slices.Clone(r.back) diff --git a/vendor/go.opentelemetry.io/otel/log/severity.go b/vendor/go.opentelemetry.io/otel/log/severity.go index 29aed675de..4f305be362 100644 --- a/vendor/go.opentelemetry.io/otel/log/severity.go +++ b/vendor/go.opentelemetry.io/otel/log/severity.go @@ -5,56 +5,61 @@ package log -// Severity represents a log record severity (also known as log level). Smaller -// numerical values correspond to less severe log records (such as debug -// events), larger numerical values correspond to more severe log records (such -// as errors and critical events). +// Severity represents a log record's severity (also known as its log level). +// Smaller numerical values correspond to less severe log records (such as +// debug events); larger numerical values correspond to more severe log records +// (such as errors and critical events). type Severity int -// Severity values defined by OpenTelemetry. +// The following Severity values are defined by OpenTelemetry. const ( // SeverityUndefined represents an unset Severity. SeverityUndefined Severity = 0 // UNDEFINED - // A fine-grained debugging log record. Typically disabled in default - // configurations. + // The following are severity values for fine-grained debugging log records. + // They are typically disabled in default configurations. SeverityTrace1 Severity = 1 // TRACE SeverityTrace2 Severity = 2 // TRACE2 SeverityTrace3 Severity = 3 // TRACE3 SeverityTrace4 Severity = 4 // TRACE4 - // A debugging log record. + // The following are severity values for debugging log records. SeverityDebug1 Severity = 5 // DEBUG SeverityDebug2 Severity = 6 // DEBUG2 SeverityDebug3 Severity = 7 // DEBUG3 SeverityDebug4 Severity = 8 // DEBUG4 - // An informational log record. Indicates that an event happened. + // The following are severity values for informational log records indicating + // that an event happened. SeverityInfo1 Severity = 9 // INFO SeverityInfo2 Severity = 10 // INFO2 SeverityInfo3 Severity = 11 // INFO3 SeverityInfo4 Severity = 12 // INFO4 - // A warning log record. Not an error but is likely more important than an - // informational event. + // The following are severity values for warning log records. These records + // are not errors, but they are likely more important than informational + // events. SeverityWarn1 Severity = 13 // WARN SeverityWarn2 Severity = 14 // WARN2 SeverityWarn3 Severity = 15 // WARN3 SeverityWarn4 Severity = 16 // WARN4 - // An error log record. Something went wrong. + // The following are severity values for error log records indicating that + // something went wrong. SeverityError1 Severity = 17 // ERROR SeverityError2 Severity = 18 // ERROR2 SeverityError3 Severity = 19 // ERROR3 SeverityError4 Severity = 20 // ERROR4 - // A fatal log record such as application or system crash. + // The following are severity values for fatal log records, such as those + // associated with an application or system crash. SeverityFatal1 Severity = 21 // FATAL SeverityFatal2 Severity = 22 // FATAL2 SeverityFatal3 Severity = 23 // FATAL3 SeverityFatal4 Severity = 24 // FATAL4 - // Convenience definitions for the base severity of each level. + // The following are convenience definitions for the base severity of each + // level. SeverityTrace = SeverityTrace1 SeverityDebug = SeverityDebug1 SeverityInfo = SeverityInfo1 diff --git a/vendor/go.opentelemetry.io/otel/metric/meter.go b/vendor/go.opentelemetry.io/otel/metric/meter.go index 70ff4c7318..971241572b 100644 --- a/vendor/go.opentelemetry.io/otel/metric/meter.go +++ b/vendor/go.opentelemetry.io/otel/metric/meter.go @@ -320,7 +320,7 @@ type Observer interface { ObserveInt64(obsrv Int64Observable, value int64, opts ...ObserveOption) } -// Registration is an token representing the unique registration of a callback +// Registration is a token representing the unique registration of a callback // for a set of instruments with a Meter. // // Warning: Methods may be added to this interface in minor releases. See diff --git a/vendor/go.opentelemetry.io/otel/propagation/internal/hextable/hextable.go b/vendor/go.opentelemetry.io/otel/propagation/internal/hextable/hextable.go new file mode 100644 index 0000000000..3d63244c27 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/propagation/internal/hextable/hextable.go @@ -0,0 +1,32 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package hextable provides a lookup table for decoding lowercase +// hexadecimal. +package hextable + +// Rev is a reverse hex lookup table for lowercase hex digits. Valid +// hexadecimal characters are indexed at their respective values. All other +// characters, including the upper-case A-F disallowed by the W3C trace +// context specification, are represented with '\xff'. +// +// The '\xff' character is used as invalid because no valid character has the +// upper 4 bits set. Meaning, an efficient validation can be performed over +// multiple character parsing by checking these bits remain zero. +const Rev = "" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" diff --git a/vendor/go.opentelemetry.io/otel/propagation/trace_context.go b/vendor/go.opentelemetry.io/otel/propagation/trace_context.go index ffaa903039..1eb36b88e8 100644 --- a/vendor/go.opentelemetry.io/otel/propagation/trace_context.go +++ b/vendor/go.opentelemetry.io/otel/propagation/trace_context.go @@ -9,6 +9,7 @@ import ( "fmt" "strings" + "go.opentelemetry.io/otel/propagation/internal/hextable" "go.opentelemetry.io/otel/trace" ) @@ -126,27 +127,23 @@ func (TraceContext) extract(carrier TextMapCarrier) trace.SpanContext { return sc } -// upperHex detect hex is upper case Unicode characters. -func upperHex(v string) bool { - for _, c := range v { - if c >= 'A' && c <= 'F' { - return true - } - } - return false -} - func extractPart(dst []byte, h *string, n int) bool { part, left, _ := strings.Cut(*h, delimiter) *h = left - // hex.Decode decodes unsupported upper-case characters, so exclude explicitly. - if len(part) != n || upperHex(part) { + if len(part) != n { return false } - if p, err := hex.Decode(dst, []byte(part)); err != nil || p != n/2 { - return false + // hextable.Rev maps every invalid character to 0xff, including the + // upper-case A-F the specification disallows. OR-ing every looked-up value + // together lets a single check detect any invalid character, because no + // valid value has the upper 4 bits set. + invalidMark := byte(0) + for i := 0; i < n; i += 2 { + hi, lo := hextable.Rev[part[i]], hextable.Rev[part[i+1]] + dst[i/2] = (hi << 4) | lo + invalidMark |= hi | lo } - return true + return invalidMark&0xf0 == 0 } // Fields returns the keys who's values are set with Inject. diff --git a/vendor/go.opentelemetry.io/otel/renovate.json b/vendor/go.opentelemetry.io/otel/renovate.json index fa5acf2d3b..5008ab2bf1 100644 --- a/vendor/go.opentelemetry.io/otel/renovate.json +++ b/vendor/go.opentelemetry.io/otel/renovate.json @@ -15,6 +15,13 @@ "matchDepTypes": ["indirect"], "enabled": true }, + { + "description": "Disable Go module major updates to v2+", + "matchManagers": ["gomod"], + "matchUpdateTypes": ["major"], + "matchNewValue": "/^v?([2-9]|[1-9][0-9]+)\\./", + "enabled": false + }, { "matchPackageNames": ["go.opentelemetry.io/build-tools/**"], "groupName": "build-tools" diff --git a/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/dedup.go b/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/dedup.go index fe9ddc96db..d72cfb3c92 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/dedup.go +++ b/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/dedup.go @@ -28,40 +28,142 @@ type rawValue struct { slice any } -// Value returns value with all map values deduplicated and whether it changed. +type valueChanges uint8 + +const ( + depthLimitChanged valueChanges = 1 << iota + deduplicationChanged +) + +// ValueDedup returns value with all map values deduplicated and whether +// it changed. // // Duplicate map keys are resolved using last-value-wins semantics. -func Value(value attribute.Value) (attribute.Value, bool) { +func ValueDedup(value attribute.Value) (attribute.Value, bool) { switch value.Type() { case attribute.SLICE: - return deduplicateSliceValue(value) + return sliceValueDedup(value) case attribute.MAP: - return deduplicateMapValue(value) + return mapValueDedup(value) default: return value, false } } -// KeyValue returns kv with all map values deduplicated and whether it changed. -func KeyValue(kv attribute.KeyValue) (attribute.KeyValue, bool) { - value, changed := Value(kv.Value) +// ValueDedupLimitDepth returns value with all map values +// deduplicated and all array and map values limited to depthLimit. The boolean +// results report depth limiting and deduplication changes, respectively. +// +// Duplicate map keys are resolved using last-value-wins semantics. Depth +// starts at one for value and increments when descending into an array element +// or map value. An array or map beyond a non-negative depthLimit is replaced by +// an empty value. A negative depthLimit disables depth limiting. +func ValueDedupLimitDepth( + value attribute.Value, + depthLimit int, +) (attribute.Value, bool, bool) { + if depthLimit < 0 { + value, deduplicated := ValueDedup(value) + return value, false, deduplicated + } + + // Keep the common scalar and primitive-array cases in this wrapper. Routing + // them through the recursive, multi-result transform adds measurable + // overhead to the dominant simple attribute path. + switch value.Type() { + case attribute.BOOLSLICE, + attribute.INT64SLICE, + attribute.FLOAT64SLICE, + attribute.STRINGSLICE, + attribute.BYTESLICE: + if depthLimit == 0 { + return attribute.Value{}, true, false + } + return value, false, false + case attribute.SLICE, attribute.MAP: + default: + return value, false, false + } + + value, changes := valueDedupLimitDepth(value, depthLimit) + return value, changes&depthLimitChanged != 0, changes&deduplicationChanged != 0 +} + +// ValueLimitDepth returns value with all array and map values limited to +// depthLimit. Map keys are not deduplicated. +// +// Depth starts at one for value and increments when descending into an array +// element or map value. An array or map beyond a non-negative depthLimit is +// replaced by an empty value. A negative depthLimit disables depth limiting. +func ValueLimitDepth(value attribute.Value, depthLimit int) (attribute.Value, bool) { + if depthLimit < 0 { + return value, false + } + + switch value.Type() { + case attribute.BOOLSLICE, + attribute.INT64SLICE, + attribute.FLOAT64SLICE, + attribute.STRINGSLICE, + attribute.BYTESLICE: + if depthLimit == 0 { + return attribute.Value{}, true + } + return value, false + case attribute.SLICE, attribute.MAP: + default: + return value, false + } + + return valueLimitDepth(value, depthLimit) +} + +// KeyValueDedup returns kv with all map values deduplicated and whether +// it changed. +func KeyValueDedup(kv attribute.KeyValue) (attribute.KeyValue, bool) { + value, changed := ValueDedup(kv.Value) if changed { kv.Value = value } return kv, changed } -// KeyValues returns kvs with all map values deduplicated and whether they changed. +// KeyValueDedupLimitDepth returns kv with all map values +// deduplicated and all array and map values limited to depthLimit. The boolean +// results report depth limiting and deduplication changes, respectively. +func KeyValueDedupLimitDepth( + kv attribute.KeyValue, + depthLimit int, +) (attribute.KeyValue, bool, bool) { + value, depthLimited, deduplicated := ValueDedupLimitDepth(kv.Value, depthLimit) + if depthLimited || deduplicated { + kv.Value = value + } + return kv, depthLimited, deduplicated +} + +// KeyValueLimitDepth returns kv with all array and map values limited to +// depthLimit. Map keys are not deduplicated. +func KeyValueLimitDepth(kv attribute.KeyValue, depthLimit int) (attribute.KeyValue, bool) { + value, changed := ValueLimitDepth(kv.Value, depthLimit) + if changed { + kv.Value = value + } + return kv, changed +} + +// KeyValuesDedup returns kvs with all map values deduplicated and whether +// they changed. // // The returned slice is the original kvs slice if no value needs // deduplication. Top-level keys in kvs are not deduplicated. -func KeyValues(kvs []attribute.KeyValue) ([]attribute.KeyValue, bool) { +func KeyValuesDedup(kvs []attribute.KeyValue) ([]attribute.KeyValue, bool) { // Preserve the caller's slice on the common no-op path. Once a changed // value is found, copy the prior values exactly once and fill the rest in // place as the scan continues. var normalized []attribute.KeyValue for i, kv := range kvs { - kv, changed := KeyValue(kv) + kv, changed := KeyValueDedup(kv) if normalized != nil { normalized[i] = kv continue @@ -80,22 +182,67 @@ func KeyValues(kvs []attribute.KeyValue) ([]attribute.KeyValue, bool) { return normalized, true } -// Set returns set with all map values deduplicated and whether it changed. +// KeyValuesDedupLimitDepth returns kvs with all map values +// deduplicated and all array and map values limited to depthLimit. The boolean +// results report depth limiting and deduplication changes, respectively. +// +// The returned slice is the original kvs slice if no value needs +// normalization. Top-level keys in kvs are not deduplicated. +func KeyValuesDedupLimitDepth( + kvs []attribute.KeyValue, + depthLimit int, +) ([]attribute.KeyValue, bool, bool) { + if depthLimit < 0 { + kvs, deduplicated := KeyValuesDedup(kvs) + return kvs, false, deduplicated + } + + var normalized []attribute.KeyValue + var allChanges valueChanges + for i, kv := range kvs { + value, changes := valueDedupLimitDepth(kv.Value, depthLimit) + allChanges |= changes + if changes != 0 { + kv.Value = value + } + if normalized != nil { + normalized[i] = kv + continue + } + if changes == 0 { + continue + } + + normalized = make([]attribute.KeyValue, len(kvs)) + copy(normalized, kvs[:i]) + normalized[i] = kv + } + if normalized == nil { + return kvs, false, false + } + return normalized, + allChanges&depthLimitChanged != 0, + allChanges&deduplicationChanged != 0 +} + +// SetDedup returns set with all map values deduplicated and whether it +// changed. // // The returned Set is the original set if no value needs deduplication. // Top-level key uniqueness remains attribute.Set's responsibility; this only // normalizes map attribute values. -func Set(set attribute.Set) (attribute.Set, bool) { - if set.Len() == 0 { +func SetDedup(set attribute.Set) (attribute.Set, bool) { + length := set.Len() + if length == 0 { return set, false } // Most attribute sets contain no duplicate map keys. Delay allocation until // the first changed value so the no-op path returns the original Set. var normalized []attribute.KeyValue - for i := range set.Len() { + for i := range length { kv, _ := set.Get(i) - kv, changed := KeyValue(kv) + kv, changed := KeyValueDedup(kv) if normalized != nil { normalized = append(normalized, kv) continue @@ -104,7 +251,7 @@ func Set(set attribute.Set) (attribute.Set, bool) { continue } - normalized = make([]attribute.KeyValue, 0, set.Len()) + normalized = make([]attribute.KeyValue, 0, length) for j := range i { prior, _ := set.Get(j) normalized = append(normalized, prior) @@ -118,7 +265,359 @@ func Set(set attribute.Set) (attribute.Set, bool) { return attribute.NewSet(normalized...), true } -func deduplicateSliceValue(value attribute.Value) (attribute.Value, bool) { +// SetDedupLimitDepth returns set with all map values deduplicated and +// all array and map values limited to depthLimit. The boolean results report +// depth limiting and deduplication changes, respectively. +// +// The returned Set is the original set if no value needs normalization. +// Top-level key uniqueness remains attribute.Set's responsibility; this only +// normalizes attribute values. +func SetDedupLimitDepth( + set attribute.Set, + depthLimit int, +) (attribute.Set, bool, bool) { + if depthLimit < 0 { + set, deduplicated := SetDedup(set) + return set, false, deduplicated + } + length := set.Len() + if length == 0 { + return set, false, false + } + + var normalized []attribute.KeyValue + var allChanges valueChanges + for i := range length { + kv, _ := set.Get(i) + value, changes := valueDedupLimitDepth(kv.Value, depthLimit) + allChanges |= changes + if changes != 0 { + kv.Value = value + } + if normalized != nil { + normalized = append(normalized, kv) + continue + } + if changes == 0 { + continue + } + + normalized = make([]attribute.KeyValue, 0, length) + for j := range i { + prior, _ := set.Get(j) + normalized = append(normalized, prior) + } + normalized = append(normalized, kv) + } + if normalized == nil { + return set, false, false + } + return attribute.NewSet(normalized...), + allChanges&depthLimitChanged != 0, + allChanges&deduplicationChanged != 0 +} + +// SetLimitDepth returns set with all array and map values limited to +// depthLimit. Map keys are not deduplicated. +// +// The returned Set is the original set if no value changes. +func SetLimitDepth(set attribute.Set, depthLimit int) (attribute.Set, bool) { + if depthLimit < 0 { + return set, false + } + length := set.Len() + if length == 0 { + return set, false + } + + var normalized []attribute.KeyValue + for i := range length { + kv, _ := set.Get(i) + value, changed := valueLimitDepth(kv.Value, depthLimit) + if changed { + kv.Value = value + } + if normalized != nil { + normalized = append(normalized, kv) + continue + } + if !changed { + continue + } + + normalized = make([]attribute.KeyValue, 0, length) + for j := range i { + prior, _ := set.Get(j) + normalized = append(normalized, prior) + } + normalized = append(normalized, kv) + } + if normalized == nil { + return set, false + } + return attribute.NewSet(normalized...), true +} + +// valueDedupLimitDepth combines depth limiting with recursive map +// deduplication. remainingDepth is non-negative. It checks the remaining +// budget before reading collection storage and lazily rebuilds only changed +// ancestry. +func valueDedupLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, valueChanges) { + switch value.Type() { + case attribute.BOOLSLICE, + attribute.INT64SLICE, + attribute.FLOAT64SLICE, + attribute.STRINGSLICE, + attribute.BYTESLICE: + if remainingDepth == 0 { + return attribute.Value{}, depthLimitChanged + } + case attribute.SLICE: + if remainingDepth == 0 { + return attribute.Value{}, depthLimitChanged + } + return sliceValueDedupLimitDepth(value, remainingDepth) + case attribute.MAP: + if remainingDepth == 0 { + return attribute.Value{}, depthLimitChanged + } + return mapValueDedupLimitDepth(value, remainingDepth) + } + return value, 0 +} + +// valueLimitDepth limits collection depth while preserving duplicate map keys. +func valueLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, bool) { + switch value.Type() { + case attribute.BOOLSLICE, + attribute.INT64SLICE, + attribute.FLOAT64SLICE, + attribute.STRINGSLICE, + attribute.BYTESLICE: + if remainingDepth == 0 { + return attribute.Value{}, true + } + case attribute.SLICE: + if remainingDepth == 0 { + return attribute.Value{}, true + } + return sliceValueLimitDepth(value, remainingDepth) + case attribute.MAP: + if remainingDepth == 0 { + return attribute.Value{}, true + } + return mapValueLimitDepth(value, remainingDepth) + } + return value, false +} + +func sliceValueDedupLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, valueChanges) { + storage := valueStorage(value) + length := valueLen(storage) + if length <= 1 { + if length == 1 { + elem := valueAt(storage, 0) + newElem, changes := valueDedupLimitDepth( + elem, + remainingDepth-1, + ) + if changes != 0 { + return attribute.SliceValue(newElem), changes + } + } + return value, 0 + } + + var normalized []attribute.Value + var allChanges valueChanges + for i := range length { + elem := valueAt(storage, i) + newElem, changes := valueDedupLimitDepth( + elem, + remainingDepth-1, + ) + allChanges |= changes + if normalized != nil { + normalized[i] = newElem + continue + } + if changes == 0 { + continue + } + + normalized = make([]attribute.Value, length) + for j := range i { + normalized[j] = valueAt(storage, j) + } + normalized[i] = newElem + } + if normalized == nil { + return value, 0 + } + return attribute.SliceValue(normalized...), allChanges +} + +func sliceValueLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, bool) { + storage := valueStorage(value) + length := valueLen(storage) + if length <= 1 { + if length == 1 { + elem := valueAt(storage, 0) + newElem, changed := valueLimitDepth(elem, remainingDepth-1) + if changed { + return attribute.SliceValue(newElem), true + } + } + return value, false + } + + var normalized []attribute.Value + for i := range length { + elem := valueAt(storage, i) + newElem, changed := valueLimitDepth(elem, remainingDepth-1) + if normalized != nil { + normalized[i] = newElem + continue + } + if !changed { + continue + } + + normalized = make([]attribute.Value, length) + for j := range i { + normalized[j] = valueAt(storage, j) + } + normalized[i] = newElem + } + if normalized == nil { + return value, false + } + return attribute.SliceValue(normalized...), true +} + +func mapValueDedupLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, valueChanges) { + storage := valueStorage(value) + length := keyValueLen(storage) + if length <= 1 { + if length == 1 { + kv := keyValueAt(storage, 0) + newValue, changes := valueDedupLimitDepth( + kv.Value, + remainingDepth-1, + ) + if changes != 0 { + kv.Value = newValue + return attribute.MapValue(kv), changes + } + } + return value, 0 + } + + var normalized []attribute.KeyValue + var allChanges valueChanges + for i := 0; i < length; { + // attribute.MapValue stores key-values sorted by key using a stable + // sort. Only the last entry in an equal-key run survives, so avoid + // traversing values that will be discarded. + first := keyValueAt(storage, i) + j := i + 1 + for j < length && keyValueAt(storage, j).Key == first.Key { + j++ + } + + kv := keyValueAt(storage, j-1) + newValue, changes := valueDedupLimitDepth( + kv.Value, + remainingDepth-1, + ) + if changes != 0 { + kv.Value = newValue + } + if j-i > 1 { + changes |= deduplicationChanged + } + allChanges |= changes + if normalized != nil { + normalized = append(normalized, kv) + } else if changes != 0 { + if i == 0 && j == length { + return attribute.MapValue(kv), allChanges + } + normalized = make([]attribute.KeyValue, 0, length-(j-i-1)) + for k := range i { + normalized = append(normalized, keyValueAt(storage, k)) + } + normalized = append(normalized, kv) + } + i = j + } + if normalized == nil { + return value, 0 + } + return attribute.MapValue(normalized...), allChanges +} + +func mapValueLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, bool) { + storage := valueStorage(value) + length := keyValueLen(storage) + if length <= 1 { + if length == 1 { + kv := keyValueAt(storage, 0) + newValue, changed := valueLimitDepth(kv.Value, remainingDepth-1) + if changed { + kv.Value = newValue + return attribute.MapValue(kv), true + } + } + return value, false + } + + var normalized []attribute.KeyValue + for i := range length { + kv := keyValueAt(storage, i) + newValue, changed := valueLimitDepth(kv.Value, remainingDepth-1) + if changed { + kv.Value = newValue + } + if normalized != nil { + normalized[i] = kv + continue + } + if !changed { + continue + } + + normalized = make([]attribute.KeyValue, length) + for j := range i { + normalized[j] = keyValueAt(storage, j) + } + normalized[i] = kv + } + if normalized == nil { + return value, false + } + return attribute.MapValue(normalized...), true +} + +func sliceValueDedup(value attribute.Value) (attribute.Value, bool) { storage := valueStorage(value) length := valueLen(storage) @@ -127,7 +626,7 @@ func deduplicateSliceValue(value attribute.Value) (attribute.Value, bool) { var normalized []attribute.Value for i := range length { elem := valueAt(storage, i) - elem, changed := Value(elem) + elem, changed := ValueDedup(elem) if normalized != nil { normalized[i] = elem continue @@ -148,14 +647,14 @@ func deduplicateSliceValue(value attribute.Value) (attribute.Value, bool) { return attribute.SliceValue(normalized...), true } -func deduplicateMapValue(value attribute.Value) (attribute.Value, bool) { +func mapValueDedup(value attribute.Value) (attribute.Value, bool) { storage := valueStorage(value) length := keyValueLen(storage) if length <= 1 { // A single map entry cannot duplicate its own key, but its value might // contain a map or slice that needs recursive normalization. if length == 1 { - kv, changed := KeyValue(keyValueAt(storage, 0)) + kv, changed := KeyValueDedup(keyValueAt(storage, 0)) if changed { return attribute.MapValue(kv), true } @@ -174,13 +673,16 @@ func deduplicateMapValue(value attribute.Value) (attribute.Value, bool) { j++ } - kv, nestedChanged := KeyValue(keyValueAt(storage, j-1)) + kv, nestedChanged := KeyValueDedup(keyValueAt(storage, j-1)) // j-i > 1 means the current key run contained duplicates. changed := nestedChanged || j-i > 1 if normalized != nil { normalized = append(normalized, kv) } else if changed { - normalized = make([]attribute.KeyValue, 0, length) + if i == 0 && j == length { + return attribute.MapValue(kv), true + } + normalized = make([]attribute.KeyValue, 0, length-(j-i-1)) for k := range i { normalized = append(normalized, keyValueAt(storage, k)) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/truncate.go b/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/truncate.go index 9955e90726..db7c5388ca 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/truncate.go +++ b/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/truncate.go @@ -7,7 +7,7 @@ package attrnorm import ( - "slices" + "reflect" "strings" "unicode/utf8" @@ -16,53 +16,34 @@ import ( // Truncate returns a truncated version of attr. Only string, string slice, // byte slice, slice, and map attribute values are truncated. String values are -// truncated to at most a length of limit. Each string slice value is truncated -// in this fashion (the slice length itself is unaffected), and byte slice -// values are truncated to at most limit bytes. For slice and map attribute -// values, the limit is applied recursively to contained values. +// truncated according to limit. Each string slice value is truncated in this +// fashion (the slice length itself is unaffected), and byte slice values are +// truncated to at most limit bytes. For slice and map attribute values, the +// limit is applied recursively to contained values. // // No truncation is performed for a negative limit. func Truncate(limit int, attr attribute.KeyValue) attribute.KeyValue { if limit < 0 { return attr } + + // Keep scalar cases in this wrapper. Routing them through the recursive, + // multi-result transform adds measurable overhead to the dominant simple + // attribute path. switch attr.Value.Type() { case attribute.STRING: - v := attr.Value.AsString() - return attr.Key.String(truncate(limit, v)) - case attribute.STRINGSLICE: - v := attr.Value.AsStringSlice() - for i := range v { - v[i] = truncate(limit, v[i]) - } - return attr.Key.StringSlice(v) + attr.Value = attribute.StringValue(truncate(limit, attr.Value.AsString())) case attribute.BYTESLICE: - v := attr.Value.AsString() - if len(v) > limit { - return attr.Key.ByteSlice([]byte(v[:limit])) + s := attr.Value.AsString() + if len(s) > limit { + attr.Value = attribute.ByteSliceValue([]byte(s[:limit])) } - return attr + case attribute.STRINGSLICE: + attr.Value, _ = truncateStringSliceValue(limit, attr.Value) case attribute.SLICE: - v := attr.Value.AsSlice() - if !slices.ContainsFunc(v, func(e attribute.Value) bool { return needsTruncation(limit, e) }) { - return attr - } - newV := make([]attribute.Value, len(v)) - for i, elem := range v { - newV[i] = TruncateValue(limit, elem) - } - return attr.Key.Slice(newV...) + attr.Value, _ = truncateSliceValue(limit, attr.Value) case attribute.MAP: - v := attr.Value.AsMap() - if !slices.ContainsFunc(v, func(kv attribute.KeyValue) bool { return needsTruncation(limit, kv.Value) }) { - return attr - } - newV := make([]attribute.KeyValue, len(v)) - for i, elem := range v { - elem.Value = TruncateValue(limit, elem.Value) - newV[i] = elem - } - return attr.Key.Map(newV...) + attr.Value, _ = truncateMapValue(limit, attr.Value) } return attr } @@ -76,101 +57,289 @@ func TruncateValue(limit int, v attribute.Value) attribute.Value { return v } + // Match Truncate's direct scalar path to avoid paying for the recursive, + // multi-result transform when no composite traversal is needed. switch v.Type() { case attribute.STRING: return attribute.StringValue(truncate(limit, v.AsString())) + case attribute.BYTESLICE: + s := v.AsString() + if len(s) > limit { + return attribute.ByteSliceValue([]byte(s[:limit])) + } case attribute.STRINGSLICE: - ss := v.AsStringSlice() - for i := range ss { - ss[i] = truncate(limit, ss[i]) + v, _ = truncateStringSliceValue(limit, v) + case attribute.SLICE: + v, _ = truncateSliceValue(limit, v) + case attribute.MAP: + v, _ = truncateMapValue(limit, v) + } + return v +} + +// truncateValue traverses composite values once and rebuilds them lazily on +// the first changed child. Recursion provides O(depth) temporary stack space +// without forcing a heap allocation on the common no-op path. +func truncateValue(limit int, v attribute.Value) (attribute.Value, bool) { + switch v.Type() { + case attribute.STRING: + s := v.AsString() + truncated := truncate(limit, s) + if truncated != s { + return attribute.StringValue(truncated), true } - return attribute.StringSliceValue(ss) + case attribute.STRINGSLICE: + return truncateStringSliceValue(limit, v) case attribute.BYTESLICE: // len(v.AsString()) is identical to len(v.AsByteSlice()) but // avoids allocating the full slice before truncation. s := v.AsString() - if limit >= 0 && len(s) > limit { - return attribute.ByteSliceValue([]byte(s[:limit])) + if len(s) > limit { + return attribute.ByteSliceValue([]byte(s[:limit])), true } case attribute.SLICE: - sl := v.AsSlice() - if !slices.ContainsFunc(sl, func(e attribute.Value) bool { return needsTruncation(limit, e) }) { - return v + return truncateSliceValue(limit, v) + case attribute.MAP: + return truncateMapValue(limit, v) + } + return v, false +} + +func truncateStringSliceValue(limit int, value attribute.Value) (attribute.Value, bool) { + storage := valueStorage(value) + switch values := storage.(type) { + case [0]string: + return value, false + case [1]string: + return truncateStrings(limit, value, values[:]) + case [2]string: + return truncateStrings(limit, value, values[:]) + case [3]string: + return truncateStrings(limit, value, values[:]) + default: + array := reflect.ValueOf(storage) + if array.Kind() != reflect.Array || array.Type().Elem() != stringType { + return value, false } - newSl := make([]attribute.Value, len(sl)) - for i, elem := range sl { - newSl[i] = TruncateValue(limit, elem) + return truncateStringArray(limit, value, array) + } +} + +func truncateStrings(limit int, value attribute.Value, values []string) (attribute.Value, bool) { + var truncated []string + for i, s := range values { + newS := truncate(limit, s) + if truncated != nil { + truncated[i] = newS + continue } - return attribute.SliceValue(newSl...) - case attribute.MAP: - m := v.AsMap() - if !slices.ContainsFunc(m, func(kv attribute.KeyValue) bool { return needsTruncation(limit, kv.Value) }) { - return v + if newS == s { + continue } - newM := make([]attribute.KeyValue, len(m)) - for i, elem := range m { - elem.Value = TruncateValue(limit, elem.Value) - newM[i] = elem + + truncated = make([]string, len(values)) + copy(truncated, values[:i]) + truncated[i] = newS + } + if truncated == nil { + return value, false + } + return attribute.StringSliceValue(truncated), true +} + +func truncateStringArray(limit int, value attribute.Value, values reflect.Value) (attribute.Value, bool) { + var truncated []string + for i := range values.Len() { + s := values.Index(i).String() + newS := truncate(limit, s) + if truncated != nil { + truncated[i] = newS + continue + } + if newS == s { + continue + } + + truncated = make([]string, values.Len()) + for j := range i { + truncated[j] = values.Index(j).String() } - return attribute.MapValue(newM...) + truncated[i] = newS } - return v + if truncated == nil { + return value, false + } + return attribute.StringSliceValue(truncated), true } -// stringNeedsTruncation reports whether s would be modified by truncate for the -// given limit. -func stringNeedsTruncation(limit int, s string) bool { - if limit < 0 || len(s) <= limit { - return false +func truncateSliceValue(limit int, value attribute.Value) (attribute.Value, bool) { + storage := valueStorage(value) + switch values := storage.(type) { + case [0]attribute.Value: + return value, false + case [1]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + case [2]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + case [3]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + case [4]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + case [5]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + default: + array := reflect.ValueOf(storage) + if array.Kind() != reflect.Array || array.Type().Elem() != valueType { + return value, false + } + return truncateValueArray(limit, value, array) } - return utf8.RuneCountInString(s) > limit || !utf8.ValidString(s) } -// needsTruncation reports whether v would be modified by TruncateValue for the -// given limit. -func needsTruncation(limit int, v attribute.Value) bool { - switch v.Type() { - case attribute.STRING: - return stringNeedsTruncation(limit, v.AsString()) - case attribute.BYTESLICE: - // len(v.AsString()) is identical to len(v.AsByteSlice()) but - // avoids memory allocation. - if limit >= 0 && len(v.AsString()) > limit { - return true +func truncateValueSlice(limit int, value attribute.Value, values []attribute.Value) (attribute.Value, bool) { + var truncated []attribute.Value + for i, elem := range values { + newElem, changed := truncateValue(limit, elem) + if truncated != nil { + truncated[i] = newElem + continue } - case attribute.STRINGSLICE: - for _, s := range v.AsStringSlice() { - if stringNeedsTruncation(limit, s) { - return true - } + if !changed { + continue } - case attribute.SLICE: - return slices.ContainsFunc(v.AsSlice(), func(e attribute.Value) bool { return needsTruncation(limit, e) }) - case attribute.MAP: - return slices.ContainsFunc( - v.AsMap(), - func(kv attribute.KeyValue) bool { return needsTruncation(limit, kv.Value) }, - ) + + truncated = make([]attribute.Value, len(values)) + copy(truncated, values[:i]) + truncated[i] = newElem + } + if truncated == nil { + return value, false + } + return attribute.SliceValue(truncated...), true +} + +func truncateValueArray(limit int, value attribute.Value, values reflect.Value) (attribute.Value, bool) { + var truncated []attribute.Value + for i := range values.Len() { + elem := values.Index(i).Interface().(attribute.Value) + newElem, changed := truncateValue(limit, elem) + if truncated != nil { + truncated[i] = newElem + continue + } + if !changed { + continue + } + + truncated = make([]attribute.Value, values.Len()) + for j := range i { + truncated[j] = values.Index(j).Interface().(attribute.Value) + } + truncated[i] = newElem + } + if truncated == nil { + return value, false + } + return attribute.SliceValue(truncated...), true +} + +func truncateMapValue(limit int, value attribute.Value) (attribute.Value, bool) { + storage := valueStorage(value) + switch keyValues := storage.(type) { + case [0]attribute.KeyValue: + return value, false + case [1]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + case [2]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + case [3]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + case [4]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + case [5]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + default: + array := reflect.ValueOf(storage) + if array.Kind() != reflect.Array || array.Type().Elem() != keyValueType { + return value, false + } + return truncateKeyValueArray(limit, value, array) + } +} + +func truncateKeyValueSlice( + limit int, + value attribute.Value, + keyValues []attribute.KeyValue, +) (attribute.Value, bool) { + var truncated []attribute.KeyValue + for i, kv := range keyValues { + newValue, changed := truncateValue(limit, kv.Value) + if changed { + kv.Value = newValue + } + if truncated != nil { + truncated[i] = kv + continue + } + if !changed { + continue + } + + truncated = make([]attribute.KeyValue, len(keyValues)) + copy(truncated, keyValues[:i]) + truncated[i] = kv + } + if truncated == nil { + return value, false } - return false + return attribute.MapValue(truncated...), true } -// truncate returns a truncated version of s such that it contains less than -// the limit number of characters. Truncation is applied by returning the limit -// number of valid characters contained in s. +func truncateKeyValueArray(limit int, value attribute.Value, keyValues reflect.Value) (attribute.Value, bool) { + var truncated []attribute.KeyValue + for i := range keyValues.Len() { + kv := keyValues.Index(i).Interface().(attribute.KeyValue) + newValue, changed := truncateValue(limit, kv.Value) + if changed { + kv.Value = newValue + } + if truncated != nil { + truncated[i] = kv + continue + } + if !changed { + continue + } + + truncated = make([]attribute.KeyValue, keyValues.Len()) + for j := range i { + truncated[j] = keyValues.Index(j).Interface().(attribute.KeyValue) + } + truncated[i] = kv + } + if truncated == nil { + return value, false + } + return attribute.MapValue(truncated...), true +} + +var stringType = reflect.TypeFor[string]() + +// truncate returns a version of s truncated according to limit. // // If limit is negative, it returns the original string. // -// UTF-8 is supported. When truncating, all invalid characters are dropped +// UTF-8 is supported. When truncating, all invalid UTF-8 bytes are dropped // before applying truncation. // -// If s already contains less than the limit number of bytes, it is returned -// unchanged. No invalid characters are removed. +// If s already contains at most limit bytes, it is returned unchanged. No +// invalid characters are removed. func truncate(limit int, s string) string { - // This prioritize performance in the following order based on the most - // common expected use-cases. + // This prioritizes performance in the following order based on the most + // common expected use cases. // - // - Short values less than the default limit (128). + // - Values whose byte length does not exceed the limit. // - Strings with valid encodings that exceed the limit. // - No limit. // - Strings with invalid encodings that exceed the limit. @@ -190,14 +359,27 @@ func truncate(limit int, s string) string { continue } + // A zero limit also truncates a leading invalid byte or U+FFFD. + if limit == 0 { + return "" + } + // Range reports RuneError for both an invalid byte and a valid U+FFFD. + // Only a size-1 decoding indicates invalid UTF-8. _, size := utf8.DecodeRuneInString(s[i:]) if size == 1 { - // Invalid encoding. + // Removing this byte makes len(s)-1 an upper bound for a rebuilt + // result. Keep the valid prefix before rescanning s[i:]. b.Grow(len(s) - 1) _, _ = b.WriteString(s[:i]) s = s[i:] break } + + // A valid U+FFFD still consumes one character of the limit. + count++ + if count > limit { + return s[:i] + } } // Fast-path, no invalid input. @@ -205,7 +387,9 @@ func truncate(limit int, s string) string { return s } - // Truncate while validating UTF-8. + // The builder holds the valid prefix before the first invalid byte, and + // count includes its runes. Skip malformed bytes without counting them + // while copying the remaining valid runes up to the limit. for i := 0; i < len(s) && count < limit; { c := s[i] if c < utf8.RuneSelf { diff --git a/vendor/go.opentelemetry.io/otel/sdk/internal/x/x.go b/vendor/go.opentelemetry.io/otel/sdk/internal/x/x.go index e829d17948..67eea20a74 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/internal/x/x.go +++ b/vendor/go.opentelemetry.io/otel/sdk/internal/x/x.go @@ -34,9 +34,9 @@ func newFeature[T any](suffix []string, parse func(string) (T, bool)) Feature[T] // feature. func (f Feature[T]) Keys() []string { return f.keys } -// Lookup returns the user configured value for the feature and true if the +// Lookup returns the user-configured value for the feature and true if the // user has enabled the feature. Otherwise, if the feature is not enabled, a -// zero-value and false are returned. +// zero value and false are returned. func (f Feature[T]) Lookup() (v T, ok bool) { // https://github.com/open-telemetry/opentelemetry-specification/blob/62effed618589a0bec416a87e559c0a9d96289bb/specification/configuration/sdk-environment-variables.md#parsing-empty-value // diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/aggregation.go b/vendor/go.opentelemetry.io/otel/sdk/metric/aggregation.go index f52e7ea542..5c7e85904d 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/aggregation.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/aggregation.go @@ -79,7 +79,7 @@ func (l AggregationLastValue) copy() Aggregation { return l } func (AggregationLastValue) err() error { return nil } // AggregationExplicitBucketHistogram is an Aggregation that summarizes a set of -// measurements as an histogram with explicitly defined buckets. +// measurements as a histogram with explicitly defined buckets. type AggregationExplicitBucketHistogram struct { // Boundaries are the increasing bucket boundary values. Boundary values // define bucket upper bounds. Buckets are exclusive of their lower @@ -138,7 +138,7 @@ func (h AggregationExplicitBucketHistogram) copy() Aggregation { } // AggregationBase2ExponentialHistogram is an Aggregation that summarizes a set of -// measurements as an histogram with bucket widths that grow exponentially. +// measurements as a histogram with bucket widths that grow exponentially. type AggregationBase2ExponentialHistogram struct { // MaxSize is the maximum number of buckets to use for the histogram. MaxSize int32 diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/env.go b/vendor/go.opentelemetry.io/otel/sdk/metric/env.go index 132664a7e6..090446d844 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/env.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/env.go @@ -4,6 +4,7 @@ package metric import ( + "errors" "os" "strconv" "time" @@ -11,6 +12,8 @@ import ( "go.opentelemetry.io/otel/internal/global" ) +var errDurationOverflow = errors.New("duration overflows time.Duration") + // Environment variable names. const ( // The time interval (in milliseconds) between the start of two export attempts. @@ -26,7 +29,7 @@ func envDuration(key string, defaultValue time.Duration) time.Duration { if v == "" { return defaultValue } - d, err := strconv.Atoi(v) + d, err := strconv.ParseInt(v, 10, 64) if err != nil { global.Error(err, "parse duration", "environment variable", key, "value", v) return defaultValue @@ -35,5 +38,9 @@ func envDuration(key string, defaultValue time.Duration) time.Duration { global.Error(errNonPositiveDuration, "non-positive duration", "environment variable", key, "value", v) return defaultValue } + if d > int64(time.Duration(1<<63-1)/time.Millisecond) { + global.Error(errDurationOverflow, "duration overflows time.Duration", "environment variable", key, "value", v) + return defaultValue + } return time.Duration(d) * time.Millisecond } diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/exemplar/fixed_size_reservoir.go b/vendor/go.opentelemetry.io/otel/sdk/metric/exemplar/fixed_size_reservoir.go index 48f2b464cb..64f5884d04 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/exemplar/fixed_size_reservoir.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/exemplar/fixed_size_reservoir.go @@ -24,6 +24,12 @@ func FixedSizeReservoirProvider(k int) ReservoirProvider { // sample each one. If there are more than k, the Reservoir will then randomly // sample all additional measurement with a decreasing probability. func NewFixedSizeReservoir(k int) *FixedSizeReservoir { + // A negative size is invalid. The constructor cannot return an error, so + // clamp it to zero and treat it as an empty reservoir (consistent with the + // existing behavior for k == 0) rather than panicking in make below. + if k < 0 { + k = 0 + } r := &FixedSizeReservoir{ storage: make([]measurement, k), } diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/exemplar/value.go b/vendor/go.opentelemetry.io/otel/sdk/metric/exemplar/value.go index c7d1645b6e..af045e2761 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/exemplar/value.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/exemplar/value.go @@ -49,8 +49,8 @@ func (v Value) Int64() int64 { return 0 } -// Float64 returns the value of v as an float64. If the ValueType of v is not -// an Float64ValueType, 0 is returned. +// Float64 returns the value of v as a float64. If the ValueType of v is not +// a Float64ValueType, 0 is returned. func (v Value) Float64() float64 { if v.t == Float64ValueType { return math.Float64frombits(v.val) diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/instrument.go b/vendor/go.opentelemetry.io/otel/sdk/metric/instrument.go index 31f7afef90..f086573140 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/instrument.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/instrument.go @@ -142,6 +142,9 @@ type Stream struct { // the attribute will not be recorded, otherwise, if it returns true, it // will record the attribute. // + // If nil, the instrument's advisory attribute keys are used. If the + // instrument has no advisory attribute keys, all attributes are recorded. + // // Note that attributes filtered out by a View may still appear on Exemplars, // because Exemplars are recorded with the dropped measurement attributes // when View attribute filtering is applied. @@ -207,11 +210,11 @@ func extractRawKVs[T any](opts []T) []attribute.KeyValue { } func resolveAttributes(configAttrs attribute.Set, rawKVs []attribute.KeyValue) attribute.Set { - configAttrs, _ = attrnorm.Set(configAttrs) + configAttrs, _ = attrnorm.SetDedup(configAttrs) if len(rawKVs) == 0 { return configAttrs } - rawKVs, _ = attrnorm.KeyValues(rawKVs) + rawKVs, _ = attrnorm.KeyValuesDedup(rawKVs) merged := make([]attribute.KeyValue, 0, configAttrs.Len()+len(rawKVs)) merged = append(merged, configAttrs.ToSlice()...) // rawKVs are appended after configAttrs, meaning they will override any duplicate keys in configAttrs. diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/aggregate.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/aggregate.go index 696fc21cab..98916ae766 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/aggregate.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/aggregate.go @@ -57,18 +57,17 @@ func (b Builder[N]) resFunc() func(attribute.Set) FilteredExemplarReservoir[N] { return DropReservoir } -type fltrMeasure[N int64 | float64] func(ctx context.Context, value N, fltrAttr attribute.Set, droppedAttr []attribute.KeyValue) +type fltrMeasure[N int64 | float64] func(ctx context.Context, value N, lazy lazyFilteredAttributes) func (b Builder[N]) filter(f fltrMeasure[N]) Measure[N] { if b.Filter != nil { fltr := b.Filter // Copy to make it immutable after assignment. return func(ctx context.Context, n N, a attribute.Set) { - fAttr, dropped := a.Filter(fltr) - f(ctx, n, fAttr, dropped) + f(ctx, n, newLazyFilteredAttributes(a, fltr)) } } return func(ctx context.Context, n N, a attribute.Set) { - f(ctx, n, a, nil) + f(ctx, n, newLazyFilteredAttributes(a, nil)) } } diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/atomic.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/atomic.go index 675c23fc3c..1e342420e0 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/atomic.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/atomic.go @@ -27,10 +27,18 @@ type atomicCounter[N int64 | float64] struct { // load returns the current value. The caller must ensure all calls to add have // returned prior to calling load. -func (n *atomicCounter[N]) load() N { - fval := math.Float64frombits(n.nFloatBits.Load()) - ival := n.nInt.Load() - return N(fval + float64(ival)) +func (n *atomicCounter[N]) load() (value N) { + switch any(value).(type) { + case int64: + value = N(n.nInt.Load()) + case float64: + fval := math.Float64frombits(n.nFloatBits.Load()) + ival := n.nInt.Load() + value = N(fval + float64(ival)) + default: + panic("unsupported type") + } + return value } func (n *atomicCounter[N]) add(value N) { @@ -183,40 +191,53 @@ type hotColdWaitGroup struct { endedCounts [2]atomic.Uint64 } +// hotIdx represents an index (0 or 1) to the currently active "hot" buffer +// where concurrent writes are accepted. +// +// coldIdx represents an index (0 or 1) to the "cold" buffer where collection +// reads and resets occur after a swap. +// +// These distinct types enforce at compile time that hot (write) and cold (read) +// indices are not accidentally interchanged across call boundaries. +type ( + hotIdx uint64 + coldIdx uint64 +) + // start returns the hot index that the writer should write to. The returned // hot index is 0 or 1. The caller must call done(hot index) after it finishes // its operation. start() is safe to call concurrently with other methods. -func (l *hotColdWaitGroup) start() uint64 { +func (l *hotColdWaitGroup) start() hotIdx { // We increment h.startedCountAndHotIdx so that the counter in the lower // 63 bits gets incremented. At the same time, we get the new value // back, which we can use to return the currently-hot index. - return l.startedCountAndHotIdx.Add(1) >> 63 + return hotIdx(l.startedCountAndHotIdx.Add(1) >> 63) } // done signals to the reader that an operation has fully completed. // done is safe to call concurrently. -func (l *hotColdWaitGroup) done(hotIdx uint64) { +func (l *hotColdWaitGroup) done(hotIdx hotIdx) { l.endedCounts[hotIdx].Add(1) } // swapHotAndWait swaps the hot bit, waits for all start() calls to be done(), // and then returns the now-cold index for the reader to read from. The // returned index is 0 or 1. swapHotAndWait must not be called concurrently. -func (l *hotColdWaitGroup) swapHotAndWait() uint64 { +func (l *hotColdWaitGroup) swapHotAndWait() coldIdx { n := l.startedCountAndHotIdx.Load() - coldIdx := (^n) >> 63 + coldIdxVal := (^n) >> 63 // Swap the hot and cold index while resetting the started measurements // count to zero. - n = l.startedCountAndHotIdx.Swap((coldIdx << 63)) - hotIdx := n >> 63 + n = l.startedCountAndHotIdx.Swap((coldIdxVal << 63)) + hotIdxVal := n >> 63 startedCount := n & ((1 << 63) - 1) // Wait for all measurements to the previously-hot map to finish. - for startedCount != l.endedCounts[hotIdx].Load() { + for startedCount != l.endedCounts[hotIdxVal].Load() { runtime.Gosched() // Let measurements complete. } // reset the number of ended operations - l.endedCounts[hotIdx].Store(0) - return hotIdx + l.endedCounts[hotIdxVal].Store(0) + return coldIdx(hotIdxVal) } // limitedSyncMap is a sync.Map which enforces the aggregation limit on @@ -228,8 +249,13 @@ type limitedSyncMap[V any] struct { lenMux sync.Mutex } -func (m *limitedSyncMap[V]) LoadOrStoreAttr(fltrAttr attribute.Set, newValue func(attribute.Set) V) V { - actual, loaded := m.Load(fltrAttr.Equivalent()) +// LoadOrStoreAttr performs lookup using lazy.Distinct() on the hot path without +// constructing a Set. If the entry is not found and the aggregation limit has not +// been exceeded, lazy.Set() is called to construct the attribute.Set for storage. +// If the aggregation limit is exceeded, overflowSet is used instead without calling lazy.Set(). +func (m *limitedSyncMap[V]) LoadOrStoreAttr(lazy lazyFilteredAttributes, newValue func(attribute.Set) V) V { + distinct := lazy.Distinct() + actual, loaded := m.Load(distinct) if loaded { return actual.(V) } @@ -246,21 +272,68 @@ func (m *limitedSyncMap[V]) LoadOrStoreAttr(fltrAttr attribute.Set, newValue fun // re-fetch now that we hold the lock to ensure we don't use the overflow // set unless we are sure the attribute set isn't being written // concurrently. - actual, loaded = m.Load(fltrAttr.Equivalent()) + actual, loaded = m.Load(distinct) if loaded { return actual.(V) } + var fltrAttr attribute.Set if m.aggLimit > 0 && m.len >= m.aggLimit-1 { fltrAttr = overflowSet + distinct = overflowSet.Equivalent() + } else { + fltrAttr = lazy.Set() } - actual, loaded = m.LoadOrStore(fltrAttr.Equivalent(), newValue(fltrAttr)) + actual, loaded = m.LoadOrStore(distinct, newValue(fltrAttr)) if !loaded { m.len++ } return actual.(V) } +// LoadOrStoreAttrReclaiming is equivalent to LoadOrStoreAttr, except that a +// slot released after overflow was created can be reused for a new attribute +// set. The shared overflow entry remains available for measurements made while +// all normal slots are occupied. It reports whether the value was loaded and +// whether this lookup was routed to the shared overflow entry. +func (m *limitedSyncMap[V]) LoadOrStoreAttrReclaiming( + lazy lazyFilteredAttributes, + newValue func(attribute.Set, bool) V, +) (value V, loaded, overflowed bool) { + distinct := lazy.Distinct() + actual, loaded := m.Load(distinct) + if loaded { + return actual.(V), true, false + } + + m.lenMux.Lock() + defer m.lenMux.Unlock() + + actual, loaded = m.Load(distinct) + if loaded { + return actual.(V), true, false + } + + overflow, hasOverflow := m.Load(overflowSet.Equivalent()) + if m.aggLimit > 0 && hasOverflow && m.len >= m.aggLimit { + return overflow.(V), true, true + } + + var attrs attribute.Set + overflowed = m.aggLimit > 0 && !hasOverflow && m.len >= m.aggLimit-1 + if overflowed { + attrs = overflowSet + distinct = overflowSet.Equivalent() + } else { + attrs = lazy.Set() + } + actual, loaded = m.LoadOrStore(distinct, newValue(attrs, overflowed)) + if !loaded { + m.len++ + } + return actual.(V), loaded, overflowed +} + func (m *limitedSyncMap[V]) Clear() { m.lenMux.Lock() defer m.lenMux.Unlock() @@ -268,8 +341,62 @@ func (m *limitedSyncMap[V]) Clear() { m.Map.Clear() } +// CompareAndDelete deletes the entry for key if its value is equal to old. +// It reports whether the entry was deleted. +func (m *limitedSyncMap[V]) CompareAndDelete(key attribute.Distinct, old V) bool { + m.lenMux.Lock() + defer m.lenMux.Unlock() + if !m.Map.CompareAndDelete(key, old) { + return false + } + m.len-- + return true +} + func (m *limitedSyncMap[V]) Len() int { m.lenMux.Lock() defer m.lenMux.Unlock() return m.len } + +// hotColdMap manages two [limitedSyncMap] instances so that measurement and +// collection operate on separate maps and do not lock each other out. +// +// Measurements write to the currently hot map returned by [hotColdMap.hot] +// using the index from [hotColdWaitGroup.start]. Collection is performed by +// calling [hotColdWaitGroup.swapHotAndWait] to atomically swap the hot and cold +// maps and wait for in-flight writes to the cold map to complete. The caller +// can then read the cold map via [hotColdMap.Range] and must call +// [hotColdMap.Clear] on the cold index so that unused attribute sets do not +// report in subsequent collection cycles and the cardinality limit budget is +// reset. +// +// swapHotAndWait must not be called concurrently. +type hotColdMap[V any] struct { + hotColdWaitGroup + hotColdValMap [2]limitedSyncMap[V] +} + +func (m *hotColdMap[V]) init(limit int) { + m.hotColdValMap[0].aggLimit = limit + m.hotColdValMap[1].aggLimit = limit +} + +func (m *hotColdMap[V]) hot(i hotIdx) *limitedSyncMap[V] { + return &m.hotColdValMap[i] +} + +// Len returns the length of the specified map. +func (m *hotColdMap[V]) Len(readIdx coldIdx) int { + return m.hotColdValMap[readIdx].Len() +} + +// Range calls f sequentially for each key and value present in the map at readIdx. +func (m *hotColdMap[V]) Range(readIdx coldIdx, f func(key, value any) bool) { + m.hotColdValMap[readIdx].Range(f) +} + +// Clear clears the map at readIdx. +func (m *hotColdMap[V]) Clear(readIdx coldIdx) { + m.hotColdValMap[readIdx].Clear() +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/drop.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/drop.go index 47ec26dba9..c78bdc6713 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/drop.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/drop.go @@ -18,7 +18,7 @@ func DropReservoir[N int64 | float64](attribute.Set) FilteredExemplarReservoir[N type dropRes[N int64 | float64] struct{} // Offer does nothing, all measurements offered will be dropped. -func (*dropRes[N]) Offer(context.Context, N, []attribute.KeyValue) {} +func (*dropRes[N]) Offer(context.Context, N, lazyFilteredAttributes) {} // Collect resets dest. No exemplars will ever be returned. func (*dropRes[N]) Collect(dest *[]exemplar.Exemplar) { diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/exponential_histogram.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/exponential_histogram.go index 77c20a315c..f539be9422 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/exponential_histogram.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/exponential_histogram.go @@ -331,8 +331,7 @@ type expoHistogram[N int64 | float64] struct { func (e *expoHistogram[N]) measure( ctx context.Context, value N, - fltrAttr attribute.Set, - droppedAttr []attribute.KeyValue, + lazy lazyFilteredAttributes, ) { // Ignore NaN and infinity. if math.IsInf(float64(value), 0) || math.IsNaN(float64(value)) { @@ -342,13 +341,17 @@ func (e *expoHistogram[N]) measure( e.valuesMu.Lock() defer e.valuesMu.Unlock() - v, ok := e.values[fltrAttr.Equivalent()] + distinct := lazy.Distinct() + v, ok := e.values[distinct] if !ok { - fltrAttr = e.limit.Attributes(fltrAttr, e.values) - // If we overflowed, make sure we add to the existing overflow series - // if it already exists. - v, ok = e.values[fltrAttr.Equivalent()] + v, ok = e.values[overflowSet.Equivalent()] if !ok { + var fltrAttr attribute.Set + if e.limit.aggLimit > 0 && len(e.values) >= e.limit.aggLimit-1 { + fltrAttr = overflowSet + } else { + fltrAttr = lazy.Set() + } v = newExpoHistogramDataPoint[N](fltrAttr, e.maxSize, e.maxScale, e.noMinMax, e.noSum) r := e.newRes(fltrAttr) _, isDrop := r.(*dropRes[N]) @@ -360,7 +363,7 @@ func (e *expoHistogram[N]) measure( } v.record(value) if !v.dropExemplars { - v.res.Offer(ctx, value, droppedAttr) + v.res.Offer(ctx, value, lazy) } } diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/filtered_reservoir.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/filtered_reservoir.go index 9aac90f035..20e26c57d3 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/filtered_reservoir.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/filtered_reservoir.go @@ -8,7 +8,6 @@ import ( "sync" "time" - "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/sdk/metric/exemplar" "go.opentelemetry.io/otel/sdk/metric/internal/reservoir" ) @@ -22,7 +21,10 @@ type FilteredExemplarReservoir[N int64 | float64] interface { // The passed ctx needs to contain any baggage or span that were active // when the measurement was made. This information may be used by the // Reservoir in making a sampling decision. - Offer(ctx context.Context, val N, attr []attribute.KeyValue) + // + // The lazy parameter provides filtered attribute details when sampled, + // allowing dropped attributes to be computed only if the measurement is sampled. + Offer(ctx context.Context, val N, lazy lazyFilteredAttributes) // Collect returns all the held exemplars in the reservoir. Collect(dest *[]exemplar.Exemplar) } @@ -52,10 +54,11 @@ func NewFilteredExemplarReservoir[N int64 | float64]( } } -func (f *filteredExemplarReservoir[N]) Offer(ctx context.Context, val N, attr []attribute.KeyValue) { +func (f *filteredExemplarReservoir[N]) Offer(ctx context.Context, val N, lazy lazyFilteredAttributes) { if f.filter(ctx) { // only record the current time if we are sampling this measurement. ts := time.Now() + attr := lazy.Dropped() if !f.concurrentSafe { f.reservoirMux.Lock() defer f.reservoirMux.Unlock() diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/finish_sum.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/finish_sum.go new file mode 100644 index 0000000000..d167acdae1 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/finish_sum.go @@ -0,0 +1,313 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package aggregate + +import ( + "context" + "sync" + "sync/atomic" + "time" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/sdk/metric/internal/finish" + "go.opentelemetry.io/otel/sdk/metric/metricdata" +) + +type finishSumValue[N int64 | float64] struct { + lifecycle finish.Lifecycle + value atomicCounter[N] + attrs attribute.Set + start time.Time + dropExemplars bool + reservoir FilteredExemplarReservoir[N] +} + +func newFinishSumValue[N int64 | float64]( + attrs attribute.Set, + reservoir func(attribute.Set) FilteredExemplarReservoir[N], +) *finishSumValue[N] { + r := reservoir(attrs) + _, drop := r.(*dropRes[N]) + point := &finishSumValue[N]{ + attrs: attrs, + start: now(), + dropExemplars: drop, + reservoir: r, + } + return point +} + +func (v *finishSumValue[N]) measure( + ctx context.Context, + value N, + lazy lazyFilteredAttributes, +) bool { + measurement, ok := v.lifecycle.AcquireMeasurement() + if !ok { + return false + } + v.measureAcquired(ctx, value, lazy, measurement) + return true +} + +func (v *finishSumValue[N]) measureOverflow( + ctx context.Context, + value N, + lazy lazyFilteredAttributes, +) bool { + measurement, ok := v.lifecycle.AcquireSharedMeasurement() + if !ok { + return false + } + v.measureAcquired(ctx, value, lazy, measurement) + return true +} + +func (v *finishSumValue[N]) measureAcquired( + ctx context.Context, + value N, + lazy lazyFilteredAttributes, + measurement finish.Measurement, +) { + v.value.add(value) + if v.dropExemplars { + measurement.Release() + return + } + defer measurement.Release() + v.reservoir.Offer(ctx, value, lazy) +} + +func (v *finishSumValue[N]) finish(t time.Time) { + v.lifecycle.Finish(t) +} + +func (v *finishSumValue[N]) collectCumulative( + t time.Time, +) (metricdata.DataPoint[N], bool, bool) { + collection, ok := v.lifecycle.BeginCumulativeCollection(t) + if !ok { + return metricdata.DataPoint[N]{}, false, false + } + dp, retire := v.collect(v.start, collection) + return dp, true, retire +} + +func (v *finishSumValue[N]) collectDelta( + start time.Time, + t time.Time, +) (metricdata.DataPoint[N], bool, bool) { + collection, ok := v.lifecycle.BeginDeltaCollection(t) + if !ok { + return metricdata.DataPoint[N]{}, false, false + } + dp, retire := v.collect(start, collection) + return dp, true, retire +} + +func (v *finishSumValue[N]) collect( + start time.Time, + collection finish.Collection, +) (metricdata.DataPoint[N], bool) { + defer collection.Complete() + + dp := metricdata.DataPoint[N]{ + Attributes: v.attrs, + StartTime: start, + Time: collection.Time(), + Value: v.value.load(), + } + collectExemplars(&dp.Exemplars, v.reservoir.Collect) + return dp, collection.ShouldRetire() +} + +func (v *finishSumValue[N]) shutdown() { + v.lifecycle.Retire() +} + +// FinishSum contains the operations of a finish-aware Sum aggregation. +type FinishSum[N int64 | float64] struct { + Measure Measure[N] + ComputeAggregation ComputeAggregation + Finish func(attribute.Distinct, time.Time) + Shutdown func() +} + +type finishSum[N int64 | float64] struct { + collectMu sync.Mutex + shutdownOnce sync.Once + stopped atomic.Bool + + values limitedSyncMap[*finishSumValue[N]] + start time.Time + temporality metricdata.Temporality + monotonic bool + reservoir func(attribute.Set) FilteredExemplarReservoir[N] +} + +func newFinishSum[N int64 | float64]( + monotonic bool, + temporality metricdata.Temporality, + limit int, + reservoir func(attribute.Set) FilteredExemplarReservoir[N], +) *finishSum[N] { + var start time.Time + if temporality != metricdata.DeltaTemporality { + temporality = metricdata.CumulativeTemporality + } else { + start = now() + } + return &finishSum[N]{ + values: limitedSyncMap[*finishSumValue[N]]{ + aggLimit: limit, + }, + start: start, + temporality: temporality, + monotonic: monotonic, + reservoir: reservoir, + } +} + +func (s *finishSum[N]) measure( + ctx context.Context, + value N, + lazy lazyFilteredAttributes, +) { + for { + if s.stopped.Load() { + return + } + var initial finish.Measurement + point, loaded, overflowed := s.values.LoadOrStoreAttrReclaiming(lazy, func( + attrs attribute.Set, + overflow bool, + ) *finishSumValue[N] { + point := newFinishSumValue(attrs, s.reservoir) + // The point has not been published, so its new lifecycle cannot be + // retired and this initial measurement admission cannot fail. + if overflow { + initial, _ = point.lifecycle.AcquireSharedMeasurement() + } else { + initial, _ = point.lifecycle.AcquireMeasurement() + } + return point + }) + if !loaded { + point.measureAcquired(ctx, value, lazy, initial) + if s.stopped.Load() { + s.retireAndDelete(point) + } + return + } + if overflowed { + if point.measureOverflow(ctx, value, lazy) { + if s.stopped.Load() { + s.retireAndDelete(point) + } + return + } + continue + } + if point.measure(ctx, value, lazy) { + if s.stopped.Load() { + s.retireAndDelete(point) + } + return + } + s.values.CompareAndDelete(lazy.Distinct(), point) + } +} + +func (s *finishSum[N]) retireAndDelete(point *finishSumValue[N]) { + point.shutdown() + s.values.CompareAndDelete(point.attrs.Equivalent(), point) +} + +func (s *finishSum[N]) finish( + distinct attribute.Distinct, + t time.Time, +) { + if s.stopped.Load() { + return + } + value, ok := s.values.Load(distinct) + if !ok { + return + } + point := value.(*finishSumValue[N]) + point.finish(t) +} + +func (s *finishSum[N]) collect( + dest *metricdata.Aggregation, //nolint:gocritic // Required by ComputeAggregation. +) int { + s.collectMu.Lock() + defer s.collectMu.Unlock() + if s.stopped.Load() { + return 0 + } + + t := now() + start := s.start + if s.temporality == metricdata.DeltaTemporality { + s.start = t + } + sData, _ := (*dest).(metricdata.Sum[N]) + sData.Temporality = s.temporality + sData.IsMonotonic = s.monotonic + points := reset(sData.DataPoints, 0, s.values.Len()) + + s.values.Range(func(key, raw any) bool { + point := raw.(*finishSumValue[N]) + var dp metricdata.DataPoint[N] + var emit, retire bool + if s.temporality == metricdata.DeltaTemporality { + dp, emit, retire = point.collectDelta(start, t) + } else { + dp, emit, retire = point.collectCumulative(t) + } + if !emit { + return true + } + points = append(points, dp) + + if retire { + s.values.CompareAndDelete(key.(attribute.Distinct), point) + } + return true + }) + + sData.DataPoints = points + *dest = sData + return len(points) +} + +func (s *finishSum[N]) shutdown() { + s.shutdownOnce.Do(func() { + s.stopped.Store(true) + s.collectMu.Lock() + defer s.collectMu.Unlock() + s.values.Range(func(_, raw any) bool { + raw.(*finishSumValue[N]).shutdown() + return true + }) + s.values.Clear() + }) +} + +// FinishSum returns a Sum aggregation with exact-attribute lifecycle support. +func (b Builder[N]) FinishSum(monotonic bool) FinishSum[N] { + store := newFinishSum( + monotonic, + b.Temporality, + b.AggregationLimit, + b.resFunc(), + ) + return FinishSum[N]{ + Measure: b.filter(store.measure), + ComputeAggregation: store.collect, + Finish: store.finish, + Shutdown: store.shutdown, + } +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/histogram.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/histogram.go index 17807e11e4..152ae46ea1 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/histogram.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/histogram.go @@ -85,18 +85,8 @@ func (b *histogramPointCounters[N]) mergeIntoAndReset( // nolint:revive // Inten // deltaHistogram is a histogram whose internal storage is reset when it is // collected. -// -// deltaHistogram's measure is implemented without locking, even when called -// concurrently with collect. This is done by maintaining two separate maps: -// one "hot" which is concurrently updated by measure(), and one "cold", which -// is read and reset by collect(). The [hotcoldWaitGroup] allows collect() to -// swap the hot and cold maps, and wait for updates to the cold map to complete -// prior to reading. deltaHistogram swaps ald clears complete maps so that -// unused attribute sets do not report in subsequent collect() calls. type deltaHistogram[N int64 | float64] struct { - hcwg hotColdWaitGroup - hotColdValMap [2]limitedSyncMap[*histogramPoint[N]] - + vals hotColdMap[*histogramPoint[N]] start time.Time noMinMax bool noSum bool @@ -107,15 +97,15 @@ type deltaHistogram[N int64 | float64] struct { func (s *deltaHistogram[N]) measure( ctx context.Context, value N, - fltrAttr attribute.Set, - droppedAttr []attribute.KeyValue, + lazy lazyFilteredAttributes, ) { - hotIdx := s.hcwg.start() - defer s.hcwg.done(hotIdx) - h := s.hotColdValMap[hotIdx].LoadOrStoreAttr(fltrAttr, func(attr attribute.Set) *histogramPoint[N] { + hotIdx := s.vals.start() + defer s.vals.done(hotIdx) + + h := s.vals.hot(hotIdx).LoadOrStoreAttr(lazy, func(attr attribute.Set) *histogramPoint[N] { r := s.newRes(attr) _, isDrop := r.(*dropRes[N]) - hPt := &histogramPoint[N]{ + return &histogramPoint[N]{ res: r, attrs: attr, dropExemplars: isDrop, @@ -128,7 +118,6 @@ func (s *deltaHistogram[N]) measure( // counts = (-∞, 0], (0, 5.0], (5.0, 10.0], (10.0, +∞) histogramPointCounters: histogramPointCounters[N]{counts: make([]atomic.Uint64, len(s.bounds)+1)}, } - return hPt }) // This search will return an index in the range [0, len(s.bounds)], where @@ -145,7 +134,7 @@ func (s *deltaHistogram[N]) measure( h.total.add(value) } if !h.dropExemplars { - h.res.Offer(ctx, value, droppedAttr) + h.res.Offer(ctx, value, lazy) } } @@ -163,17 +152,15 @@ func newDeltaHistogram[N int64 | float64]( // complete control over the fix. b := slices.Clone(boundaries) slices.Sort(b) - return &deltaHistogram[N]{ + h := &deltaHistogram[N]{ start: now(), noMinMax: noMinMax, noSum: noSum, bounds: b, newRes: r, - hotColdValMap: [2]limitedSyncMap[*histogramPoint[N]]{ - {aggLimit: limit}, - {aggLimit: limit}, - }, } + h.vals.init(limit) + return h } func (s *deltaHistogram[N]) collect( @@ -187,20 +174,19 @@ func (s *deltaHistogram[N]) collect( h.Temporality = metricdata.DeltaTemporality // delta always clears values on collection - readIdx := s.hcwg.swapHotAndWait() + readIdx := s.vals.swapHotAndWait() // Do not allow modification of our copy of bounds. bounds := slices.Clone(s.bounds) // The len will not change while we iterate over values, since we waited // for all writes to finish to the cold values and len. - n := s.hotColdValMap[readIdx].Len() + n := s.vals.Len(readIdx) hDPts := reset(h.DataPoints, n, n) var i int - s.hotColdValMap[readIdx].Range(func(_, value any) bool { + s.vals.Range(readIdx, func(_, value any) bool { val := value.(*histogramPoint[N]) - count := val.loadCountsInto(&hDPts[i].BucketCounts) hDPts[i].Attributes = val.attrs hDPts[i].StartTime = s.start @@ -223,12 +209,12 @@ func (s *deltaHistogram[N]) collect( } collectExemplars(&hDPts[i].Exemplars, val.res.Collect) - i++ return true }) // Unused attribute sets do not report. - s.hotColdValMap[readIdx].Clear() + s.vals.Clear(readIdx) + // The delta collection cycle resets. s.start = t @@ -286,10 +272,9 @@ func newCumulativeHistogram[N int64 | float64]( func (s *cumulativeHistogram[N]) measure( ctx context.Context, value N, - fltrAttr attribute.Set, - droppedAttr []attribute.KeyValue, + lazy lazyFilteredAttributes, ) { - h := s.values.LoadOrStoreAttr(fltrAttr, func(attr attribute.Set) *hotColdHistogramPoint[N] { + h := s.values.LoadOrStoreAttr(lazy, func(attr attribute.Set) *hotColdHistogramPoint[N] { r := s.newRes(attr) _, isDrop := r.(*dropRes[N]) hPt := &hotColdHistogramPoint[N]{ @@ -334,7 +319,7 @@ func (s *cumulativeHistogram[N]) measure( h.hotColdPoint[hotIdx].total.add(value) } if !h.dropExemplars { - h.res.Offer(ctx, value, droppedAttr) + h.res.Offer(ctx, value, lazy) } } @@ -405,7 +390,7 @@ func (s *cumulativeHistogram[N]) collect( } // Once we've read the point, merge it back into the hot histogram // point since it is cumulative. - hotIdx := (readIdx + 1) % 2 + hotIdx := hotIdx((readIdx + 1) % 2) val.hotColdPoint[readIdx].mergeIntoAndReset(&val.hotColdPoint[hotIdx], s.noMinMax, s.noSum) collectExemplars(&dp.Exemplars, val.res.Collect) diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/lastvalue.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/lastvalue.go index 0fddc9dcc9..8c90143452 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/lastvalue.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/lastvalue.go @@ -21,19 +21,35 @@ type lastValuePoint[N int64 | float64] struct { dropExemplars bool } -// lastValueMap summarizes a set of measurements as the last one made. -type lastValueMap[N int64 | float64] struct { +func newDeltaLastValue[N int64 | float64]( + limit int, + r func(attribute.Set) FilteredExemplarReservoir[N], +) *deltaLastValue[N] { + s := &deltaLastValue[N]{ + newRes: r, + start: now(), + } + s.vals.init(limit) + return s +} + +// deltaLastValue summarizes a set of measurements as the last one made. +type deltaLastValue[N int64 | float64] struct { newRes func(attribute.Set) FilteredExemplarReservoir[N] - values limitedSyncMap[*lastValuePoint[N]] + start time.Time + + vals hotColdMap[*lastValuePoint[N]] } -func (s *lastValueMap[N]) measure( +func (s *deltaLastValue[N]) measure( ctx context.Context, value N, - fltrAttr attribute.Set, - droppedAttr []attribute.KeyValue, + lazy lazyFilteredAttributes, ) { - lv := s.values.LoadOrStoreAttr(fltrAttr, func(attr attribute.Set) *lastValuePoint[N] { + hotIdx := s.vals.start() + defer s.vals.done(hotIdx) + + lv := s.vals.hot(hotIdx).LoadOrStoreAttr(lazy, func(attr attribute.Set) *lastValuePoint[N] { r := s.newRes(attr) _, isDrop := r.(*dropRes[N]) p := &lastValuePoint[N]{ @@ -48,50 +64,10 @@ func (s *lastValueMap[N]) measure( lv.value.Store(value) if !lv.dropExemplars { - lv.res.Offer(ctx, value, droppedAttr) + lv.res.Offer(ctx, value, lazy) } } -func newDeltaLastValue[N int64 | float64]( - limit int, - r func(attribute.Set) FilteredExemplarReservoir[N], -) *deltaLastValue[N] { - return &deltaLastValue[N]{ - newRes: r, - start: now(), - hotColdValMap: [2]lastValueMap[N]{ - { - newRes: r, - values: limitedSyncMap[*lastValuePoint[N]]{aggLimit: limit}, - }, - { - newRes: r, - values: limitedSyncMap[*lastValuePoint[N]]{aggLimit: limit}, - }, - }, - } -} - -// deltaLastValue summarizes a set of measurements as the last one made. -type deltaLastValue[N int64 | float64] struct { - newRes func(attribute.Set) FilteredExemplarReservoir[N] - start time.Time - - hcwg hotColdWaitGroup - hotColdValMap [2]lastValueMap[N] -} - -func (s *deltaLastValue[N]) measure( - ctx context.Context, - value N, - fltrAttr attribute.Set, - droppedAttr []attribute.KeyValue, -) { - hotIdx := s.hcwg.start() - defer s.hcwg.done(hotIdx) - s.hotColdValMap[hotIdx].measure(ctx, value, fltrAttr, droppedAttr) -} - func (s *deltaLastValue[N]) collect( dest *metricdata.Aggregation, //nolint:gocritic // The pointer is needed for the ComputeAggregation interface ) int { @@ -112,14 +88,14 @@ func (s *deltaLastValue[N]) copyAndClearDpts( // the DataPoints is missed (better luck next time). gData, _ := (*dest).(metricdata.Gauge[N]) // delta always clears values on collection - readIdx := s.hcwg.swapHotAndWait() + readIdx := s.vals.swapHotAndWait() // The len will not change while we iterate over values, since we waited // for all writes to finish to the cold values and len. - n := s.hotColdValMap[readIdx].values.Len() + n := s.vals.Len(readIdx) dPts := reset(gData.DataPoints, n, n) var i int - s.hotColdValMap[readIdx].values.Range(func(_, value any) bool { + s.vals.Range(readIdx, func(_, value any) bool { v := value.(*lastValuePoint[N]) dPts[i].Attributes = v.attrs dPts[i].StartTime = s.start @@ -129,17 +105,19 @@ func (s *deltaLastValue[N]) copyAndClearDpts( i++ return true }) - gData.DataPoints = dPts // Do not report stale values. - s.hotColdValMap[readIdx].values.Clear() + s.vals.Clear(readIdx) + + gData.DataPoints = dPts *dest = gData return i } // cumulativeLastValue summarizes a set of measurements as the last one made. type cumulativeLastValue[N int64 | float64] struct { - lastValueMap[N] - start time.Time + values limitedSyncMap[*lastValuePoint[N]] + newRes func(attribute.Set) FilteredExemplarReservoir[N] + start time.Time } func newCumulativeLastValue[N int64 | float64]( @@ -147,11 +125,33 @@ func newCumulativeLastValue[N int64 | float64]( r func(attribute.Set) FilteredExemplarReservoir[N], ) *cumulativeLastValue[N] { return &cumulativeLastValue[N]{ - lastValueMap: lastValueMap[N]{ - newRes: r, - values: limitedSyncMap[*lastValuePoint[N]]{aggLimit: limit}, - }, - start: now(), + values: limitedSyncMap[*lastValuePoint[N]]{aggLimit: limit}, + newRes: r, + start: now(), + } +} + +func (s *cumulativeLastValue[N]) measure( + ctx context.Context, + value N, + lazy lazyFilteredAttributes, +) { + lv := s.values.LoadOrStoreAttr(lazy, func(attr attribute.Set) *lastValuePoint[N] { + r := s.newRes(attr) + _, isDrop := r.(*dropRes[N]) + p := &lastValuePoint[N]{ + res: r, + attrs: attr, + startTime: now(), + dropExemplars: isDrop, + } + p.value.Store(value) + return p + }) + + lv.value.Store(value) + if !lv.dropExemplars { + lv.res.Offer(ctx, value, lazy) } } diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/lazy_attributes.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/lazy_attributes.go new file mode 100644 index 0000000000..2fe8862470 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/lazy_attributes.go @@ -0,0 +1,146 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package aggregate + +import ( + "math/bits" + + "go.opentelemetry.io/otel/attribute" +) + +type lazyFilteredAttributes struct { + orig attribute.Set + distinct attribute.Distinct + mask uint64 // bitmask of kept attributes (bit i == 1 if kept) for len <= 64 + bigMask []bool // fallback decision slice for len > 64 + hasDropped bool +} + +// newLazyFilteredAttributes filters orig using filter and computes the distinct +// hash of the resulting attributes. The filter function is evaluated once per +// attribute during initialization, and kept attribute indices are recorded in a +// bitmask so subsequent Set and Dropped calls do not re-evaluate filter. +func newLazyFilteredAttributes(orig attribute.Set, filter attribute.Filter) lazyFilteredAttributes { + if filter == nil { + return lazyFilteredAttributes{ + orig: orig, + distinct: orig.Equivalent(), + } + } + l := lazyFilteredAttributes{orig: orig, hasDropped: true} + + n := orig.Len() + hasher := attribute.NewHasher() + keptCount := 0 + for i := range n { + kv, _ := orig.Get(i) + if filter(kv) { + hasher.Write(kv) + l.recordKept(i, keptCount, n) + keptCount++ + } + } + if keptCount == n { + l.hasDropped = false + l.mask = 0 + l.bigMask = nil + l.distinct = orig.Equivalent() + return l + } + keptBefore64 := bits.OnesCount64(l.mask) + if keptCount-keptBefore64 > 0 { + l.ensureBigMask(n, keptCount) + } + l.distinct = hasher.Distinct() + return l +} + +// recordKept marks index i as kept in the bitmask or fallback slice. +func (l *lazyFilteredAttributes) recordKept(i, keptCount, total int) { + if i < 64 { + l.mask |= uint64(1) << i + return + } + if l.bigMask == nil && keptCount < i { + l.ensureBigMask(total, keptCount) + } + if l.bigMask != nil { + l.bigMask[i] = true + } +} + +// ensureBigMask initializes the bigMask slice and backfills any attributes past +// index 63 that were kept before attributes were dropped. +func (l *lazyFilteredAttributes) ensureBigMask(total, keptCount int) { + if l.bigMask != nil { + return + } + l.bigMask = make([]bool, total) + keptBefore64 := bits.OnesCount64(l.mask) + for j := 64; j < 64+(keptCount-keptBefore64); j++ { + l.bigMask[j] = true + } +} + +// isKept reports whether the attribute at index i was kept by the filter. +func (l lazyFilteredAttributes) isKept(i int) bool { + if i < 64 { + return (l.mask & (uint64(1) << i)) != 0 + } + return i < len(l.bigMask) && l.bigMask[i] +} + +// Distinct returns the precomputed Distinct hash of the filtered attributes. +func (l lazyFilteredAttributes) Distinct() attribute.Distinct { + return l.distinct +} + +// HasDroppedAttributes reports whether the filter dropped any attributes. +func (l lazyFilteredAttributes) HasDroppedAttributes() bool { + return l.hasDropped +} + +// Set constructs the filtered attribute Set using the recorded bitmask. +func (l lazyFilteredAttributes) Set() attribute.Set { + if !l.hasDropped { + return l.orig + } + if l.mask == 0 && l.bigMask == nil { + return attribute.NewSet() + } + n := l.orig.Len() + var kept []attribute.KeyValue + for i := range n { + if l.isKept(i) { + if kept == nil { + kept = make([]attribute.KeyValue, 0, n) + } + kv, _ := l.orig.Get(i) + kept = append(kept, kv) + } + } + return attribute.NewSet(kept...) +} + +// Dropped constructs the dropped attribute slice using the recorded bitmask. +func (l lazyFilteredAttributes) Dropped() []attribute.KeyValue { + if !l.hasDropped { + return nil + } + if l.mask == 0 && l.bigMask == nil { + return l.orig.ToSlice() + } + n := l.orig.Len() + var dropped []attribute.KeyValue + for i := range n { + if !l.isKept(i) { + if dropped == nil { + dropped = make([]attribute.KeyValue, 0, n) + } + kv, _ := l.orig.Get(i) + dropped = append(dropped, kv) + } + } + return dropped +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/sum.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/sum.go index bee5ca3701..ed3530cff6 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/sum.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/aggregate/sum.go @@ -20,36 +20,6 @@ type sumValue[N int64 | float64] struct { dropExemplars bool } -type sumValueMap[N int64 | float64] struct { - newRes func(attribute.Set) FilteredExemplarReservoir[N] - values limitedSyncMap[*sumValue[N]] -} - -func (s *sumValueMap[N]) measure( - ctx context.Context, - value N, - fltrAttr attribute.Set, - droppedAttr []attribute.KeyValue, -) { - sv := s.values.LoadOrStoreAttr(fltrAttr, func(attr attribute.Set) *sumValue[N] { - r := s.newRes(attr) - _, isDrop := r.(*dropRes[N]) - return &sumValue[N]{ - res: r, - attrs: attr, - startTime: now(), - dropExemplars: isDrop, - } - }) - sv.n.add(value) - // It is possible for collection to race with measurement and observe the - // exemplar in the batch of metrics after the add() for cumulative sums. - // This is an accepted tradeoff to avoid locking during measurement. - if !sv.dropExemplars { - sv.res.Offer(ctx, value, droppedAttr) - } -} - // newDeltaSum returns an aggregator that summarizes a set of measurements as // their arithmetic sum. Each sum is scoped by attributes and the aggregation // cycle the measurements were made in. @@ -58,20 +28,13 @@ func newDeltaSum[N int64 | float64]( limit int, r func(attribute.Set) FilteredExemplarReservoir[N], ) *deltaSum[N] { - return &deltaSum[N]{ + s := &deltaSum[N]{ monotonic: monotonic, start: now(), - hotColdValMap: [2]sumValueMap[N]{ - { - newRes: r, - values: limitedSyncMap[*sumValue[N]]{aggLimit: limit}, - }, - { - newRes: r, - values: limitedSyncMap[*sumValue[N]]{aggLimit: limit}, - }, - }, + newRes: r, } + s.vals.init(limit) + return s } // deltaSum is the storage for sums which resets every collection interval. @@ -79,14 +42,28 @@ type deltaSum[N int64 | float64] struct { monotonic bool start time.Time - hcwg hotColdWaitGroup - hotColdValMap [2]sumValueMap[N] + vals hotColdMap[*sumValue[N]] + newRes func(attribute.Set) FilteredExemplarReservoir[N] } -func (s *deltaSum[N]) measure(ctx context.Context, value N, fltrAttr attribute.Set, droppedAttr []attribute.KeyValue) { - hotIdx := s.hcwg.start() - defer s.hcwg.done(hotIdx) - s.hotColdValMap[hotIdx].measure(ctx, value, fltrAttr, droppedAttr) +func (s *deltaSum[N]) measure(ctx context.Context, value N, lazy lazyFilteredAttributes) { + hotIdx := s.vals.start() + defer s.vals.done(hotIdx) + + sv := s.vals.hot(hotIdx).LoadOrStoreAttr(lazy, func(attr attribute.Set) *sumValue[N] { + r := s.newRes(attr) + _, isDrop := r.(*dropRes[N]) + return &sumValue[N]{ + res: r, + attrs: attr, + startTime: now(), + dropExemplars: isDrop, + } + }) + sv.n.add(value) + if !sv.dropExemplars { + sv.res.Offer(ctx, value, lazy) + } } func (s *deltaSum[N]) collect( @@ -101,14 +78,14 @@ func (s *deltaSum[N]) collect( sData.IsMonotonic = s.monotonic // delta always clears values on collection - readIdx := s.hcwg.swapHotAndWait() + readIdx := s.vals.swapHotAndWait() // The len will not change while we iterate over values, since we waited // for all writes to finish to the cold values and len. - n := s.hotColdValMap[readIdx].values.Len() + n := s.vals.Len(readIdx) dPts := reset(sData.DataPoints, n, n) var i int - s.hotColdValMap[readIdx].values.Range(func(_, value any) bool { + s.vals.Range(readIdx, func(_, value any) bool { val := value.(*sumValue[N]) collectExemplars(&dPts[i].Exemplars, val.res.Collect) dPts[i].Attributes = val.attrs @@ -118,7 +95,9 @@ func (s *deltaSum[N]) collect( i++ return true }) - s.hotColdValMap[readIdx].values.Clear() + // Unused attribute sets do not report. + s.vals.Clear(readIdx) + // The delta collection cycle resets. s.start = t @@ -139,19 +118,38 @@ func newCumulativeSum[N int64 | float64]( return &cumulativeSum[N]{ monotonic: monotonic, start: now(), - sumValueMap: sumValueMap[N]{ - newRes: r, - values: limitedSyncMap[*sumValue[N]]{aggLimit: limit}, - }, + values: limitedSyncMap[*sumValue[N]]{aggLimit: limit}, + newRes: r, } } -// deltaSum is the storage for sums which never reset. +// cumulativeSum is the storage for sums which never reset. type cumulativeSum[N int64 | float64] struct { monotonic bool start time.Time - sumValueMap[N] + values limitedSyncMap[*sumValue[N]] + newRes func(attribute.Set) FilteredExemplarReservoir[N] +} + +func (s *cumulativeSum[N]) measure(ctx context.Context, value N, lazy lazyFilteredAttributes) { + sv := s.values.LoadOrStoreAttr(lazy, func(attr attribute.Set) *sumValue[N] { + r := s.newRes(attr) + _, isDrop := r.(*dropRes[N]) + return &sumValue[N]{ + res: r, + attrs: attr, + startTime: now(), + dropExemplars: isDrop, + } + }) + sv.n.add(value) + // It is possible for collection to race with measurement and observe the + // exemplar in the batch of metrics after the add() for cumulative sums. + // This is an accepted tradeoff to avoid locking during measurement. + if !sv.dropExemplars { + sv.res.Offer(ctx, value, lazy) + } } func (s *cumulativeSum[N]) collect( @@ -210,7 +208,7 @@ func newPrecomputedSum[N int64 | float64]( r func(attribute.Set) FilteredExemplarReservoir[N], ) *precomputedSum[N] { return &precomputedSum[N]{ - deltaSum: newDeltaSum(monotonic, limit, r), + deltaSum: newDeltaSum[N](monotonic, limit, r), } } @@ -234,14 +232,14 @@ func (s *precomputedSum[N]) delta( sData.IsMonotonic = s.monotonic // delta always clears values on collection - readIdx := s.hcwg.swapHotAndWait() + readIdx := s.vals.swapHotAndWait() // The len will not change while we iterate over values, since we waited // for all writes to finish to the cold values and len. - n := s.hotColdValMap[readIdx].values.Len() + n := s.vals.Len(readIdx) dPts := reset(sData.DataPoints, n, n) var i int - s.hotColdValMap[readIdx].values.Range(func(key, value any) bool { + s.vals.Range(readIdx, func(key, value any) bool { val := value.(*sumValue[N]) n := val.n.load() @@ -255,7 +253,8 @@ func (s *precomputedSum[N]) delta( i++ return true }) - s.hotColdValMap[readIdx].values.Clear() + // Unused attribute sets do not report. + s.vals.Clear(readIdx) s.reported = newReported // The delta collection cycle resets. s.start = t @@ -278,14 +277,14 @@ func (s *precomputedSum[N]) cumulative( sData.IsMonotonic = s.monotonic // cumulative precomputed always clears values on collection - readIdx := s.hcwg.swapHotAndWait() + readIdx := s.vals.swapHotAndWait() // The len will not change while we iterate over values, since we waited // for all writes to finish to the cold values and len. - n := s.hotColdValMap[readIdx].values.Len() + n := s.vals.Len(readIdx) dPts := reset(sData.DataPoints, n, n) var i int - s.hotColdValMap[readIdx].values.Range(func(_, value any) bool { + s.vals.Range(readIdx, func(_, value any) bool { val := value.(*sumValue[N]) collectExemplars(&dPts[i].Exemplars, val.res.Collect) dPts[i].Attributes = val.attrs @@ -295,7 +294,8 @@ func (s *precomputedSum[N]) cumulative( i++ return true }) - s.hotColdValMap[readIdx].values.Clear() + // Unused attribute sets do not report. + s.vals.Clear(readIdx) sData.DataPoints = dPts *dest = sData diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/attrnorm/dedup.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/attrnorm/dedup.go index fe9ddc96db..3e183f5576 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/attrnorm/dedup.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/attrnorm/dedup.go @@ -28,40 +28,43 @@ type rawValue struct { slice any } -// Value returns value with all map values deduplicated and whether it changed. +// ValueDedup returns value with all map values deduplicated and whether +// it changed. // // Duplicate map keys are resolved using last-value-wins semantics. -func Value(value attribute.Value) (attribute.Value, bool) { +func ValueDedup(value attribute.Value) (attribute.Value, bool) { switch value.Type() { case attribute.SLICE: - return deduplicateSliceValue(value) + return sliceValueDedup(value) case attribute.MAP: - return deduplicateMapValue(value) + return mapValueDedup(value) default: return value, false } } -// KeyValue returns kv with all map values deduplicated and whether it changed. -func KeyValue(kv attribute.KeyValue) (attribute.KeyValue, bool) { - value, changed := Value(kv.Value) +// KeyValueDedup returns kv with all map values deduplicated and whether +// it changed. +func KeyValueDedup(kv attribute.KeyValue) (attribute.KeyValue, bool) { + value, changed := ValueDedup(kv.Value) if changed { kv.Value = value } return kv, changed } -// KeyValues returns kvs with all map values deduplicated and whether they changed. +// KeyValuesDedup returns kvs with all map values deduplicated and whether +// they changed. // // The returned slice is the original kvs slice if no value needs // deduplication. Top-level keys in kvs are not deduplicated. -func KeyValues(kvs []attribute.KeyValue) ([]attribute.KeyValue, bool) { +func KeyValuesDedup(kvs []attribute.KeyValue) ([]attribute.KeyValue, bool) { // Preserve the caller's slice on the common no-op path. Once a changed // value is found, copy the prior values exactly once and fill the rest in // place as the scan continues. var normalized []attribute.KeyValue for i, kv := range kvs { - kv, changed := KeyValue(kv) + kv, changed := KeyValueDedup(kv) if normalized != nil { normalized[i] = kv continue @@ -80,22 +83,24 @@ func KeyValues(kvs []attribute.KeyValue) ([]attribute.KeyValue, bool) { return normalized, true } -// Set returns set with all map values deduplicated and whether it changed. +// SetDedup returns set with all map values deduplicated and whether it +// changed. // // The returned Set is the original set if no value needs deduplication. // Top-level key uniqueness remains attribute.Set's responsibility; this only // normalizes map attribute values. -func Set(set attribute.Set) (attribute.Set, bool) { - if set.Len() == 0 { +func SetDedup(set attribute.Set) (attribute.Set, bool) { + length := set.Len() + if length == 0 { return set, false } // Most attribute sets contain no duplicate map keys. Delay allocation until // the first changed value so the no-op path returns the original Set. var normalized []attribute.KeyValue - for i := range set.Len() { + for i := range length { kv, _ := set.Get(i) - kv, changed := KeyValue(kv) + kv, changed := KeyValueDedup(kv) if normalized != nil { normalized = append(normalized, kv) continue @@ -104,7 +109,7 @@ func Set(set attribute.Set) (attribute.Set, bool) { continue } - normalized = make([]attribute.KeyValue, 0, set.Len()) + normalized = make([]attribute.KeyValue, 0, length) for j := range i { prior, _ := set.Get(j) normalized = append(normalized, prior) @@ -118,7 +123,7 @@ func Set(set attribute.Set) (attribute.Set, bool) { return attribute.NewSet(normalized...), true } -func deduplicateSliceValue(value attribute.Value) (attribute.Value, bool) { +func sliceValueDedup(value attribute.Value) (attribute.Value, bool) { storage := valueStorage(value) length := valueLen(storage) @@ -127,7 +132,7 @@ func deduplicateSliceValue(value attribute.Value) (attribute.Value, bool) { var normalized []attribute.Value for i := range length { elem := valueAt(storage, i) - elem, changed := Value(elem) + elem, changed := ValueDedup(elem) if normalized != nil { normalized[i] = elem continue @@ -148,14 +153,14 @@ func deduplicateSliceValue(value attribute.Value) (attribute.Value, bool) { return attribute.SliceValue(normalized...), true } -func deduplicateMapValue(value attribute.Value) (attribute.Value, bool) { +func mapValueDedup(value attribute.Value) (attribute.Value, bool) { storage := valueStorage(value) length := keyValueLen(storage) if length <= 1 { // A single map entry cannot duplicate its own key, but its value might // contain a map or slice that needs recursive normalization. if length == 1 { - kv, changed := KeyValue(keyValueAt(storage, 0)) + kv, changed := KeyValueDedup(keyValueAt(storage, 0)) if changed { return attribute.MapValue(kv), true } @@ -174,13 +179,16 @@ func deduplicateMapValue(value attribute.Value) (attribute.Value, bool) { j++ } - kv, nestedChanged := KeyValue(keyValueAt(storage, j-1)) + kv, nestedChanged := KeyValueDedup(keyValueAt(storage, j-1)) // j-i > 1 means the current key run contained duplicates. changed := nestedChanged || j-i > 1 if normalized != nil { normalized = append(normalized, kv) } else if changed { - normalized = make([]attribute.KeyValue, 0, length) + if i == 0 && j == length { + return attribute.MapValue(kv), true + } + normalized = make([]attribute.KeyValue, 0, length-(j-i-1)) for k := range i { normalized = append(normalized, keyValueAt(storage, k)) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/attrnorm/distinct.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/attrnorm/distinct.go new file mode 100644 index 0000000000..2bfc243da7 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/attrnorm/distinct.go @@ -0,0 +1,110 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package attrnorm + +import ( + "cmp" + "slices" + + "go.opentelemetry.io/otel/attribute" +) + +// stackAttributes is the maximum number of unordered attributes copied to a +// stack buffer for canonicalization. Larger inputs use an allocated copy to +// keep sorting time bounded without modifying caller-owned attributes. +const stackAttributes = 10 + +// NewDistinct returns the identity of kvs after normalization and filtering. +// It does not retain or modify kvs. Duplicate keys use the last value supplied. +// The filter is called once for each unique normalized attribute in ascending +// key order. +func NewDistinct(kvs []attribute.KeyValue, filter attribute.Filter) attribute.Distinct { + if filter == nil { + if distinct, ok := tryUnfilteredDistinct(kvs); ok { + return distinct + } + } else if ordered(kvs) { + return orderedDistinct(kvs, filter) + } + if len(kvs) <= stackAttributes { + return sortedDistinct(kvs, filter) + } + return allocatedDistinct(kvs, filter) +} + +// tryUnfilteredDistinct hashes kvs while verifying their keys are ordered. The +// partial hash is discarded if an out-of-order key is found. +func tryUnfilteredDistinct(kvs []attribute.KeyValue) (attribute.Distinct, bool) { + hasher := attribute.NewHasher() + if len(kvs) == 0 { + return hasher.Distinct(), true + } + + // pending identifies the last value seen for the current key. + pending := 0 + for i := 1; i < len(kvs); i++ { + if kvs[i].Key < kvs[pending].Key { + return attribute.Distinct{}, false + } + if kvs[i].Key == kvs[pending].Key { + pending = i + continue + } + + normalized, _ := KeyValueDedup(kvs[pending]) + hasher.Write(normalized) + pending = i + } + + normalized, _ := KeyValueDedup(kvs[pending]) + hasher.Write(normalized) + return hasher.Distinct(), true +} + +// Keep this direct loop instead of slices.IsSortedFunc. It only needs a +// greater-than comparison and benchmarks faster for typical attribute counts. +func ordered(kvs []attribute.KeyValue) bool { + for i := 1; i < len(kvs); i++ { + if kvs[i-1].Key > kvs[i].Key { + return false + } + } + return true +} + +// orderedDistinct hashes key-values whose keys are in ascending order. Equal +// keys remain in input order so selecting the last retains last-value-wins. +func orderedDistinct(kvs []attribute.KeyValue, filter attribute.Filter) attribute.Distinct { + hasher := attribute.NewHasher() + for i := 0; i < len(kvs); { + j := i + 1 + for j < len(kvs) && kvs[j].Key == kvs[i].Key { + j++ + } + kv, _ := KeyValueDedup(kvs[j-1]) + if filter == nil || filter(kv) { + hasher.Write(kv) + } + i = j + } + return hasher.Distinct() +} + +func sortedDistinct(kvs []attribute.KeyValue, filter attribute.Filter) attribute.Distinct { + var scratch [stackAttributes]attribute.KeyValue + cpy := scratch[:len(kvs)] + copy(cpy, kvs) + return sortDistinct(cpy, filter) +} + +func allocatedDistinct(kvs []attribute.KeyValue, filter attribute.Filter) attribute.Distinct { + return sortDistinct(slices.Clone(kvs), filter) +} + +func sortDistinct(kvs []attribute.KeyValue, filter attribute.Filter) attribute.Distinct { + slices.SortStableFunc(kvs, func(a, b attribute.KeyValue) int { + return cmp.Compare(a.Key, b.Key) + }) + return orderedDistinct(kvs, filter) +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/finish/doc.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/finish/doc.go new file mode 100644 index 0000000000..7dcd373701 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/finish/doc.go @@ -0,0 +1,5 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package finish coordinates the lifecycle of finish-aware metric series. +package finish diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/finish/lifecycle.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/finish/lifecycle.go new file mode 100644 index 0000000000..2638fc77dd --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/finish/lifecycle.go @@ -0,0 +1,253 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package finish + +import ( + "runtime" + "sync" + "sync/atomic" + "time" +) + +type lifecycleState uint32 + +const ( + lifecycleActive lifecycleState = iota + lifecycleShared + lifecycleFinishPending + lifecycleRetired + lifecycleCollecting +) + +// Lifecycle coordinates measurements, explicit finishes, collections, and +// retirement for one metric series. Its zero value is ready for use. +// +// Lifecycle methods are safe to call concurrently. A successful measurement +// acquisition and an emitted collection must each be completed exactly once. +// A Lifecycle must not be copied after first use. +// +// The valid transitions are active to finish-pending on Finish, active or +// finish-pending to shared on a shared measurement, finish-pending to active on +// an ordinary measurement, any non-retired state to collecting on collection, +// and collecting to its prior state or retired when collection completes. +// Shared lifetimes ignore Finish. Retired is terminal. +type Lifecycle struct { + control sync.Mutex + state atomic.Uint32 + writers atomic.Uint64 + // finished is meaningful only while a pending finish is being collected. + // Reactivation leaves the old value in place so measurements remain lock-free. + finished time.Time +} + +// Measurement represents admission to update one metric-series lifetime. A +// successful call to Lifecycle.AcquireMeasurement returns a Measurement, which +// must be released exactly once after the aggregate and exemplars are updated. +type Measurement struct { + lifecycle *Lifecycle +} + +// Release completes the admitted measurement. +func (m Measurement) Release() { + m.lifecycle.releaseMeasurement() +} + +// Collection describes an exclusive collection phase for a metric-series +// lifetime. A Collection returned with true by a Lifecycle collection method +// must be completed exactly once after the aggregate and exemplars are read. +type Collection struct { + lifecycle *Lifecycle + time time.Time + restore lifecycleState + retire bool +} + +// Time returns the timestamp to use for the collected point. +func (c Collection) Time() time.Time { + return c.time +} + +// ShouldRetire reports whether Complete will retire the series lifetime. +func (c Collection) ShouldRetire() bool { + return c.retire +} + +// Complete ends the exclusive collection phase. It must be called exactly once. +func (c Collection) Complete() { + state := c.restore + if c.retire { + state = lifecycleRetired + } + c.lifecycle.finished = time.Time{} + c.lifecycle.state.Store(uint32(state)) + c.lifecycle.control.Unlock() +} + +// AcquireMeasurement reserves this series lifetime for a measurement. It waits +// for an in-progress collection and returns false only if the lifetime is +// retired. A successful acquisition must be paired with exactly one call to +// Measurement.Release after the aggregate and exemplars are updated. +func (l *Lifecycle) AcquireMeasurement() (Measurement, bool) { + for { + // Increment before checking state so a collection either waits for this + // attempt or closes admission before the attempt can update the aggregate. + l.writers.Add(1) + switch lifecycleState(l.state.Load()) { + case lifecycleActive, lifecycleShared: + return Measurement{lifecycle: l}, true + case lifecycleFinishPending: + if l.state.CompareAndSwap( + uint32(lifecycleFinishPending), + uint32(lifecycleActive), + ) { + return Measurement{lifecycle: l}, true + } + l.releaseMeasurement() + case lifecycleCollecting: + l.releaseMeasurement() + l.waitForCollection() + case lifecycleRetired: + l.releaseMeasurement() + return Measurement{}, false + } + } +} + +// AcquireSharedMeasurement reserves this series lifetime for a measurement and +// atomically makes the lifetime shared. A shared lifetime cannot be finished. +// It waits for an in-progress collection and returns false only if the lifetime +// is retired. A successful acquisition must be paired with exactly one call to +// Measurement.Release after the aggregate and exemplars are updated. +func (l *Lifecycle) AcquireSharedMeasurement() (Measurement, bool) { + for { + // Increment before checking state so a collection either waits for this + // attempt or closes admission before the attempt can update the aggregate. + l.writers.Add(1) + switch lifecycleState(l.state.Load()) { + case lifecycleShared: + return Measurement{lifecycle: l}, true + case lifecycleActive: + if l.state.CompareAndSwap( + uint32(lifecycleActive), + uint32(lifecycleShared), + ) { + return Measurement{lifecycle: l}, true + } + l.releaseMeasurement() + case lifecycleFinishPending: + if l.state.CompareAndSwap( + uint32(lifecycleFinishPending), + uint32(lifecycleShared), + ) { + return Measurement{lifecycle: l}, true + } + l.releaseMeasurement() + case lifecycleCollecting: + l.releaseMeasurement() + l.waitForCollection() + case lifecycleRetired: + l.releaseMeasurement() + return Measurement{}, false + } + } +} + +func (l *Lifecycle) waitForCollection() { + l.control.Lock() + l.control.Unlock() //nolint:gocritic,staticcheck // Lock acquisition parks until collection completes. +} + +func (l *Lifecycle) releaseMeasurement() { + // atomic.Uint64 has no subtraction operation. Adding MaxUint64 decrements + // the writer count modulo 2^64. A matching acquisition guarantees the count + // is nonzero. + l.writers.Add(^uint64(0)) +} + +// Finish marks an active series lifetime to be retired by its next collection +// at the supplied time. It returns false if the lifetime is already pending, +// shared, collecting, or retired. A measurement admitted after Finish +// reactivates the lifetime. +func (l *Lifecycle) Finish(at time.Time) bool { + l.control.Lock() + defer l.control.Unlock() + if !l.state.CompareAndSwap( + uint32(lifecycleActive), + uint32(lifecycleFinishPending), + ) { + return false + } + // Collection also holds control, so it cannot observe finish-pending before + // its timestamp is available. A concurrent measurement may reactivate or + // share the lifetime; in that case the timestamp is intentionally ignored. + l.finished = at + return true +} + +// BeginCumulativeCollection closes measurement admission and waits for admitted +// measurements to complete. An active or shared lifetime returns to its prior +// state when the returned Collection is completed; a finish-pending lifetime is +// retired. It returns false without a Collection if the lifetime is retired. A +// returned Collection must be completed exactly once. +func (l *Lifecycle) BeginCumulativeCollection(at time.Time) (Collection, bool) { + l.control.Lock() + collection, ok := l.beginCollection(at) + if !ok { + l.control.Unlock() + } + return collection, ok +} + +// BeginDeltaCollection closes measurement admission and waits for admitted +// measurements to complete. Every emitted lifetime is retired when the returned +// Collection is completed. It returns false without a Collection if the +// lifetime is retired. A returned Collection must be completed exactly once. +func (l *Lifecycle) BeginDeltaCollection(at time.Time) (Collection, bool) { + l.control.Lock() + collection, ok := l.beginCollection(at) + if !ok { + l.control.Unlock() + return Collection{}, false + } + collection.retire = true + return collection, true +} + +func (l *Lifecycle) beginCollection(at time.Time) (Collection, bool) { + state := lifecycleState(l.state.Load()) + if state == lifecycleRetired { + return Collection{}, false + } + state = lifecycleState(l.state.Swap(uint32(lifecycleCollecting))) + for l.writers.Load() != 0 { + runtime.Gosched() + } + + if state == lifecycleFinishPending { + return Collection{ + lifecycle: l, + time: l.finished, + restore: state, + retire: true, + }, true + } + return Collection{lifecycle: l, time: at, restore: state}, true +} + +// Retire permanently closes the series lifetime. It waits for admitted +// measurements to complete and has no effect if the lifetime is already +// retired. +func (l *Lifecycle) Retire() { + l.control.Lock() + defer l.control.Unlock() + if lifecycleState(l.state.Load()) == lifecycleRetired { + return + } + l.state.Store(uint32(lifecycleCollecting)) + for l.writers.Load() != 0 { + runtime.Gosched() + } + l.finished = time.Time{} + l.state.Store(uint32(lifecycleRetired)) +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/x/README.md b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/x/README.md deleted file mode 100644 index 41a4c29969..0000000000 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/x/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Experimental Features - -The Metric SDK contains features that have not yet stabilized in the OpenTelemetry specification. -These features are added to the OpenTelemetry Go Metric SDK prior to stabilization in the specification so that users can start experimenting with them and provide feedback. - -These feature may change in backwards incompatible ways as feedback is applied. -See the [Compatibility and Stability](#compatibility-and-stability) section for more information. - -## Features - -- [Metric Export Batch Size](#metric-export-batch-size) - -### Metric Export Batch Size - -The metric export can be split into batches before exporting by specifying a maximum number of data points per batch. - -This experimental feature can be enabled by setting the `OTEL_GO_X_METRIC_EXPORT_BATCH_SIZE` environment variable. -The value MUST be a positive integer. -All other values or an empty value will result in the default behavior of not batching. - -#### Examples - -Enable metrics to be batched by maximum export batch size of 200. - -```console -export OTEL_GO_X_METRIC_EXPORT_BATCH_SIZE=200 -``` - -Disable metric export batching. - -```console -unset OTEL_GO_X_METRIC_EXPORT_BATCH_SIZE -``` - -## Compatibility and Stability - -Experimental features do not fall within the scope of the OpenTelemetry Go versioning and stability [policy](../../../../VERSIONING.md). -These features may be removed or modified in successive version releases, including patch versions. - -When an experimental feature is promoted to a stable feature, a migration path will be included in the changelog entry of the release. -There is no guarantee that any environment variable feature flags that enabled the experimental feature will be supported by the stable version. -If they are supported, they may be accompanied with a deprecation notice stating a timeline for the removal of that support. diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/x/features.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/x/features.go deleted file mode 100644 index a8268702a6..0000000000 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/x/features.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package x - -import "strconv" - -// MetricExportBatchSize is an experimental feature flag that controls the -// max export batch size for metric data. -// -// To enable this feature set the OTEL_GO_X_METRIC_EXPORT_BATCH_SIZE environment -// variable to a positive integer value. -var MetricExportBatchSize = newFeature( - []string{"METRIC_EXPORT_BATCH_SIZE"}, - func(v string) (int, bool) { - val, err := strconv.Atoi(v) - if err == nil && val > 0 { - return val, true - } - return 0, false - }, -) diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/x/x.go b/vendor/go.opentelemetry.io/otel/sdk/metric/internal/x/x.go deleted file mode 100644 index f501984ae5..0000000000 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/internal/x/x.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// DO NOT MODIFY. Generated by gotmpl. -// source: internal/shared/x/x.go.tmpl - -// Package x documents experimental features for [go.opentelemetry.io/otel/sdk/metric]. -package x - -import ( - "os" -) - -// Feature is an experimental feature control flag. It provides a uniform way -// to interact with these feature flags and parse their values. -type Feature[T any] struct { - keys []string - parse func(v string) (T, bool) -} - -func newFeature[T any](suffix []string, parse func(string) (T, bool)) Feature[T] { - const envKeyRoot = "OTEL_GO_X_" - keys := make([]string, 0, len(suffix)) - for _, s := range suffix { - keys = append(keys, envKeyRoot+s) - } - return Feature[T]{ - keys: keys, - parse: parse, - } -} - -// Keys returns the environment variable keys that can be set to enable the -// feature. -func (f Feature[T]) Keys() []string { return f.keys } - -// Lookup returns the user configured value for the feature and true if the -// user has enabled the feature. Otherwise, if the feature is not enabled, a -// zero-value and false are returned. -func (f Feature[T]) Lookup() (v T, ok bool) { - // https://github.com/open-telemetry/opentelemetry-specification/blob/62effed618589a0bec416a87e559c0a9d96289bb/specification/configuration/sdk-environment-variables.md#parsing-empty-value - // - // > The SDK MUST interpret an empty value of an environment variable the - // > same way as when the variable is unset. - for _, key := range f.keys { - vRaw := os.Getenv(key) - if vRaw != "" { - return f.parse(vRaw) - } - } - return v, ok -} - -// Enabled reports whether the feature is enabled. -func (f Feature[T]) Enabled() bool { - _, ok := f.Lookup() - return ok -} diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/metricdata/data.go b/vendor/go.opentelemetry.io/otel/sdk/metric/metricdata/data.go index 1caed336e9..3155a22bbe 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/metricdata/data.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/metricdata/data.go @@ -190,7 +190,7 @@ type ExponentialHistogramDataPoint[N int64 | float64] struct { type ExponentialBucket struct { // Offset is the bucket index of the first entry in the Counts slice. Offset int32 - // Counts is an slice where Counts[i] carries the count of the bucket at + // Counts is a slice where Counts[i] carries the count of the bucket at // index (Offset+i). Counts[i] is the count of values greater than // base^(Offset+i) and less than or equal to base^(Offset+i+1). Counts []uint64 diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/periodic_reader.go b/vendor/go.opentelemetry.io/otel/sdk/metric/periodic_reader.go index 9f7712bd51..9405959c65 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/periodic_reader.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/periodic_reader.go @@ -14,7 +14,6 @@ import ( "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/internal/global" "go.opentelemetry.io/otel/sdk/metric/internal/observ" - "go.opentelemetry.io/otel/sdk/metric/internal/x" "go.opentelemetry.io/otel/sdk/metric/metricdata" semconv "go.opentelemetry.io/otel/semconv/v1.43.0" ) @@ -29,6 +28,7 @@ const ( type periodicReaderConfig struct { interval time.Duration timeout time.Duration + maxExportBatchSize int producers []Producer cardinalityLimitSelector CardinalityLimitSelector } @@ -99,6 +99,21 @@ func WithInterval(d time.Duration) PeriodicReaderOption { }) } +// WithMaxExportBatchSize configures the maximum number of metric data points in +// a batch that are exported at once. +// +// If this option is not used or size is less than or equal to zero, no limit is +// applied. +func WithMaxExportBatchSize(size int) PeriodicReaderOption { + return periodicReaderOptionFunc(func(conf periodicReaderConfig) periodicReaderConfig { + if size <= 0 { + return conf + } + conf.maxExportBatchSize = size + return conf + }) +} + // NewPeriodicReader returns a Reader that collects and exports metric data to // the exporter at a defined interval. By default, the returned Reader will // collect and export data every 60 seconds, and will cancel any attempts that @@ -116,6 +131,7 @@ func NewPeriodicReader(exporter Exporter, options ...PeriodicReaderOption) *Peri r := &PeriodicReader{ interval: conf.interval, timeout: conf.timeout, + batcher: batcher{size: conf.maxExportBatchSize}, exporter: exporter, flushCh: make(chan chan error), cancel: cancel, @@ -127,16 +143,8 @@ func NewPeriodicReader(exporter Exporter, options ...PeriodicReaderOption) *Peri }, }, } - if val, ok := x.MetricExportBatchSize.Lookup(); ok { - r.batcher = batcher{size: val} - } r.externalProducers.Store(conf.producers) - go func() { - defer func() { close(r.done) }() - r.run(ctx, conf.interval) - }() - var err error r.inst, err = observ.NewInstrumentation( semconv.OTelComponentTypePeriodicMetricReader.Value.AsString(), @@ -146,6 +154,11 @@ func NewPeriodicReader(exporter Exporter, options ...PeriodicReaderOption) *Peri otel.Handle(err) } + go func() { + defer func() { close(r.done) }() + r.run(ctx, conf.interval) + }() + return r } diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/pipeline.go b/vendor/go.opentelemetry.io/otel/sdk/metric/pipeline.go index f04c2ddcec..af705ea919 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/pipeline.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/pipeline.go @@ -255,7 +255,7 @@ func (i *inserter[N]) Instrument( continue } matched = true - in, id, e := i.cachedAggregator(inst.Scope, inst.Kind, stream, readerAggregation) + in, id, e := i.cachedAggregator(inst.Scope, inst.Kind, stream, allowedKeys, readerAggregation) if e != nil { err = errors.Join(err, e) } @@ -284,13 +284,7 @@ func (i *inserter[N]) Instrument( Description: inst.Description, Unit: inst.Unit, } - // allowedKeys == nil indicates that the WithDefaultAttributes option was not passed, - // and all keys are allowed. An empty (non-nil) slice indicates that the option was passed - // with an empty set of keys, and no keys are allowed. - if allowedKeys != nil { - stream.AttributeFilter = attribute.NewAllowKeysFilter(allowedKeys...) - } - in, _, e := i.cachedAggregator(inst.Scope, inst.Kind, stream, readerAggregation) + in, _, e := i.cachedAggregator(inst.Scope, inst.Kind, stream, allowedKeys, readerAggregation) if e != nil { if err == nil { err = errCreatingAggregators @@ -364,6 +358,7 @@ func (i *inserter[N]) cachedAggregator( scope instrumentation.Scope, kind InstrumentKind, stream Stream, + allowedKeys []attribute.Key, readerAggregation Aggregation, ) (meas aggregate.Measure[N], aggID uint64, err error) { switch stream.Aggregation.(type) { @@ -378,6 +373,14 @@ func (i *inserter[N]) cachedAggregator( if stream.ExemplarReservoirProviderSelector == nil { stream.ExemplarReservoirProviderSelector = DefaultExemplarReservoirProviderSelector } + // If attribute_keys is not provided on the view (AttributeFilter == nil), + // use the advisory Attributes configured on the instrument (allowedKeys). + // allowedKeys == nil indicates that the WithDefaultAttributes option was not passed, + // and all keys are allowed. An empty (non-nil) slice indicates that the option was passed + // with an empty set of keys, and no keys are allowed. + if stream.AttributeFilter == nil && allowedKeys != nil { + stream.AttributeFilter = attribute.NewAllowKeysFilter(allowedKeys...) + } if err := isAggregatorCompatible(kind, stream.Aggregation); err != nil { return nil, 0, fmt.Errorf( diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/provider.go b/vendor/go.opentelemetry.io/otel/sdk/metric/provider.go index 9f9f01f432..2a9f29ac2d 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/provider.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/provider.go @@ -77,7 +77,7 @@ func (mp *MeterProvider) Meter(name string, options ...metric.MeterOption) metri } c := metric.NewMeterConfig(options...) - attrs, _ := attrnorm.Set(c.InstrumentationAttributes()) + attrs, _ := attrnorm.SetDedup(c.InstrumentationAttributes()) s := instrumentation.Scope{ Name: name, Version: c.InstrumentationVersion(), diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/version.go b/vendor/go.opentelemetry.io/otel/sdk/metric/version.go index 4c1cd75e2c..2310096801 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/version.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/version.go @@ -5,5 +5,5 @@ package metric // version is the current release version of the metric SDK in use. func version() string { - return "1.45.0" + return "1.47.0" } diff --git a/vendor/go.opentelemetry.io/otel/sdk/metric/view.go b/vendor/go.opentelemetry.io/otel/sdk/metric/view.go index 3f98928f96..62ee9727a5 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/metric/view.go +++ b/vendor/go.opentelemetry.io/otel/sdk/metric/view.go @@ -44,7 +44,7 @@ type View func(Instrument) (Stream, bool) // the Instrument the View matches against will be use for the Name, // Description, and Unit of the returned Stream and no Aggregation or // AttributeFilter are set. All non-zero-value fields of mask are used instead -// of the default. If you need to zero out an Stream field returned from a +// of the default. If you need to zero out a Stream field returned from a // View, create a View directly. func NewView(criteria Instrument, mask Stream) View { if criteria.IsEmpty() { diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go b/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go index 68ab274d2f..1ab929a3ab 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go @@ -90,7 +90,7 @@ func NewSchemaless(attrs ...attribute.KeyValue) *Resource { return &Resource{} } - attrs, _ = attrnorm.KeyValues(attrs) + attrs, _ = attrnorm.KeyValuesDedup(attrs) // Ensure attributes comply with the specification: // https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/common/README.md#attribute @@ -120,6 +120,9 @@ func (r *Resource) String() string { // MarshalLog is the marshaling function used by the logging system to represent this Resource. func (r *Resource) MarshalLog() any { + if r == nil { + r = Empty() + } return struct { Attributes attribute.Set SchemaURL string diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/batch_span_processor.go b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/batch_span_processor.go index 896ed517f0..b55750a844 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/batch_span_processor.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/batch_span_processor.go @@ -47,6 +47,8 @@ type BSP struct { processedQueueFullOpts []metric.AddOption } +// NewBSP creates new instrumentation for a BatchSpanProcessor. +// It returns nil if observability is not enabled. func NewBSP(id int64, qLen func() int64, qMax int64) (*BSP, error) { if !x.Observability.Enabled() { return nil, nil @@ -108,12 +110,16 @@ func NewBSP(id int64, qLen func() int64, qMax int64) (*BSP, error) { }, err } +// Shutdown unregisters the callbacks registered by NewBSP. func (b *BSP) Shutdown() error { return b.reg.Unregister() } +// Processed records n spans as having finished processing successfully. func (b *BSP) Processed(ctx context.Context, n int64) { b.processed.Add(ctx, n, b.processedOpts...) } +// ProcessedQueueFull records n spans as having finished processing with a +// queue-full error. func (b *BSP) ProcessedQueueFull(ctx context.Context, n int64) { b.processed.Add(ctx, n, b.processedQueueFullOpts...) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/simple_span_processor.go b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/simple_span_processor.go index 89922e4b80..e7ca1a6d97 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/simple_span_processor.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/simple_span_processor.go @@ -6,7 +6,6 @@ package observ import ( "context" "fmt" - "sync" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" @@ -17,22 +16,10 @@ import ( "go.opentelemetry.io/otel/semconv/v1.43.0/otelconv" ) -var measureAttrsPool = sync.Pool{ - New: func() any { - // "component.name" + "component.type" + "error.type" - const n = 1 + 1 + 1 - s := make([]attribute.KeyValue, 0, n) - // Return a pointer to a slice instead of a slice itself - // to avoid allocations on every call. - return &s - }, -} - // SSP is the instrumentation for an OTel SDK SimpleSpanProcessor. type SSP struct { spansProcessedCounter metric.Int64Counter addOpts []metric.AddOption - attrs []attribute.KeyValue } // SSPComponentName returns the component name attribute for a @@ -70,29 +57,12 @@ func NewSSP(id int64) (*SSP, error) { return &SSP{ spansProcessedCounter: spansProcessedCounter.Inst(), addOpts: addOpts, - attrs: attrs, }, err } -// SpanProcessed records that a span has been processed by the SimpleSpanProcessor. -// If err is non-nil, it records the processing error as an attribute. -func (ssp *SSP) SpanProcessed(ctx context.Context, err error) { - ssp.spansProcessedCounter.Add(ctx, 1, ssp.addOption(err)...) -} - -func (ssp *SSP) addOption(err error) []metric.AddOption { - if err == nil { - return ssp.addOpts - } - attrs := measureAttrsPool.Get().(*[]attribute.KeyValue) - defer func() { - clear(*attrs) - *attrs = (*attrs)[:0] // reset the slice for reuse - measureAttrsPool.Put(attrs) - }() - *attrs = append(*attrs, ssp.attrs...) - *attrs = append(*attrs, semconv.ErrorType(err)) - // Do not inefficiently make a copy of attrs by using - // WithAttributes instead of WithAttributeSet. - return []metric.AddOption{metric.WithAttributeSet(attribute.NewSet(*attrs...))} +// SpanProcessed records that a span has been submitted to the exporter by the +// SimpleSpanProcessor. Per the semantic conventions, this count is recorded at +// submission time and MUST NOT be affected by the export outcome. +func (ssp *SSP) SpanProcessed(ctx context.Context) { + ssp.spansProcessedCounter.Add(ctx, 1, ssp.addOpts...) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/tracer.go b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/tracer.go index 3428aa8949..16fad3c43d 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/tracer.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/tracer.go @@ -30,6 +30,8 @@ type Tracer struct { started metric.Int64Counter } +// NewTracer creates new instrumentation for a Tracer. +// It returns an empty, disabled Tracer if observability is not enabled. func NewTracer() (Tracer, error) { if !x.Observability.Enabled() { return Tracer{}, nil @@ -52,8 +54,11 @@ func NewTracer() (Tracer, error) { return Tracer{enabled: true, live: l.Inst(), started: s.Inst()}, err } +// Enabled returns whether observability is enabled for t. func (t Tracer) Enabled() bool { return t.enabled } +// SpanStarted records the start of span, which was created with psc as its +// parent span context. func (t Tracer) SpanStarted(ctx context.Context, psc trace.SpanContext, span trace.Span) { if !t.started.Enabled(ctx) { return @@ -84,10 +89,12 @@ func (t Tracer) SpanStarted(ctx context.Context, psc trace.SpanContext, span tra t.started.Add(ctx, 1, opts...) } +// SpanLive records span as a live span. func (t Tracer) SpanLive(ctx context.Context, span trace.Span) { t.spanLive(ctx, 1, span) } +// SpanEnded records span as no longer being live. func (t Tracer) SpanEnded(ctx context.Context, span trace.Span) { t.spanLive(ctx, -1, span) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go b/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go index 6b2368413a..ce615a1b02 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go @@ -150,7 +150,10 @@ func (p *TracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.T return noop.NewTracerProvider().Tracer(name, opts...) } c := trace.NewTracerConfig(opts...) - attrs, _ := attrnorm.Set(c.InstrumentationAttributes()) + attrs, _, _ := attrnorm.SetDedupLimitDepth( + c.InstrumentationAttributes(), + p.spanLimits.AttributeValueDepthLimit, + ) if name == "" { name = defaultTracerName } @@ -255,13 +258,14 @@ func (p *TracerProvider) UnregisterSpanProcessor(sp SpanProcessor) { idx = i } } - if stopOnce != nil { - stopOnce.state.Do(func() { - if err := sp.Shutdown(context.Background()); err != nil { - otel.Handle(err) - } - }) + if stopOnce == nil { + return } + stopOnce.state.Do(func() { + if err := sp.Shutdown(context.Background()); err != nil { + otel.Handle(err) + } + }) if len(spss) > 1 { copy(spss[idx:], spss[idx+1:]) } @@ -429,6 +433,29 @@ func WithSampler(s Sampler) TracerProviderOption { }) } +// WithAttributeValueDepthLimit sets the maximum allowed depth for attribute +// values. Depth starts at one for the top-level value and increments when +// descending into an array element or map value. An array or map beyond this +// depth is replaced by an empty value. +// +// This limit applies to span, event, link, and instrumentation scope +// attributes processed by this TracerProvider. It does not apply to Resource +// attributes. +// +// Setting this to zero means the default limit of 64 is used. Setting this to +// a negative value means no limit is applied. +// +// There is no environment variable for this limit. +func WithAttributeValueDepthLimit(limit int) TracerProviderOption { + if limit == 0 { + limit = DefaultAttributeValueDepthLimit + } + return traceProviderOptionFunc(func(cfg tracerProviderConfig) tracerProviderConfig { + cfg.spanLimits.AttributeValueDepthLimit = limit + return cfg + }) +} + // WithSpanLimits returns a TracerProviderOption that configures a // TracerProvider to use the SpanLimits sl. These SpanLimits bound any Span // created by a Tracer from the TracerProvider. @@ -448,6 +475,9 @@ func WithSpanLimits(sl SpanLimits) TracerProviderOption { if sl.AttributeValueLengthLimit <= 0 { sl.AttributeValueLengthLimit = DefaultAttributeValueLengthLimit } + if sl.AttributeValueDepthLimit <= 0 { + sl.AttributeValueDepthLimit = DefaultAttributeValueDepthLimit + } if sl.AttributeCountLimit <= 0 { sl.AttributeCountLimit = DefaultAttributeCountLimit } @@ -473,13 +503,14 @@ func WithSpanLimits(sl SpanLimits) TracerProviderOption { // TracerProvider to use these limits. These limits bound any Span created by // a Tracer from the TracerProvider. // -// The limits will be used as-is. Zero or negative values will not be changed -// to the default value like WithSpanLimits does. Setting a limit to zero will -// effectively disable the related resource it limits and setting to a -// negative value will mean that resource is unlimited. Consequentially, this -// means that the zero-value SpanLimits will disable all span resources. -// Because of this, limits should be constructed using NewSpanLimits and -// updated accordingly. +// The limits will be used as-is, except that an AttributeValueDepthLimit of +// zero means the default limit is used. Other zero or negative values will not +// be changed to the default value like WithSpanLimits does. Setting a limit to +// zero will effectively disable the related resource it limits and setting to +// a negative value will mean that resource is unlimited. Consequentially, the +// zero-value SpanLimits will disable all span resources except the attribute +// value depth limit. Because of this, limits should be constructed using +// NewSpanLimits and updated accordingly. // // If this or WithSpanLimits are not provided, the TracerProvider will use the // limits defined by environment variables, or the defaults if unset. Refer to @@ -525,5 +556,8 @@ func ensureValidTracerProviderConfig(cfg tracerProviderConfig) tracerProviderCon if cfg.resource == nil { cfg.resource = resource.Default() } + if cfg.spanLimits.AttributeValueDepthLimit == 0 { + cfg.spanLimits.AttributeValueDepthLimit = DefaultAttributeValueDepthLimit + } return cfg } diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/sampler_env.go b/vendor/go.opentelemetry.io/otel/sdk/trace/sampler_env.go index b0fa94ed2d..76cca5cd5b 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/sampler_env.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/sampler_env.go @@ -46,14 +46,13 @@ func (e samplerArgParseError) Unwrap() error { } func samplerFromEnv() (Sampler, error) { - sampler, ok := os.LookupEnv(tracesSamplerKey) - if !ok { + sampler := strings.ToLower(strings.TrimSpace(os.Getenv(tracesSamplerKey))) + if sampler == "" { return nil, nil } - sampler = strings.ToLower(strings.TrimSpace(sampler)) - samplerArg, hasSamplerArg := os.LookupEnv(tracesSamplerArgKey) - samplerArg = strings.TrimSpace(samplerArg) + samplerArg := strings.TrimSpace(os.Getenv(tracesSamplerArgKey)) + hasSamplerArg := samplerArg != "" switch sampler { case samplerAlwaysOn: diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go b/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go index e9bec43948..1e6be12486 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go @@ -67,19 +67,19 @@ func (ssp *simpleSpanProcessor) OnEnd(s ReadOnlySpan) { ssp.exporterMu.Lock() defer ssp.exporterMu.Unlock() - var err error - if ssp.exporter != nil && s.SpanContext().TraceFlags().IsSampled() { - err = ssp.exporter.ExportSpans(context.Background(), []ReadOnlySpan{s}) - if err != nil { - otel.Handle(err) - } - } - if ssp.inst != nil { // Add the span to the context to ensure the metric is recorded - // with the correct span context. + // with the correct span context. Record the span as processed before + // invoking the exporter so the count is unaffected by the export + // outcome. ctx := trace.ContextWithSpanContext(context.Background(), s.SpanContext()) - ssp.inst.SpanProcessed(ctx, err) + ssp.inst.SpanProcessed(ctx) + } + + if ssp.exporter != nil && s.SpanContext().TraceFlags().IsSampled() { + if err := ssp.exporter.ExportSpans(context.Background(), []ReadOnlySpan{s}); err != nil { + otel.Handle(err) + } } } @@ -104,10 +104,15 @@ func (ssp *simpleSpanProcessor) Shutdown(ctx context.Context) error { // span would need to be exported. Meaning, OnEnd would be called and // try acquiring the lock that is held here. ssp.exporterMu.Lock() - done, shutdown := stopFunc(ssp.exporter) + exp := ssp.exporter ssp.exporter = nil ssp.exporterMu.Unlock() + if exp == nil { + return + } + + done, shutdown := stopFunc(exp) go shutdown() // Wait for the exporter to shut down or the deadline to expire. diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/snapshot.go b/vendor/go.opentelemetry.io/otel/sdk/trace/snapshot.go index 8893dc39f1..6e0c06be5e 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/snapshot.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/snapshot.go @@ -12,7 +12,7 @@ import ( "go.opentelemetry.io/otel/trace" ) -// snapshot is an record of a spans state at a particular checkpointed time. +// snapshot is a record of a span's state at a particular checkpointed time. // It is used as a read-only representation of that state. type snapshot struct { name string diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/span.go b/vendor/go.opentelemetry.io/otel/sdk/trace/span.go index 0aae5f5bb2..05920ab872 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/span.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/span.go @@ -138,6 +138,11 @@ type recordingSpan struct { attributes []attribute.KeyValue droppedAttributes int logDropAttrsOnce sync.Once + // attributesDirty indicates attributes may contain duplicate keys. + attributesDirty bool + // attributesShared indicates the attributes backing array has been exposed + // to a reader and must not be modified. + attributesShared bool // events are stored in FIFO queue capped by configured limit. events evictedQueue[Event] @@ -251,6 +256,11 @@ func (s *recordingSpan) SetAttributes(attributes ...attribute.KeyValue) { s.addDroppedAttr(len(attributes)) return } + maxCap := len(s.attributes) + len(attributes) + if limit > 0 { + maxCap = min(maxCap, limit) + } + s.ensureAttrsWritable(maxCap) // If adding these attributes could exceed the capacity of s perform a // de-duplication and truncation while adding to avoid over allocation. @@ -268,10 +278,27 @@ func (s *recordingSpan) SetAttributes(attributes ...attribute.KeyValue) { s.addDroppedAttr(1) continue } - a = dedupAttr(a) - a = attrnorm.Truncate(s.tracer.provider.spanLimits.AttributeValueLengthLimit, a) + a = normAttr( + a, + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + s.tracer.provider.spanLimits.AttributeValueLengthLimit, + ) s.attributes = append(s.attributes, a) + s.attributesDirty = true + } +} + +// ensureAttrsWritable copies shared attributes into a backing array with at +// least capacity. This method assumes s.mu.Lock is held by the caller. +func (s *recordingSpan) ensureAttrsWritable(capacity int) { + if !s.attributesShared { + return } + capacity = max(capacity, len(s.attributes)) + attrs := make([]attribute.KeyValue, len(s.attributes), capacity) + copy(attrs, s.attributes) + s.attributes = attrs + s.attributesShared = false } // Declared as a var so tests can override. @@ -329,8 +356,11 @@ func (s *recordingSpan) addOverCapAttrs(limit int, attrs []attribute.KeyValue) { if idx, ok := exists[a.Key]; ok { // Perform all updates before dropping, even when at capacity. - a = dedupAttr(a) - a = attrnorm.Truncate(s.tracer.provider.spanLimits.AttributeValueLengthLimit, a) + a = normAttr( + a, + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + s.tracer.provider.spanLimits.AttributeValueLengthLimit, + ) s.attributes[idx] = a continue } @@ -340,22 +370,27 @@ func (s *recordingSpan) addOverCapAttrs(limit int, attrs []attribute.KeyValue) { // updates are checked and performed. s.addDroppedAttr(1) } else { - a = dedupAttr(a) - a = attrnorm.Truncate(s.tracer.provider.spanLimits.AttributeValueLengthLimit, a) + a = normAttr( + a, + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + s.tracer.provider.spanLimits.AttributeValueLengthLimit, + ) s.attributes = append(s.attributes, a) exists[a.Key] = len(s.attributes) - 1 } } } -func dedupAttr(attr attribute.KeyValue) attribute.KeyValue { +func normAttr(attr attribute.KeyValue, depthLimit, lengthLimit int) attribute.KeyValue { switch attr.Value.Type() { case attribute.SLICE, attribute.MAP: - attr, _ = attrnorm.KeyValue(attr) - return attr - default: - return attr + if depthLimit < 0 { + attr, _ = attrnorm.KeyValueDedup(attr) + } else { + attr, _, _ = attrnorm.KeyValueDedupLimitDepth(attr, depthLimit) + } } + return attrnorm.Truncate(lengthLimit, attr) } // End ends the span. This method does nothing if the span is already ended or @@ -459,9 +494,7 @@ func (s *recordingSpan) RecordError(err error, opts ...trace.EventOption) { return } - s.mu.Lock() - defer s.mu.Unlock() - if !s.isRecording() { + if !s.IsRecording() { return } @@ -477,7 +510,7 @@ func (s *recordingSpan) RecordError(err error, opts ...trace.EventOption) { )) } - s.addEvent(semconv.ExceptionEventName, opts...) + s.AddEvent(semconv.ExceptionEventName, opts...) } func typeStr(i any) string { @@ -516,7 +549,10 @@ func (s *recordingSpan) AddEvent(name string, o ...trace.EventOption) { // This method assumes s.mu.Lock is held by the caller. func (s *recordingSpan) addEvent(name string, o ...trace.EventOption) { c := trace.NewEventConfig(o...) - attrs, _ := attrnorm.KeyValues(c.Attributes()) + attrs, _, _ := attrnorm.KeyValuesDedupLimitDepth( + c.Attributes(), + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + ) e := Event{Name: name, Attributes: attrs, Time: c.Timestamp()} // Discard attributes over limit. @@ -556,7 +592,7 @@ func (s *recordingSpan) Name() string { return s.name } -// Name returns the SpanContext of this span's parent span. +// Parent returns the SpanContext of this span's parent span. func (s *recordingSpan) Parent() trace.SpanContext { s.mu.Lock() defer s.mu.Unlock() @@ -592,6 +628,7 @@ func (s *recordingSpan) Attributes() []attribute.KeyValue { s.mu.Lock() defer s.mu.Unlock() s.dedupeAttrs() + s.attributesShared = cap(s.attributes) > 0 return s.attributes } @@ -599,6 +636,10 @@ func (s *recordingSpan) Attributes() []attribute.KeyValue { // // This method assumes s.mu.Lock is held by the caller. func (s *recordingSpan) dedupeAttrs() { + if !s.attributesDirty { + return + } + s.ensureAttrsWritable(len(s.attributes)) // Do not set a capacity when creating this map. Benchmark testing has // showed this to only add unused memory allocations in general use. exists := make(map[attribute.Key]int, len(s.attributes)) @@ -622,6 +663,7 @@ func (s *recordingSpan) dedupeAttrsFromRecord(record map[attribute.Key]int) { } clear(s.attributes[len(unique):]) // Erase unneeded elements to let GC collect objects. s.attributes = unique + s.attributesDirty = false } // Links returns the links of this span. @@ -690,7 +732,10 @@ func (s *recordingSpan) AddLink(link trace.Link) { return } - attrs, _ := attrnorm.KeyValues(link.Attributes) + attrs, _, _ := attrnorm.KeyValuesDedupLimitDepth( + link.Attributes, + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + ) l := Link{SpanContext: link.SpanContext, Attributes: attrs} // Discard attributes over limit. @@ -765,6 +810,7 @@ func (s *recordingSpan) snapshot() ReadOnlySpan { if len(s.attributes) > 0 { s.dedupeAttrs() sd.attributes = s.attributes + s.attributesShared = true } sd.droppedAttributeCount = s.droppedAttributes if len(s.events.queue) > 0 { diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/span_limits.go b/vendor/go.opentelemetry.io/otel/sdk/trace/span_limits.go index 5ee15a8848..3069e22692 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/span_limits.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/span_limits.go @@ -10,6 +10,10 @@ const ( // attribute value length, unlimited. DefaultAttributeValueLengthLimit = -1 + // DefaultAttributeValueDepthLimit is the default maximum allowed depth for + // nested attribute values. + DefaultAttributeValueDepthLimit = 64 + // DefaultAttributeCountLimit is the default maximum number of attributes // a span can have. DefaultAttributeCountLimit = 128 @@ -43,6 +47,20 @@ type SpanLimits struct { // Setting this to a negative value means no limit is applied. AttributeValueLengthLimit int + // AttributeValueDepthLimit is the maximum allowed depth for an attribute + // value. Depth starts at one for the top-level value and increments when + // descending into an array element or map value. An array or map beyond this + // depth is replaced by an empty value. + // + // This limit applies to span, event, link, and instrumentation scope + // attributes processed by a TracerProvider. It does not apply to Resource + // attributes. + // + // Setting this to zero means the default limit is used. + // + // Setting this to a negative value means no limit is applied. + AttributeValueDepthLimit int + // AttributeCountLimit is the maximum allowed span attribute count. Any // attribute added to a span once this limit is reached will be dropped. // @@ -88,12 +106,15 @@ type SpanLimits struct { AttributePerLinkCountLimit int } -// NewSpanLimits returns a SpanLimits with all limits set to the value their -// corresponding environment variable holds, or the default if unset. +// NewSpanLimits returns a SpanLimits with all limits set to their default. +// Limits with a corresponding environment variable are set from the +// environment when the variable is defined. // // • AttributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT // (default: unlimited) // +// • AttributeValueDepthLimit: default 64 (no environment variable) +// // • AttributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT (default: 128) // // • EventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT (default: 128) @@ -107,6 +128,7 @@ type SpanLimits struct { func NewSpanLimits() SpanLimits { return SpanLimits{ AttributeValueLengthLimit: env.SpanAttributeValueLength(DefaultAttributeValueLengthLimit), + AttributeValueDepthLimit: DefaultAttributeValueDepthLimit, AttributeCountLimit: env.SpanAttributeCount(DefaultAttributeCountLimit), EventCountLimit: env.SpanEventCount(DefaultEventCountLimit), LinkCountLimit: env.SpanLinkCount(DefaultLinkCountLimit), diff --git a/vendor/go.opentelemetry.io/otel/sdk/version.go b/vendor/go.opentelemetry.io/otel/sdk/version.go index 1619fb3fa1..2335ebdd76 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/version.go +++ b/vendor/go.opentelemetry.io/otel/sdk/version.go @@ -6,5 +6,5 @@ package sdk // Version is the current release version of the OpenTelemetry SDK in use. func Version() string { - return "1.45.0" + return "1.47.0" } diff --git a/vendor/go.opentelemetry.io/otel/trace/auto.go b/vendor/go.opentelemetry.io/otel/trace/auto.go index 17cf898cd9..be4a964459 100644 --- a/vendor/go.opentelemetry.io/otel/trace/auto.go +++ b/vendor/go.opentelemetry.io/otel/trace/auto.go @@ -372,7 +372,7 @@ func convAttrValue(value attribute.Value) telemetry.Value { return telemetry.Value{} } -// truncate returns a truncated version of s such that it contains less than +// truncate returns a truncated version of s such that it contains at most // the limit number of characters. Truncation is applied by returning the limit // number of valid characters contained in s. // @@ -381,7 +381,7 @@ func convAttrValue(value attribute.Value) telemetry.Value { // UTF-8 is supported. When truncating, all invalid characters are dropped // before applying truncation. // -// If s already contains less than the limit number of bytes, it is returned +// If s already contains at most the limit number of bytes, it is returned // unchanged. No invalid characters are removed. func truncate(limit int, s string) string { // This prioritize performance in the following order based on the most @@ -407,6 +407,10 @@ func truncate(limit int, s string) string { continue } + // A zero limit also truncates a leading invalid byte or U+FFFD. + if limit == 0 { + return "" + } _, size := utf8.DecodeRuneInString(s[i:]) if size == 1 { // Invalid encoding. @@ -415,6 +419,12 @@ func truncate(limit int, s string) string { s = s[i:] break } + + // A valid U+FFFD still consumes one character of the limit. + count++ + if count > limit { + return s[:i] + } } // Fast-path, no invalid input. diff --git a/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go b/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go index 29e629d667..5bb3b16c70 100644 --- a/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go +++ b/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go @@ -41,7 +41,7 @@ func (i *protoInt64) UnmarshalJSON(data []byte) error { // strings or integers. type protoUint64 uint64 -// Int64 returns the protoUint64 as a uint64. +// Uint64 returns the protoUint64 as a uint64. func (i *protoUint64) Uint64() uint64 { return uint64(*i) } // UnmarshalJSON decodes both strings and integers. diff --git a/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go b/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go index 9d2d680634..b7b0e8b58d 100644 --- a/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go +++ b/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go @@ -327,7 +327,7 @@ func (v Value) String() string { // Try to handle this as gracefully as possible. // // Don't panic here. The goal here is to have developers find this - // first if a slog.Kind is is not handled. It is + // first if a slog.Kind is not handled. It is // preferable to have user's open issue asking why their attributes // have a "unhandled: " prefix than say that their code is panicking. return fmt.Sprintf("", v.Kind()) diff --git a/vendor/go.opentelemetry.io/otel/trace/trace.go b/vendor/go.opentelemetry.io/otel/trace/trace.go index c4c383819f..66b967e7dc 100644 --- a/vendor/go.opentelemetry.io/otel/trace/trace.go +++ b/vendor/go.opentelemetry.io/otel/trace/trace.go @@ -134,13 +134,49 @@ func TraceIDFromHex(h string) (TraceID, error) { if len(h) != 32 { return [16]byte{}, errInvalidTraceIDLength } - var b [16]byte - invalidMark := byte(0) - for i := 0; i < len(h); i += 4 { - b[i/2] = (hexRev[h[i]] << 4) | hexRev[h[i+1]] - b[i/2+1] = (hexRev[h[i+2]] << 4) | hexRev[h[i+3]] - invalidMark |= hexRev[h[i]] | hexRev[h[i+1]] | hexRev[h[i+2]] | hexRev[h[i+3]] + // Decoding every character at a constant index allows the compiler to + // eliminate the bounds checks a loop over h would retain. + n0, n1 := hexRev[h[0]], hexRev[h[1]] + n2, n3 := hexRev[h[2]], hexRev[h[3]] + n4, n5 := hexRev[h[4]], hexRev[h[5]] + n6, n7 := hexRev[h[6]], hexRev[h[7]] + n8, n9 := hexRev[h[8]], hexRev[h[9]] + n10, n11 := hexRev[h[10]], hexRev[h[11]] + n12, n13 := hexRev[h[12]], hexRev[h[13]] + n14, n15 := hexRev[h[14]], hexRev[h[15]] + n16, n17 := hexRev[h[16]], hexRev[h[17]] + n18, n19 := hexRev[h[18]], hexRev[h[19]] + n20, n21 := hexRev[h[20]], hexRev[h[21]] + n22, n23 := hexRev[h[22]], hexRev[h[23]] + n24, n25 := hexRev[h[24]], hexRev[h[25]] + n26, n27 := hexRev[h[26]], hexRev[h[27]] + n28, n29 := hexRev[h[28]], hexRev[h[29]] + n30, n31 := hexRev[h[30]], hexRev[h[31]] + + b := [16]byte{ + (n0 << 4) | n1, + (n2 << 4) | n3, + (n4 << 4) | n5, + (n6 << 4) | n7, + (n8 << 4) | n9, + (n10 << 4) | n11, + (n12 << 4) | n13, + (n14 << 4) | n15, + (n16 << 4) | n17, + (n18 << 4) | n19, + (n20 << 4) | n21, + (n22 << 4) | n23, + (n24 << 4) | n25, + (n26 << 4) | n27, + (n28 << 4) | n29, + (n30 << 4) | n31, } + + invalidMark := n0 | n1 | n2 | n3 | n4 | n5 | n6 | n7 | + n8 | n9 | n10 | n11 | n12 | n13 | n14 | n15 | + n16 | n17 | n18 | n19 | n20 | n21 | n22 | n23 | + n24 | n25 | n26 | n27 | n28 | n29 | n30 | n31 + // If the upper 4 bits of any byte are not zero, there was an invalid hex // character since invalid hex characters are 0xff in hexRev. if invalidMark&0xf0 != 0 { @@ -160,13 +196,31 @@ func SpanIDFromHex(h string) (SpanID, error) { if len(h) != 16 { return [8]byte{}, errInvalidSpanIDLength } - var b [8]byte - invalidMark := byte(0) - for i := 0; i < len(h); i += 4 { - b[i/2] = (hexRev[h[i]] << 4) | hexRev[h[i+1]] - b[i/2+1] = (hexRev[h[i+2]] << 4) | hexRev[h[i+3]] - invalidMark |= hexRev[h[i]] | hexRev[h[i+1]] | hexRev[h[i+2]] | hexRev[h[i+3]] + // Decoding every character at a constant index allows the compiler to + // eliminate the bounds checks a loop over h would retain. + n0, n1 := hexRev[h[0]], hexRev[h[1]] + n2, n3 := hexRev[h[2]], hexRev[h[3]] + n4, n5 := hexRev[h[4]], hexRev[h[5]] + n6, n7 := hexRev[h[6]], hexRev[h[7]] + n8, n9 := hexRev[h[8]], hexRev[h[9]] + n10, n11 := hexRev[h[10]], hexRev[h[11]] + n12, n13 := hexRev[h[12]], hexRev[h[13]] + n14, n15 := hexRev[h[14]], hexRev[h[15]] + + b := [8]byte{ + (n0 << 4) | n1, + (n2 << 4) | n3, + (n4 << 4) | n5, + (n6 << 4) | n7, + (n8 << 4) | n9, + (n10 << 4) | n11, + (n12 << 4) | n13, + (n14 << 4) | n15, } + + invalidMark := n0 | n1 | n2 | n3 | n4 | n5 | n6 | n7 | + n8 | n9 | n10 | n11 | n12 | n13 | n14 | n15 + // If the upper 4 bits of any byte are not zero, there was an invalid hex // character since invalid hex characters are 0xff in hexRev. if invalidMark&0xf0 != 0 { diff --git a/vendor/go.opentelemetry.io/otel/trace/tracestate.go b/vendor/go.opentelemetry.io/otel/trace/tracestate.go index 9ac78fa04c..062ceb2ad2 100644 --- a/vendor/go.opentelemetry.io/otel/trace/tracestate.go +++ b/vendor/go.opentelemetry.io/otel/trace/tracestate.go @@ -283,7 +283,7 @@ func (ts TraceState) Walk(f func(key, value string) bool) { // specification an error is returned with the original TraceState. // // If adding a new list-member means the TraceState would have more members -// then is allowed, the new list-member will be inserted and the right-most +// than is allowed, the new list-member will be inserted and the right-most // list-member will be dropped in the returned TraceState. func (ts TraceState) Insert(key, value string) (TraceState, error) { m, err := newMember(key, value) diff --git a/vendor/go.opentelemetry.io/otel/version.go b/vendor/go.opentelemetry.io/otel/version.go index ea79030969..29ff1801fa 100644 --- a/vendor/go.opentelemetry.io/otel/version.go +++ b/vendor/go.opentelemetry.io/otel/version.go @@ -5,5 +5,5 @@ package otel // Version is the current release version of OpenTelemetry in use. func Version() string { - return "1.45.0" + return "1.47.0" } diff --git a/vendor/go.opentelemetry.io/otel/versions.yaml b/vendor/go.opentelemetry.io/otel/versions.yaml index 3b1ad7301a..a0cb35f4d4 100644 --- a/vendor/go.opentelemetry.io/otel/versions.yaml +++ b/vendor/go.opentelemetry.io/otel/versions.yaml @@ -3,7 +3,7 @@ module-sets: stable-v1: - version: v1.45.0 + version: v1.47.0 modules: - go.opentelemetry.io/otel - go.opentelemetry.io/otel/bridge/opencensus @@ -17,27 +17,31 @@ module-sets: - go.opentelemetry.io/otel/exporters/stdout/stdoutmetric - go.opentelemetry.io/otel/exporters/stdout/stdouttrace - go.opentelemetry.io/otel/exporters/zipkin + - go.opentelemetry.io/otel/log - go.opentelemetry.io/otel/metric - go.opentelemetry.io/otel/sdk + - go.opentelemetry.io/otel/sdk/log - go.opentelemetry.io/otel/sdk/metric - go.opentelemetry.io/otel/trace experimental-metrics: - version: v0.67.0 + version: v0.69.0 modules: - go.opentelemetry.io/otel/exporters/prometheus - go.opentelemetry.io/otel/metric/x experimental-logs: - version: v0.21.0 + version: v0.23.0 modules: - - go.opentelemetry.io/otel/log - go.opentelemetry.io/otel/log/logtest - - go.opentelemetry.io/otel/sdk/log - go.opentelemetry.io/otel/sdk/log/logtest - go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc - go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp - go.opentelemetry.io/otel/exporters/stdout/stdoutlog + experimental-traces: + version: v0.1.0 + modules: + - go.opentelemetry.io/otel/sdk/trace/x experimental-schema: - version: v0.0.18 + version: v0.0.19 modules: - go.opentelemetry.io/otel/schema excluded-modules: diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service.pb.go index 978efdde93..23ac94f4d6 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/collector/logs/v1/logs_service.proto package v1 @@ -26,6 +26,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -36,25 +37,22 @@ const ( ) type ExportLogsServiceRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // An array of ResourceLogs. // For data coming from a single resource this array will typically contain one // element. Intermediary nodes (such as OpenTelemetry Collector) that receive // data from multiple origins typically batch the data before forwarding further and // in that case this array will contain multiple elements. - ResourceLogs []*v1.ResourceLogs `protobuf:"bytes,1,rep,name=resource_logs,json=resourceLogs,proto3" json:"resource_logs,omitempty"` + ResourceLogs []*v1.ResourceLogs `protobuf:"bytes,1,rep,name=resource_logs,json=resourceLogs,proto3" json:"resource_logs,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportLogsServiceRequest) Reset() { *x = ExportLogsServiceRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportLogsServiceRequest) String() string { @@ -65,7 +63,7 @@ func (*ExportLogsServiceRequest) ProtoMessage() {} func (x *ExportLogsServiceRequest) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -88,10 +86,7 @@ func (x *ExportLogsServiceRequest) GetResourceLogs() []*v1.ResourceLogs { } type ExportLogsServiceResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The details of a partially successful export request. // // If the request is only partially accepted @@ -108,15 +103,15 @@ type ExportLogsServiceResponse struct { // `error_message` = "") is equivalent to it not being set/present. Senders // SHOULD interpret it the same way as in the full success case. PartialSuccess *ExportLogsPartialSuccess `protobuf:"bytes,1,opt,name=partial_success,json=partialSuccess,proto3" json:"partial_success,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportLogsServiceResponse) Reset() { *x = ExportLogsServiceResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportLogsServiceResponse) String() string { @@ -127,7 +122,7 @@ func (*ExportLogsServiceResponse) ProtoMessage() {} func (x *ExportLogsServiceResponse) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -150,10 +145,7 @@ func (x *ExportLogsServiceResponse) GetPartialSuccess() *ExportLogsPartialSucces } type ExportLogsPartialSuccess struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The number of rejected log records. // // A `rejected_` field holding a `0` value indicates that the @@ -166,16 +158,16 @@ type ExportLogsPartialSuccess struct { // // error_message is an optional field. An error_message with an empty value // is equivalent to it not being set. - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` + ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportLogsPartialSuccess) Reset() { *x = ExportLogsPartialSuccess{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportLogsPartialSuccess) String() string { @@ -186,7 +178,7 @@ func (*ExportLogsPartialSuccess) ProtoMessage() {} func (x *ExportLogsPartialSuccess) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -217,75 +209,34 @@ func (x *ExportLogsPartialSuccess) GetErrorMessage() string { var File_opentelemetry_proto_collector_logs_v1_logs_service_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDesc = []byte{ - 0x0a, 0x38, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, - 0x6c, 0x6f, 0x67, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6c, 0x6f, 0x67, 0x73, 0x5f, 0x73, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x25, 0x6f, 0x70, 0x65, 0x6e, - 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, - 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x6c, 0x6f, 0x67, 0x73, 0x2e, 0x76, - 0x31, 0x1a, 0x26, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6c, 0x6f, 0x67, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6c, - 0x6f, 0x67, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x6a, 0x0a, 0x18, 0x45, 0x78, 0x70, - 0x6f, 0x72, 0x74, 0x4c, 0x6f, 0x67, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x4e, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x5f, 0x6c, 0x6f, 0x67, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x6f, - 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x2e, 0x6c, 0x6f, 0x67, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, - 0x72, 0x63, 0x65, 0x4c, 0x6f, 0x67, 0x73, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x4c, 0x6f, 0x67, 0x73, 0x22, 0x85, 0x01, 0x0a, 0x19, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, - 0x4c, 0x6f, 0x67, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x68, 0x0a, 0x0f, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x73, - 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x3f, 0x2e, 0x6f, - 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x6c, 0x6f, 0x67, - 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x4c, 0x6f, 0x67, 0x73, 0x50, - 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x52, 0x0e, 0x70, - 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x71, 0x0a, - 0x18, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x4c, 0x6f, 0x67, 0x73, 0x50, 0x61, 0x72, 0x74, 0x69, - 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x12, 0x30, 0x0a, 0x14, 0x72, 0x65, 0x6a, - 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x6c, 0x6f, 0x67, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, - 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x12, 0x72, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x65, - 0x64, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x73, 0x12, 0x23, 0x0a, 0x0d, 0x65, - 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, - 0x32, 0x9d, 0x01, 0x0a, 0x0b, 0x4c, 0x6f, 0x67, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, - 0x12, 0x8d, 0x01, 0x0a, 0x06, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x3f, 0x2e, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x6c, 0x6f, 0x67, 0x73, - 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x4c, 0x6f, 0x67, 0x73, 0x53, 0x65, - 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x40, 0x2e, 0x6f, - 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x6c, 0x6f, 0x67, - 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x4c, 0x6f, 0x67, 0x73, 0x53, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, - 0x42, 0x98, 0x01, 0x0a, 0x28, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, - 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, - 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x6c, 0x6f, 0x67, 0x73, 0x2e, 0x76, 0x31, 0x42, 0x10, 0x4c, - 0x6f, 0x67, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, - 0x01, 0x5a, 0x30, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, - 0x70, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, 0x6c, 0x6f, 0x67, 0x73, - 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x25, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6c, 0x6c, 0x65, 0x63, - 0x74, 0x6f, 0x72, 0x2e, 0x4c, 0x6f, 0x67, 0x73, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDesc = "" + + "\n" + + "8opentelemetry/proto/collector/logs/v1/logs_service.proto\x12%opentelemetry.proto.collector.logs.v1\x1a&opentelemetry/proto/logs/v1/logs.proto\"j\n" + + "\x18ExportLogsServiceRequest\x12N\n" + + "\rresource_logs\x18\x01 \x03(\v2).opentelemetry.proto.logs.v1.ResourceLogsR\fresourceLogs\"\x85\x01\n" + + "\x19ExportLogsServiceResponse\x12h\n" + + "\x0fpartial_success\x18\x01 \x01(\v2?.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccessR\x0epartialSuccess\"q\n" + + "\x18ExportLogsPartialSuccess\x120\n" + + "\x14rejected_log_records\x18\x01 \x01(\x03R\x12rejectedLogRecords\x12#\n" + + "\rerror_message\x18\x02 \x01(\tR\ferrorMessage2\x9d\x01\n" + + "\vLogsService\x12\x8d\x01\n" + + "\x06Export\x12?.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest\x1a@.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse\"\x00B\x98\x01\n" + + "(io.opentelemetry.proto.collector.logs.v1B\x10LogsServiceProtoP\x01Z0go.opentelemetry.io/proto/otlp/collector/logs/v1\xaa\x02%OpenTelemetry.Proto.Collector.Logs.V1b\x06proto3" var ( file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDescOnce sync.Once - file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDescData = file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDesc + file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDescData []byte ) func file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDescGZIP() []byte { file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDescData) + file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDesc), len(file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDesc))) }) return file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDescData } var file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes = make([]protoimpl.MessageInfo, 3) -var file_opentelemetry_proto_collector_logs_v1_logs_service_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_collector_logs_v1_logs_service_proto_goTypes = []any{ (*ExportLogsServiceRequest)(nil), // 0: opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest (*ExportLogsServiceResponse)(nil), // 1: opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse (*ExportLogsPartialSuccess)(nil), // 2: opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess @@ -308,49 +259,11 @@ func file_opentelemetry_proto_collector_logs_v1_logs_service_proto_init() { if File_opentelemetry_proto_collector_logs_v1_logs_service_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportLogsServiceRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportLogsServiceResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportLogsPartialSuccess); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDesc), len(file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDesc)), NumEnums: 0, NumMessages: 3, NumExtensions: 0, @@ -361,7 +274,6 @@ func file_opentelemetry_proto_collector_logs_v1_logs_service_proto_init() { MessageInfos: file_opentelemetry_proto_collector_logs_v1_logs_service_proto_msgTypes, }.Build() File_opentelemetry_proto_collector_logs_v1_logs_service_proto = out.File - file_opentelemetry_proto_collector_logs_v1_logs_service_proto_rawDesc = nil file_opentelemetry_proto_collector_logs_v1_logs_service_proto_goTypes = nil file_opentelemetry_proto_collector_logs_v1_logs_service_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service.pb.gw.go b/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service.pb.gw.go index d34f32d91b..fc9f564e4c 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service.pb.gw.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service.pb.gw.go @@ -10,6 +10,7 @@ package v1 import ( "context" + "errors" "io" "net/http" @@ -24,62 +25,56 @@ import ( ) // Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = metadata.Join +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = errors.New + _ = runtime.String + _ = utilities.NewDoubleArray + _ = metadata.Join +) func request_LogsService_Export_0(ctx context.Context, marshaler runtime.Marshaler, client LogsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportLogsServiceRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportLogsServiceRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.Export(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_LogsService_Export_0(ctx context.Context, marshaler runtime.Marshaler, server LogsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportLogsServiceRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportLogsServiceRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.Export(ctx, &protoReq) return msg, metadata, err - } // RegisterLogsServiceHandlerServer registers the http handlers for service LogsService to "mux". // UnaryRPC :call LogsServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterLogsServiceHandlerFromEndpoint instead. +// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterLogsServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server LogsServiceServer) error { - - mux.Handle("POST", pattern_LogsService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_LogsService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/opentelemetry.proto.collector.logs.v1.LogsService/Export", runtime.WithHTTPPathPattern("/v1/logs")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/opentelemetry.proto.collector.logs.v1.LogsService/Export", runtime.WithHTTPPathPattern("/v1/logs")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -91,9 +86,7 @@ func RegisterLogsServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_LogsService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) return nil @@ -102,25 +95,24 @@ func RegisterLogsServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux // RegisterLogsServiceHandlerFromEndpoint is same as RegisterLogsServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterLogsServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) + conn, err := grpc.NewClient(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } }() }() - return RegisterLogsServiceHandler(ctx, mux, conn) } @@ -134,16 +126,13 @@ func RegisterLogsServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "LogsServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "LogsServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "LogsServiceClient" to call the correct interceptors. +// "LogsServiceClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterLogsServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client LogsServiceClient) error { - - mux.Handle("POST", pattern_LogsService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_LogsService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/opentelemetry.proto.collector.logs.v1.LogsService/Export", runtime.WithHTTPPathPattern("/v1/logs")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/opentelemetry.proto.collector.logs.v1.LogsService/Export", runtime.WithHTTPPathPattern("/v1/logs")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -154,11 +143,8 @@ func RegisterLogsServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_LogsService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - return nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service_grpc.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service_grpc.pb.go index d1d24fe620..a361ba81c7 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service_grpc.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/logs/v1/logs_service_grpc.pb.go @@ -1,7 +1,21 @@ +// Copyright 2020, OpenTelemetry 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. + // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.1.0 -// - protoc v3.21.6 +// - protoc-gen-go-grpc v1.5.1 +// - protoc v7.35.0 // source: opentelemetry/proto/collector/logs/v1/logs_service.proto package v1 @@ -15,12 +29,20 @@ import ( // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + LogsService_Export_FullMethodName = "/opentelemetry.proto.collector.logs.v1.LogsService/Export" +) // LogsServiceClient is the client API for LogsService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// Service that can be used to push logs between one Application instrumented with +// OpenTelemetry and an collector, or between an collector and a central collector (in this +// case logs are sent/received to/from multiple Applications). type LogsServiceClient interface { Export(ctx context.Context, in *ExportLogsServiceRequest, opts ...grpc.CallOption) (*ExportLogsServiceResponse, error) } @@ -34,8 +56,9 @@ func NewLogsServiceClient(cc grpc.ClientConnInterface) LogsServiceClient { } func (c *logsServiceClient) Export(ctx context.Context, in *ExportLogsServiceRequest, opts ...grpc.CallOption) (*ExportLogsServiceResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ExportLogsServiceResponse) - err := c.cc.Invoke(ctx, "/opentelemetry.proto.collector.logs.v1.LogsService/Export", in, out, opts...) + err := c.cc.Invoke(ctx, LogsService_Export_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -44,20 +67,28 @@ func (c *logsServiceClient) Export(ctx context.Context, in *ExportLogsServiceReq // LogsServiceServer is the server API for LogsService service. // All implementations must embed UnimplementedLogsServiceServer -// for forward compatibility +// for forward compatibility. +// +// Service that can be used to push logs between one Application instrumented with +// OpenTelemetry and an collector, or between an collector and a central collector (in this +// case logs are sent/received to/from multiple Applications). type LogsServiceServer interface { Export(context.Context, *ExportLogsServiceRequest) (*ExportLogsServiceResponse, error) mustEmbedUnimplementedLogsServiceServer() } -// UnimplementedLogsServiceServer must be embedded to have forward compatible implementations. -type UnimplementedLogsServiceServer struct { -} +// UnimplementedLogsServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedLogsServiceServer struct{} func (UnimplementedLogsServiceServer) Export(context.Context, *ExportLogsServiceRequest) (*ExportLogsServiceResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Export not implemented") } func (UnimplementedLogsServiceServer) mustEmbedUnimplementedLogsServiceServer() {} +func (UnimplementedLogsServiceServer) testEmbeddedByValue() {} // UnsafeLogsServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to LogsServiceServer will @@ -67,6 +98,13 @@ type UnsafeLogsServiceServer interface { } func RegisterLogsServiceServer(s grpc.ServiceRegistrar, srv LogsServiceServer) { + // If the following call pancis, it indicates UnimplementedLogsServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } s.RegisterService(&LogsService_ServiceDesc, srv) } @@ -80,7 +118,7 @@ func _LogsService_Export_Handler(srv interface{}, ctx context.Context, dec func( } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/opentelemetry.proto.collector.logs.v1.LogsService/Export", + FullMethod: LogsService_Export_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(LogsServiceServer).Export(ctx, req.(*ExportLogsServiceRequest)) diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service.pb.go index 8e13d157c2..eb7fbc67b2 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/collector/metrics/v1/metrics_service.proto package v1 @@ -26,6 +26,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -36,25 +37,22 @@ const ( ) type ExportMetricsServiceRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // An array of ResourceMetrics. // For data coming from a single resource this array will typically contain one // element. Intermediary nodes (such as OpenTelemetry Collector) that receive // data from multiple origins typically batch the data before forwarding further and // in that case this array will contain multiple elements. ResourceMetrics []*v1.ResourceMetrics `protobuf:"bytes,1,rep,name=resource_metrics,json=resourceMetrics,proto3" json:"resource_metrics,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportMetricsServiceRequest) Reset() { *x = ExportMetricsServiceRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportMetricsServiceRequest) String() string { @@ -65,7 +63,7 @@ func (*ExportMetricsServiceRequest) ProtoMessage() {} func (x *ExportMetricsServiceRequest) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -88,10 +86,7 @@ func (x *ExportMetricsServiceRequest) GetResourceMetrics() []*v1.ResourceMetrics } type ExportMetricsServiceResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The details of a partially successful export request. // // If the request is only partially accepted @@ -108,15 +103,15 @@ type ExportMetricsServiceResponse struct { // `error_message` = "") is equivalent to it not being set/present. Senders // SHOULD interpret it the same way as in the full success case. PartialSuccess *ExportMetricsPartialSuccess `protobuf:"bytes,1,opt,name=partial_success,json=partialSuccess,proto3" json:"partial_success,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportMetricsServiceResponse) Reset() { *x = ExportMetricsServiceResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportMetricsServiceResponse) String() string { @@ -127,7 +122,7 @@ func (*ExportMetricsServiceResponse) ProtoMessage() {} func (x *ExportMetricsServiceResponse) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -150,10 +145,7 @@ func (x *ExportMetricsServiceResponse) GetPartialSuccess() *ExportMetricsPartial } type ExportMetricsPartialSuccess struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The number of rejected data points. // // A `rejected_` field holding a `0` value indicates that the @@ -166,16 +158,16 @@ type ExportMetricsPartialSuccess struct { // // error_message is an optional field. An error_message with an empty value // is equivalent to it not being set. - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` + ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportMetricsPartialSuccess) Reset() { *x = ExportMetricsPartialSuccess{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportMetricsPartialSuccess) String() string { @@ -186,7 +178,7 @@ func (*ExportMetricsPartialSuccess) ProtoMessage() {} func (x *ExportMetricsPartialSuccess) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -217,79 +209,34 @@ func (x *ExportMetricsPartialSuccess) GetErrorMessage() string { var File_opentelemetry_proto_collector_metrics_v1_metrics_service_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDesc = []byte{ - 0x0a, 0x3e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, - 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x65, 0x74, 0x72, 0x69, - 0x63, 0x73, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x12, 0x28, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, - 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x1a, 0x2c, 0x6f, 0x70, 0x65, 0x6e, - 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, - 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x65, 0x74, 0x72, 0x69, - 0x63, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x79, 0x0a, 0x1b, 0x45, 0x78, 0x70, 0x6f, - 0x72, 0x74, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x5a, 0x0a, 0x10, 0x72, 0x65, 0x73, 0x6f, 0x75, - 0x72, 0x63, 0x65, 0x5f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x2f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, - 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4d, 0x65, 0x74, 0x72, 0x69, - 0x63, 0x73, 0x52, 0x0f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4d, 0x65, 0x74, 0x72, - 0x69, 0x63, 0x73, 0x22, 0x8e, 0x01, 0x0a, 0x1c, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x4d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6e, 0x0a, 0x0f, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x5f, - 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x45, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x6d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x4d, - 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x50, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, - 0x63, 0x65, 0x73, 0x73, 0x52, 0x0e, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, - 0x63, 0x65, 0x73, 0x73, 0x22, 0x74, 0x0a, 0x1b, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x4d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x50, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, - 0x65, 0x73, 0x73, 0x12, 0x30, 0x0a, 0x14, 0x72, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, - 0x64, 0x61, 0x74, 0x61, 0x5f, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x03, 0x52, 0x12, 0x72, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x65, 0x64, 0x44, 0x61, 0x74, 0x61, 0x50, - 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, - 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, - 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0xac, 0x01, 0x0a, 0x0e, 0x4d, - 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x99, 0x01, - 0x0a, 0x06, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x45, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, - 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, - 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, - 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, - 0x46, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, - 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, - 0x74, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0xa4, 0x01, 0x0a, 0x2b, 0x69, 0x6f, - 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x6d, - 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x42, 0x13, 0x4d, 0x65, 0x74, 0x72, 0x69, - 0x63, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, - 0x5a, 0x33, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, - 0x2f, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, 0x6d, 0x65, 0x74, 0x72, 0x69, - 0x63, 0x73, 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x28, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, - 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6c, 0x6c, - 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x56, 0x31, - 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDesc = "" + + "\n" + + ">opentelemetry/proto/collector/metrics/v1/metrics_service.proto\x12(opentelemetry.proto.collector.metrics.v1\x1a,opentelemetry/proto/metrics/v1/metrics.proto\"y\n" + + "\x1bExportMetricsServiceRequest\x12Z\n" + + "\x10resource_metrics\x18\x01 \x03(\v2/.opentelemetry.proto.metrics.v1.ResourceMetricsR\x0fresourceMetrics\"\x8e\x01\n" + + "\x1cExportMetricsServiceResponse\x12n\n" + + "\x0fpartial_success\x18\x01 \x01(\v2E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccessR\x0epartialSuccess\"t\n" + + "\x1bExportMetricsPartialSuccess\x120\n" + + "\x14rejected_data_points\x18\x01 \x01(\x03R\x12rejectedDataPoints\x12#\n" + + "\rerror_message\x18\x02 \x01(\tR\ferrorMessage2\xac\x01\n" + + "\x0eMetricsService\x12\x99\x01\n" + + "\x06Export\x12E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest\x1aF.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse\"\x00B\xa4\x01\n" + + "+io.opentelemetry.proto.collector.metrics.v1B\x13MetricsServiceProtoP\x01Z3go.opentelemetry.io/proto/otlp/collector/metrics/v1\xaa\x02(OpenTelemetry.Proto.Collector.Metrics.V1b\x06proto3" var ( file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDescOnce sync.Once - file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDescData = file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDesc + file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDescData []byte ) func file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDescGZIP() []byte { file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDescData) + file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDesc), len(file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDesc))) }) return file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDescData } var file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes = make([]protoimpl.MessageInfo, 3) -var file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_goTypes = []any{ (*ExportMetricsServiceRequest)(nil), // 0: opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest (*ExportMetricsServiceResponse)(nil), // 1: opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse (*ExportMetricsPartialSuccess)(nil), // 2: opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess @@ -312,49 +259,11 @@ func file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_init() if File_opentelemetry_proto_collector_metrics_v1_metrics_service_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportMetricsServiceRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportMetricsServiceResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportMetricsPartialSuccess); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDesc), len(file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDesc)), NumEnums: 0, NumMessages: 3, NumExtensions: 0, @@ -365,7 +274,6 @@ func file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_init() MessageInfos: file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_msgTypes, }.Build() File_opentelemetry_proto_collector_metrics_v1_metrics_service_proto = out.File - file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_rawDesc = nil file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_goTypes = nil file_opentelemetry_proto_collector_metrics_v1_metrics_service_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service.pb.gw.go b/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service.pb.gw.go index c42f1454ed..3da3d6f5d6 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service.pb.gw.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service.pb.gw.go @@ -10,6 +10,7 @@ package v1 import ( "context" + "errors" "io" "net/http" @@ -24,62 +25,56 @@ import ( ) // Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = metadata.Join +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = errors.New + _ = runtime.String + _ = utilities.NewDoubleArray + _ = metadata.Join +) func request_MetricsService_Export_0(ctx context.Context, marshaler runtime.Marshaler, client MetricsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportMetricsServiceRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportMetricsServiceRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.Export(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_MetricsService_Export_0(ctx context.Context, marshaler runtime.Marshaler, server MetricsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportMetricsServiceRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportMetricsServiceRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.Export(ctx, &protoReq) return msg, metadata, err - } // RegisterMetricsServiceHandlerServer registers the http handlers for service MetricsService to "mux". // UnaryRPC :call MetricsServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterMetricsServiceHandlerFromEndpoint instead. +// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterMetricsServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server MetricsServiceServer) error { - - mux.Handle("POST", pattern_MetricsService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_MetricsService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", runtime.WithHTTPPathPattern("/v1/metrics")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", runtime.WithHTTPPathPattern("/v1/metrics")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -91,9 +86,7 @@ func RegisterMetricsServiceHandlerServer(ctx context.Context, mux *runtime.Serve runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_MetricsService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) return nil @@ -102,25 +95,24 @@ func RegisterMetricsServiceHandlerServer(ctx context.Context, mux *runtime.Serve // RegisterMetricsServiceHandlerFromEndpoint is same as RegisterMetricsServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterMetricsServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) + conn, err := grpc.NewClient(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } }() }() - return RegisterMetricsServiceHandler(ctx, mux, conn) } @@ -134,16 +126,13 @@ func RegisterMetricsServiceHandler(ctx context.Context, mux *runtime.ServeMux, c // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "MetricsServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "MetricsServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "MetricsServiceClient" to call the correct interceptors. +// "MetricsServiceClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterMetricsServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client MetricsServiceClient) error { - - mux.Handle("POST", pattern_MetricsService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_MetricsService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", runtime.WithHTTPPathPattern("/v1/metrics")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", runtime.WithHTTPPathPattern("/v1/metrics")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -154,11 +143,8 @@ func RegisterMetricsServiceHandlerClient(ctx context.Context, mux *runtime.Serve runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_MetricsService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - return nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service_grpc.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service_grpc.pb.go index fc668643c1..328b74a12a 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service_grpc.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/metrics/v1/metrics_service_grpc.pb.go @@ -1,7 +1,21 @@ +// Copyright 2019, OpenTelemetry 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. + // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.1.0 -// - protoc v3.21.6 +// - protoc-gen-go-grpc v1.5.1 +// - protoc v7.35.0 // source: opentelemetry/proto/collector/metrics/v1/metrics_service.proto package v1 @@ -15,12 +29,20 @@ import ( // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + MetricsService_Export_FullMethodName = "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export" +) // MetricsServiceClient is the client API for MetricsService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// Service that can be used to push metrics between one Application +// instrumented with OpenTelemetry and a collector, or between a collector and a +// central collector. type MetricsServiceClient interface { Export(ctx context.Context, in *ExportMetricsServiceRequest, opts ...grpc.CallOption) (*ExportMetricsServiceResponse, error) } @@ -34,8 +56,9 @@ func NewMetricsServiceClient(cc grpc.ClientConnInterface) MetricsServiceClient { } func (c *metricsServiceClient) Export(ctx context.Context, in *ExportMetricsServiceRequest, opts ...grpc.CallOption) (*ExportMetricsServiceResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ExportMetricsServiceResponse) - err := c.cc.Invoke(ctx, "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", in, out, opts...) + err := c.cc.Invoke(ctx, MetricsService_Export_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -44,20 +67,28 @@ func (c *metricsServiceClient) Export(ctx context.Context, in *ExportMetricsServ // MetricsServiceServer is the server API for MetricsService service. // All implementations must embed UnimplementedMetricsServiceServer -// for forward compatibility +// for forward compatibility. +// +// Service that can be used to push metrics between one Application +// instrumented with OpenTelemetry and a collector, or between a collector and a +// central collector. type MetricsServiceServer interface { Export(context.Context, *ExportMetricsServiceRequest) (*ExportMetricsServiceResponse, error) mustEmbedUnimplementedMetricsServiceServer() } -// UnimplementedMetricsServiceServer must be embedded to have forward compatible implementations. -type UnimplementedMetricsServiceServer struct { -} +// UnimplementedMetricsServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedMetricsServiceServer struct{} func (UnimplementedMetricsServiceServer) Export(context.Context, *ExportMetricsServiceRequest) (*ExportMetricsServiceResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Export not implemented") } func (UnimplementedMetricsServiceServer) mustEmbedUnimplementedMetricsServiceServer() {} +func (UnimplementedMetricsServiceServer) testEmbeddedByValue() {} // UnsafeMetricsServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to MetricsServiceServer will @@ -67,6 +98,13 @@ type UnsafeMetricsServiceServer interface { } func RegisterMetricsServiceServer(s grpc.ServiceRegistrar, srv MetricsServiceServer) { + // If the following call pancis, it indicates UnimplementedMetricsServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } s.RegisterService(&MetricsService_ServiceDesc, srv) } @@ -80,7 +118,7 @@ func _MetricsService_Export_Handler(srv interface{}, ctx context.Context, dec fu } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", + FullMethod: MetricsService_Export_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MetricsServiceServer).Export(ctx, req.(*ExportMetricsServiceRequest)) diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go index c1af04e84e..2234be22dd 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/collector/trace/v1/trace_service.proto package v1 @@ -26,6 +26,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -36,25 +37,22 @@ const ( ) type ExportTraceServiceRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // An array of ResourceSpans. // For data coming from a single resource this array will typically contain one // element. Intermediary nodes (such as OpenTelemetry Collector) that receive // data from multiple origins typically batch the data before forwarding further and // in that case this array will contain multiple elements. ResourceSpans []*v1.ResourceSpans `protobuf:"bytes,1,rep,name=resource_spans,json=resourceSpans,proto3" json:"resource_spans,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportTraceServiceRequest) Reset() { *x = ExportTraceServiceRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportTraceServiceRequest) String() string { @@ -65,7 +63,7 @@ func (*ExportTraceServiceRequest) ProtoMessage() {} func (x *ExportTraceServiceRequest) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -88,10 +86,7 @@ func (x *ExportTraceServiceRequest) GetResourceSpans() []*v1.ResourceSpans { } type ExportTraceServiceResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The details of a partially successful export request. // // If the request is only partially accepted @@ -108,15 +103,15 @@ type ExportTraceServiceResponse struct { // `error_message` = "") is equivalent to it not being set/present. Senders // SHOULD interpret it the same way as in the full success case. PartialSuccess *ExportTracePartialSuccess `protobuf:"bytes,1,opt,name=partial_success,json=partialSuccess,proto3" json:"partial_success,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportTraceServiceResponse) Reset() { *x = ExportTraceServiceResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportTraceServiceResponse) String() string { @@ -127,7 +122,7 @@ func (*ExportTraceServiceResponse) ProtoMessage() {} func (x *ExportTraceServiceResponse) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -150,10 +145,7 @@ func (x *ExportTraceServiceResponse) GetPartialSuccess() *ExportTracePartialSucc } type ExportTracePartialSuccess struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The number of rejected spans. // // A `rejected_` field holding a `0` value indicates that the @@ -166,16 +158,16 @@ type ExportTracePartialSuccess struct { // // error_message is an optional field. An error_message with an empty value // is equivalent to it not being set. - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` + ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportTracePartialSuccess) Reset() { *x = ExportTracePartialSuccess{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportTracePartialSuccess) String() string { @@ -186,7 +178,7 @@ func (*ExportTracePartialSuccess) ProtoMessage() {} func (x *ExportTracePartialSuccess) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -217,75 +209,34 @@ func (x *ExportTracePartialSuccess) GetErrorMessage() string { var File_opentelemetry_proto_collector_trace_v1_trace_service_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc = []byte{ - 0x0a, 0x3a, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x73, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x26, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, - 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x28, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, - 0x76, 0x31, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x6f, - 0x0a, 0x19, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x52, 0x0a, 0x0e, 0x72, - 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x18, 0x01, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, - 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, - 0x52, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x22, - 0x88, 0x01, 0x0a, 0x1a, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6a, - 0x0a, 0x0f, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, - 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x41, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, - 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, - 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, 0x61, 0x72, 0x74, - 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x52, 0x0e, 0x70, 0x61, 0x72, 0x74, - 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x67, 0x0a, 0x19, 0x45, 0x78, - 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, - 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x12, 0x25, 0x0a, 0x0e, 0x72, 0x65, 0x6a, 0x65, 0x63, - 0x74, 0x65, 0x64, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, - 0x0d, 0x72, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x65, 0x64, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x23, - 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, - 0x61, 0x67, 0x65, 0x32, 0xa2, 0x01, 0x0a, 0x0c, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x12, 0x91, 0x01, 0x0a, 0x06, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x12, - 0x41, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, - 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x1a, 0x42, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, - 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, - 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x9c, 0x01, 0x0a, 0x29, 0x69, 0x6f, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x42, 0x11, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x31, 0x67, 0x6f, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, - 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0xaa, 0x02, - 0x26, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x54, - 0x72, 0x61, 0x63, 0x65, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc = "" + + "\n" + + ":opentelemetry/proto/collector/trace/v1/trace_service.proto\x12&opentelemetry.proto.collector.trace.v1\x1a(opentelemetry/proto/trace/v1/trace.proto\"o\n" + + "\x19ExportTraceServiceRequest\x12R\n" + + "\x0eresource_spans\x18\x01 \x03(\v2+.opentelemetry.proto.trace.v1.ResourceSpansR\rresourceSpans\"\x88\x01\n" + + "\x1aExportTraceServiceResponse\x12j\n" + + "\x0fpartial_success\x18\x01 \x01(\v2A.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccessR\x0epartialSuccess\"g\n" + + "\x19ExportTracePartialSuccess\x12%\n" + + "\x0erejected_spans\x18\x01 \x01(\x03R\rrejectedSpans\x12#\n" + + "\rerror_message\x18\x02 \x01(\tR\ferrorMessage2\xa2\x01\n" + + "\fTraceService\x12\x91\x01\n" + + "\x06Export\x12A.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest\x1aB.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse\"\x00B\x9c\x01\n" + + ")io.opentelemetry.proto.collector.trace.v1B\x11TraceServiceProtoP\x01Z1go.opentelemetry.io/proto/otlp/collector/trace/v1\xaa\x02&OpenTelemetry.Proto.Collector.Trace.V1b\x06proto3" var ( file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescOnce sync.Once - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData = file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc + file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData []byte ) func file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescGZIP() []byte { file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData) + file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc), len(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc))) }) return file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData } var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes = make([]protoimpl.MessageInfo, 3) -var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_goTypes = []any{ (*ExportTraceServiceRequest)(nil), // 0: opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest (*ExportTraceServiceResponse)(nil), // 1: opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse (*ExportTracePartialSuccess)(nil), // 2: opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess @@ -308,49 +259,11 @@ func file_opentelemetry_proto_collector_trace_v1_trace_service_proto_init() { if File_opentelemetry_proto_collector_trace_v1_trace_service_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportTraceServiceRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportTraceServiceResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportTracePartialSuccess); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc), len(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc)), NumEnums: 0, NumMessages: 3, NumExtensions: 0, @@ -361,7 +274,6 @@ func file_opentelemetry_proto_collector_trace_v1_trace_service_proto_init() { MessageInfos: file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes, }.Build() File_opentelemetry_proto_collector_trace_v1_trace_service_proto = out.File - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc = nil file_opentelemetry_proto_collector_trace_v1_trace_service_proto_goTypes = nil file_opentelemetry_proto_collector_trace_v1_trace_service_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go index bb1bd261ed..b2cf91e2f6 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go @@ -10,6 +10,7 @@ package v1 import ( "context" + "errors" "io" "net/http" @@ -24,62 +25,56 @@ import ( ) // Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = metadata.Join +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = errors.New + _ = runtime.String + _ = utilities.NewDoubleArray + _ = metadata.Join +) func request_TraceService_Export_0(ctx context.Context, marshaler runtime.Marshaler, client TraceServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportTraceServiceRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportTraceServiceRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.Export(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_TraceService_Export_0(ctx context.Context, marshaler runtime.Marshaler, server TraceServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportTraceServiceRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportTraceServiceRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.Export(ctx, &protoReq) return msg, metadata, err - } // RegisterTraceServiceHandlerServer registers the http handlers for service TraceService to "mux". // UnaryRPC :call TraceServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterTraceServiceHandlerFromEndpoint instead. +// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterTraceServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server TraceServiceServer) error { - - mux.Handle("POST", pattern_TraceService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_TraceService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/traces")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/traces")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -91,9 +86,7 @@ func RegisterTraceServiceHandlerServer(ctx context.Context, mux *runtime.ServeMu runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_TraceService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) return nil @@ -102,25 +95,24 @@ func RegisterTraceServiceHandlerServer(ctx context.Context, mux *runtime.ServeMu // RegisterTraceServiceHandlerFromEndpoint is same as RegisterTraceServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterTraceServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) + conn, err := grpc.NewClient(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } }() }() - return RegisterTraceServiceHandler(ctx, mux, conn) } @@ -134,16 +126,13 @@ func RegisterTraceServiceHandler(ctx context.Context, mux *runtime.ServeMux, con // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "TraceServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "TraceServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "TraceServiceClient" to call the correct interceptors. +// "TraceServiceClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterTraceServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client TraceServiceClient) error { - - mux.Handle("POST", pattern_TraceService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_TraceService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/traces")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/traces")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -154,11 +143,8 @@ func RegisterTraceServiceHandlerClient(ctx context.Context, mux *runtime.ServeMu runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_TraceService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - return nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go index 892864ea62..0c93f2da4c 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go @@ -1,7 +1,21 @@ +// Copyright 2019, OpenTelemetry 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. + // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.1.0 -// - protoc v3.21.6 +// - protoc-gen-go-grpc v1.5.1 +// - protoc v7.35.0 // source: opentelemetry/proto/collector/trace/v1/trace_service.proto package v1 @@ -15,12 +29,20 @@ import ( // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + TraceService_Export_FullMethodName = "/opentelemetry.proto.collector.trace.v1.TraceService/Export" +) // TraceServiceClient is the client API for TraceService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// Service that can be used to push spans between one Application instrumented with +// OpenTelemetry and a collector, or between a collector and a central collector (in this +// case spans are sent/received to/from multiple Applications). type TraceServiceClient interface { Export(ctx context.Context, in *ExportTraceServiceRequest, opts ...grpc.CallOption) (*ExportTraceServiceResponse, error) } @@ -34,8 +56,9 @@ func NewTraceServiceClient(cc grpc.ClientConnInterface) TraceServiceClient { } func (c *traceServiceClient) Export(ctx context.Context, in *ExportTraceServiceRequest, opts ...grpc.CallOption) (*ExportTraceServiceResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ExportTraceServiceResponse) - err := c.cc.Invoke(ctx, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", in, out, opts...) + err := c.cc.Invoke(ctx, TraceService_Export_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -44,20 +67,28 @@ func (c *traceServiceClient) Export(ctx context.Context, in *ExportTraceServiceR // TraceServiceServer is the server API for TraceService service. // All implementations must embed UnimplementedTraceServiceServer -// for forward compatibility +// for forward compatibility. +// +// Service that can be used to push spans between one Application instrumented with +// OpenTelemetry and a collector, or between a collector and a central collector (in this +// case spans are sent/received to/from multiple Applications). type TraceServiceServer interface { Export(context.Context, *ExportTraceServiceRequest) (*ExportTraceServiceResponse, error) mustEmbedUnimplementedTraceServiceServer() } -// UnimplementedTraceServiceServer must be embedded to have forward compatible implementations. -type UnimplementedTraceServiceServer struct { -} +// UnimplementedTraceServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedTraceServiceServer struct{} func (UnimplementedTraceServiceServer) Export(context.Context, *ExportTraceServiceRequest) (*ExportTraceServiceResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Export not implemented") } func (UnimplementedTraceServiceServer) mustEmbedUnimplementedTraceServiceServer() {} +func (UnimplementedTraceServiceServer) testEmbeddedByValue() {} // UnsafeTraceServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to TraceServiceServer will @@ -67,6 +98,13 @@ type UnsafeTraceServiceServer interface { } func RegisterTraceServiceServer(s grpc.ServiceRegistrar, srv TraceServiceServer) { + // If the following call pancis, it indicates UnimplementedTraceServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } s.RegisterService(&TraceService_ServiceDesc, srv) } @@ -80,7 +118,7 @@ func _TraceService_Export_Handler(srv interface{}, ctx context.Context, dec func } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/opentelemetry.proto.collector.trace.v1.TraceService/Export", + FullMethod: TraceService_Export_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TraceServiceServer).Export(ctx, req.(*ExportTraceServiceRequest)) diff --git a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go index cef3580008..626d8c600e 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/common/v1/common.proto package v1 @@ -25,6 +25,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -38,14 +39,12 @@ const ( // primitive value such as a string or integer or it may contain an arbitrary nested // object containing arrays, key-value lists and primitives. type AnyValue struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The value is one of the listed fields. It is valid for all values to be unspecified // in which case this AnyValue is considered to be "empty". // - // Types that are assignable to Value: + // Types that are valid to be assigned to Value: + // // *AnyValue_StringValue // *AnyValue_BoolValue // *AnyValue_IntValue @@ -54,16 +53,16 @@ type AnyValue struct { // *AnyValue_KvlistValue // *AnyValue_BytesValue // *AnyValue_StringValueStrindex - Value isAnyValue_Value `protobuf_oneof:"value"` + Value isAnyValue_Value `protobuf_oneof:"value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *AnyValue) Reset() { *x = AnyValue{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *AnyValue) String() string { @@ -74,7 +73,7 @@ func (*AnyValue) ProtoMessage() {} func (x *AnyValue) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -89,65 +88,81 @@ func (*AnyValue) Descriptor() ([]byte, []int) { return file_opentelemetry_proto_common_v1_common_proto_rawDescGZIP(), []int{0} } -func (m *AnyValue) GetValue() isAnyValue_Value { - if m != nil { - return m.Value +func (x *AnyValue) GetValue() isAnyValue_Value { + if x != nil { + return x.Value } return nil } func (x *AnyValue) GetStringValue() string { - if x, ok := x.GetValue().(*AnyValue_StringValue); ok { - return x.StringValue + if x != nil { + if x, ok := x.Value.(*AnyValue_StringValue); ok { + return x.StringValue + } } return "" } func (x *AnyValue) GetBoolValue() bool { - if x, ok := x.GetValue().(*AnyValue_BoolValue); ok { - return x.BoolValue + if x != nil { + if x, ok := x.Value.(*AnyValue_BoolValue); ok { + return x.BoolValue + } } return false } func (x *AnyValue) GetIntValue() int64 { - if x, ok := x.GetValue().(*AnyValue_IntValue); ok { - return x.IntValue + if x != nil { + if x, ok := x.Value.(*AnyValue_IntValue); ok { + return x.IntValue + } } return 0 } func (x *AnyValue) GetDoubleValue() float64 { - if x, ok := x.GetValue().(*AnyValue_DoubleValue); ok { - return x.DoubleValue + if x != nil { + if x, ok := x.Value.(*AnyValue_DoubleValue); ok { + return x.DoubleValue + } } return 0 } func (x *AnyValue) GetArrayValue() *ArrayValue { - if x, ok := x.GetValue().(*AnyValue_ArrayValue); ok { - return x.ArrayValue + if x != nil { + if x, ok := x.Value.(*AnyValue_ArrayValue); ok { + return x.ArrayValue + } } return nil } func (x *AnyValue) GetKvlistValue() *KeyValueList { - if x, ok := x.GetValue().(*AnyValue_KvlistValue); ok { - return x.KvlistValue + if x != nil { + if x, ok := x.Value.(*AnyValue_KvlistValue); ok { + return x.KvlistValue + } } return nil } func (x *AnyValue) GetBytesValue() []byte { - if x, ok := x.GetValue().(*AnyValue_BytesValue); ok { - return x.BytesValue + if x != nil { + if x, ok := x.Value.(*AnyValue_BytesValue); ok { + return x.BytesValue + } } return nil } func (x *AnyValue) GetStringValueStrindex() int32 { - if x, ok := x.GetValue().(*AnyValue_StringValueStrindex); ok { - return x.StringValueStrindex + if x != nil { + if x, ok := x.Value.(*AnyValue_StringValueStrindex); ok { + return x.StringValueStrindex + } } return 0 } @@ -195,6 +210,8 @@ type AnyValue_StringValueStrindex struct { // empty, ignoring its semantic content for the non-Profiling signal. // // Status: [Alpha] + // + // [Since v1.10.0] StringValueStrindex int32 `protobuf:"varint,8,opt,name=string_value_strindex,json=stringValueStrindex,proto3,oneof"` } @@ -217,21 +234,18 @@ func (*AnyValue_StringValueStrindex) isAnyValue_Value() {} // ArrayValue is a list of AnyValue messages. We need ArrayValue as a message // since oneof in AnyValue does not allow repeated fields. type ArrayValue struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Array of values. The array may be empty (contain 0 elements). - Values []*AnyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + Values []*AnyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ArrayValue) Reset() { *x = ArrayValue{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ArrayValue) String() string { @@ -242,7 +256,7 @@ func (*ArrayValue) ProtoMessage() {} func (x *ArrayValue) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -270,26 +284,23 @@ func (x *ArrayValue) GetValues() []*AnyValue { // avoid unnecessary extra wrapping (which slows down the protocol). The 2 approaches // are semantically equivalent. type KeyValueList struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A collection of key/value pairs of key-value pairs. The list may be empty (may // contain 0 elements). // // The keys MUST be unique (it is not allowed to have more than one // value with the same key). // The behavior of software that receives duplicated keys can be unpredictable. - Values []*KeyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + Values []*KeyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *KeyValueList) Reset() { *x = KeyValueList{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *KeyValueList) String() string { @@ -300,7 +311,7 @@ func (*KeyValueList) ProtoMessage() {} func (x *KeyValueList) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -325,10 +336,7 @@ func (x *KeyValueList) GetValues() []*KeyValue { // Represents a key-value pair that is used to store Span attributes, Link // attributes, etc. type KeyValue struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The key name of the pair. // key_strindex MUST NOT be set if key is used. Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` @@ -345,16 +353,18 @@ type KeyValue struct { // empty, ignoring its semantic content for the non-Profiling signal. // // Status: [Alpha] - KeyStrindex int32 `protobuf:"varint,3,opt,name=key_strindex,json=keyStrindex,proto3" json:"key_strindex,omitempty"` + // + // [Since v1.10.0] + KeyStrindex int32 `protobuf:"varint,3,opt,name=key_strindex,json=keyStrindex,proto3" json:"key_strindex,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *KeyValue) Reset() { *x = KeyValue{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *KeyValue) String() string { @@ -365,7 +375,7 @@ func (*KeyValue) ProtoMessage() {} func (x *KeyValue) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -404,10 +414,7 @@ func (x *KeyValue) GetKeyStrindex() int32 { // InstrumentationScope is a message representing the instrumentation scope information // such as the fully qualified name and version. type InstrumentationScope struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A name denoting the Instrumentation scope. // An empty instrumentation scope name means the name is unknown. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` @@ -423,15 +430,15 @@ type InstrumentationScope struct { // can be discarded because their keys are too long or because there are too many // attributes. If this value is 0, then no attributes were dropped. DroppedAttributesCount uint32 `protobuf:"varint,4,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *InstrumentationScope) Reset() { *x = InstrumentationScope{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *InstrumentationScope) String() string { @@ -442,7 +449,7 @@ func (*InstrumentationScope) ProtoMessage() {} func (x *InstrumentationScope) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -489,11 +496,10 @@ func (x *InstrumentationScope) GetDroppedAttributesCount() uint32 { // Entity represents an object of interest associated with produced telemetry: e.g spans, metrics, profiles, or logs. // // Status: [Development] +// +// [Since v1.6.0] type EntityRef struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The Schema URL, if known. This is the identifier of the Schema that the entity data // is recorded in. To learn more about Schema URL see // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url @@ -518,15 +524,15 @@ type EntityRef struct { // These attribute keys are not part of entity's identity. // These keys MUST exist in the containing {message}.attributes. DescriptionKeys []string `protobuf:"bytes,4,rep,name=description_keys,json=descriptionKeys,proto3" json:"description_keys,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *EntityRef) Reset() { *x = EntityRef{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *EntityRef) String() string { @@ -537,7 +543,7 @@ func (*EntityRef) ProtoMessage() {} func (x *EntityRef) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -582,101 +588,60 @@ func (x *EntityRef) GetDescriptionKeys() []string { var File_opentelemetry_proto_common_v1_common_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_common_v1_common_proto_rawDesc = []byte{ - 0x0a, 0x2a, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, 0x2f, - 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1d, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x22, 0x96, 0x03, 0x0a, 0x08, - 0x41, 0x6e, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x23, 0x0a, 0x0c, 0x73, 0x74, 0x72, 0x69, - 0x6e, 0x67, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, - 0x52, 0x0b, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1f, 0x0a, - 0x0a, 0x62, 0x6f, 0x6f, 0x6c, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x08, 0x48, 0x00, 0x52, 0x09, 0x62, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1d, - 0x0a, 0x09, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x03, 0x48, 0x00, 0x52, 0x08, 0x69, 0x6e, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x23, 0x0a, - 0x0c, 0x64, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x04, 0x20, - 0x01, 0x28, 0x01, 0x48, 0x00, 0x52, 0x0b, 0x64, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x12, 0x4c, 0x0a, 0x0b, 0x61, 0x72, 0x72, 0x61, 0x79, 0x5f, 0x76, 0x61, 0x6c, 0x75, - 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, - 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x72, 0x72, 0x61, 0x79, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x48, 0x00, 0x52, 0x0a, 0x61, 0x72, 0x72, 0x61, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x12, 0x50, 0x0a, 0x0c, 0x6b, 0x76, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, - 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, - 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, - 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4c, - 0x69, 0x73, 0x74, 0x48, 0x00, 0x52, 0x0b, 0x6b, 0x76, 0x6c, 0x69, 0x73, 0x74, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x12, 0x21, 0x0a, 0x0b, 0x62, 0x79, 0x74, 0x65, 0x73, 0x5f, 0x76, 0x61, 0x6c, 0x75, - 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x0a, 0x62, 0x79, 0x74, 0x65, 0x73, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x34, 0x0a, 0x15, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x5f, - 0x76, 0x61, 0x6c, 0x75, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x18, 0x08, - 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x13, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x42, 0x07, 0x0a, 0x05, 0x76, - 0x61, 0x6c, 0x75, 0x65, 0x22, 0x4d, 0x0a, 0x0a, 0x41, 0x72, 0x72, 0x61, 0x79, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x12, 0x3f, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, - 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, - 0x76, 0x31, 0x2e, 0x41, 0x6e, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x76, 0x61, 0x6c, - 0x75, 0x65, 0x73, 0x22, 0x4f, 0x0a, 0x0c, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4c, - 0x69, 0x73, 0x74, 0x12, 0x3f, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x01, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, - 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x76, 0x61, - 0x6c, 0x75, 0x65, 0x73, 0x22, 0x7e, 0x0a, 0x08, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, - 0x65, 0x79, 0x12, 0x3d, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, - 0x31, 0x2e, 0x41, 0x6e, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, - 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x6b, 0x65, 0x79, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x64, 0x65, - 0x78, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0b, 0x6b, 0x65, 0x79, 0x53, 0x74, 0x72, 0x69, - 0x6e, 0x64, 0x65, 0x78, 0x22, 0xc7, 0x01, 0x0a, 0x14, 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, - 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x12, 0x0a, - 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, - 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x47, 0x0a, 0x0a, 0x61, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, - 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, - 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, - 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, - 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x82, - 0x01, 0x0a, 0x09, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x52, 0x65, 0x66, 0x12, 0x1d, 0x0a, 0x0a, - 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x09, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x55, 0x72, 0x6c, 0x12, 0x12, 0x0a, 0x04, 0x74, - 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, - 0x17, 0x0a, 0x07, 0x69, 0x64, 0x5f, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x09, - 0x52, 0x06, 0x69, 0x64, 0x4b, 0x65, 0x79, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x64, 0x65, 0x73, 0x63, - 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x04, 0x20, 0x03, - 0x28, 0x09, 0x52, 0x0f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4b, - 0x65, 0x79, 0x73, 0x42, 0x7b, 0x0a, 0x20, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, - 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x28, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, - 0xaa, 0x02, 0x1d, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x56, 0x31, - 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_common_v1_common_proto_rawDesc = "" + + "\n" + + "*opentelemetry/proto/common/v1/common.proto\x12\x1dopentelemetry.proto.common.v1\"\x96\x03\n" + + "\bAnyValue\x12#\n" + + "\fstring_value\x18\x01 \x01(\tH\x00R\vstringValue\x12\x1f\n" + + "\n" + + "bool_value\x18\x02 \x01(\bH\x00R\tboolValue\x12\x1d\n" + + "\tint_value\x18\x03 \x01(\x03H\x00R\bintValue\x12#\n" + + "\fdouble_value\x18\x04 \x01(\x01H\x00R\vdoubleValue\x12L\n" + + "\varray_value\x18\x05 \x01(\v2).opentelemetry.proto.common.v1.ArrayValueH\x00R\n" + + "arrayValue\x12P\n" + + "\fkvlist_value\x18\x06 \x01(\v2+.opentelemetry.proto.common.v1.KeyValueListH\x00R\vkvlistValue\x12!\n" + + "\vbytes_value\x18\a \x01(\fH\x00R\n" + + "bytesValue\x124\n" + + "\x15string_value_strindex\x18\b \x01(\x05H\x00R\x13stringValueStrindexB\a\n" + + "\x05value\"M\n" + + "\n" + + "ArrayValue\x12?\n" + + "\x06values\x18\x01 \x03(\v2'.opentelemetry.proto.common.v1.AnyValueR\x06values\"O\n" + + "\fKeyValueList\x12?\n" + + "\x06values\x18\x01 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\x06values\"~\n" + + "\bKeyValue\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12=\n" + + "\x05value\x18\x02 \x01(\v2'.opentelemetry.proto.common.v1.AnyValueR\x05value\x12!\n" + + "\fkey_strindex\x18\x03 \x01(\x05R\vkeyStrindex\"\xc7\x01\n" + + "\x14InstrumentationScope\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x18\n" + + "\aversion\x18\x02 \x01(\tR\aversion\x12G\n" + + "\n" + + "attributes\x18\x03 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\x04 \x01(\rR\x16droppedAttributesCount\"\x82\x01\n" + + "\tEntityRef\x12\x1d\n" + + "\n" + + "schema_url\x18\x01 \x01(\tR\tschemaUrl\x12\x12\n" + + "\x04type\x18\x02 \x01(\tR\x04type\x12\x17\n" + + "\aid_keys\x18\x03 \x03(\tR\x06idKeys\x12)\n" + + "\x10description_keys\x18\x04 \x03(\tR\x0fdescriptionKeysB{\n" + + " io.opentelemetry.proto.common.v1B\vCommonProtoP\x01Z(go.opentelemetry.io/proto/otlp/common/v1\xaa\x02\x1dOpenTelemetry.Proto.Common.V1b\x06proto3" var ( file_opentelemetry_proto_common_v1_common_proto_rawDescOnce sync.Once - file_opentelemetry_proto_common_v1_common_proto_rawDescData = file_opentelemetry_proto_common_v1_common_proto_rawDesc + file_opentelemetry_proto_common_v1_common_proto_rawDescData []byte ) func file_opentelemetry_proto_common_v1_common_proto_rawDescGZIP() []byte { file_opentelemetry_proto_common_v1_common_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_common_v1_common_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_common_v1_common_proto_rawDescData) + file_opentelemetry_proto_common_v1_common_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_common_v1_common_proto_rawDesc), len(file_opentelemetry_proto_common_v1_common_proto_rawDesc))) }) return file_opentelemetry_proto_common_v1_common_proto_rawDescData } var file_opentelemetry_proto_common_v1_common_proto_msgTypes = make([]protoimpl.MessageInfo, 6) -var file_opentelemetry_proto_common_v1_common_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_common_v1_common_proto_goTypes = []any{ (*AnyValue)(nil), // 0: opentelemetry.proto.common.v1.AnyValue (*ArrayValue)(nil), // 1: opentelemetry.proto.common.v1.ArrayValue (*KeyValueList)(nil), // 2: opentelemetry.proto.common.v1.KeyValueList @@ -703,81 +668,7 @@ func file_opentelemetry_proto_common_v1_common_proto_init() { if File_opentelemetry_proto_common_v1_common_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_common_v1_common_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AnyValue); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ArrayValue); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*KeyValueList); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*KeyValue); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*InstrumentationScope); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*EntityRef); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[0].OneofWrappers = []interface{}{ + file_opentelemetry_proto_common_v1_common_proto_msgTypes[0].OneofWrappers = []any{ (*AnyValue_StringValue)(nil), (*AnyValue_BoolValue)(nil), (*AnyValue_IntValue)(nil), @@ -791,7 +682,7 @@ func file_opentelemetry_proto_common_v1_common_proto_init() { out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_common_v1_common_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_common_v1_common_proto_rawDesc), len(file_opentelemetry_proto_common_v1_common_proto_rawDesc)), NumEnums: 0, NumMessages: 6, NumExtensions: 0, @@ -802,7 +693,6 @@ func file_opentelemetry_proto_common_v1_common_proto_init() { MessageInfos: file_opentelemetry_proto_common_v1_common_proto_msgTypes, }.Build() File_opentelemetry_proto_common_v1_common_proto = out.File - file_opentelemetry_proto_common_v1_common_proto_rawDesc = nil file_opentelemetry_proto_common_v1_common_proto_goTypes = nil file_opentelemetry_proto_common_v1_common_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/logs/v1/logs.pb.go b/vendor/go.opentelemetry.io/proto/otlp/logs/v1/logs.pb.go index ab284c0c0d..5504e11d8c 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/logs/v1/logs.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/logs/v1/logs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/logs/v1/logs.proto package v1 @@ -27,6 +27,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -158,8 +159,7 @@ func (SeverityNumber) EnumDescriptor() ([]byte, []int) { // a bit-mask. To extract the bit-field, for example, use an // expression like: // -// (logRecord.flags & LOG_RECORD_FLAGS_TRACE_FLAGS_MASK) -// +// (logRecord.flags & LOG_RECORD_FLAGS_TRACE_FLAGS_MASK) type LogRecordFlags int32 const ( @@ -220,25 +220,22 @@ func (LogRecordFlags) EnumDescriptor() ([]byte, []int) { // When new fields are added into this message, the OTLP request MUST be updated // as well. type LogsData struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // An array of ResourceLogs. // For data coming from a single resource this array will typically contain // one element. Intermediary nodes that receive data from multiple origins // typically batch the data before forwarding further and in that case this // array will contain multiple elements. - ResourceLogs []*ResourceLogs `protobuf:"bytes,1,rep,name=resource_logs,json=resourceLogs,proto3" json:"resource_logs,omitempty"` + ResourceLogs []*ResourceLogs `protobuf:"bytes,1,rep,name=resource_logs,json=resourceLogs,proto3" json:"resource_logs,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *LogsData) Reset() { *x = LogsData{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *LogsData) String() string { @@ -249,7 +246,7 @@ func (*LogsData) ProtoMessage() {} func (x *LogsData) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -273,10 +270,7 @@ func (x *LogsData) GetResourceLogs() []*ResourceLogs { // A collection of ScopeLogs from a Resource. type ResourceLogs struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The resource for the logs in this message. // If this field is not set then resource info is unknown. Resource *v1.Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` @@ -288,16 +282,16 @@ type ResourceLogs struct { // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to the data in the "resource" field. It does not apply // to the data in the "scope_logs" field which have their own schema_url field. - SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ResourceLogs) Reset() { *x = ResourceLogs{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ResourceLogs) String() string { @@ -308,7 +302,7 @@ func (*ResourceLogs) ProtoMessage() {} func (x *ResourceLogs) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -346,10 +340,7 @@ func (x *ResourceLogs) GetSchemaUrl() string { // A collection of Logs produced by a Scope. type ScopeLogs struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The instrumentation scope information for the logs in this message. // Semantically when InstrumentationScope isn't set, it is equivalent with // an empty instrumentation scope name (unknown). @@ -362,16 +353,16 @@ type ScopeLogs struct { // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to the data in the "scope" field and all logs in the // "log_records" field. - SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ScopeLogs) Reset() { *x = ScopeLogs{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ScopeLogs) String() string { @@ -382,7 +373,7 @@ func (*ScopeLogs) ProtoMessage() {} func (x *ScopeLogs) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -421,10 +412,7 @@ func (x *ScopeLogs) GetSchemaUrl() string { // A log record according to OpenTelemetry Log Data Model: // https://github.com/open-telemetry/oteps/blob/main/text/logs/0097-log-data-model.md type LogRecord struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // time_unix_nano is the time when the event occurred. // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970. // Value of 0 indicates unknown or missing timestamp. @@ -502,16 +490,18 @@ type LogRecord struct { // as an event. // // [Optional]. - EventName string `protobuf:"bytes,12,opt,name=event_name,json=eventName,proto3" json:"event_name,omitempty"` + // + // [Since v1.5.0] + EventName string `protobuf:"bytes,12,opt,name=event_name,json=eventName,proto3" json:"event_name,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *LogRecord) Reset() { *x = LogRecord{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *LogRecord) String() string { @@ -522,7 +512,7 @@ func (*LogRecord) ProtoMessage() {} func (x *LogRecord) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -616,156 +606,86 @@ func (x *LogRecord) GetEventName() string { var File_opentelemetry_proto_logs_v1_logs_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_logs_v1_logs_proto_rawDesc = []byte{ - 0x0a, 0x26, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6c, 0x6f, 0x67, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6c, 0x6f, - 0x67, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1b, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6c, 0x6f, - 0x67, 0x73, 0x2e, 0x76, 0x31, 0x1a, 0x2a, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, - 0x65, 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, - 0x6e, 0x2f, 0x76, 0x31, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x1a, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2f, - 0x76, 0x31, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x22, 0x5a, 0x0a, 0x08, 0x4c, 0x6f, 0x67, 0x73, 0x44, 0x61, 0x74, 0x61, 0x12, 0x4e, 0x0a, - 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x6c, 0x6f, 0x67, 0x73, 0x18, 0x01, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, - 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6c, 0x6f, 0x67, 0x73, 0x2e, - 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4c, 0x6f, 0x67, 0x73, 0x52, - 0x0c, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4c, 0x6f, 0x67, 0x73, 0x22, 0xc3, 0x01, - 0x0a, 0x0c, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4c, 0x6f, 0x67, 0x73, 0x12, 0x45, - 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x29, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, - 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, - 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x45, 0x0a, 0x0a, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x6c, - 0x6f, 0x67, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x6f, 0x70, 0x65, 0x6e, - 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, - 0x6c, 0x6f, 0x67, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x4c, 0x6f, 0x67, - 0x73, 0x52, 0x09, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x4c, 0x6f, 0x67, 0x73, 0x12, 0x1d, 0x0a, 0x0a, - 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x09, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x55, 0x72, 0x6c, 0x4a, 0x06, 0x08, 0xe8, 0x07, - 0x10, 0xe9, 0x07, 0x22, 0xbe, 0x01, 0x0a, 0x09, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x4c, 0x6f, 0x67, - 0x73, 0x12, 0x49, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x33, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, - 0x2e, 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x47, 0x0a, 0x0b, - 0x6c, 0x6f, 0x67, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x26, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6c, 0x6f, 0x67, 0x73, 0x2e, 0x76, 0x31, 0x2e, - 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x52, 0x0a, 0x6c, 0x6f, 0x67, 0x52, 0x65, - 0x63, 0x6f, 0x72, 0x64, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, - 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x63, 0x68, 0x65, 0x6d, - 0x61, 0x55, 0x72, 0x6c, 0x22, 0x92, 0x04, 0x0a, 0x09, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x63, 0x6f, - 0x72, 0x64, 0x12, 0x24, 0x0a, 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, - 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0c, 0x74, 0x69, 0x6d, 0x65, - 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x35, 0x0a, 0x17, 0x6f, 0x62, 0x73, 0x65, - 0x72, 0x76, 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, - 0x61, 0x6e, 0x6f, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x06, 0x52, 0x14, 0x6f, 0x62, 0x73, 0x65, 0x72, - 0x76, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, - 0x54, 0x0a, 0x0f, 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x5f, 0x6e, 0x75, 0x6d, 0x62, - 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6c, - 0x6f, 0x67, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x4e, - 0x75, 0x6d, 0x62, 0x65, 0x72, 0x52, 0x0e, 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x4e, - 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x23, 0x0a, 0x0d, 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, - 0x79, 0x5f, 0x74, 0x65, 0x78, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x73, 0x65, - 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x54, 0x65, 0x78, 0x74, 0x12, 0x3b, 0x0a, 0x04, 0x62, 0x6f, - 0x64, 0x79, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, - 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x6e, 0x79, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, - 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, - 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, - 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, - 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, 0x72, 0x69, - 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x6c, - 0x61, 0x67, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x07, 0x52, 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, - 0x12, 0x19, 0x0a, 0x08, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x09, 0x20, 0x01, - 0x28, 0x0c, 0x52, 0x07, 0x74, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x73, - 0x70, 0x61, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x70, - 0x61, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x6e, 0x61, - 0x6d, 0x65, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x4e, - 0x61, 0x6d, 0x65, 0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x2a, 0xc3, 0x05, 0x0a, 0x0e, 0x53, 0x65, - 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x1f, 0x0a, 0x1b, - 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, - 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x19, 0x0a, - 0x15, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, - 0x5f, 0x54, 0x52, 0x41, 0x43, 0x45, 0x10, 0x01, 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, - 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x54, 0x52, 0x41, 0x43, - 0x45, 0x32, 0x10, 0x02, 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, - 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x54, 0x52, 0x41, 0x43, 0x45, 0x33, 0x10, 0x03, - 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, - 0x42, 0x45, 0x52, 0x5f, 0x54, 0x52, 0x41, 0x43, 0x45, 0x34, 0x10, 0x04, 0x12, 0x19, 0x0a, 0x15, - 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, - 0x44, 0x45, 0x42, 0x55, 0x47, 0x10, 0x05, 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, 0x52, - 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x44, 0x45, 0x42, 0x55, 0x47, - 0x32, 0x10, 0x06, 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, - 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x44, 0x45, 0x42, 0x55, 0x47, 0x33, 0x10, 0x07, 0x12, - 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, - 0x45, 0x52, 0x5f, 0x44, 0x45, 0x42, 0x55, 0x47, 0x34, 0x10, 0x08, 0x12, 0x18, 0x0a, 0x14, 0x53, - 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x49, - 0x4e, 0x46, 0x4f, 0x10, 0x09, 0x12, 0x19, 0x0a, 0x15, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, - 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x49, 0x4e, 0x46, 0x4f, 0x32, 0x10, 0x0a, - 0x12, 0x19, 0x0a, 0x15, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, - 0x42, 0x45, 0x52, 0x5f, 0x49, 0x4e, 0x46, 0x4f, 0x33, 0x10, 0x0b, 0x12, 0x19, 0x0a, 0x15, 0x53, - 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x49, - 0x4e, 0x46, 0x4f, 0x34, 0x10, 0x0c, 0x12, 0x18, 0x0a, 0x14, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, - 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x57, 0x41, 0x52, 0x4e, 0x10, 0x0d, - 0x12, 0x19, 0x0a, 0x15, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, - 0x42, 0x45, 0x52, 0x5f, 0x57, 0x41, 0x52, 0x4e, 0x32, 0x10, 0x0e, 0x12, 0x19, 0x0a, 0x15, 0x53, - 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x57, - 0x41, 0x52, 0x4e, 0x33, 0x10, 0x0f, 0x12, 0x19, 0x0a, 0x15, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, - 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x57, 0x41, 0x52, 0x4e, 0x34, 0x10, - 0x10, 0x12, 0x19, 0x0a, 0x15, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, - 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x11, 0x12, 0x1a, 0x0a, 0x16, - 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, - 0x45, 0x52, 0x52, 0x4f, 0x52, 0x32, 0x10, 0x12, 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, - 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x45, 0x52, 0x52, 0x4f, - 0x52, 0x33, 0x10, 0x13, 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, - 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x34, 0x10, 0x14, - 0x12, 0x19, 0x0a, 0x15, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, - 0x42, 0x45, 0x52, 0x5f, 0x46, 0x41, 0x54, 0x41, 0x4c, 0x10, 0x15, 0x12, 0x1a, 0x0a, 0x16, 0x53, - 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x46, - 0x41, 0x54, 0x41, 0x4c, 0x32, 0x10, 0x16, 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, 0x52, - 0x49, 0x54, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x46, 0x41, 0x54, 0x41, 0x4c, - 0x33, 0x10, 0x17, 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, - 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x5f, 0x46, 0x41, 0x54, 0x41, 0x4c, 0x34, 0x10, 0x18, 0x2a, - 0x59, 0x0a, 0x0e, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x46, 0x6c, 0x61, 0x67, - 0x73, 0x12, 0x1f, 0x0a, 0x1b, 0x4c, 0x4f, 0x47, 0x5f, 0x52, 0x45, 0x43, 0x4f, 0x52, 0x44, 0x5f, - 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x44, 0x4f, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x55, 0x53, 0x45, - 0x10, 0x00, 0x12, 0x26, 0x0a, 0x21, 0x4c, 0x4f, 0x47, 0x5f, 0x52, 0x45, 0x43, 0x4f, 0x52, 0x44, - 0x5f, 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x54, 0x52, 0x41, 0x43, 0x45, 0x5f, 0x46, 0x4c, 0x41, - 0x47, 0x53, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0xff, 0x01, 0x42, 0x73, 0x0a, 0x1e, 0x69, 0x6f, - 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6c, 0x6f, 0x67, 0x73, 0x2e, 0x76, 0x31, 0x42, 0x09, 0x4c, 0x6f, - 0x67, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x26, 0x67, 0x6f, 0x2e, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x6c, 0x6f, 0x67, 0x73, 0x2f, 0x76, - 0x31, 0xaa, 0x02, 0x1b, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x4c, 0x6f, 0x67, 0x73, 0x2e, 0x56, 0x31, 0x62, - 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_logs_v1_logs_proto_rawDesc = "" + + "\n" + + "&opentelemetry/proto/logs/v1/logs.proto\x12\x1bopentelemetry.proto.logs.v1\x1a*opentelemetry/proto/common/v1/common.proto\x1a.opentelemetry/proto/resource/v1/resource.proto\"Z\n" + + "\bLogsData\x12N\n" + + "\rresource_logs\x18\x01 \x03(\v2).opentelemetry.proto.logs.v1.ResourceLogsR\fresourceLogs\"\xc3\x01\n" + + "\fResourceLogs\x12E\n" + + "\bresource\x18\x01 \x01(\v2).opentelemetry.proto.resource.v1.ResourceR\bresource\x12E\n" + + "\n" + + "scope_logs\x18\x02 \x03(\v2&.opentelemetry.proto.logs.v1.ScopeLogsR\tscopeLogs\x12\x1d\n" + + "\n" + + "schema_url\x18\x03 \x01(\tR\tschemaUrlJ\x06\b\xe8\a\x10\xe9\a\"\xbe\x01\n" + + "\tScopeLogs\x12I\n" + + "\x05scope\x18\x01 \x01(\v23.opentelemetry.proto.common.v1.InstrumentationScopeR\x05scope\x12G\n" + + "\vlog_records\x18\x02 \x03(\v2&.opentelemetry.proto.logs.v1.LogRecordR\n" + + "logRecords\x12\x1d\n" + + "\n" + + "schema_url\x18\x03 \x01(\tR\tschemaUrl\"\x92\x04\n" + + "\tLogRecord\x12$\n" + + "\x0etime_unix_nano\x18\x01 \x01(\x06R\ftimeUnixNano\x125\n" + + "\x17observed_time_unix_nano\x18\v \x01(\x06R\x14observedTimeUnixNano\x12T\n" + + "\x0fseverity_number\x18\x02 \x01(\x0e2+.opentelemetry.proto.logs.v1.SeverityNumberR\x0eseverityNumber\x12#\n" + + "\rseverity_text\x18\x03 \x01(\tR\fseverityText\x12;\n" + + "\x04body\x18\x05 \x01(\v2'.opentelemetry.proto.common.v1.AnyValueR\x04body\x12G\n" + + "\n" + + "attributes\x18\x06 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\a \x01(\rR\x16droppedAttributesCount\x12\x14\n" + + "\x05flags\x18\b \x01(\aR\x05flags\x12\x19\n" + + "\btrace_id\x18\t \x01(\fR\atraceId\x12\x17\n" + + "\aspan_id\x18\n" + + " \x01(\fR\x06spanId\x12\x1d\n" + + "\n" + + "event_name\x18\f \x01(\tR\teventNameJ\x04\b\x04\x10\x05*\xc3\x05\n" + + "\x0eSeverityNumber\x12\x1f\n" + + "\x1bSEVERITY_NUMBER_UNSPECIFIED\x10\x00\x12\x19\n" + + "\x15SEVERITY_NUMBER_TRACE\x10\x01\x12\x1a\n" + + "\x16SEVERITY_NUMBER_TRACE2\x10\x02\x12\x1a\n" + + "\x16SEVERITY_NUMBER_TRACE3\x10\x03\x12\x1a\n" + + "\x16SEVERITY_NUMBER_TRACE4\x10\x04\x12\x19\n" + + "\x15SEVERITY_NUMBER_DEBUG\x10\x05\x12\x1a\n" + + "\x16SEVERITY_NUMBER_DEBUG2\x10\x06\x12\x1a\n" + + "\x16SEVERITY_NUMBER_DEBUG3\x10\a\x12\x1a\n" + + "\x16SEVERITY_NUMBER_DEBUG4\x10\b\x12\x18\n" + + "\x14SEVERITY_NUMBER_INFO\x10\t\x12\x19\n" + + "\x15SEVERITY_NUMBER_INFO2\x10\n" + + "\x12\x19\n" + + "\x15SEVERITY_NUMBER_INFO3\x10\v\x12\x19\n" + + "\x15SEVERITY_NUMBER_INFO4\x10\f\x12\x18\n" + + "\x14SEVERITY_NUMBER_WARN\x10\r\x12\x19\n" + + "\x15SEVERITY_NUMBER_WARN2\x10\x0e\x12\x19\n" + + "\x15SEVERITY_NUMBER_WARN3\x10\x0f\x12\x19\n" + + "\x15SEVERITY_NUMBER_WARN4\x10\x10\x12\x19\n" + + "\x15SEVERITY_NUMBER_ERROR\x10\x11\x12\x1a\n" + + "\x16SEVERITY_NUMBER_ERROR2\x10\x12\x12\x1a\n" + + "\x16SEVERITY_NUMBER_ERROR3\x10\x13\x12\x1a\n" + + "\x16SEVERITY_NUMBER_ERROR4\x10\x14\x12\x19\n" + + "\x15SEVERITY_NUMBER_FATAL\x10\x15\x12\x1a\n" + + "\x16SEVERITY_NUMBER_FATAL2\x10\x16\x12\x1a\n" + + "\x16SEVERITY_NUMBER_FATAL3\x10\x17\x12\x1a\n" + + "\x16SEVERITY_NUMBER_FATAL4\x10\x18*Y\n" + + "\x0eLogRecordFlags\x12\x1f\n" + + "\x1bLOG_RECORD_FLAGS_DO_NOT_USE\x10\x00\x12&\n" + + "!LOG_RECORD_FLAGS_TRACE_FLAGS_MASK\x10\xff\x01Bs\n" + + "\x1eio.opentelemetry.proto.logs.v1B\tLogsProtoP\x01Z&go.opentelemetry.io/proto/otlp/logs/v1\xaa\x02\x1bOpenTelemetry.Proto.Logs.V1b\x06proto3" var ( file_opentelemetry_proto_logs_v1_logs_proto_rawDescOnce sync.Once - file_opentelemetry_proto_logs_v1_logs_proto_rawDescData = file_opentelemetry_proto_logs_v1_logs_proto_rawDesc + file_opentelemetry_proto_logs_v1_logs_proto_rawDescData []byte ) func file_opentelemetry_proto_logs_v1_logs_proto_rawDescGZIP() []byte { file_opentelemetry_proto_logs_v1_logs_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_logs_v1_logs_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_logs_v1_logs_proto_rawDescData) + file_opentelemetry_proto_logs_v1_logs_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_logs_v1_logs_proto_rawDesc), len(file_opentelemetry_proto_logs_v1_logs_proto_rawDesc))) }) return file_opentelemetry_proto_logs_v1_logs_proto_rawDescData } var file_opentelemetry_proto_logs_v1_logs_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_opentelemetry_proto_logs_v1_logs_proto_msgTypes = make([]protoimpl.MessageInfo, 4) -var file_opentelemetry_proto_logs_v1_logs_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_logs_v1_logs_proto_goTypes = []any{ (SeverityNumber)(0), // 0: opentelemetry.proto.logs.v1.SeverityNumber (LogRecordFlags)(0), // 1: opentelemetry.proto.logs.v1.LogRecordFlags (*LogsData)(nil), // 2: opentelemetry.proto.logs.v1.LogsData @@ -798,61 +718,11 @@ func file_opentelemetry_proto_logs_v1_logs_proto_init() { if File_opentelemetry_proto_logs_v1_logs_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*LogsData); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ResourceLogs); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ScopeLogs); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_logs_v1_logs_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*LogRecord); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_logs_v1_logs_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_logs_v1_logs_proto_rawDesc), len(file_opentelemetry_proto_logs_v1_logs_proto_rawDesc)), NumEnums: 2, NumMessages: 4, NumExtensions: 0, @@ -864,7 +734,6 @@ func file_opentelemetry_proto_logs_v1_logs_proto_init() { MessageInfos: file_opentelemetry_proto_logs_v1_logs_proto_msgTypes, }.Build() File_opentelemetry_proto_logs_v1_logs_proto = out.File - file_opentelemetry_proto_logs_v1_logs_proto_rawDesc = nil file_opentelemetry_proto_logs_v1_logs_proto_goTypes = nil file_opentelemetry_proto_logs_v1_logs_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/metrics/v1/metrics.pb.go b/vendor/go.opentelemetry.io/proto/otlp/metrics/v1/metrics.pb.go index e148ddd134..55b7d1bb2e 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/metrics/v1/metrics.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/metrics/v1/metrics.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/metrics/v1/metrics.proto package v1 @@ -27,6 +27,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -56,18 +57,18 @@ const ( // it receives and reports the sum of these requests every second as a // DELTA metric: // - // 1. The system starts receiving at time=t_0. - // 2. A request is received, the system measures 1 request. - // 3. A request is received, the system measures 1 request. - // 4. A request is received, the system measures 1 request. - // 5. The 1 second collection cycle ends. A metric is exported for the - // number of requests received over the interval of time t_0 to - // t_0+1 with a value of 3. - // 6. A request is received, the system measures 1 request. - // 7. A request is received, the system measures 1 request. - // 8. The 1 second collection cycle ends. A metric is exported for the - // number of requests received over the interval of time t_0+1 to - // t_0+2 with a value of 2. + // 1. The system starts receiving at time=t_0. + // 2. A request is received, the system measures 1 request. + // 3. A request is received, the system measures 1 request. + // 4. A request is received, the system measures 1 request. + // 5. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_0 to + // t_0+1 with a value of 3. + // 6. A request is received, the system measures 1 request. + // 7. A request is received, the system measures 1 request. + // 8. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_0+1 to + // t_0+2 with a value of 2. AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA AggregationTemporality = 1 // CUMULATIVE is an AggregationTemporality for a metric aggregator which // reports changes since a fixed start time. This means that current values @@ -81,24 +82,24 @@ const ( // it receives and reports the sum of these requests every second as a // CUMULATIVE metric: // - // 1. The system starts receiving at time=t_0. - // 2. A request is received, the system measures 1 request. - // 3. A request is received, the system measures 1 request. - // 4. A request is received, the system measures 1 request. - // 5. The 1 second collection cycle ends. A metric is exported for the - // number of requests received over the interval of time t_0 to - // t_0+1 with a value of 3. - // 6. A request is received, the system measures 1 request. - // 7. A request is received, the system measures 1 request. - // 8. The 1 second collection cycle ends. A metric is exported for the - // number of requests received over the interval of time t_0 to - // t_0+2 with a value of 5. - // 9. The system experiences a fault and loses state. - // 10. The system recovers and resumes receiving at time=t_1. - // 11. A request is received, the system measures 1 request. - // 12. The 1 second collection cycle ends. A metric is exported for the - // number of requests received over the interval of time t_1 to - // t_0+1 with a value of 1. + // 1. The system starts receiving at time=t_0. + // 2. A request is received, the system measures 1 request. + // 3. A request is received, the system measures 1 request. + // 4. A request is received, the system measures 1 request. + // 5. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_0 to + // t_0+1 with a value of 3. + // 6. A request is received, the system measures 1 request. + // 7. A request is received, the system measures 1 request. + // 8. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_0 to + // t_0+2 with a value of 5. + // 9. The system experiences a fault and loses state. + // 10. The system recovers and resumes receiving at time=t_1. + // 11. A request is received, the system measures 1 request. + // 12. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_1 to + // t_0+1 with a value of 1. // // Note: Even though, when reporting changes since last report time, using // CUMULATIVE is valid, it is not recommended. This may cause problems for @@ -153,8 +154,7 @@ func (AggregationTemporality) EnumDescriptor() ([]byte, []int) { // enum is a bit-mask. To test the presence of a single flag in the flags of // a data point, for example, use an expression like: // -// (point.flags & DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK) == DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK -// +// (point.flags & DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK) == DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK type DataPointFlags int32 const ( @@ -212,21 +212,22 @@ func (DataPointFlags) EnumDescriptor() ([]byte, []int) { // // MetricsData // └─── ResourceMetrics -// ├── Resource -// ├── SchemaURL -// └── ScopeMetrics -// ├── Scope -// ├── SchemaURL -// └── Metric -// ├── Name -// ├── Description -// ├── Unit -// └── data -// ├── Gauge -// ├── Sum -// ├── Histogram -// ├── ExponentialHistogram -// └── Summary +// +// ├── Resource +// ├── SchemaURL +// └── ScopeMetrics +// ├── Scope +// ├── SchemaURL +// └── Metric +// ├── Name +// ├── Description +// ├── Unit +// └── data +// ├── Gauge +// ├── Sum +// ├── Histogram +// ├── ExponentialHistogram +// └── Summary // // The main difference between this message and collector protocol is that // in this message there will not be any "control" or "metadata" specific to @@ -235,25 +236,22 @@ func (DataPointFlags) EnumDescriptor() ([]byte, []int) { // When new fields are added into this message, the OTLP request MUST be updated // as well. type MetricsData struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // An array of ResourceMetrics. // For data coming from a single resource this array will typically contain // one element. Intermediary nodes that receive data from multiple origins // typically batch the data before forwarding further and in that case this // array will contain multiple elements. ResourceMetrics []*ResourceMetrics `protobuf:"bytes,1,rep,name=resource_metrics,json=resourceMetrics,proto3" json:"resource_metrics,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *MetricsData) Reset() { *x = MetricsData{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *MetricsData) String() string { @@ -264,7 +262,7 @@ func (*MetricsData) ProtoMessage() {} func (x *MetricsData) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -288,10 +286,7 @@ func (x *MetricsData) GetResourceMetrics() []*ResourceMetrics { // A collection of ScopeMetrics from a Resource. type ResourceMetrics struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The resource for the metrics in this message. // If this field is not set then no resource info is known. Resource *v1.Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` @@ -303,16 +298,16 @@ type ResourceMetrics struct { // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to the data in the "resource" field. It does not apply // to the data in the "scope_metrics" field which have their own schema_url field. - SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ResourceMetrics) Reset() { *x = ResourceMetrics{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ResourceMetrics) String() string { @@ -323,7 +318,7 @@ func (*ResourceMetrics) ProtoMessage() {} func (x *ResourceMetrics) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -361,10 +356,7 @@ func (x *ResourceMetrics) GetSchemaUrl() string { // A collection of Metrics produced by an Scope. type ScopeMetrics struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The instrumentation scope information for the metrics in this message. // Semantically when InstrumentationScope isn't set, it is equivalent with // an empty instrumentation scope name (unknown). @@ -377,16 +369,16 @@ type ScopeMetrics struct { // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to the data in the "scope" field and all metrics in the // "metrics" field. - SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ScopeMetrics) Reset() { *x = ScopeMetrics{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ScopeMetrics) String() string { @@ -397,7 +389,7 @@ func (*ScopeMetrics) ProtoMessage() {} func (x *ScopeMetrics) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -436,65 +428,68 @@ func (x *ScopeMetrics) GetSchemaUrl() string { // Defines a Metric which has one or more timeseries. The following is a // brief summary of the Metric data model. For more details, see: // -// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md +// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md // // The data model and relation between entities is shown in the // diagram below. Here, "DataPoint" is the term used to refer to any // one of the specific data point value types, and "points" is the term used // to refer to any one of the lists of points contained in the Metric. // -// - Metric is composed of a metadata and data. -// - Metadata part contains a name, description, unit. -// - Data is one of the possible types (Sum, Gauge, Histogram, Summary). -// - DataPoint contains timestamps, attributes, and one of the possible value type -// fields. +// - Metric is composed of a metadata and data. +// +// - Metadata part contains a name, description, unit. +// +// - Data is one of the possible types (Sum, Gauge, Histogram, Summary). +// +// - DataPoint contains timestamps, attributes, and one of the possible value type +// fields. // -// Metric -// +------------+ -// |name | -// |description | -// |unit | +------------------------------------+ -// |data |---> |Gauge, Sum, Histogram, Summary, ... | -// +------------+ +------------------------------------+ +// Metric +// +------------+ +// |name | +// |description | +// |unit | +------------------------------------+ +// |data |---> |Gauge, Sum, Histogram, Summary, ... | +// +------------+ +------------------------------------+ // -// Data [One of Gauge, Sum, Histogram, Summary, ...] -// +-----------+ -// |... | // Metadata about the Data. -// |points |--+ -// +-----------+ | -// | +---------------------------+ -// | |DataPoint 1 | -// v |+------+------+ +------+ | -// +-----+ ||label |label |...|label | | -// | 1 |-->||value1|value2|...|valueN| | -// +-----+ |+------+------+ +------+ | -// | . | |+-----+ | -// | . | ||value| | -// | . | |+-----+ | -// | . | +---------------------------+ -// | . | . -// | . | . -// | . | . -// | . | +---------------------------+ -// | . | |DataPoint M | -// +-----+ |+------+------+ +------+ | -// | M |-->||label |label |...|label | | -// +-----+ ||value1|value2|...|valueN| | -// |+------+------+ +------+ | -// |+-----+ | -// ||value| | -// |+-----+ | -// +---------------------------+ +// Data [One of Gauge, Sum, Histogram, Summary, ...] +// +-----------+ +// |... | // Metadata about the Data. +// |points |--+ +// +-----------+ | +// | +---------------------------+ +// | |DataPoint 1 | +// v |+------+------+ +------+ | +// +-----+ ||label |label |...|label | | +// | 1 |-->||value1|value2|...|valueN| | +// +-----+ |+------+------+ +------+ | +// | . | |+-----+ | +// | . | ||value| | +// | . | |+-----+ | +// | . | +---------------------------+ +// | . | . +// | . | . +// | . | . +// | . | +---------------------------+ +// | . | |DataPoint M | +// +-----+ |+------+------+ +------+ | +// | M |-->||label |label |...|label | | +// +-----+ ||value1|value2|...|valueN| | +// |+------+------+ +------+ | +// |+-----+ | +// ||value| | +// |+-----+ | +// +---------------------------+ // // Each distinct type of DataPoint represents the output of a specific // aggregation function, the result of applying the DataPoint's // associated function of to one or more measurements. // // All DataPoint types have three common fields: -// - Attributes includes key-value pairs associated with the data point -// - TimeUnixNano is required, set to the end time of the aggregation -// - StartTimeUnixNano is optional, but strongly encouraged for DataPoints -// having an AggregationTemporality field, as discussed below. +// - Attributes includes key-value pairs associated with the data point +// - TimeUnixNano is required, set to the end time of the aggregation +// - StartTimeUnixNano is optional, but strongly encouraged for DataPoints +// having an AggregationTemporality field, as discussed below. // // Both TimeUnixNano and StartTimeUnixNano values are expressed as // UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970. @@ -518,10 +513,7 @@ func (x *ScopeMetrics) GetSchemaUrl() string { // when the start time is truly unknown, setting StartTimeUnixNano is // strongly encouraged. type Metric struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The name of the metric. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // A description of the metric, which can be used in documentation. @@ -530,10 +522,11 @@ type Metric struct { // described by https://ucum.org/ucum and https://units-of-measurement.org/ Unit string `protobuf:"bytes,3,opt,name=unit,proto3" json:"unit,omitempty"` // Data determines the aggregation type (if any) of the metric, what is the - // reported value type for the data points, as well as the relatationship to + // reported value type for the data points, as well as the relationship to // the time interval over which they are reported. // - // Types that are assignable to Data: + // Types that are valid to be assigned to Data: + // // *Metric_Gauge // *Metric_Sum // *Metric_Histogram @@ -548,16 +541,18 @@ type Metric struct { // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). // The behavior of software that receives duplicated keys can be unpredictable. - Metadata []*v11.KeyValue `protobuf:"bytes,12,rep,name=metadata,proto3" json:"metadata,omitempty"` + // + // [Since v1.2.0] + Metadata []*v11.KeyValue `protobuf:"bytes,12,rep,name=metadata,proto3" json:"metadata,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Metric) Reset() { *x = Metric{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Metric) String() string { @@ -568,7 +563,7 @@ func (*Metric) ProtoMessage() {} func (x *Metric) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -604,44 +599,54 @@ func (x *Metric) GetUnit() string { return "" } -func (m *Metric) GetData() isMetric_Data { - if m != nil { - return m.Data +func (x *Metric) GetData() isMetric_Data { + if x != nil { + return x.Data } return nil } func (x *Metric) GetGauge() *Gauge { - if x, ok := x.GetData().(*Metric_Gauge); ok { - return x.Gauge + if x != nil { + if x, ok := x.Data.(*Metric_Gauge); ok { + return x.Gauge + } } return nil } func (x *Metric) GetSum() *Sum { - if x, ok := x.GetData().(*Metric_Sum); ok { - return x.Sum + if x != nil { + if x, ok := x.Data.(*Metric_Sum); ok { + return x.Sum + } } return nil } func (x *Metric) GetHistogram() *Histogram { - if x, ok := x.GetData().(*Metric_Histogram); ok { - return x.Histogram + if x != nil { + if x, ok := x.Data.(*Metric_Histogram); ok { + return x.Histogram + } } return nil } func (x *Metric) GetExponentialHistogram() *ExponentialHistogram { - if x, ok := x.GetData().(*Metric_ExponentialHistogram); ok { - return x.ExponentialHistogram + if x != nil { + if x, ok := x.Data.(*Metric_ExponentialHistogram); ok { + return x.ExponentialHistogram + } } return nil } func (x *Metric) GetSummary() *Summary { - if x, ok := x.GetData().(*Metric_Summary); ok { - return x.Summary + if x != nil { + if x, ok := x.Data.(*Metric_Summary); ok { + return x.Summary + } } return nil } @@ -697,22 +702,19 @@ func (*Metric_Summary) isMetric_Data() {} // AggregationTemporality is not included. Consequently, this also means // "StartTimeUnixNano" is ignored for all data points. type Gauge struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The time series data points. // Note: Multiple time series may be included (same timestamp, different attributes). - DataPoints []*NumberDataPoint `protobuf:"bytes,1,rep,name=data_points,json=dataPoints,proto3" json:"data_points,omitempty"` + DataPoints []*NumberDataPoint `protobuf:"bytes,1,rep,name=data_points,json=dataPoints,proto3" json:"data_points,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Gauge) Reset() { *x = Gauge{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Gauge) String() string { @@ -723,7 +725,7 @@ func (*Gauge) ProtoMessage() {} func (x *Gauge) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -748,10 +750,7 @@ func (x *Gauge) GetDataPoints() []*NumberDataPoint { // Sum represents the type of a scalar metric that is calculated as a sum of all // reported measurements over a time interval. type Sum struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The time series data points. // Note: Multiple time series may be included (same timestamp, different attributes). DataPoints []*NumberDataPoint `protobuf:"bytes,1,rep,name=data_points,json=dataPoints,proto3" json:"data_points,omitempty"` @@ -759,16 +758,16 @@ type Sum struct { // since last report time, or cumulative changes since a fixed start time. AggregationTemporality AggregationTemporality `protobuf:"varint,2,opt,name=aggregation_temporality,json=aggregationTemporality,proto3,enum=opentelemetry.proto.metrics.v1.AggregationTemporality" json:"aggregation_temporality,omitempty"` // Represents whether the sum is monotonic. - IsMonotonic bool `protobuf:"varint,3,opt,name=is_monotonic,json=isMonotonic,proto3" json:"is_monotonic,omitempty"` + IsMonotonic bool `protobuf:"varint,3,opt,name=is_monotonic,json=isMonotonic,proto3" json:"is_monotonic,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Sum) Reset() { *x = Sum{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Sum) String() string { @@ -779,7 +778,7 @@ func (*Sum) ProtoMessage() {} func (x *Sum) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -818,25 +817,22 @@ func (x *Sum) GetIsMonotonic() bool { // Histogram represents the type of a metric that is calculated by aggregating // as a Histogram of all reported measurements over a time interval. type Histogram struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The time series data points. // Note: Multiple time series may be included (same timestamp, different attributes). DataPoints []*HistogramDataPoint `protobuf:"bytes,1,rep,name=data_points,json=dataPoints,proto3" json:"data_points,omitempty"` // aggregation_temporality describes if the aggregator reports delta changes // since last report time, or cumulative changes since a fixed start time. AggregationTemporality AggregationTemporality `protobuf:"varint,2,opt,name=aggregation_temporality,json=aggregationTemporality,proto3,enum=opentelemetry.proto.metrics.v1.AggregationTemporality" json:"aggregation_temporality,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Histogram) Reset() { *x = Histogram{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Histogram) String() string { @@ -847,7 +843,7 @@ func (*Histogram) ProtoMessage() {} func (x *Histogram) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -879,25 +875,22 @@ func (x *Histogram) GetAggregationTemporality() AggregationTemporality { // ExponentialHistogram represents the type of a metric that is calculated by aggregating // as a ExponentialHistogram of all reported double measurements over a time interval. type ExponentialHistogram struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The time series data points. // Note: Multiple time series may be included (same timestamp, different attributes). DataPoints []*ExponentialHistogramDataPoint `protobuf:"bytes,1,rep,name=data_points,json=dataPoints,proto3" json:"data_points,omitempty"` // aggregation_temporality describes if the aggregator reports delta changes // since last report time, or cumulative changes since a fixed start time. AggregationTemporality AggregationTemporality `protobuf:"varint,2,opt,name=aggregation_temporality,json=aggregationTemporality,proto3,enum=opentelemetry.proto.metrics.v1.AggregationTemporality" json:"aggregation_temporality,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExponentialHistogram) Reset() { *x = ExponentialHistogram{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExponentialHistogram) String() string { @@ -908,7 +901,7 @@ func (*ExponentialHistogram) ProtoMessage() {} func (x *ExponentialHistogram) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[7] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -947,22 +940,19 @@ func (x *ExponentialHistogram) GetAggregationTemporality() AggregationTemporalit // because the count and sum fields of a SummaryDataPoint are assumed to be // cumulative values. type Summary struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The time series data points. // Note: Multiple time series may be included (same timestamp, different attributes). - DataPoints []*SummaryDataPoint `protobuf:"bytes,1,rep,name=data_points,json=dataPoints,proto3" json:"data_points,omitempty"` + DataPoints []*SummaryDataPoint `protobuf:"bytes,1,rep,name=data_points,json=dataPoints,proto3" json:"data_points,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Summary) Reset() { *x = Summary{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Summary) String() string { @@ -973,7 +963,7 @@ func (*Summary) ProtoMessage() {} func (x *Summary) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[8] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -998,10 +988,7 @@ func (x *Summary) GetDataPoints() []*SummaryDataPoint { // NumberDataPoint is a single data point in a timeseries that describes the // time-varying scalar value of a metric. type NumberDataPoint struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The set of key/value pairs that uniquely identify the timeseries from // where this point belongs. The list may be empty (may contain 0 elements). // Attribute keys MUST be unique (it is not allowed to have more than one @@ -1022,7 +1009,8 @@ type NumberDataPoint struct { // The value itself. A point is considered invalid when one of the recognized // value fields is not present inside this oneof. // - // Types that are assignable to Value: + // Types that are valid to be assigned to Value: + // // *NumberDataPoint_AsDouble // *NumberDataPoint_AsInt Value isNumberDataPoint_Value `protobuf_oneof:"value"` @@ -1031,16 +1019,16 @@ type NumberDataPoint struct { Exemplars []*Exemplar `protobuf:"bytes,5,rep,name=exemplars,proto3" json:"exemplars,omitempty"` // Flags that apply to this specific data point. See DataPointFlags // for the available flags and their meaning. - Flags uint32 `protobuf:"varint,8,opt,name=flags,proto3" json:"flags,omitempty"` + Flags uint32 `protobuf:"varint,8,opt,name=flags,proto3" json:"flags,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *NumberDataPoint) Reset() { *x = NumberDataPoint{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *NumberDataPoint) String() string { @@ -1051,7 +1039,7 @@ func (*NumberDataPoint) ProtoMessage() {} func (x *NumberDataPoint) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[9] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -1087,23 +1075,27 @@ func (x *NumberDataPoint) GetTimeUnixNano() uint64 { return 0 } -func (m *NumberDataPoint) GetValue() isNumberDataPoint_Value { - if m != nil { - return m.Value +func (x *NumberDataPoint) GetValue() isNumberDataPoint_Value { + if x != nil { + return x.Value } return nil } func (x *NumberDataPoint) GetAsDouble() float64 { - if x, ok := x.GetValue().(*NumberDataPoint_AsDouble); ok { - return x.AsDouble + if x != nil { + if x, ok := x.Value.(*NumberDataPoint_AsDouble); ok { + return x.AsDouble + } } return 0 } func (x *NumberDataPoint) GetAsInt() int64 { - if x, ok := x.GetValue().(*NumberDataPoint_AsInt); ok { - return x.AsInt + if x != nil { + if x, ok := x.Value.(*NumberDataPoint_AsInt); ok { + return x.AsInt + } } return 0 } @@ -1149,10 +1141,7 @@ func (*NumberDataPoint_AsInt) isNumberDataPoint_Value() {} // "explicit_bounds" and "bucket_counts" must be omitted and only "count" and // "sum" are known. type HistogramDataPoint struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The set of key/value pairs that uniquely identify the timeseries from // where this point belongs. The list may be empty (may contain 0 elements). // Attribute keys MUST be unique (it is not allowed to have more than one @@ -1219,16 +1208,16 @@ type HistogramDataPoint struct { // min is the minimum value over (start_time, end_time]. Min *float64 `protobuf:"fixed64,11,opt,name=min,proto3,oneof" json:"min,omitempty"` // max is the maximum value over (start_time, end_time]. - Max *float64 `protobuf:"fixed64,12,opt,name=max,proto3,oneof" json:"max,omitempty"` + Max *float64 `protobuf:"fixed64,12,opt,name=max,proto3,oneof" json:"max,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *HistogramDataPoint) Reset() { *x = HistogramDataPoint{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[10] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *HistogramDataPoint) String() string { @@ -1239,7 +1228,7 @@ func (*HistogramDataPoint) ProtoMessage() {} func (x *HistogramDataPoint) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[10] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -1335,12 +1324,8 @@ func (x *HistogramDataPoint) GetMax() float64 { // time-varying values of a ExponentialHistogram of double values. A ExponentialHistogram contains // summary statistics for a population of values, it may optionally contain the // distribution of those values across a set of buckets. -// type ExponentialHistogramDataPoint struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The set of key/value pairs that uniquely identify the timeseries from // where this point belongs. The list may be empty (may contain 0 elements). // Attribute keys MUST be unique (it is not allowed to have more than one @@ -1374,7 +1359,7 @@ type ExponentialHistogramDataPoint struct { // scale describes the resolution of the histogram. Boundaries are // located at powers of the base, where: // - // base = (2^(2^-scale)) + // base = (2^(2^-scale)) // // The histogram bucket identified by `index`, a signed integer, // contains values that are greater than (base^index) and @@ -1417,15 +1402,15 @@ type ExponentialHistogramDataPoint struct { // expressed using the standard exponential formula as well as values that // have been rounded to zero. ZeroThreshold float64 `protobuf:"fixed64,14,opt,name=zero_threshold,json=zeroThreshold,proto3" json:"zero_threshold,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExponentialHistogramDataPoint) Reset() { *x = ExponentialHistogramDataPoint{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[11] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExponentialHistogramDataPoint) String() string { @@ -1436,7 +1421,7 @@ func (*ExponentialHistogramDataPoint) ProtoMessage() {} func (x *ExponentialHistogramDataPoint) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[11] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -1553,10 +1538,7 @@ func (x *ExponentialHistogramDataPoint) GetZeroThreshold() float64 { // time-varying values of a Summary metric. The count and sum fields represent // cumulative values. type SummaryDataPoint struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The set of key/value pairs that uniquely identify the timeseries from // where this point belongs. The list may be empty (may contain 0 elements). // Attribute keys MUST be unique (it is not allowed to have more than one @@ -1590,16 +1572,16 @@ type SummaryDataPoint struct { QuantileValues []*SummaryDataPoint_ValueAtQuantile `protobuf:"bytes,6,rep,name=quantile_values,json=quantileValues,proto3" json:"quantile_values,omitempty"` // Flags that apply to this specific data point. See DataPointFlags // for the available flags and their meaning. - Flags uint32 `protobuf:"varint,8,opt,name=flags,proto3" json:"flags,omitempty"` + Flags uint32 `protobuf:"varint,8,opt,name=flags,proto3" json:"flags,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SummaryDataPoint) Reset() { *x = SummaryDataPoint{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[12] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SummaryDataPoint) String() string { @@ -1610,7 +1592,7 @@ func (*SummaryDataPoint) ProtoMessage() {} func (x *SummaryDataPoint) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[12] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -1679,10 +1661,7 @@ func (x *SummaryDataPoint) GetFlags() uint32 { // was recorded, for example the span and trace ID of the active span when the // exemplar was recorded. type Exemplar struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The set of key/value pairs that were filtered out by the aggregator, but // recorded alongside the original measurement. Only key/value pairs that were // filtered out by the aggregator should be included @@ -1696,7 +1675,8 @@ type Exemplar struct { // considered invalid when one of the recognized value fields is not present // inside this oneof. // - // Types that are assignable to Value: + // Types that are valid to be assigned to Value: + // // *Exemplar_AsDouble // *Exemplar_AsInt Value isExemplar_Value `protobuf_oneof:"value"` @@ -1707,16 +1687,16 @@ type Exemplar struct { // (Optional) Trace ID of the exemplar trace. // trace_id may be missing if the measurement is not recorded inside a trace // or if the trace is not sampled. - TraceId []byte `protobuf:"bytes,5,opt,name=trace_id,json=traceId,proto3" json:"trace_id,omitempty"` + TraceId []byte `protobuf:"bytes,5,opt,name=trace_id,json=traceId,proto3" json:"trace_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Exemplar) Reset() { *x = Exemplar{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[13] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Exemplar) String() string { @@ -1727,7 +1707,7 @@ func (*Exemplar) ProtoMessage() {} func (x *Exemplar) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[13] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -1756,23 +1736,27 @@ func (x *Exemplar) GetTimeUnixNano() uint64 { return 0 } -func (m *Exemplar) GetValue() isExemplar_Value { - if m != nil { - return m.Value +func (x *Exemplar) GetValue() isExemplar_Value { + if x != nil { + return x.Value } return nil } func (x *Exemplar) GetAsDouble() float64 { - if x, ok := x.GetValue().(*Exemplar_AsDouble); ok { - return x.AsDouble + if x != nil { + if x, ok := x.Value.(*Exemplar_AsDouble); ok { + return x.AsDouble + } } return 0 } func (x *Exemplar) GetAsInt() int64 { - if x, ok := x.GetValue().(*Exemplar_AsInt); ok { - return x.AsInt + if x != nil { + if x, ok := x.Value.(*Exemplar_AsInt); ok { + return x.AsInt + } } return 0 } @@ -1810,10 +1794,7 @@ func (*Exemplar_AsInt) isExemplar_Value() {} // Buckets are a set of bucket counts, encoded in a contiguous array // of counts. type ExponentialHistogramDataPoint_Buckets struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The bucket index of the first entry in the bucket_counts array. // // Note: This uses a varint encoding as a simple form of compression. @@ -1827,16 +1808,16 @@ type ExponentialHistogramDataPoint_Buckets struct { // fixed64. This field is expected to have many buckets, // especially zeros, so uint64 has been selected to ensure // varint encoding. - BucketCounts []uint64 `protobuf:"varint,2,rep,packed,name=bucket_counts,json=bucketCounts,proto3" json:"bucket_counts,omitempty"` + BucketCounts []uint64 `protobuf:"varint,2,rep,packed,name=bucket_counts,json=bucketCounts,proto3" json:"bucket_counts,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExponentialHistogramDataPoint_Buckets) Reset() { *x = ExponentialHistogramDataPoint_Buckets{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[14] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExponentialHistogramDataPoint_Buckets) String() string { @@ -1847,7 +1828,7 @@ func (*ExponentialHistogramDataPoint_Buckets) ProtoMessage() {} func (x *ExponentialHistogramDataPoint_Buckets) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[14] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -1885,26 +1866,23 @@ func (x *ExponentialHistogramDataPoint_Buckets) GetBucketCounts() []uint64 { // See the following issue for more context: // https://github.com/open-telemetry/opentelemetry-proto/issues/125 type SummaryDataPoint_ValueAtQuantile struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The quantile of a distribution. Must be in the interval // [0.0, 1.0]. Quantile float64 `protobuf:"fixed64,1,opt,name=quantile,proto3" json:"quantile,omitempty"` // The value at the given quantile of a distribution. // // Quantile values must NOT be negative. - Value float64 `protobuf:"fixed64,2,opt,name=value,proto3" json:"value,omitempty"` + Value float64 `protobuf:"fixed64,2,opt,name=value,proto3" json:"value,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SummaryDataPoint_ValueAtQuantile) Reset() { *x = SummaryDataPoint_ValueAtQuantile{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[15] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SummaryDataPoint_ValueAtQuantile) String() string { @@ -1915,7 +1893,7 @@ func (*SummaryDataPoint_ValueAtQuantile) ProtoMessage() {} func (x *SummaryDataPoint_ValueAtQuantile) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[15] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -1946,321 +1924,151 @@ func (x *SummaryDataPoint_ValueAtQuantile) GetValue() float64 { var File_opentelemetry_proto_metrics_v1_metrics_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_metrics_v1_metrics_proto_rawDesc = []byte{ - 0x0a, 0x2c, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2f, 0x76, 0x31, - 0x2f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x1a, 0x2a, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, 0x2f, 0x63, 0x6f, - 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2e, 0x6f, 0x70, 0x65, 0x6e, - 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, - 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x72, 0x65, 0x73, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x69, 0x0a, 0x0b, 0x4d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x44, 0x61, 0x74, 0x61, 0x12, 0x5a, 0x0a, 0x10, 0x72, 0x65, 0x73, - 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x18, 0x01, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, - 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4d, 0x65, 0x74, - 0x72, 0x69, 0x63, 0x73, 0x52, 0x0f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x22, 0xd2, 0x01, 0x0a, 0x0f, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x12, 0x45, 0x0a, 0x08, 0x72, 0x65, 0x73, - 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, - 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x12, 0x51, 0x0a, 0x0d, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, - 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x4d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x52, 0x0c, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x4d, 0x65, 0x74, 0x72, - 0x69, 0x63, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x75, 0x72, - 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x55, - 0x72, 0x6c, 0x4a, 0x06, 0x08, 0xe8, 0x07, 0x10, 0xe9, 0x07, 0x22, 0xba, 0x01, 0x0a, 0x0c, 0x53, - 0x63, 0x6f, 0x70, 0x65, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x12, 0x49, 0x0a, 0x05, 0x73, - 0x63, 0x6f, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x73, 0x74, 0x72, - 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, - 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x40, 0x0a, 0x07, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, - 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x52, - 0x07, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, 0x68, 0x65, - 0x6d, 0x61, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x63, - 0x68, 0x65, 0x6d, 0x61, 0x55, 0x72, 0x6c, 0x22, 0xa6, 0x04, 0x0a, 0x06, 0x4d, 0x65, 0x74, 0x72, - 0x69, 0x63, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, - 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, - 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x75, 0x6e, 0x69, 0x74, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x75, 0x6e, 0x69, 0x74, 0x12, 0x3d, 0x0a, 0x05, - 0x67, 0x61, 0x75, 0x67, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x61, 0x75, - 0x67, 0x65, 0x48, 0x00, 0x52, 0x05, 0x67, 0x61, 0x75, 0x67, 0x65, 0x12, 0x37, 0x0a, 0x03, 0x73, - 0x75, 0x6d, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, - 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x75, 0x6d, 0x48, 0x00, 0x52, - 0x03, 0x73, 0x75, 0x6d, 0x12, 0x49, 0x0a, 0x09, 0x68, 0x69, 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, - 0x6d, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x67, 0x72, - 0x61, 0x6d, 0x48, 0x00, 0x52, 0x09, 0x68, 0x69, 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x12, - 0x6b, 0x0a, 0x15, 0x65, 0x78, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x68, - 0x69, 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x34, - 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, - 0x45, 0x78, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x48, 0x69, 0x73, 0x74, 0x6f, - 0x67, 0x72, 0x61, 0x6d, 0x48, 0x00, 0x52, 0x14, 0x65, 0x78, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, - 0x69, 0x61, 0x6c, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x12, 0x43, 0x0a, 0x07, - 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x53, - 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x48, 0x00, 0x52, 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, - 0x79, 0x12, 0x43, 0x0a, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x0c, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, - 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x6d, 0x65, - 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x42, 0x06, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x4a, 0x04, - 0x08, 0x04, 0x10, 0x05, 0x4a, 0x04, 0x08, 0x06, 0x10, 0x07, 0x4a, 0x04, 0x08, 0x08, 0x10, 0x09, - 0x22, 0x59, 0x0a, 0x05, 0x47, 0x61, 0x75, 0x67, 0x65, 0x12, 0x50, 0x0a, 0x0b, 0x64, 0x61, 0x74, - 0x61, 0x5f, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, - 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, - 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x52, - 0x0a, 0x64, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x22, 0xeb, 0x01, 0x0a, 0x03, - 0x53, 0x75, 0x6d, 0x12, 0x50, 0x0a, 0x0b, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x70, 0x6f, 0x69, 0x6e, - 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, - 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, - 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x0a, 0x64, 0x61, 0x74, 0x61, 0x50, - 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x12, 0x6f, 0x0a, 0x17, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x61, 0x6c, 0x69, 0x74, 0x79, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x36, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, - 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, - 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x54, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x52, 0x16, - 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x65, 0x6d, 0x70, 0x6f, - 0x72, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x12, 0x21, 0x0a, 0x0c, 0x69, 0x73, 0x5f, 0x6d, 0x6f, 0x6e, - 0x6f, 0x74, 0x6f, 0x6e, 0x69, 0x63, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0b, 0x69, 0x73, - 0x4d, 0x6f, 0x6e, 0x6f, 0x74, 0x6f, 0x6e, 0x69, 0x63, 0x22, 0xd1, 0x01, 0x0a, 0x09, 0x48, 0x69, - 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x12, 0x53, 0x0a, 0x0b, 0x64, 0x61, 0x74, 0x61, 0x5f, - 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x32, 0x2e, 0x6f, - 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x69, - 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, - 0x52, 0x0a, 0x64, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x12, 0x6f, 0x0a, 0x17, - 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x65, 0x6d, 0x70, - 0x6f, 0x72, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x36, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x41, - 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x65, 0x6d, 0x70, 0x6f, 0x72, - 0x61, 0x6c, 0x69, 0x74, 0x79, 0x52, 0x16, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x54, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x22, 0xe7, 0x01, - 0x0a, 0x14, 0x45, 0x78, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x48, 0x69, 0x73, - 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x12, 0x5e, 0x0a, 0x0b, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x70, - 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3d, 0x2e, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, - 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, - 0x6d, 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x0a, 0x64, 0x61, 0x74, 0x61, - 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x12, 0x6f, 0x0a, 0x17, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x61, 0x6c, 0x69, 0x74, - 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x36, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x52, - 0x16, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x65, 0x6d, 0x70, - 0x6f, 0x72, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x22, 0x5c, 0x0a, 0x07, 0x53, 0x75, 0x6d, 0x6d, 0x61, - 0x72, 0x79, 0x12, 0x51, 0x0a, 0x0b, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x70, 0x6f, 0x69, 0x6e, 0x74, - 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, - 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x0a, 0x64, 0x61, 0x74, 0x61, 0x50, - 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x22, 0xd6, 0x02, 0x0a, 0x0f, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, - 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, - 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, - 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, - 0x65, 0x73, 0x12, 0x2f, 0x0a, 0x14, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, - 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x06, - 0x52, 0x11, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, - 0x61, 0x6e, 0x6f, 0x12, 0x24, 0x0a, 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, - 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x03, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0c, 0x74, 0x69, 0x6d, - 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x1d, 0x0a, 0x09, 0x61, 0x73, 0x5f, - 0x64, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x01, 0x48, 0x00, 0x52, 0x08, - 0x61, 0x73, 0x44, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x12, 0x17, 0x0a, 0x06, 0x61, 0x73, 0x5f, 0x69, - 0x6e, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x10, 0x48, 0x00, 0x52, 0x05, 0x61, 0x73, 0x49, 0x6e, - 0x74, 0x12, 0x46, 0x0a, 0x09, 0x65, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x73, 0x18, 0x05, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, - 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, - 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x52, 0x09, - 0x65, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x6c, 0x61, - 0x67, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x42, - 0x07, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x22, 0xd9, - 0x03, 0x0a, 0x12, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x44, 0x61, 0x74, 0x61, - 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, - 0x74, 0x65, 0x73, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, - 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, - 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x2f, - 0x0a, 0x14, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, - 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x06, 0x52, 0x11, 0x73, 0x74, - 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, - 0x24, 0x0a, 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, - 0x6f, 0x18, 0x03, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, - 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x14, 0x0a, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, - 0x20, 0x01, 0x28, 0x06, 0x52, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x15, 0x0a, 0x03, 0x73, - 0x75, 0x6d, 0x18, 0x05, 0x20, 0x01, 0x28, 0x01, 0x48, 0x00, 0x52, 0x03, 0x73, 0x75, 0x6d, 0x88, - 0x01, 0x01, 0x12, 0x23, 0x0a, 0x0d, 0x62, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x5f, 0x63, 0x6f, 0x75, - 0x6e, 0x74, 0x73, 0x18, 0x06, 0x20, 0x03, 0x28, 0x06, 0x52, 0x0c, 0x62, 0x75, 0x63, 0x6b, 0x65, - 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x12, 0x27, 0x0a, 0x0f, 0x65, 0x78, 0x70, 0x6c, 0x69, - 0x63, 0x69, 0x74, 0x5f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x01, - 0x52, 0x0e, 0x65, 0x78, 0x70, 0x6c, 0x69, 0x63, 0x69, 0x74, 0x42, 0x6f, 0x75, 0x6e, 0x64, 0x73, - 0x12, 0x46, 0x0a, 0x09, 0x65, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x73, 0x18, 0x08, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, - 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x52, 0x09, 0x65, - 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x6c, 0x61, 0x67, - 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x12, 0x15, - 0x0a, 0x03, 0x6d, 0x69, 0x6e, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x01, 0x48, 0x01, 0x52, 0x03, 0x6d, - 0x69, 0x6e, 0x88, 0x01, 0x01, 0x12, 0x15, 0x0a, 0x03, 0x6d, 0x61, 0x78, 0x18, 0x0c, 0x20, 0x01, - 0x28, 0x01, 0x48, 0x02, 0x52, 0x03, 0x6d, 0x61, 0x78, 0x88, 0x01, 0x01, 0x42, 0x06, 0x0a, 0x04, - 0x5f, 0x73, 0x75, 0x6d, 0x42, 0x06, 0x0a, 0x04, 0x5f, 0x6d, 0x69, 0x6e, 0x42, 0x06, 0x0a, 0x04, - 0x5f, 0x6d, 0x61, 0x78, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x22, 0xfa, 0x05, 0x0a, 0x1d, 0x45, - 0x78, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x67, - 0x72, 0x61, 0x6d, 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x47, 0x0a, 0x0a, - 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, - 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, - 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x2f, 0x0a, 0x14, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, - 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x06, 0x52, 0x11, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, - 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x24, 0x0a, 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, - 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x03, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0c, - 0x74, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x14, 0x0a, 0x05, - 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x06, 0x52, 0x05, 0x63, 0x6f, 0x75, - 0x6e, 0x74, 0x12, 0x15, 0x0a, 0x03, 0x73, 0x75, 0x6d, 0x18, 0x05, 0x20, 0x01, 0x28, 0x01, 0x48, - 0x00, 0x52, 0x03, 0x73, 0x75, 0x6d, 0x88, 0x01, 0x01, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x63, 0x61, - 0x6c, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x11, 0x52, 0x05, 0x73, 0x63, 0x61, 0x6c, 0x65, 0x12, - 0x1d, 0x0a, 0x0a, 0x7a, 0x65, 0x72, 0x6f, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x07, 0x20, - 0x01, 0x28, 0x06, 0x52, 0x09, 0x7a, 0x65, 0x72, 0x6f, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x61, - 0x0a, 0x08, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x76, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x45, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, - 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x48, 0x69, 0x73, - 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x2e, - 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x52, 0x08, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x76, - 0x65, 0x12, 0x61, 0x0a, 0x08, 0x6e, 0x65, 0x67, 0x61, 0x74, 0x69, 0x76, 0x65, 0x18, 0x09, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x45, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, - 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, - 0x48, 0x69, 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, - 0x6e, 0x74, 0x2e, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x52, 0x08, 0x6e, 0x65, 0x67, 0x61, - 0x74, 0x69, 0x76, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x18, 0x0a, 0x20, - 0x01, 0x28, 0x0d, 0x52, 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x12, 0x46, 0x0a, 0x09, 0x65, 0x78, - 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x45, - 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x52, 0x09, 0x65, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, - 0x72, 0x73, 0x12, 0x15, 0x0a, 0x03, 0x6d, 0x69, 0x6e, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x01, 0x48, - 0x01, 0x52, 0x03, 0x6d, 0x69, 0x6e, 0x88, 0x01, 0x01, 0x12, 0x15, 0x0a, 0x03, 0x6d, 0x61, 0x78, - 0x18, 0x0d, 0x20, 0x01, 0x28, 0x01, 0x48, 0x02, 0x52, 0x03, 0x6d, 0x61, 0x78, 0x88, 0x01, 0x01, - 0x12, 0x25, 0x0a, 0x0e, 0x7a, 0x65, 0x72, 0x6f, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, - 0x6c, 0x64, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0d, 0x7a, 0x65, 0x72, 0x6f, 0x54, 0x68, - 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x1a, 0x46, 0x0a, 0x07, 0x42, 0x75, 0x63, 0x6b, 0x65, - 0x74, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x11, 0x52, 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x62, 0x75, - 0x63, 0x6b, 0x65, 0x74, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, - 0x04, 0x52, 0x0c, 0x62, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x42, - 0x06, 0x0a, 0x04, 0x5f, 0x73, 0x75, 0x6d, 0x42, 0x06, 0x0a, 0x04, 0x5f, 0x6d, 0x69, 0x6e, 0x42, - 0x06, 0x0a, 0x04, 0x5f, 0x6d, 0x61, 0x78, 0x22, 0xa6, 0x03, 0x0a, 0x10, 0x53, 0x75, 0x6d, 0x6d, - 0x61, 0x72, 0x79, 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x47, 0x0a, 0x0a, - 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, - 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, - 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x2f, 0x0a, 0x14, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, - 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x06, 0x52, 0x11, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, - 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x24, 0x0a, 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, - 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x03, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0c, - 0x74, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x14, 0x0a, 0x05, - 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x06, 0x52, 0x05, 0x63, 0x6f, 0x75, - 0x6e, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x73, 0x75, 0x6d, 0x18, 0x05, 0x20, 0x01, 0x28, 0x01, 0x52, - 0x03, 0x73, 0x75, 0x6d, 0x12, 0x69, 0x0a, 0x0f, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, - 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x40, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x53, - 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x44, 0x61, 0x74, 0x61, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x2e, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x41, 0x74, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x52, - 0x0e, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x12, - 0x14, 0x0a, 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, - 0x66, 0x6c, 0x61, 0x67, 0x73, 0x1a, 0x43, 0x0a, 0x0f, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x41, 0x74, - 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x71, 0x75, 0x61, 0x6e, - 0x74, 0x69, 0x6c, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52, 0x08, 0x71, 0x75, 0x61, 0x6e, - 0x74, 0x69, 0x6c, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x01, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, - 0x22, 0x85, 0x02, 0x0a, 0x08, 0x45, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x12, 0x58, 0x0a, - 0x13, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, - 0x75, 0x74, 0x65, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x12, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x65, 0x64, 0x41, 0x74, 0x74, - 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x24, 0x0a, 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x5f, - 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x06, 0x52, - 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x1d, 0x0a, - 0x09, 0x61, 0x73, 0x5f, 0x64, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x01, - 0x48, 0x00, 0x52, 0x08, 0x61, 0x73, 0x44, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x12, 0x17, 0x0a, 0x06, - 0x61, 0x73, 0x5f, 0x69, 0x6e, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x10, 0x48, 0x00, 0x52, 0x05, - 0x61, 0x73, 0x49, 0x6e, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x73, 0x70, 0x61, 0x6e, 0x5f, 0x69, 0x64, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x70, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x19, - 0x0a, 0x08, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x07, 0x74, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, 0x42, 0x07, 0x0a, 0x05, 0x76, 0x61, 0x6c, - 0x75, 0x65, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x2a, 0x8c, 0x01, 0x0a, 0x16, 0x41, 0x67, 0x67, - 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x61, 0x6c, - 0x69, 0x74, 0x79, 0x12, 0x27, 0x0a, 0x23, 0x41, 0x47, 0x47, 0x52, 0x45, 0x47, 0x41, 0x54, 0x49, - 0x4f, 0x4e, 0x5f, 0x54, 0x45, 0x4d, 0x50, 0x4f, 0x52, 0x41, 0x4c, 0x49, 0x54, 0x59, 0x5f, 0x55, - 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x21, 0x0a, 0x1d, - 0x41, 0x47, 0x47, 0x52, 0x45, 0x47, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x54, 0x45, 0x4d, 0x50, - 0x4f, 0x52, 0x41, 0x4c, 0x49, 0x54, 0x59, 0x5f, 0x44, 0x45, 0x4c, 0x54, 0x41, 0x10, 0x01, 0x12, - 0x26, 0x0a, 0x22, 0x41, 0x47, 0x47, 0x52, 0x45, 0x47, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x54, - 0x45, 0x4d, 0x50, 0x4f, 0x52, 0x41, 0x4c, 0x49, 0x54, 0x59, 0x5f, 0x43, 0x55, 0x4d, 0x55, 0x4c, - 0x41, 0x54, 0x49, 0x56, 0x45, 0x10, 0x02, 0x2a, 0x5e, 0x0a, 0x0e, 0x44, 0x61, 0x74, 0x61, 0x50, - 0x6f, 0x69, 0x6e, 0x74, 0x46, 0x6c, 0x61, 0x67, 0x73, 0x12, 0x1f, 0x0a, 0x1b, 0x44, 0x41, 0x54, - 0x41, 0x5f, 0x50, 0x4f, 0x49, 0x4e, 0x54, 0x5f, 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x44, 0x4f, - 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x55, 0x53, 0x45, 0x10, 0x00, 0x12, 0x2b, 0x0a, 0x27, 0x44, 0x41, - 0x54, 0x41, 0x5f, 0x50, 0x4f, 0x49, 0x4e, 0x54, 0x5f, 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x4e, - 0x4f, 0x5f, 0x52, 0x45, 0x43, 0x4f, 0x52, 0x44, 0x45, 0x44, 0x5f, 0x56, 0x41, 0x4c, 0x55, 0x45, - 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0x01, 0x42, 0x7f, 0x0a, 0x21, 0x69, 0x6f, 0x2e, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x76, 0x31, 0x42, 0x0c, 0x4d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x29, 0x67, 0x6f, - 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, - 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x6d, 0x65, 0x74, - 0x72, 0x69, 0x63, 0x73, 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x1e, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x4d, 0x65, - 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_metrics_v1_metrics_proto_rawDesc = "" + + "\n" + + ",opentelemetry/proto/metrics/v1/metrics.proto\x12\x1eopentelemetry.proto.metrics.v1\x1a*opentelemetry/proto/common/v1/common.proto\x1a.opentelemetry/proto/resource/v1/resource.proto\"i\n" + + "\vMetricsData\x12Z\n" + + "\x10resource_metrics\x18\x01 \x03(\v2/.opentelemetry.proto.metrics.v1.ResourceMetricsR\x0fresourceMetrics\"\xd2\x01\n" + + "\x0fResourceMetrics\x12E\n" + + "\bresource\x18\x01 \x01(\v2).opentelemetry.proto.resource.v1.ResourceR\bresource\x12Q\n" + + "\rscope_metrics\x18\x02 \x03(\v2,.opentelemetry.proto.metrics.v1.ScopeMetricsR\fscopeMetrics\x12\x1d\n" + + "\n" + + "schema_url\x18\x03 \x01(\tR\tschemaUrlJ\x06\b\xe8\a\x10\xe9\a\"\xba\x01\n" + + "\fScopeMetrics\x12I\n" + + "\x05scope\x18\x01 \x01(\v23.opentelemetry.proto.common.v1.InstrumentationScopeR\x05scope\x12@\n" + + "\ametrics\x18\x02 \x03(\v2&.opentelemetry.proto.metrics.v1.MetricR\ametrics\x12\x1d\n" + + "\n" + + "schema_url\x18\x03 \x01(\tR\tschemaUrl\"\xa6\x04\n" + + "\x06Metric\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12 \n" + + "\vdescription\x18\x02 \x01(\tR\vdescription\x12\x12\n" + + "\x04unit\x18\x03 \x01(\tR\x04unit\x12=\n" + + "\x05gauge\x18\x05 \x01(\v2%.opentelemetry.proto.metrics.v1.GaugeH\x00R\x05gauge\x127\n" + + "\x03sum\x18\a \x01(\v2#.opentelemetry.proto.metrics.v1.SumH\x00R\x03sum\x12I\n" + + "\thistogram\x18\t \x01(\v2).opentelemetry.proto.metrics.v1.HistogramH\x00R\thistogram\x12k\n" + + "\x15exponential_histogram\x18\n" + + " \x01(\v24.opentelemetry.proto.metrics.v1.ExponentialHistogramH\x00R\x14exponentialHistogram\x12C\n" + + "\asummary\x18\v \x01(\v2'.opentelemetry.proto.metrics.v1.SummaryH\x00R\asummary\x12C\n" + + "\bmetadata\x18\f \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\bmetadataB\x06\n" + + "\x04dataJ\x04\b\x04\x10\x05J\x04\b\x06\x10\aJ\x04\b\b\x10\t\"Y\n" + + "\x05Gauge\x12P\n" + + "\vdata_points\x18\x01 \x03(\v2/.opentelemetry.proto.metrics.v1.NumberDataPointR\n" + + "dataPoints\"\xeb\x01\n" + + "\x03Sum\x12P\n" + + "\vdata_points\x18\x01 \x03(\v2/.opentelemetry.proto.metrics.v1.NumberDataPointR\n" + + "dataPoints\x12o\n" + + "\x17aggregation_temporality\x18\x02 \x01(\x0e26.opentelemetry.proto.metrics.v1.AggregationTemporalityR\x16aggregationTemporality\x12!\n" + + "\fis_monotonic\x18\x03 \x01(\bR\visMonotonic\"\xd1\x01\n" + + "\tHistogram\x12S\n" + + "\vdata_points\x18\x01 \x03(\v22.opentelemetry.proto.metrics.v1.HistogramDataPointR\n" + + "dataPoints\x12o\n" + + "\x17aggregation_temporality\x18\x02 \x01(\x0e26.opentelemetry.proto.metrics.v1.AggregationTemporalityR\x16aggregationTemporality\"\xe7\x01\n" + + "\x14ExponentialHistogram\x12^\n" + + "\vdata_points\x18\x01 \x03(\v2=.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPointR\n" + + "dataPoints\x12o\n" + + "\x17aggregation_temporality\x18\x02 \x01(\x0e26.opentelemetry.proto.metrics.v1.AggregationTemporalityR\x16aggregationTemporality\"\\\n" + + "\aSummary\x12Q\n" + + "\vdata_points\x18\x01 \x03(\v20.opentelemetry.proto.metrics.v1.SummaryDataPointR\n" + + "dataPoints\"\xd6\x02\n" + + "\x0fNumberDataPoint\x12G\n" + + "\n" + + "attributes\x18\a \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x12/\n" + + "\x14start_time_unix_nano\x18\x02 \x01(\x06R\x11startTimeUnixNano\x12$\n" + + "\x0etime_unix_nano\x18\x03 \x01(\x06R\ftimeUnixNano\x12\x1d\n" + + "\tas_double\x18\x04 \x01(\x01H\x00R\basDouble\x12\x17\n" + + "\x06as_int\x18\x06 \x01(\x10H\x00R\x05asInt\x12F\n" + + "\texemplars\x18\x05 \x03(\v2(.opentelemetry.proto.metrics.v1.ExemplarR\texemplars\x12\x14\n" + + "\x05flags\x18\b \x01(\rR\x05flagsB\a\n" + + "\x05valueJ\x04\b\x01\x10\x02\"\xd9\x03\n" + + "\x12HistogramDataPoint\x12G\n" + + "\n" + + "attributes\x18\t \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x12/\n" + + "\x14start_time_unix_nano\x18\x02 \x01(\x06R\x11startTimeUnixNano\x12$\n" + + "\x0etime_unix_nano\x18\x03 \x01(\x06R\ftimeUnixNano\x12\x14\n" + + "\x05count\x18\x04 \x01(\x06R\x05count\x12\x15\n" + + "\x03sum\x18\x05 \x01(\x01H\x00R\x03sum\x88\x01\x01\x12#\n" + + "\rbucket_counts\x18\x06 \x03(\x06R\fbucketCounts\x12'\n" + + "\x0fexplicit_bounds\x18\a \x03(\x01R\x0eexplicitBounds\x12F\n" + + "\texemplars\x18\b \x03(\v2(.opentelemetry.proto.metrics.v1.ExemplarR\texemplars\x12\x14\n" + + "\x05flags\x18\n" + + " \x01(\rR\x05flags\x12\x15\n" + + "\x03min\x18\v \x01(\x01H\x01R\x03min\x88\x01\x01\x12\x15\n" + + "\x03max\x18\f \x01(\x01H\x02R\x03max\x88\x01\x01B\x06\n" + + "\x04_sumB\x06\n" + + "\x04_minB\x06\n" + + "\x04_maxJ\x04\b\x01\x10\x02\"\xfa\x05\n" + + "\x1dExponentialHistogramDataPoint\x12G\n" + + "\n" + + "attributes\x18\x01 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x12/\n" + + "\x14start_time_unix_nano\x18\x02 \x01(\x06R\x11startTimeUnixNano\x12$\n" + + "\x0etime_unix_nano\x18\x03 \x01(\x06R\ftimeUnixNano\x12\x14\n" + + "\x05count\x18\x04 \x01(\x06R\x05count\x12\x15\n" + + "\x03sum\x18\x05 \x01(\x01H\x00R\x03sum\x88\x01\x01\x12\x14\n" + + "\x05scale\x18\x06 \x01(\x11R\x05scale\x12\x1d\n" + + "\n" + + "zero_count\x18\a \x01(\x06R\tzeroCount\x12a\n" + + "\bpositive\x18\b \x01(\v2E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.BucketsR\bpositive\x12a\n" + + "\bnegative\x18\t \x01(\v2E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.BucketsR\bnegative\x12\x14\n" + + "\x05flags\x18\n" + + " \x01(\rR\x05flags\x12F\n" + + "\texemplars\x18\v \x03(\v2(.opentelemetry.proto.metrics.v1.ExemplarR\texemplars\x12\x15\n" + + "\x03min\x18\f \x01(\x01H\x01R\x03min\x88\x01\x01\x12\x15\n" + + "\x03max\x18\r \x01(\x01H\x02R\x03max\x88\x01\x01\x12%\n" + + "\x0ezero_threshold\x18\x0e \x01(\x01R\rzeroThreshold\x1aF\n" + + "\aBuckets\x12\x16\n" + + "\x06offset\x18\x01 \x01(\x11R\x06offset\x12#\n" + + "\rbucket_counts\x18\x02 \x03(\x04R\fbucketCountsB\x06\n" + + "\x04_sumB\x06\n" + + "\x04_minB\x06\n" + + "\x04_max\"\xa6\x03\n" + + "\x10SummaryDataPoint\x12G\n" + + "\n" + + "attributes\x18\a \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x12/\n" + + "\x14start_time_unix_nano\x18\x02 \x01(\x06R\x11startTimeUnixNano\x12$\n" + + "\x0etime_unix_nano\x18\x03 \x01(\x06R\ftimeUnixNano\x12\x14\n" + + "\x05count\x18\x04 \x01(\x06R\x05count\x12\x10\n" + + "\x03sum\x18\x05 \x01(\x01R\x03sum\x12i\n" + + "\x0fquantile_values\x18\x06 \x03(\v2@.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantileR\x0equantileValues\x12\x14\n" + + "\x05flags\x18\b \x01(\rR\x05flags\x1aC\n" + + "\x0fValueAtQuantile\x12\x1a\n" + + "\bquantile\x18\x01 \x01(\x01R\bquantile\x12\x14\n" + + "\x05value\x18\x02 \x01(\x01R\x05valueJ\x04\b\x01\x10\x02\"\x85\x02\n" + + "\bExemplar\x12X\n" + + "\x13filtered_attributes\x18\a \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\x12filteredAttributes\x12$\n" + + "\x0etime_unix_nano\x18\x02 \x01(\x06R\ftimeUnixNano\x12\x1d\n" + + "\tas_double\x18\x03 \x01(\x01H\x00R\basDouble\x12\x17\n" + + "\x06as_int\x18\x06 \x01(\x10H\x00R\x05asInt\x12\x17\n" + + "\aspan_id\x18\x04 \x01(\fR\x06spanId\x12\x19\n" + + "\btrace_id\x18\x05 \x01(\fR\atraceIdB\a\n" + + "\x05valueJ\x04\b\x01\x10\x02*\x8c\x01\n" + + "\x16AggregationTemporality\x12'\n" + + "#AGGREGATION_TEMPORALITY_UNSPECIFIED\x10\x00\x12!\n" + + "\x1dAGGREGATION_TEMPORALITY_DELTA\x10\x01\x12&\n" + + "\"AGGREGATION_TEMPORALITY_CUMULATIVE\x10\x02*^\n" + + "\x0eDataPointFlags\x12\x1f\n" + + "\x1bDATA_POINT_FLAGS_DO_NOT_USE\x10\x00\x12+\n" + + "'DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK\x10\x01B\x7f\n" + + "!io.opentelemetry.proto.metrics.v1B\fMetricsProtoP\x01Z)go.opentelemetry.io/proto/otlp/metrics/v1\xaa\x02\x1eOpenTelemetry.Proto.Metrics.V1b\x06proto3" var ( file_opentelemetry_proto_metrics_v1_metrics_proto_rawDescOnce sync.Once - file_opentelemetry_proto_metrics_v1_metrics_proto_rawDescData = file_opentelemetry_proto_metrics_v1_metrics_proto_rawDesc + file_opentelemetry_proto_metrics_v1_metrics_proto_rawDescData []byte ) func file_opentelemetry_proto_metrics_v1_metrics_proto_rawDescGZIP() []byte { file_opentelemetry_proto_metrics_v1_metrics_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_metrics_v1_metrics_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_metrics_v1_metrics_proto_rawDescData) + file_opentelemetry_proto_metrics_v1_metrics_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_metrics_v1_metrics_proto_rawDesc), len(file_opentelemetry_proto_metrics_v1_metrics_proto_rawDesc))) }) return file_opentelemetry_proto_metrics_v1_metrics_proto_rawDescData } var file_opentelemetry_proto_metrics_v1_metrics_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes = make([]protoimpl.MessageInfo, 16) -var file_opentelemetry_proto_metrics_v1_metrics_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_metrics_v1_metrics_proto_goTypes = []any{ (AggregationTemporality)(0), // 0: opentelemetry.proto.metrics.v1.AggregationTemporality (DataPointFlags)(0), // 1: opentelemetry.proto.metrics.v1.DataPointFlags (*MetricsData)(nil), // 2: opentelemetry.proto.metrics.v1.MetricsData @@ -2326,214 +2134,20 @@ func file_opentelemetry_proto_metrics_v1_metrics_proto_init() { if File_opentelemetry_proto_metrics_v1_metrics_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MetricsData); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ResourceMetrics); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ScopeMetrics); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Metric); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Gauge); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Sum); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Histogram); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExponentialHistogram); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Summary); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*NumberDataPoint); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*HistogramDataPoint); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExponentialHistogramDataPoint); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SummaryDataPoint); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Exemplar); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExponentialHistogramDataPoint_Buckets); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SummaryDataPoint_ValueAtQuantile); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[3].OneofWrappers = []interface{}{ + file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[3].OneofWrappers = []any{ (*Metric_Gauge)(nil), (*Metric_Sum)(nil), (*Metric_Histogram)(nil), (*Metric_ExponentialHistogram)(nil), (*Metric_Summary)(nil), } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[9].OneofWrappers = []interface{}{ + file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[9].OneofWrappers = []any{ (*NumberDataPoint_AsDouble)(nil), (*NumberDataPoint_AsInt)(nil), } - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[10].OneofWrappers = []interface{}{} - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[11].OneofWrappers = []interface{}{} - file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[13].OneofWrappers = []interface{}{ + file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[10].OneofWrappers = []any{} + file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[11].OneofWrappers = []any{} + file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes[13].OneofWrappers = []any{ (*Exemplar_AsDouble)(nil), (*Exemplar_AsInt)(nil), } @@ -2541,7 +2155,7 @@ func file_opentelemetry_proto_metrics_v1_metrics_proto_init() { out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_metrics_v1_metrics_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_metrics_v1_metrics_proto_rawDesc), len(file_opentelemetry_proto_metrics_v1_metrics_proto_rawDesc)), NumEnums: 2, NumMessages: 16, NumExtensions: 0, @@ -2553,7 +2167,6 @@ func file_opentelemetry_proto_metrics_v1_metrics_proto_init() { MessageInfos: file_opentelemetry_proto_metrics_v1_metrics_proto_msgTypes, }.Build() File_opentelemetry_proto_metrics_v1_metrics_proto = out.File - file_opentelemetry_proto_metrics_v1_metrics_proto_rawDesc = nil file_opentelemetry_proto_metrics_v1_metrics_proto_goTypes = nil file_opentelemetry_proto_metrics_v1_metrics_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go b/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go index 301247ddfe..de95b8f21c 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/resource/v1/resource.proto package v1 @@ -26,6 +26,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -37,10 +38,7 @@ const ( // Resource information. type Resource struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Set of attributes that describe the resource. // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). @@ -54,16 +52,18 @@ type Resource struct { // Note: keys in the references MUST exist in attributes of this message. // // Status: [Development] - EntityRefs []*v1.EntityRef `protobuf:"bytes,3,rep,name=entity_refs,json=entityRefs,proto3" json:"entity_refs,omitempty"` + // + // [Since v1.6.0] + EntityRefs []*v1.EntityRef `protobuf:"bytes,3,rep,name=entity_refs,json=entityRefs,proto3" json:"entity_refs,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Resource) Reset() { *x = Resource{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_resource_v1_resource_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_resource_v1_resource_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Resource) String() string { @@ -74,7 +74,7 @@ func (*Resource) ProtoMessage() {} func (x *Resource) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_resource_v1_resource_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -112,54 +112,32 @@ func (x *Resource) GetEntityRefs() []*v1.EntityRef { var File_opentelemetry_proto_resource_v1_resource_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_resource_v1_resource_proto_rawDesc = []byte{ - 0x0a, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2f, 0x76, - 0x31, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x12, 0x1f, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x76, - 0x31, 0x1a, 0x2a, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, - 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xd8, 0x01, - 0x0a, 0x08, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, - 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, - 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, - 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x49, 0x0a, - 0x0b, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x72, 0x65, 0x66, 0x73, 0x18, 0x03, 0x20, 0x03, - 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, - 0x76, 0x31, 0x2e, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x52, 0x65, 0x66, 0x52, 0x0a, 0x65, 0x6e, - 0x74, 0x69, 0x74, 0x79, 0x52, 0x65, 0x66, 0x73, 0x42, 0x83, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x42, - 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, - 0x5a, 0x2a, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, - 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x1f, 0x4f, - 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x6f, - 0x74, 0x6f, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x56, 0x31, 0x62, 0x06, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_resource_v1_resource_proto_rawDesc = "" + + "\n" + + ".opentelemetry/proto/resource/v1/resource.proto\x12\x1fopentelemetry.proto.resource.v1\x1a*opentelemetry/proto/common/v1/common.proto\"\xd8\x01\n" + + "\bResource\x12G\n" + + "\n" + + "attributes\x18\x01 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\x02 \x01(\rR\x16droppedAttributesCount\x12I\n" + + "\ventity_refs\x18\x03 \x03(\v2(.opentelemetry.proto.common.v1.EntityRefR\n" + + "entityRefsB\x83\x01\n" + + "\"io.opentelemetry.proto.resource.v1B\rResourceProtoP\x01Z*go.opentelemetry.io/proto/otlp/resource/v1\xaa\x02\x1fOpenTelemetry.Proto.Resource.V1b\x06proto3" var ( file_opentelemetry_proto_resource_v1_resource_proto_rawDescOnce sync.Once - file_opentelemetry_proto_resource_v1_resource_proto_rawDescData = file_opentelemetry_proto_resource_v1_resource_proto_rawDesc + file_opentelemetry_proto_resource_v1_resource_proto_rawDescData []byte ) func file_opentelemetry_proto_resource_v1_resource_proto_rawDescGZIP() []byte { file_opentelemetry_proto_resource_v1_resource_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_resource_v1_resource_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_resource_v1_resource_proto_rawDescData) + file_opentelemetry_proto_resource_v1_resource_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_resource_v1_resource_proto_rawDesc), len(file_opentelemetry_proto_resource_v1_resource_proto_rawDesc))) }) return file_opentelemetry_proto_resource_v1_resource_proto_rawDescData } var file_opentelemetry_proto_resource_v1_resource_proto_msgTypes = make([]protoimpl.MessageInfo, 1) -var file_opentelemetry_proto_resource_v1_resource_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_resource_v1_resource_proto_goTypes = []any{ (*Resource)(nil), // 0: opentelemetry.proto.resource.v1.Resource (*v1.KeyValue)(nil), // 1: opentelemetry.proto.common.v1.KeyValue (*v1.EntityRef)(nil), // 2: opentelemetry.proto.common.v1.EntityRef @@ -179,25 +157,11 @@ func file_opentelemetry_proto_resource_v1_resource_proto_init() { if File_opentelemetry_proto_resource_v1_resource_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_resource_v1_resource_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Resource); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_resource_v1_resource_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_resource_v1_resource_proto_rawDesc), len(file_opentelemetry_proto_resource_v1_resource_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, @@ -208,7 +172,6 @@ func file_opentelemetry_proto_resource_v1_resource_proto_init() { MessageInfos: file_opentelemetry_proto_resource_v1_resource_proto_msgTypes, }.Build() File_opentelemetry_proto_resource_v1_resource_proto = out.File - file_opentelemetry_proto_resource_v1_resource_proto_rawDesc = nil file_opentelemetry_proto_resource_v1_resource_proto_goTypes = nil file_opentelemetry_proto_resource_v1_resource_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go index d7bfca9029..9a9daf44d0 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/trace/v1/trace.proto package v1 @@ -27,6 +27,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -42,7 +43,7 @@ const ( // a bit-mask. To extract the bit-field, for example, use an // expression like: // -// (span.flags & SPAN_FLAGS_TRACE_FLAGS_MASK) +// (span.flags & SPAN_FLAGS_TRACE_FLAGS_MASK) // // See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions. // @@ -50,6 +51,8 @@ const ( // OpenTelemetry protocol. Older Span producers do not set this // field, consequently consumers should not rely on the absence of a // particular flag bit to indicate the presence of a particular feature. +// +// [Since v1.1.0] type SpanFlags int32 const ( @@ -61,8 +64,11 @@ const ( // Bits 8 and 9 are used to indicate that the parent span or link span is remote. // Bit 8 (`HAS_IS_REMOTE`) indicates whether the value is known. // Bit 9 (`IS_REMOTE`) indicates whether the span or link is remote. + // + // [Since v1.2.0] SpanFlags_SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK SpanFlags = 256 - SpanFlags_SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK SpanFlags = 512 + // [Since v1.2.0] + SpanFlags_SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK SpanFlags = 512 ) // Enum value maps for SpanFlags. @@ -248,25 +254,22 @@ func (Status_StatusCode) EnumDescriptor() ([]byte, []int) { // When new fields are added into this message, the OTLP request MUST be updated // as well. type TracesData struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // An array of ResourceSpans. // For data coming from a single resource this array will typically contain // one element. Intermediary nodes that receive data from multiple origins // typically batch the data before forwarding further and in that case this // array will contain multiple elements. ResourceSpans []*ResourceSpans `protobuf:"bytes,1,rep,name=resource_spans,json=resourceSpans,proto3" json:"resource_spans,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *TracesData) Reset() { *x = TracesData{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *TracesData) String() string { @@ -277,7 +280,7 @@ func (*TracesData) ProtoMessage() {} func (x *TracesData) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -301,10 +304,7 @@ func (x *TracesData) GetResourceSpans() []*ResourceSpans { // A collection of ScopeSpans from a Resource. type ResourceSpans struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The resource for the spans in this message. // If this field is not set then no resource info is known. Resource *v1.Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` @@ -316,16 +316,16 @@ type ResourceSpans struct { // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to the data in the "resource" field. It does not apply // to the data in the "scope_spans" field which have their own schema_url field. - SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ResourceSpans) Reset() { *x = ResourceSpans{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ResourceSpans) String() string { @@ -336,7 +336,7 @@ func (*ResourceSpans) ProtoMessage() {} func (x *ResourceSpans) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -374,10 +374,7 @@ func (x *ResourceSpans) GetSchemaUrl() string { // A collection of Spans produced by an InstrumentationScope. type ScopeSpans struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The instrumentation scope information for the spans in this message. // Semantically when InstrumentationScope isn't set, it is equivalent with // an empty instrumentation scope name (unknown). @@ -390,16 +387,16 @@ type ScopeSpans struct { // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to the data in the "scope" field and all spans and span // events in the "spans" field. - SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ScopeSpans) Reset() { *x = ScopeSpans{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ScopeSpans) String() string { @@ -410,7 +407,7 @@ func (*ScopeSpans) ProtoMessage() {} func (x *ScopeSpans) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -450,10 +447,7 @@ func (x *ScopeSpans) GetSchemaUrl() string { // // The next available field id is 17. type Span struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A unique identifier for a trace. All spans from the same trace share // the same `trace_id`. The ID is a 16-byte array. An ID with all zeroes OR // of length other than 16 bytes is considered invalid (empty string in OTLP/JSON @@ -496,6 +490,8 @@ type Span struct { // Readers MUST NOT assume that bits 10-31 (22 most significant bits) will be zero. // // [Optional]. + // + // [Since v1.1.0] Flags uint32 `protobuf:"fixed32,16,opt,name=flags,proto3" json:"flags,omitempty"` // A description of the span's operation. // @@ -528,12 +524,12 @@ type Span struct { // This field is semantically required and it is expected that end_time >= start_time. EndTimeUnixNano uint64 `protobuf:"fixed64,8,opt,name=end_time_unix_nano,json=endTimeUnixNano,proto3" json:"end_time_unix_nano,omitempty"` // A collection of key/value pairs. Note, global attributes - // like server name can be set using the resource API. Examples of attributes: + // like service name can be set using the resource API. Examples of attributes: // - // "/http/user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" - // "/http/server_latency": 300 - // "example.com/myattribute": true - // "example.com/score": 10.239 + // "user_agent.original": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" + // "http.response.status_code": 200 + // "com.example.myattribute": true + // "com.example.score": 10.239 // // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). @@ -556,16 +552,16 @@ type Span struct { DroppedLinksCount uint32 `protobuf:"varint,14,opt,name=dropped_links_count,json=droppedLinksCount,proto3" json:"dropped_links_count,omitempty"` // An optional final status for this span. Semantically when Status isn't set, it means // span's status code is unset, i.e. assume STATUS_CODE_UNSET (code = 0). - Status *Status `protobuf:"bytes,15,opt,name=status,proto3" json:"status,omitempty"` + Status *Status `protobuf:"bytes,15,opt,name=status,proto3" json:"status,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Span) Reset() { *x = Span{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Span) String() string { @@ -576,7 +572,7 @@ func (*Span) ProtoMessage() {} func (x *Span) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -706,23 +702,20 @@ func (x *Span) GetStatus() *Status { // The Status type defines a logical error model that is suitable for different // programming environments, including REST APIs and RPC APIs. type Status struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A developer-facing human readable error message. Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` // The status code. - Code Status_StatusCode `protobuf:"varint,3,opt,name=code,proto3,enum=opentelemetry.proto.trace.v1.Status_StatusCode" json:"code,omitempty"` + Code Status_StatusCode `protobuf:"varint,3,opt,name=code,proto3,enum=opentelemetry.proto.trace.v1.Status_StatusCode" json:"code,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Status) Reset() { *x = Status{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Status) String() string { @@ -733,7 +726,7 @@ func (*Status) ProtoMessage() {} func (x *Status) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -765,10 +758,7 @@ func (x *Status) GetCode() Status_StatusCode { // Event is a time-stamped annotation of the span, consisting of user-supplied // text description and key-value pairs. type Span_Event struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The time the event occurred. TimeUnixNano uint64 `protobuf:"fixed64,1,opt,name=time_unix_nano,json=timeUnixNano,proto3" json:"time_unix_nano,omitempty"` // The name of the event. @@ -782,15 +772,15 @@ type Span_Event struct { // The number of dropped attributes. If the value is 0, // then no attributes were dropped. DroppedAttributesCount uint32 `protobuf:"varint,4,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Span_Event) Reset() { *x = Span_Event{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Span_Event) String() string { @@ -801,7 +791,7 @@ func (*Span_Event) ProtoMessage() {} func (x *Span_Event) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -849,10 +839,7 @@ func (x *Span_Event) GetDroppedAttributesCount() uint32 { // where a single batch handler processes multiple requests from different // traces or when the handler receives a request from a different project. type Span_Link struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A unique identifier of a trace that this linked span is part of. The ID is a // 16-byte array. TraceId []byte `protobuf:"bytes,1,opt,name=trace_id,json=traceId,proto3" json:"trace_id,omitempty"` @@ -885,16 +872,18 @@ type Span_Link struct { // When creating new spans, bits 10-31 (most-significant 22-bits) MUST be zero. // // [Optional]. - Flags uint32 `protobuf:"fixed32,6,opt,name=flags,proto3" json:"flags,omitempty"` + // + // [Since v1.1.0] + Flags uint32 `protobuf:"fixed32,6,opt,name=flags,proto3" json:"flags,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Span_Link) Reset() { *x = Span_Link{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Span_Link) String() string { @@ -905,7 +894,7 @@ func (*Span_Link) ProtoMessage() {} func (x *Span_Link) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -964,179 +953,101 @@ func (x *Span_Link) GetFlags() uint32 { var File_opentelemetry_proto_trace_v1_trace_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_trace_v1_trace_proto_rawDesc = []byte{ - 0x0a, 0x28, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x74, - 0x72, 0x61, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1c, 0x6f, 0x70, 0x65, 0x6e, - 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x2a, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, - 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x60, 0x0a, 0x0a, 0x54, 0x72, 0x61, 0x63, 0x65, 0x73, 0x44, 0x61, - 0x74, 0x61, 0x12, 0x52, 0x0a, 0x0e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x73, - 0x70, 0x61, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x22, 0xc8, 0x01, 0x0a, 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, - 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x45, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, - 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, - 0x49, 0x0a, 0x0b, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x18, 0x02, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, - 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, - 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x52, 0x0a, - 0x73, 0x63, 0x6f, 0x70, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, - 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, - 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x55, 0x72, 0x6c, 0x4a, 0x06, 0x08, 0xe8, 0x07, 0x10, 0xe9, - 0x07, 0x22, 0xb0, 0x01, 0x0a, 0x0a, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, - 0x12, 0x49, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x33, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, - 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, - 0x63, 0x6f, 0x70, 0x65, 0x52, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x38, 0x0a, 0x05, 0x73, - 0x70, 0x61, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x52, 0x05, - 0x73, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, - 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x63, 0x68, 0x65, 0x6d, - 0x61, 0x55, 0x72, 0x6c, 0x22, 0xc8, 0x0a, 0x0a, 0x04, 0x53, 0x70, 0x61, 0x6e, 0x12, 0x19, 0x0a, - 0x08, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x07, 0x74, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x73, 0x70, 0x61, 0x6e, - 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x70, 0x61, 0x6e, 0x49, - 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x72, 0x61, 0x63, 0x65, 0x53, 0x74, 0x61, - 0x74, 0x65, 0x12, 0x24, 0x0a, 0x0e, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x70, 0x61, - 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x70, 0x61, 0x72, 0x65, - 0x6e, 0x74, 0x53, 0x70, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x6c, 0x61, 0x67, - 0x73, 0x18, 0x10, 0x20, 0x01, 0x28, 0x07, 0x52, 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x12, 0x12, - 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, - 0x6d, 0x65, 0x12, 0x3f, 0x0a, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, - 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, - 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x4b, 0x69, 0x6e, 0x64, 0x52, 0x04, 0x6b, - 0x69, 0x6e, 0x64, 0x12, 0x2f, 0x0a, 0x14, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, - 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x07, 0x20, 0x01, 0x28, - 0x06, 0x52, 0x11, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, - 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x2b, 0x0a, 0x12, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, - 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x08, 0x20, 0x01, 0x28, 0x06, - 0x52, 0x0f, 0x65, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, - 0x6f, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, - 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, - 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, - 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, - 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, - 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, - 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, - 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, - 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x40, 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x0b, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, - 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, - 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, - 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x30, 0x0a, 0x14, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, - 0x64, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0c, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x12, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x45, 0x76, 0x65, - 0x6e, 0x74, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x3d, 0x0a, 0x05, 0x6c, 0x69, 0x6e, 0x6b, - 0x73, 0x18, 0x0d, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x4c, 0x69, 0x6e, 0x6b, - 0x52, 0x05, 0x6c, 0x69, 0x6e, 0x6b, 0x73, 0x12, 0x2e, 0x0a, 0x13, 0x64, 0x72, 0x6f, 0x70, 0x70, - 0x65, 0x64, 0x5f, 0x6c, 0x69, 0x6e, 0x6b, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0e, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x11, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x4c, 0x69, 0x6e, - 0x6b, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, - 0x73, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, - 0x74, 0x61, 0x74, 0x75, 0x73, 0x1a, 0xc4, 0x01, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, - 0x24, 0x0a, 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, - 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, - 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, - 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, - 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, - 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, - 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x1a, 0xf4, 0x01, 0x0a, - 0x04, 0x4c, 0x69, 0x6e, 0x6b, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, - 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x74, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, - 0x12, 0x17, 0x0a, 0x07, 0x73, 0x70, 0x61, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0c, 0x52, 0x06, 0x73, 0x70, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x72, 0x61, - 0x63, 0x65, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, - 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, - 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, - 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, - 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x14, 0x0a, - 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x07, 0x52, 0x05, 0x66, 0x6c, - 0x61, 0x67, 0x73, 0x22, 0x99, 0x01, 0x0a, 0x08, 0x53, 0x70, 0x61, 0x6e, 0x4b, 0x69, 0x6e, 0x64, - 0x12, 0x19, 0x0a, 0x15, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x55, 0x4e, - 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x16, 0x0a, 0x12, 0x53, - 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, - 0x4c, 0x10, 0x01, 0x12, 0x14, 0x0a, 0x10, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, - 0x5f, 0x53, 0x45, 0x52, 0x56, 0x45, 0x52, 0x10, 0x02, 0x12, 0x14, 0x0a, 0x10, 0x53, 0x50, 0x41, - 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x10, 0x03, 0x12, - 0x16, 0x0a, 0x12, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x50, 0x52, 0x4f, - 0x44, 0x55, 0x43, 0x45, 0x52, 0x10, 0x04, 0x12, 0x16, 0x0a, 0x12, 0x53, 0x50, 0x41, 0x4e, 0x5f, - 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x43, 0x4f, 0x4e, 0x53, 0x55, 0x4d, 0x45, 0x52, 0x10, 0x05, 0x22, - 0xbd, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, - 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, - 0x73, 0x61, 0x67, 0x65, 0x12, 0x43, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, - 0x28, 0x0e, 0x32, 0x2f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, - 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, - 0x6f, 0x64, 0x65, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x4e, 0x0a, 0x0a, 0x53, 0x74, 0x61, - 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, 0x55, - 0x53, 0x5f, 0x43, 0x4f, 0x44, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x12, - 0x0a, 0x0e, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x44, 0x45, 0x5f, 0x4f, 0x4b, - 0x10, 0x01, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x44, - 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x2a, - 0x9c, 0x01, 0x0a, 0x09, 0x53, 0x70, 0x61, 0x6e, 0x46, 0x6c, 0x61, 0x67, 0x73, 0x12, 0x19, 0x0a, - 0x15, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x44, 0x4f, 0x5f, 0x4e, - 0x4f, 0x54, 0x5f, 0x55, 0x53, 0x45, 0x10, 0x00, 0x12, 0x20, 0x0a, 0x1b, 0x53, 0x50, 0x41, 0x4e, - 0x5f, 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x54, 0x52, 0x41, 0x43, 0x45, 0x5f, 0x46, 0x4c, 0x41, - 0x47, 0x53, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0xff, 0x01, 0x12, 0x2a, 0x0a, 0x25, 0x53, 0x50, - 0x41, 0x4e, 0x5f, 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x43, 0x4f, 0x4e, 0x54, 0x45, 0x58, 0x54, - 0x5f, 0x48, 0x41, 0x53, 0x5f, 0x49, 0x53, 0x5f, 0x52, 0x45, 0x4d, 0x4f, 0x54, 0x45, 0x5f, 0x4d, - 0x41, 0x53, 0x4b, 0x10, 0x80, 0x02, 0x12, 0x26, 0x0a, 0x21, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x46, - 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x43, 0x4f, 0x4e, 0x54, 0x45, 0x58, 0x54, 0x5f, 0x49, 0x53, 0x5f, - 0x52, 0x45, 0x4d, 0x4f, 0x54, 0x45, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0x80, 0x04, 0x42, 0x77, - 0x0a, 0x1f, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, - 0x31, 0x42, 0x0a, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, - 0x27, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x1c, 0x4f, 0x70, 0x65, 0x6e, 0x54, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x54, - 0x72, 0x61, 0x63, 0x65, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_trace_v1_trace_proto_rawDesc = "" + + "\n" + + "(opentelemetry/proto/trace/v1/trace.proto\x12\x1copentelemetry.proto.trace.v1\x1a*opentelemetry/proto/common/v1/common.proto\x1a.opentelemetry/proto/resource/v1/resource.proto\"`\n" + + "\n" + + "TracesData\x12R\n" + + "\x0eresource_spans\x18\x01 \x03(\v2+.opentelemetry.proto.trace.v1.ResourceSpansR\rresourceSpans\"\xc8\x01\n" + + "\rResourceSpans\x12E\n" + + "\bresource\x18\x01 \x01(\v2).opentelemetry.proto.resource.v1.ResourceR\bresource\x12I\n" + + "\vscope_spans\x18\x02 \x03(\v2(.opentelemetry.proto.trace.v1.ScopeSpansR\n" + + "scopeSpans\x12\x1d\n" + + "\n" + + "schema_url\x18\x03 \x01(\tR\tschemaUrlJ\x06\b\xe8\a\x10\xe9\a\"\xb0\x01\n" + + "\n" + + "ScopeSpans\x12I\n" + + "\x05scope\x18\x01 \x01(\v23.opentelemetry.proto.common.v1.InstrumentationScopeR\x05scope\x128\n" + + "\x05spans\x18\x02 \x03(\v2\".opentelemetry.proto.trace.v1.SpanR\x05spans\x12\x1d\n" + + "\n" + + "schema_url\x18\x03 \x01(\tR\tschemaUrl\"\xc8\n" + + "\n" + + "\x04Span\x12\x19\n" + + "\btrace_id\x18\x01 \x01(\fR\atraceId\x12\x17\n" + + "\aspan_id\x18\x02 \x01(\fR\x06spanId\x12\x1f\n" + + "\vtrace_state\x18\x03 \x01(\tR\n" + + "traceState\x12$\n" + + "\x0eparent_span_id\x18\x04 \x01(\fR\fparentSpanId\x12\x14\n" + + "\x05flags\x18\x10 \x01(\aR\x05flags\x12\x12\n" + + "\x04name\x18\x05 \x01(\tR\x04name\x12?\n" + + "\x04kind\x18\x06 \x01(\x0e2+.opentelemetry.proto.trace.v1.Span.SpanKindR\x04kind\x12/\n" + + "\x14start_time_unix_nano\x18\a \x01(\x06R\x11startTimeUnixNano\x12+\n" + + "\x12end_time_unix_nano\x18\b \x01(\x06R\x0fendTimeUnixNano\x12G\n" + + "\n" + + "attributes\x18\t \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\n" + + " \x01(\rR\x16droppedAttributesCount\x12@\n" + + "\x06events\x18\v \x03(\v2(.opentelemetry.proto.trace.v1.Span.EventR\x06events\x120\n" + + "\x14dropped_events_count\x18\f \x01(\rR\x12droppedEventsCount\x12=\n" + + "\x05links\x18\r \x03(\v2'.opentelemetry.proto.trace.v1.Span.LinkR\x05links\x12.\n" + + "\x13dropped_links_count\x18\x0e \x01(\rR\x11droppedLinksCount\x12<\n" + + "\x06status\x18\x0f \x01(\v2$.opentelemetry.proto.trace.v1.StatusR\x06status\x1a\xc4\x01\n" + + "\x05Event\x12$\n" + + "\x0etime_unix_nano\x18\x01 \x01(\x06R\ftimeUnixNano\x12\x12\n" + + "\x04name\x18\x02 \x01(\tR\x04name\x12G\n" + + "\n" + + "attributes\x18\x03 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\x04 \x01(\rR\x16droppedAttributesCount\x1a\xf4\x01\n" + + "\x04Link\x12\x19\n" + + "\btrace_id\x18\x01 \x01(\fR\atraceId\x12\x17\n" + + "\aspan_id\x18\x02 \x01(\fR\x06spanId\x12\x1f\n" + + "\vtrace_state\x18\x03 \x01(\tR\n" + + "traceState\x12G\n" + + "\n" + + "attributes\x18\x04 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\x05 \x01(\rR\x16droppedAttributesCount\x12\x14\n" + + "\x05flags\x18\x06 \x01(\aR\x05flags\"\x99\x01\n" + + "\bSpanKind\x12\x19\n" + + "\x15SPAN_KIND_UNSPECIFIED\x10\x00\x12\x16\n" + + "\x12SPAN_KIND_INTERNAL\x10\x01\x12\x14\n" + + "\x10SPAN_KIND_SERVER\x10\x02\x12\x14\n" + + "\x10SPAN_KIND_CLIENT\x10\x03\x12\x16\n" + + "\x12SPAN_KIND_PRODUCER\x10\x04\x12\x16\n" + + "\x12SPAN_KIND_CONSUMER\x10\x05\"\xbd\x01\n" + + "\x06Status\x12\x18\n" + + "\amessage\x18\x02 \x01(\tR\amessage\x12C\n" + + "\x04code\x18\x03 \x01(\x0e2/.opentelemetry.proto.trace.v1.Status.StatusCodeR\x04code\"N\n" + + "\n" + + "StatusCode\x12\x15\n" + + "\x11STATUS_CODE_UNSET\x10\x00\x12\x12\n" + + "\x0eSTATUS_CODE_OK\x10\x01\x12\x15\n" + + "\x11STATUS_CODE_ERROR\x10\x02J\x04\b\x01\x10\x02*\x9c\x01\n" + + "\tSpanFlags\x12\x19\n" + + "\x15SPAN_FLAGS_DO_NOT_USE\x10\x00\x12 \n" + + "\x1bSPAN_FLAGS_TRACE_FLAGS_MASK\x10\xff\x01\x12*\n" + + "%SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK\x10\x80\x02\x12&\n" + + "!SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK\x10\x80\x04Bw\n" + + "\x1fio.opentelemetry.proto.trace.v1B\n" + + "TraceProtoP\x01Z'go.opentelemetry.io/proto/otlp/trace/v1\xaa\x02\x1cOpenTelemetry.Proto.Trace.V1b\x06proto3" var ( file_opentelemetry_proto_trace_v1_trace_proto_rawDescOnce sync.Once - file_opentelemetry_proto_trace_v1_trace_proto_rawDescData = file_opentelemetry_proto_trace_v1_trace_proto_rawDesc + file_opentelemetry_proto_trace_v1_trace_proto_rawDescData []byte ) func file_opentelemetry_proto_trace_v1_trace_proto_rawDescGZIP() []byte { file_opentelemetry_proto_trace_v1_trace_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_trace_v1_trace_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_trace_v1_trace_proto_rawDescData) + file_opentelemetry_proto_trace_v1_trace_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_trace_v1_trace_proto_rawDesc), len(file_opentelemetry_proto_trace_v1_trace_proto_rawDesc))) }) return file_opentelemetry_proto_trace_v1_trace_proto_rawDescData } var file_opentelemetry_proto_trace_v1_trace_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_opentelemetry_proto_trace_v1_trace_proto_msgTypes = make([]protoimpl.MessageInfo, 7) -var file_opentelemetry_proto_trace_v1_trace_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_trace_v1_trace_proto_goTypes = []any{ (SpanFlags)(0), // 0: opentelemetry.proto.trace.v1.SpanFlags (Span_SpanKind)(0), // 1: opentelemetry.proto.trace.v1.Span.SpanKind (Status_StatusCode)(0), // 2: opentelemetry.proto.trace.v1.Status.StatusCode @@ -1177,97 +1088,11 @@ func file_opentelemetry_proto_trace_v1_trace_proto_init() { if File_opentelemetry_proto_trace_v1_trace_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*TracesData); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ResourceSpans); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ScopeSpans); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Span); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Status); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Span_Event); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Span_Link); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_trace_v1_trace_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_trace_v1_trace_proto_rawDesc), len(file_opentelemetry_proto_trace_v1_trace_proto_rawDesc)), NumEnums: 3, NumMessages: 7, NumExtensions: 0, @@ -1279,7 +1104,6 @@ func file_opentelemetry_proto_trace_v1_trace_proto_init() { MessageInfos: file_opentelemetry_proto_trace_v1_trace_proto_msgTypes, }.Build() File_opentelemetry_proto_trace_v1_trace_proto = out.File - file_opentelemetry_proto_trace_v1_trace_proto_rawDesc = nil file_opentelemetry_proto_trace_v1_trace_proto_goTypes = nil file_opentelemetry_proto_trace_v1_trace_proto_depIdxs = nil } diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_loong64.go b/vendor/golang.org/x/crypto/chacha20/chacha_loong64.go new file mode 100644 index 0000000000..9679f9ee09 --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/chacha_loong64.go @@ -0,0 +1,22 @@ +// Copyright 2026 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. + +//go:build gc && !purego + +package chacha20 + +import "golang.org/x/sys/cpu" + +const bufSize = 256 + +//go:noescape +func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) + +func (c *Cipher) xorKeyStreamBlocks(dst, src []byte) { + if cpu.Loong64.HasLSX { + xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter) + } else { + c.xorKeyStreamBlocksGeneric(dst, src) + } +} diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_loong64.s b/vendor/golang.org/x/crypto/chacha20/chacha_loong64.s new file mode 100644 index 0000000000..e377b43273 --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/chacha_loong64.s @@ -0,0 +1,342 @@ +// Copyright 2026 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. + +// derived from chacha_arm64.s + +//go:build gc && !purego + +#include "textflag.h" + +DATA ·constants+0x00(SB)/4, $0x61707865 +DATA ·constants+0x04(SB)/4, $0x3320646e +DATA ·constants+0x08(SB)/4, $0x79622d32 +DATA ·constants+0x0c(SB)/4, $0x6b206574 +GLOBL ·constants(SB), NOPTR|RODATA, $32 + +DATA ·incRotMatrix+0x00(SB)/4, $0x00000000 +DATA ·incRotMatrix+0x04(SB)/4, $0x00000001 +DATA ·incRotMatrix+0x08(SB)/4, $0x00000002 +DATA ·incRotMatrix+0x0c(SB)/4, $0x00000003 +GLOBL ·incRotMatrix(SB), NOPTR|RODATA, $32 + +#define NUM_ROUNDS 10 + +// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) +TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 + MOVV dst+0(FP), R4 + MOVV src+24(FP), R5 + MOVV src_len+32(FP), R6 + MOVV key+48(FP), R7 + MOVV nonce+56(FP), R8 + MOVV counter+64(FP), R9 + + MOVV $·constants(SB), R10 + MOVV $·incRotMatrix(SB), R11 + + MOVW (R9), R12 + +loop: + MOVV $NUM_ROUNDS, R15 + // load 4-32bit data from incRotMatrix added to counter + VMOVQ (R11), V30 + + // load contants + VMOVQ (R10), V0.W4 + VMOVQ 4(R10), V1.W4 + VMOVQ 8(R10), V2.W4 + VMOVQ 12(R10), V3.W4 + + // load keys + VMOVQ (R7), V4.W4 + VMOVQ 4(R7), V5.W4 + VMOVQ 8(R7), V6.W4 + VMOVQ 12(R7), V7.W4 + VMOVQ 16(R7), V8.W4 + VMOVQ 20(R7), V9.W4 + VMOVQ 24(R7), V10.W4 + VMOVQ 28(R7), V11.W4 + + // load counter + nonce + VMOVQ (R9), V12.W4 + + VMOVQ (R8), V13.W4 + VMOVQ 4(R8), V14.W4 + VMOVQ 8(R8), V15.W4 + + // update counter + VADDW V30, V12, V12 + +chacha: + // V0..V3 += V4..V7 + // V12..V15 <<<= ((V12..V15 XOR V0..V3), 16) + VADDW V0, V4, V0 + VADDW V1, V5, V1 + VADDW V2, V6, V2 + VADDW V3, V7, V3 + VXORV V12, V0, V12 + VXORV V13, V1, V13 + VXORV V14, V2, V14 + VXORV V15, V3, V15 + VROTRW $16, V12, V12 + VROTRW $16, V13, V13 + VROTRW $16, V14, V14 + VROTRW $16, V15, V15 + + // V8..V11 += V12..V15 + // V4..V7 <<<= ((V4..V7 XOR V8..V11), 12) + VADDW V8, V12, V8 + VADDW V9, V13, V9 + VADDW V10, V14, V10 + VADDW V11, V15, V11 + VXORV V4, V8, V4 + VXORV V5, V9, V5 + VXORV V6, V10, V6 + VXORV V7, V11, V7 + VROTRW $20, V4, V4 + VROTRW $20, V5, V5 + VROTRW $20, V6, V6 + VROTRW $20, V7, V7 + + // V0..V3 += V4..V7 + // V12..V15 <<<= ((V12..V15 XOR V0..V3), 8) + VADDW V0, V4, V0 + VADDW V1, V5, V1 + VADDW V2, V6, V2 + VADDW V3, V7, V3 + VXORV V12, V0, V12 + VXORV V13, V1, V13 + VXORV V14, V2, V14 + VXORV V15, V3, V15 + VROTRW $24, V12, V12 + VROTRW $24, V13, V13 + VROTRW $24, V14, V14 + VROTRW $24, V15, V15 + + // V8..V11 += V12..V15 + // V4..V7 <<<= ((V4..V7 XOR V8..V11), 7) + VADDW V12, V8, V8 + VADDW V13, V9, V9 + VADDW V14, V10, V10 + VADDW V15, V11, V11 + VXORV V4, V8, V4 + VXORV V5, V9, V5 + VXORV V6, V10, V6 + VXORV V7, V11, V7 + VROTRW $25, V4, V4 + VROTRW $25, V5, V5 + VROTRW $25, V6, V6 + VROTRW $25, V7, V7 + + // V0..V3 += V5..V7, V4 + // V15,V12-V14 <<<= ((V15,V12-V14 XOR V0..V3), 16) + VADDW V0, V5, V0 + VADDW V1, V6, V1 + VADDW V2, V7, V2 + VADDW V3, V4, V3 + VXORV V15, V0, V15 + VXORV V12, V1, V12 + VXORV V13, V2, V13 + VXORV V14, V3, V14 + VROTRW $16, V15, V15 + VROTRW $16, V12, V12 + VROTRW $16, V13, V13 + VROTRW $16, V14, V14 + + // V10,V11,V8,V9 += V15,V12,V13,V14 + // V5,V6,V7,V4 <<<= ((V5,V6,V7,V4 XOR V10,V11,V8,V9), 12) + VADDW V10, V15, V10 + VADDW V11, V12, V11 + VADDW V8, V13, V8 + VADDW V9, V14, V9 + VXORV V5, V10, V5 + VXORV V6, V11, V6 + VXORV V7, V8, V7 + VXORV V4, V9, V4 + VROTRW $20, V5, V5 + VROTRW $20, V6, V6 + VROTRW $20, V7, V7 + VROTRW $20, V4, V4 + + // V0..V3 += V5..V7, V4 + // V15,V12-V14 <<<= ((V15,V12-V14 XOR V0..V3), 8) + VADDW V5, V0, V0 + VADDW V6, V1, V1 + VADDW V7, V2, V2 + VADDW V4, V3, V3 + VXORV V15, V0, V15 + VXORV V12, V1, V12 + VXORV V13, V2, V13 + VXORV V14, V3, V14 + VROTRW $24, V15, V15 + VROTRW $24, V12, V12 + VROTRW $24, V13, V13 + VROTRW $24, V14, V14 + + // V10,V11,V8,V9 += V15,V12,V13,V14 + // V5,V6,V7,V4 <<<= ((V5,V6,V7,V4 XOR V10,V11,V8,V9), 7) + VADDW V15, V10, V10 + VADDW V12, V11, V11 + VADDW V13, V8, V8 + VADDW V14, V9, V9 + VXORV V5, V10, V5 + VXORV V6, V11, V6 + VXORV V7, V8, V7 + VXORV V4, V9, V4 + VROTRW $25, V5, V5 + VROTRW $25, V6, V6 + VROTRW $25, V7, V7 + VROTRW $25, V4, V4 + + SUBV $1, R15 + BNE R15, R0, chacha + + // load origin contants + VMOVQ (R10), V16.W4 + VMOVQ 4(R10), V17.W4 + VMOVQ 8(R10), V18.W4 + VMOVQ 12(R10), V19.W4 + + // load origin keys + VMOVQ (R7), V20.W4 + VMOVQ 4(R7), V21.W4 + VMOVQ 8(R7), V22.W4 + VMOVQ 12(R7), V23.W4 + VMOVQ 16(R7), V24.W4 + VMOVQ 20(R7), V25.W4 + VMOVQ 24(R7), V26.W4 + VMOVQ 28(R7), V27.W4 + + // add back the initial state to generate the key stream + VADDW V30, V12, V12 // update counter in advance to prevent V30 from being overwritten + VADDW V16, V0, V0 + VADDW V17, V1, V1 + VADDW V18, V2, V2 + VADDW V19, V3, V3 + + // load origin counter + nonce + VMOVQ (R9), V28.W4 + VMOVQ (R8), V29.W4 + VMOVQ 4(R8), V30.W4 + VMOVQ 8(R8), V31.W4 + + VADDW V20, V4, V4 + VADDW V21, V5, V5 + VADDW V22, V6, V6 + VADDW V23, V7, V7 + VADDW V24, V8, V8 + VADDW V25, V9, V9 + VADDW V26, V10, V10 + VADDW V27, V11, V11 + VADDW V28, V12, V12 + VADDW V29, V13, V13 + VADDW V30, V14, V14 + VADDW V31, V15, V15 + + // shuffle + VILVLW V0, V1, V16 + VILVHW V0, V1, V17 + VILVLW V2, V3, V18 + VILVHW V2, V3, V19 + VILVLW V4, V5 ,V20 + VILVHW V4, V5, V21 + VILVLW V6, V7, V22 + VILVHW V6, V7, V23 + VILVLW V8, V9, V24 + VILVHW V8, V9, V25 + VILVLW V10, V11, V26 + VILVHW V10, V11, V27 + VILVLW V12, V13, V28 + VILVHW V12, V13, V29 + VILVLW V14, V15, V30 + VILVHW V14, V15, V31 + VILVLV V16, V18, V0 + VILVHV V16, V18, V4 + VILVLV V17, V19, V8 + VILVHV V17, V19, V12 + + // load src data from R5 + VMOVQ 0(R5), V16 + VMOVQ 16(R5), V17 + VMOVQ 32(R5), V18 + VMOVQ 48(R5), V19 + + VILVLV V20, V22, V1 + VILVHV V20, V22, V5 + VILVLV V21, V23, V9 + VILVHV V21, V23, V13 + + VMOVQ 64(R5), V20 + VMOVQ 80(R5), V21 + VMOVQ 96(R5), V22 + VMOVQ 112(R5), V23 + + VILVLV V24, V26, V2 + VILVHV V24, V26, V6 + VILVLV V25, V27, V10 + VILVHV V25, V27, V14 + + VMOVQ 128(R5), V24 + VMOVQ 144(R5), V25 + VMOVQ 160(R5), V26 + VMOVQ 176(R5), V27 + + VILVLV V28, V30, V3 + VILVHV V28, V30, V7 + VILVLV V29, V31, V11 + VILVHV V29, V31, V15 + + VMOVQ 192(R5), V28 + VMOVQ 208(R5), V29 + VMOVQ 224(R5), V30 + VMOVQ 240(R5), V31 + + VXORV V0, V16, V16 + VXORV V1, V17, V17 + VXORV V2, V18, V18 + VXORV V3, V19, V19 + + VMOVQ V16, 0(R4) + VMOVQ V17, 16(R4) + VMOVQ V18, 32(R4) + VMOVQ V19, 48(R4) + + VXORV V4, V20, V20 + VXORV V5, V21, V21 + VXORV V6, V22, V22 + VXORV V7, V23, V23 + + VMOVQ V20, 64(R4) + VMOVQ V21, 80(R4) + VMOVQ V22, 96(R4) + VMOVQ V23, 112(R4) + + VXORV V8, V24, V24 + VXORV V9, V25, V25 + VXORV V10, V26, V26 + VXORV V11, V27, V27 + + VMOVQ V24, 128(R4) + VMOVQ V25, 144(R4) + VMOVQ V26, 160(R4) + VMOVQ V27, 176(R4) + + VXORV V12, V28, V28 + VXORV V13, V29, V29 + VXORV V14, V30, V30 + VXORV V15, V31, V31 + + VMOVQ V28, 192(R4) + VMOVQ V29, 208(R4) + VMOVQ V30, 224(R4) + VMOVQ V31, 240(R4) + + ADD $4, R12, R12 + MOVW R12, (R9) // update counter + + ADDV $256, R4, R4 + ADDV $256, R5, R5 + SUBV $256, R6, R6 + BNE R6, R0, loop + + RET diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go b/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go index c709b72847..3853cc0e0b 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go +++ b/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build (!arm64 && !s390x && !ppc64 && !ppc64le) || !gc || purego +//go:build (!arm64 && !loong64 && !s390x && !ppc64 && !ppc64le) || !gc || purego package chacha20 diff --git a/vendor/golang.org/x/crypto/ssh/certs.go b/vendor/golang.org/x/crypto/ssh/certs.go index a3b802e4b8..8788a94b0e 100644 --- a/vendor/golang.org/x/crypto/ssh/certs.go +++ b/vendor/golang.org/x/crypto/ssh/certs.go @@ -35,6 +35,15 @@ const ( CertAlgoED25519v01 = "ssh-ed25519-cert-v01@openssh.com" CertAlgoSKED25519v01 = "sk-ssh-ed25519-cert-v01@openssh.com" + // CertAlgoMLDSA44v01Go, CertAlgoMLDSA65v01Go and CertAlgoMLDSA87v01Go + // are certificate algorithms based on ML-DSA. No specification defines + // them, so these are vendor names as per RFC 4251, Section 4.2. The + // format is that of [SSH-CERTS], with the public key encoded as in + // [SSH-MLDSA], Section 4. + CertAlgoMLDSA44v01Go = "ssh-mldsa-44-cert-v01@golang.org" + CertAlgoMLDSA65v01Go = "ssh-mldsa-65-cert-v01@golang.org" + CertAlgoMLDSA87v01Go = "ssh-mldsa-87-cert-v01@golang.org" + // CertAlgoRSASHA256v01 and CertAlgoRSASHA512v01 can't appear as a // Certificate.Type (or PublicKey.Type), but only in // ClientConfig.HostKeyAlgorithms. @@ -525,6 +534,9 @@ var certKeyAlgoNames = map[string]string{ CertAlgoSKECDSA256v01: KeyAlgoSKECDSA256, CertAlgoED25519v01: KeyAlgoED25519, CertAlgoSKED25519v01: KeyAlgoSKED25519, + CertAlgoMLDSA44v01Go: KeyAlgoMLDSA44, + CertAlgoMLDSA65v01Go: KeyAlgoMLDSA65, + CertAlgoMLDSA87v01Go: KeyAlgoMLDSA87, } // underlyingAlgo returns the signature algorithm associated with algo (which is diff --git a/vendor/golang.org/x/crypto/ssh/cipher.go b/vendor/golang.org/x/crypto/ssh/cipher.go index 48d0199545..d83cacfd37 100644 --- a/vendor/golang.org/x/crypto/ssh/cipher.go +++ b/vendor/golang.org/x/crypto/ssh/cipher.go @@ -414,10 +414,34 @@ func (c *gcmCipher) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error) return plain, nil } -// cbcCipher implements aes128-cbc cipher defined in RFC 4253 section 6.1 +// cbcCipher implements the CBC ciphers defined in RFC 4253 section 6.1, in +// MAC-then-encrypt mode and, for the *-etm@openssh.com MACs, in the +// encrypt-then-MAC mode defined in [PROTOCOL], section 1.5. +// +// 0 4 prefixLen macStart +// | | | | +// +---------------+----------------+---------+-----------------+-----------+ +// | packet_length | padding_length | payload | random padding | mac | +// +---------------+----------------+---------+-----------------+-----------+ +// |<--------- length = packet_length --------->|< macSize >| +// |< paddingLength >| +// |<-------------------------- entirePacketSize -------------------------->| +// +// MAC-then-encrypt (encStart = 0) +// |<----------------------- encLength ------------------------>| +// |<-------------- MAC'd (seqNum || plaintext) --------------->| +// +// encrypt-then-MAC (encStart = 4) +// |<--------------- encLength ---------------->| +// |<-------------- MAC'd (seqNum || ciphertext) -------------->| +// +// encLength is always a multiple of effectiveBlockSize, and in ETM mode the +// packet_length field is not part of it. The padding is only trustworthy once +// the MAC has been verified. type cbcCipher struct { mac hash.Hash macSize uint32 + etm bool decrypter cipher.BlockMode encrypter cipher.BlockMode @@ -431,16 +455,20 @@ type cbcCipher struct { oracleCamouflage uint32 } -func newCBCCipher(c cipher.Block, key, iv, macKey []byte, algs DirectionAlgorithms) (packetCipher, error) { +func newCBCCipher(c cipher.Block, _, iv, macKey []byte, algs DirectionAlgorithms) (packetCipher, error) { + macMode := macModes[algs.MAC] + if macMode == nil { + return nil, fmt.Errorf("ssh: unsupported MAC %v", algs.MAC) + } + mac := macMode.new(macKey) cbc := &cbcCipher{ - mac: macModes[algs.MAC].new(macKey), + mac: mac, + macSize: uint32(mac.Size()), + etm: macMode.etm, decrypter: cipher.NewCBCDecrypter(c, iv), encrypter: cipher.NewCBCEncrypter(c, iv), packetData: make([]byte, 1024), } - if cbc.mac != nil { - cbc.macSize = uint32(cbc.mac.Size()) - } return cbc, nil } @@ -473,13 +501,6 @@ func newTripleDESCBCCipher(key, iv, macKey []byte, algs DirectionAlgorithms) (pa return cbc, nil } -func maxUInt32(a, b int) uint32 { - if a > b { - return uint32(a) - } - return uint32(b) -} - const ( cbcMinPacketSizeMultiple = 8 cbcMinPacketSize = 16 @@ -493,25 +514,38 @@ func (e cbcError) Error() string { return string(e) } func (c *cbcCipher) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error) { p, err := c.readCipherPacketLeaky(seqNum, r) - if err != nil { - if _, ok := err.(cbcError); ok { - // Verification error: read a fixed amount of - // data, to make distinguishing between - // failing MAC and failing length check more - // difficult. - io.CopyN(io.Discard, r, int64(c.oracleCamouflage)) - } + if _, ok := err.(cbcError); ok { + // Verification error: read a fixed amount of + // data, to make distinguishing between + // failing MAC and failing length check more + // difficult. + io.CopyN(io.Discard, r, int64(c.oracleCamouflage)) } return p, err } func (c *cbcCipher) readCipherPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) { blockSize := c.decrypter.BlockSize() + // The encrypted portion of a packet is a multiple of the cipher block size + // or 8, whichever is larger. + effectiveBlockSize := uint32(max(cbcMinPacketSizeMultiple, blockSize)) + encStart := uint32(0) + // A packet is at least 16 bytes, or the cipher block size if larger. This does + // not apply to EtM (but the encrypted length still can't be zero). + minEncLength := uint32(max(cbcMinPacketSize, blockSize)) + // For EtM MACs the packet length is transmitted in the clear and is not part + // of the encrypted data, which starts after it. + if c.etm { + encStart = 4 + minEncLength = effectiveBlockSize + } // Read the header, which will include some of the subsequent data in the - // case of block ciphers - this is copied back to the payload later. - // How many bytes of payload/padding will be read with this first read. - firstBlockLength := uint32((prefixLen + blockSize - 1) / blockSize * blockSize) + // case of block ciphers - this is copied back to the payload later. The + // rounding up to the block size covers at least prefixLen bytes, so the + // padding length is always within firstBlock. + headerEncLength := prefixLen - encStart + firstBlockLength := encStart + (headerEncLength+uint32(blockSize)-1)/uint32(blockSize)*uint32(blockSize) firstBlock := c.packetData[:firstBlockLength] if _, err := io.ReadFull(r, firstBlock); err != nil { return nil, err @@ -519,30 +553,49 @@ func (c *cbcCipher) readCipherPacketLeaky(seqNum uint32, r io.Reader) ([]byte, e c.oracleCamouflage = maxPacket + 4 + c.macSize - firstBlockLength - c.decrypter.CryptBlocks(firstBlock, firstBlock) - length := binary.BigEndian.Uint32(firstBlock[:4]) + c.mac.Reset() + binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) + c.mac.Write(c.seqNumBytes[:]) + + var length uint32 + if c.etm { + // For EtM MACs the MAC is computed over the cleartext packet length + // followed by the ciphertext, so it is updated before decrypting. + length = binary.BigEndian.Uint32(firstBlock[:encStart]) + c.mac.Write(firstBlock[:encStart]) + c.mac.Write(firstBlock[encStart:]) + c.decrypter.CryptBlocks(firstBlock[encStart:], firstBlock[encStart:]) + } else { + c.decrypter.CryptBlocks(firstBlock, firstBlock) + length = binary.BigEndian.Uint32(firstBlock[:4]) + } + if length > maxPacket { return nil, cbcError("ssh: packet too large") } - if length+4 < maxUInt32(cbcMinPacketSize, blockSize) { - // The minimum size of a packet is 16 (or the cipher block size, whichever - // is larger) bytes. + // Length of the encrypted portion of the packet, which includes the packet + // length field only for non-EtM MACs. + encLength := 4 + length - encStart + if encLength < minEncLength { return nil, cbcError("ssh: packet too small") } - // The length of the packet (including the length field but not the MAC) must - // be a multiple of the block size or 8, whichever is larger. - if (length+4)%maxUInt32(cbcMinPacketSizeMultiple, blockSize) != 0 { + if encLength%effectiveBlockSize != 0 { return nil, cbcError("ssh: invalid packet length multiple") } + // The padding length is part of the encrypted data. For EtM MACs it is not + // acted upon before the MAC is verified, otherwise the CBC padding would + // still be usable as an oracle, which is what EtM prevents. paddingLength := uint32(firstBlock[4]) - if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 { - return nil, cbcError("ssh: invalid packet length") + if !c.etm { + if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 { + return nil, cbcError("ssh: invalid packet length") + } } - // Positions within the c.packetData buffer: - macStart := 4 + length - paddingStart := macStart - paddingLength + // Positions within the c.packetData buffer: the MAC follows the encrypted + // data. + macStart := encStart + encLength // Entire packet size, starting before length, ending at end of mac. entirePacketSize := macStart + c.macSize @@ -564,42 +617,58 @@ func (c *cbcCipher) readCipherPacketLeaky(seqNum uint32, r io.Reader) ([]byte, e c.oracleCamouflage -= uint32(n) remainingCrypted := c.packetData[firstBlockLength:macStart] + if c.etm { + c.mac.Write(remainingCrypted) + } c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted) - mac := c.packetData[macStart:] - if c.mac != nil { - c.mac.Reset() - binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) - c.mac.Write(c.seqNumBytes[:]) + if !c.etm { c.mac.Write(c.packetData[:macStart]) - c.macResult = c.mac.Sum(c.macResult[:0]) - if subtle.ConstantTimeCompare(c.macResult, mac) != 1 { - return nil, cbcError("ssh: MAC failure") + } + c.macResult = c.mac.Sum(c.macResult[:0]) + if subtle.ConstantTimeCompare(c.macResult, c.packetData[macStart:]) != 1 { + return nil, cbcError("ssh: MAC failure") + } + + if c.etm { + if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 { + return nil, cbcError("ssh: invalid packet length") } } - return c.packetData[prefixLen:paddingStart], nil + return c.packetData[prefixLen : macStart-paddingLength], nil } -func (c *cbcCipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { - effectiveBlockSize := maxUInt32(cbcMinPacketSizeMultiple, c.encrypter.BlockSize()) - - // Length of encrypted portion of the packet (header, payload, padding). - // Enforce minimum padding and packet size. - encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPacketSize) +func (c *cbcCipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader, payload []byte) error { + blockSize := c.encrypter.BlockSize() + // The encrypted portion of a packet is a multiple of the cipher block size + // or 8, whichever is larger. + effectiveBlockSize := uint32(max(cbcMinPacketSizeMultiple, blockSize)) + // For EtM MACs the packet length is transmitted in the clear and is not part + // of the encrypted data, which starts after it. + encStart := uint32(0) + if c.etm { + encStart = 4 + } + // Length of the encrypted portion of the packet (header, payload, padding), + // enforcing the minimum padding and the minimum packet size of RFC 4253, + // Section 6: 16 bytes, or the cipher block size if larger, excluding the + // MAC. + encLength := uint32(max(prefixLen-int(encStart)+len(payload)+cbcMinPaddingSize, cbcMinPacketSize-int(encStart))) // Enforce block size. encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize - - length := encLength - 4 - paddingLength := int(length) - (1 + len(packet)) + // The packet length field covers the whole packet except the field itself. + length := encStart + encLength - 4 + paddingLength := int(length) - (1 + len(payload)) // Overall buffer contains: header, payload, padding, mac. // Space for the MAC is reserved in the capacity but not the slice length. - bufferSize := encLength + c.macSize - if uint32(cap(c.packetData)) < bufferSize { - c.packetData = make([]byte, encLength, bufferSize) + macStart := encStart + encLength + entirePacketSize := macStart + c.macSize + if uint32(cap(c.packetData)) < entirePacketSize { + c.packetData = make([]byte, macStart, entirePacketSize) } else { - c.packetData = c.packetData[:encLength] + c.packetData = c.packetData[:macStart] } p := c.packetData @@ -611,24 +680,29 @@ func (c *cbcCipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader // Payload. p = p[1:] - copy(p, packet) + copy(p, payload) // Padding. - p = p[len(packet):] + p = p[len(payload):] if _, err := io.ReadFull(rand, p); err != nil { return err } - if c.mac != nil { - c.mac.Reset() - binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) - c.mac.Write(c.seqNumBytes[:]) + c.mac.Reset() + binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) + c.mac.Write(c.seqNumBytes[:]) + if c.etm { + // For EtM MACs the MAC is computed over the cleartext packet length + // followed by the ciphertext. + c.mac.Write(c.packetData[:encStart]) + c.encrypter.CryptBlocks(c.packetData[encStart:], c.packetData[encStart:]) + c.mac.Write(c.packetData[encStart:]) + } else { c.mac.Write(c.packetData) - // The MAC is now appended into the capacity reserved for it earlier. - c.packetData = c.mac.Sum(c.packetData) + c.encrypter.CryptBlocks(c.packetData, c.packetData) } - - c.encrypter.CryptBlocks(c.packetData[:encLength], c.packetData[:encLength]) + // The MAC is now appended into the capacity reserved for it earlier. + c.packetData = c.mac.Sum(c.packetData) if _, err := w.Write(c.packetData); err != nil { return err diff --git a/vendor/golang.org/x/crypto/ssh/common.go b/vendor/golang.org/x/crypto/ssh/common.go index aed0fd926a..544eb93d78 100644 --- a/vendor/golang.org/x/crypto/ssh/common.go +++ b/vendor/golang.org/x/crypto/ssh/common.go @@ -258,6 +258,11 @@ type Algorithms struct { } func init() { + supportedHostKeyAlgos = slices.Concat(supportedHostKeyAlgos, mldsaCertAlgos, mldsaKeyAlgos) + defaultHostKeyAlgos = slices.Concat(defaultHostKeyAlgos, mldsaCertAlgos, mldsaKeyAlgos) + supportedPubKeyAuthAlgos = slices.Concat(supportedPubKeyAuthAlgos, mldsaKeyAlgos) + defaultPubKeyAuthAlgos = slices.Concat(defaultPubKeyAuthAlgos, mldsaKeyAlgos) + if fips140.Enabled() { defaultHostKeyAlgos = slices.DeleteFunc(defaultHostKeyAlgos, func(algo string) bool { _, err := hashFunc(underlyingAlgo(algo)) @@ -281,6 +286,10 @@ func hashFunc(format string) (crypto.Hash, error) { case KeyAlgoED25519: // KeyAlgoED25519 doesn't pre-hash. return 0, nil + case KeyAlgoMLDSA44, KeyAlgoMLDSA65, KeyAlgoMLDSA87: + // ML-DSA doesn't pre-hash. This case is not build tagged, availability + // is decided by mldsaKeyAlgos. + return 0, nil case KeyAlgoRSA, InsecureKeyAlgoDSA: if fips140.Enabled() { return 0, fmt.Errorf("ssh: hash algorithm for format %q not allowed in FIPS 140 mode", format) @@ -354,7 +363,13 @@ func keyFormatForAlgorithm(sigAlgo string) string { CertAlgoECDSA521v01, CertAlgoSKECDSA256v01, CertAlgoED25519v01, - CertAlgoSKED25519v01: + CertAlgoSKED25519v01, + KeyAlgoMLDSA44, + KeyAlgoMLDSA65, + KeyAlgoMLDSA87, + CertAlgoMLDSA44v01Go, + CertAlgoMLDSA65v01Go, + CertAlgoMLDSA87v01Go: return sigAlgo default: return "" diff --git a/vendor/golang.org/x/crypto/ssh/doc.go b/vendor/golang.org/x/crypto/ssh/doc.go index 5b4de9effc..39ac133e4d 100644 --- a/vendor/golang.org/x/crypto/ssh/doc.go +++ b/vendor/golang.org/x/crypto/ssh/doc.go @@ -17,6 +17,7 @@ References: [PROTOCOL.certkeys]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?rev=HEAD [SSH-PARAMETERS]: http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1 [SSH-CERTS]: https://datatracker.ietf.org/doc/html/draft-miller-ssh-cert-01 + [SSH-MLDSA]: https://datatracker.ietf.org/doc/html/draft-sfluhrer-ssh-mldsa-08 [FIPS 140-3 mode]: https://go.dev/doc/security/fips140 This package does not fall under the stability promise of the Go language itself, diff --git a/vendor/golang.org/x/crypto/ssh/keys.go b/vendor/golang.org/x/crypto/ssh/keys.go index fbbfb6cf42..eb052381c3 100644 --- a/vendor/golang.org/x/crypto/ssh/keys.go +++ b/vendor/golang.org/x/crypto/ssh/keys.go @@ -51,6 +51,12 @@ const ( KeyAlgoED25519 = "ssh-ed25519" KeyAlgoSKED25519 = "sk-ssh-ed25519@openssh.com" + // KeyAlgoMLDSA44, KeyAlgoMLDSA65 and KeyAlgoMLDSA87 are the ML-DSA + // algorithms of [SSH-MLDSA]. + KeyAlgoMLDSA44 = "ssh-mldsa-44" + KeyAlgoMLDSA65 = "ssh-mldsa-65" + KeyAlgoMLDSA87 = "ssh-mldsa-87" + // KeyAlgoRSASHA256 and KeyAlgoRSASHA512 are only public key algorithms, not // public key formats, so they can't appear as a PublicKey.Type. The // corresponding PublicKey.Type is KeyAlgoRSA. See RFC 8332, Section 2. @@ -83,7 +89,10 @@ func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err err return parseED25519(in) case KeyAlgoSKED25519: return parseSKEd25519(in) - case CertAlgoRSAv01, InsecureCertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoSKECDSA256v01, CertAlgoED25519v01, CertAlgoSKED25519v01: + case KeyAlgoMLDSA44, KeyAlgoMLDSA65, KeyAlgoMLDSA87: + return parseMLDSA(in, algo) + case CertAlgoRSAv01, InsecureCertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoSKECDSA256v01, CertAlgoED25519v01, CertAlgoSKED25519v01, + CertAlgoMLDSA44v01Go, CertAlgoMLDSA65v01Go, CertAlgoMLDSA87v01Go: cert, err := parseCert(in, certKeyAlgoNames[algo]) if err != nil { return nil, nil, err @@ -98,11 +107,30 @@ func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err err return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", algo) } +// trimSpace removes leading and trailing ASCII space and tab. +func trimSpace(in []byte) []byte { + return bytes.Trim(in, " \t") +} + +// asciiFields splits in around each run of ASCII space and tab. +func asciiFields(in []byte) [][]byte { + return bytes.FieldsFunc(in, func(r rune) bool { + return r == ' ' || r == '\t' + }) +} + +// dropCR removes a single trailing carriage return, so that an entry written +// with CRLF line endings is read like one written with LF endings. A carriage +// return anywhere else belongs to the field that holds it. +func dropCR(in []byte) []byte { + return bytes.TrimSuffix(in, []byte("\r")) +} + // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format // (see sshd(8) manual page) once the options and key type fields have been // removed. func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) { - in = bytes.TrimSpace(in) + in = trimSpace(in) i := bytes.IndexAny(in, " \t") if i == -1 { @@ -120,7 +148,7 @@ func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) { if err != nil { return nil, "", err } - comment = string(bytes.TrimSpace(in[i:])) + comment = string(trimSpace(in[i:])) return out, comment, nil } @@ -149,12 +177,9 @@ func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey rest = nil } - end = bytes.IndexByte(in, '\r') - if end != -1 { - in = in[:end] - } + in = dropCR(in) - in = bytes.TrimSpace(in) + in = trimSpace(in) if len(in) == 0 || in[0] == '#' { in = rest continue @@ -168,8 +193,10 @@ func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey // Strip out the beginning of the known_host key. // This is either an optional marker or a (set of) hostname(s). - keyFields := bytes.Fields(in) - if len(keyFields) < 3 || len(keyFields) > 5 { + // The comment is not delimited, so there is no upper bound on the + // number of fields. + keyFields := asciiFields(in) + if len(keyFields) < 3 { return "", nil, nil, "", nil, errors.New("ssh: invalid entry in known_hosts data") } @@ -215,12 +242,9 @@ func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []str rest = nil } - end = bytes.IndexByte(in, '\r') - if end != -1 { - in = in[:end] - } + in = dropCR(in) - in = bytes.TrimSpace(in) + in = trimSpace(in) if len(in) == 0 || in[0] == '#' { in = rest continue @@ -334,7 +358,8 @@ func MarshalAuthorizedKey(key PublicKey) []byte { } // MarshalPrivateKey returns a PEM block with the private key serialized in the -// OpenSSH format. +// OpenSSH format. ML-DSA keys are not supported, since no OpenSSH format is +// defined for them: use [x509.MarshalPKCS8PrivateKey] instead. func MarshalPrivateKey(key crypto.PrivateKey, comment string) (*pem.Block, error) { return marshalOpenSSHPrivateKey(key, comment, unencryptedOpenSSHMarshaler) } @@ -1173,9 +1198,9 @@ func (k *skEd25519PublicKey) CryptoPublicKey() crypto.PublicKey { } // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey, -// *ecdsa.PrivateKey or any other crypto.Signer and returns a -// corresponding Signer instance. ECDSA keys must use P-256, P-384 or -// P-521. DSA keys must use parameter size L1024N160. +// *ecdsa.PrivateKey, *mldsa.PrivateKey, or any other crypto.Signer and returns +// a corresponding Signer instance. ECDSA keys must use P-256, P-384 or P-521. +// DSA keys must use parameter size L1024N160. func NewSignerFromKey(key interface{}) (Signer, error) { switch key := key.(type) { case crypto.Signer: @@ -1285,8 +1310,8 @@ func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm } // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, -// or ed25519.PublicKey returns a corresponding PublicKey instance. -// ECDSA keys must use P-256, P-384 or P-521. +// ed25519.PublicKey, or an *mldsa.PublicKey, and returns a corresponding +// PublicKey instance. ECDSA keys must use P-256, P-384 or P-521. func NewPublicKey(key interface{}) (PublicKey, error) { switch key := key.(type) { case *rsa.PublicKey: @@ -1304,7 +1329,13 @@ func NewPublicKey(key interface{}) (PublicKey, error) { } return ed25519PublicKey(key), nil default: - return nil, fmt.Errorf("ssh: unsupported key type %T", key) + pub, err := newMLDSAPublicKey(key) + if errors.Is(err, errNotMLDSAKey) { + return nil, fmt.Errorf("ssh: unsupported key type %T", key) + } else if err != nil { + return nil, err + } + return pub, nil } } diff --git a/vendor/golang.org/x/crypto/ssh/mldsa.go b/vendor/golang.org/x/crypto/ssh/mldsa.go new file mode 100644 index 0000000000..09176b652d --- /dev/null +++ b/vendor/golang.org/x/crypto/ssh/mldsa.go @@ -0,0 +1,133 @@ +// Copyright 2026 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. + +//go:build go1.27 && !fips140v1.0 + +package ssh + +import ( + "crypto" + "crypto/mldsa" + "errors" + "fmt" +) + +// mldsaKeyAlgos are the ML-DSA public key algorithms implemented by this +// package. +var mldsaKeyAlgos = []string{ + KeyAlgoMLDSA44, + KeyAlgoMLDSA65, + KeyAlgoMLDSA87, +} + +// mldsaCertAlgos are the certificate algorithms for the keys in mldsaKeyAlgos. +var mldsaCertAlgos = []string{ + CertAlgoMLDSA44v01Go, + CertAlgoMLDSA65v01Go, + CertAlgoMLDSA87v01Go, +} + +var errNotMLDSAKey = errors.New("ssh: not an ML-DSA key") + +// mldsaParameters returns the ML-DSA parameter set for the given public key +// algorithm name. +func mldsaParameters(algo string) (mldsa.Parameters, error) { + switch algo { + case KeyAlgoMLDSA44: + return mldsa.MLDSA44(), nil + case KeyAlgoMLDSA65: + return mldsa.MLDSA65(), nil + case KeyAlgoMLDSA87: + return mldsa.MLDSA87(), nil + default: + return mldsa.Parameters{}, fmt.Errorf("ssh: not an ML-DSA algorithm: %q", algo) + } +} + +// mldsaKeyAlgo returns the public key algorithm name for the given ML-DSA +// parameter set. +func mldsaKeyAlgo(params mldsa.Parameters) string { + switch params { + case mldsa.MLDSA44(): + return KeyAlgoMLDSA44 + case mldsa.MLDSA65(): + return KeyAlgoMLDSA65 + case mldsa.MLDSA87(): + return KeyAlgoMLDSA87 + default: + panic("ssh: internal error: unknown ML-DSA parameter set: " + params.String()) + } +} + +// mldsaPublicKey implements PublicKey for the ML-DSA algorithms of [SSH-MLDSA]. +type mldsaPublicKey struct { + key *mldsa.PublicKey +} + +func (k *mldsaPublicKey) Type() string { + return mldsaKeyAlgo(k.key.Parameters()) +} + +func parseMLDSA(in []byte, algo string) (out PublicKey, rest []byte, err error) { + params, err := mldsaParameters(algo) + if err != nil { + return nil, nil, err + } + + var w struct { + KeyBytes []byte + Rest []byte `ssh:"rest"` + } + + if err := Unmarshal(in, &w); err != nil { + return nil, nil, err + } + + key, err := mldsa.NewPublicKey(params, w.KeyBytes) + if err != nil { + return nil, nil, fmt.Errorf("ssh: invalid %s public key: %v", params, err) + } + + return &mldsaPublicKey{key: key}, w.Rest, nil +} + +func (k *mldsaPublicKey) Marshal() []byte { + w := struct { + Name string + KeyBytes []byte + }{ + k.Type(), + k.key.Bytes(), + } + return Marshal(&w) +} + +func (k *mldsaPublicKey) Verify(b []byte, sig *Signature) error { + if sig.Format != k.Type() { + return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) + } + // nil options select pure ML-DSA with an empty context, as required by + // [SSH-MLDSA], Sections 6 and 8. + if err := mldsa.Verify(k.key, b, sig.Blob, nil); err != nil { + return errors.New("ssh: signature did not verify") + } + + return nil +} + +func (k *mldsaPublicKey) CryptoPublicKey() crypto.PublicKey { + return k.key +} + +// newMLDSAPublicKey returns a PublicKey wrapping key. +func newMLDSAPublicKey(key crypto.PublicKey) (PublicKey, error) { + k, ok := key.(*mldsa.PublicKey) + if !ok { + return nil, errNotMLDSAKey + } + if k == nil || *k == (mldsa.PublicKey{}) { + return nil, errors.New("ssh: invalid ML-DSA public key") + } + return &mldsaPublicKey{key: k}, nil +} diff --git a/vendor/golang.org/x/crypto/ssh/mldsa_unsupported.go b/vendor/golang.org/x/crypto/ssh/mldsa_unsupported.go new file mode 100644 index 0000000000..9fec354a8d --- /dev/null +++ b/vendor/golang.org/x/crypto/ssh/mldsa_unsupported.go @@ -0,0 +1,29 @@ +// Copyright 2026 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. + +//go:build !go1.27 || fips140v1.0 + +package ssh + +import ( + "crypto" + "errors" + "fmt" +) + +var mldsaKeyAlgos, mldsaCertAlgos []string + +var errMLDSAUnsupported = fmt.Errorf("ssh: ML-DSA is not available in this build: %w", + errors.ErrUnsupported) + +var errNotMLDSAKey = errors.New("ssh: not an ML-DSA key") + +func parseMLDSA(in []byte, algo string) (out PublicKey, rest []byte, err error) { + return nil, nil, errMLDSAUnsupported +} + +func newMLDSAPublicKey(key crypto.PublicKey) (PublicKey, error) { + // In this version of Go, *mldsa.PublicKey does not exist. + return nil, errNotMLDSAKey +} diff --git a/vendor/golang.org/x/oauth2/google/default.go b/vendor/golang.org/x/oauth2/google/default.go index 6e5720699c..069f1aac90 100644 --- a/vendor/golang.org/x/oauth2/google/default.go +++ b/vendor/golang.org/x/oauth2/google/default.go @@ -253,7 +253,7 @@ func FindDefaultCredentialsWithParams(ctx context.Context, params CredentialsPar if metadata.OnGCE() { id, _ := metadata.ProjectID() universeDomainProvider := func() (string, error) { - universeDomain, err := metadata.Get("universe/universe_domain") + universeDomain, err := metadata.Get("universe/universe-domain") if err != nil { if _, ok := err.(metadata.NotDefinedError); ok { // http.StatusNotFound (404) diff --git a/vendor/golang.org/x/sys/cpu/cpu.go b/vendor/golang.org/x/sys/cpu/cpu.go index df8dbd1dbf..422b139cdf 100644 --- a/vendor/golang.org/x/sys/cpu/cpu.go +++ b/vendor/golang.org/x/sys/cpu/cpu.go @@ -61,7 +61,11 @@ var X86 struct { HasBMI2 bool // Bit manipulation instruction set 2 HasCX16 bool // Compare and exchange 16 Bytes HasERMS bool // Enhanced REP for MOVSB and STOSB + HasF16C bool // 16-bit floating-point conversion instructions HasFMA bool // Fused-multiply-add instructions + HasLAHF bool // LAHF/SAHF available in 64-bit mode + HasLZCNT bool // Leading zeros count instruction + HasMOVBE bool // Move data after byte swap HasOSXSAVE bool // OS supports XSAVE/XRESTOR for saving/restoring XMM registers. HasPCLMULQDQ bool // PCLMULQDQ instruction - most often used for AES-GCM HasPOPCNT bool // Hamming weight instruction POPCNT. @@ -75,6 +79,7 @@ var X86 struct { HasAVXIFMA bool // Advanced vector extension Integer Fused Multiply Add HasAVXVNNI bool // Advanced vector extension Vector Neural Network Instructions HasAVXVNNIInt8 bool // Advanced vector extension Vector Neural Network Int8 instructions + HasXSAVE bool // XSAVE/XRSTOR/XSETBV/XGETBV instructions (hardware support; see also HasOSXSAVE) _ CacheLinePad } diff --git a/vendor/golang.org/x/sys/cpu/cpu_x86.go b/vendor/golang.org/x/sys/cpu/cpu_x86.go index f5723d4f7e..7e6cead53e 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_x86.go +++ b/vendor/golang.org/x/sys/cpu/cpu_x86.go @@ -43,7 +43,11 @@ func initOptions() { {Name: "bmi2", Feature: &X86.HasBMI2}, {Name: "cx16", Feature: &X86.HasCX16}, {Name: "erms", Feature: &X86.HasERMS}, + {Name: "f16c", Feature: &X86.HasF16C}, {Name: "fma", Feature: &X86.HasFMA}, + {Name: "lahf", Feature: &X86.HasLAHF}, + {Name: "lzcnt", Feature: &X86.HasLZCNT}, + {Name: "movbe", Feature: &X86.HasMOVBE}, {Name: "osxsave", Feature: &X86.HasOSXSAVE}, {Name: "pclmulqdq", Feature: &X86.HasPCLMULQDQ}, {Name: "popcnt", Feature: &X86.HasPOPCNT}, @@ -56,6 +60,7 @@ func initOptions() { {Name: "avxifma", Feature: &X86.HasAVXIFMA}, {Name: "avxvnni", Feature: &X86.HasAVXVNNI}, {Name: "avxvnniint8", Feature: &X86.HasAVXVNNIInt8}, + {Name: "xsave", Feature: &X86.HasXSAVE}, // These capabilities should always be enabled on amd64: {Name: "sse2", Feature: &X86.HasSSE2, Required: runtime.GOARCH == "amd64"}, @@ -83,10 +88,13 @@ func archInit() { cpuid_AVX512VPOPCNTDQ = 1 << 14 cpuid_SSE41 = 1 << 19 cpuid_SSE42 = 1 << 20 + cpuid_MOVBE = 1 << 22 cpuid_POPCNT = 1 << 23 cpuid_AES = 1 << 25 + cpuid_XSAVE = 1 << 26 cpuid_OSXSAVE = 1 << 27 cpuid_AVX = 1 << 28 + cpuid_F16C = 1 << 29 // "Extended Feature Flag" bits returned in EBX for CPUID EAX=0x7 ECX=0x0 cpuid_BMI1 = 1 << 3 @@ -110,6 +118,9 @@ func archInit() { // edx bits cpuid_FSRM = 1 << 4 + // ecx bits for CPUID 0x80000001 + cpuid_LAHF = 1 << 0 + cpuid_LZCNT = 1 << 5 // edx bits for CPUID 0x80000001 cpuid_RDTSCP = 1 << 27 ) @@ -158,9 +169,21 @@ func archInit() { X86.HasSSE42 = isSet(ecx1, cpuid_SSE42) X86.HasPOPCNT = isSet(ecx1, cpuid_POPCNT) X86.HasAES = isSet(ecx1, cpuid_AES) + X86.HasXSAVE = isSet(ecx1, cpuid_XSAVE) X86.HasOSXSAVE = isSet(ecx1, cpuid_OSXSAVE) + X86.HasF16C = isSet(ecx1, cpuid_F16C) + X86.HasMOVBE = isSet(ecx1, cpuid_MOVBE) X86.HasRDRAND = isSet(ecx1, cpuid_RDRAND) + // Extended processor info and feature bits, under the separate extended + // (0x8000_0000-prefixed) leaf hierarchy, so maxID (the basic leaf count) + // doesn't gate it. + if maxExtID, _, _, _ := cpuid(0x80000000, 0); maxExtID >= 0x80000001 { + _, _, ecxExt1, _ := cpuid(0x80000001, 0) + X86.HasLAHF = isSet(ecxExt1, cpuid_LAHF) + X86.HasLZCNT = isSet(ecxExt1, cpuid_LZCNT) + } + var osSupportsAVX, osSupportsAVX512 bool // For XGETBV, OSXSAVE bit is required and sufficient. if X86.HasOSXSAVE { diff --git a/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s b/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s index bdfc024d2d..2e1f4c3e73 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s @@ -13,6 +13,16 @@ // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. +TEXT ·Syscall(SB),NOSPLIT,$0-56 + MOVD $syscall·Syscall(SB), R31 + MOVD R31, CTR + JMP (CTR) + +TEXT ·Syscall6(SB),NOSPLIT,$0-80 + MOVD $syscall·Syscall6(SB), R31 + MOVD R31, CTR + JMP (CTR) + TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 BL runtime·entersyscall(SB) MOVD a1+8(FP), R3 @@ -28,6 +38,16 @@ TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 BL runtime·exitsyscall(SB) RET +TEXT ·RawSyscall(SB),NOSPLIT,$0-56 + MOVD $syscall·RawSyscall(SB), R31 + MOVD R31, CTR + JMP (CTR) + +TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 + MOVD $syscall·RawSyscall6(SB), R31 + MOVD R31, CTR + JMP (CTR) + TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48 MOVD a1+8(FP), R3 MOVD a2+16(FP), R4 diff --git a/vendor/golang.org/x/sys/unix/asm_linux_sparc64.s b/vendor/golang.org/x/sys/unix/asm_linux_sparc64.s new file mode 100644 index 0000000000..77e1e327ed --- /dev/null +++ b/vendor/golang.org/x/sys/unix/asm_linux_sparc64.s @@ -0,0 +1,48 @@ +// Copyright 2026 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. + +//go:build linux && sparc64 && gc + +#include "textflag.h" + +// +// System calls for sparc64, Linux +// + +// Just jump to package syscall's implementation for all these functions. +// The runtime may know about them. + +TEXT ·Syscall(SB), NOSPLIT, $0-56 + JMP syscall·Syscall(SB) + +TEXT ·Syscall6(SB), NOSPLIT, $0-80 + JMP syscall·Syscall6(SB) + +TEXT ·SyscallNoError(SB), NOSPLIT, $0-48 + CALL runtime·entersyscall(SB) + MOVD trap+0(FP), R1 // syscall entry + MOVD a1+8(FP), R8 + MOVD a2+16(FP), R9 + MOVD a3+24(FP), R10 + TA $0x6d + MOVD R8, r1+32(FP) + MOVD R9, r2+40(FP) + CALL runtime·exitsyscall(SB) + RET + +TEXT ·RawSyscall(SB), NOSPLIT, $0-56 + JMP syscall·RawSyscall(SB) + +TEXT ·RawSyscall6(SB), NOSPLIT, $0-80 + JMP syscall·RawSyscall6(SB) + +TEXT ·RawSyscallNoError(SB), NOSPLIT, $0-48 + MOVD trap+0(FP), R1 // syscall entry + MOVD a1+8(FP), R8 + MOVD a2+16(FP), R9 + MOVD a3+24(FP), R10 + TA $0x6d + MOVD R8, r1+32(FP) + MOVD R9, r2+40(FP) + RET diff --git a/vendor/golang.org/x/sys/unix/asm_zos_s390x.s b/vendor/golang.org/x/sys/unix/asm_zos_s390x.s index 813dfad7d2..980f07a3b6 100644 --- a/vendor/golang.org/x/sys/unix/asm_zos_s390x.s +++ b/vendor/golang.org/x/sys/unix/asm_zos_s390x.s @@ -30,21 +30,8 @@ #define SVC_LOAD BYTE $0x0A; BYTE $0x08 // SVC 08 LOAD #define SVC_DELETE BYTE $0x0A; BYTE $0x09 // SVC 09 DELETE -DATA zosLibVec<>(SB)/8, $0 -GLOBL zosLibVec<>(SB), NOPTR, $8 - -TEXT ·initZosLibVec(SB), NOSPLIT|NOFRAME, $0-0 - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD CAA(R8), R8 - MOVD EDCHPXV(R8), R8 - MOVD R8, zosLibVec<>(SB) - RET - TEXT ·GetZosLibVec(SB), NOSPLIT|NOFRAME, $0-0 - MOVD zosLibVec<>(SB), R8 - MOVD R8, ret+0(FP) - RET + JMP runtime·GetZosLibVec(SB) TEXT ·clearErrno(SB), NOSPLIT, $0-0 BL addrerrno<>(SB) @@ -160,163 +147,13 @@ TEXT ·gettid(SB), NOSPLIT, $0 // errno and errno2 is retrieved // TEXT ·CallLeFuncWithErr(SB), NOSPLIT, $0 - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD CAA(R8), R9 - MOVD g, GOCB(R9) - - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 // R9-> LE stack frame saving address - MOVD 0(R9), R4 // R4-> restore previously saved stack frame pointer - - MOVD parms_base+8(FP), R7 // R7 -> argument array - MOVD parms_len+16(FP), R8 // R8 number of arguments - - // arg 1 ---> R1 - CMP R8, $0 - BEQ docall - SUB $1, R8 - MOVD 0(R7), R1 - - // arg 2 ---> R2 - CMP R8, $0 - BEQ docall - SUB $1, R8 - ADD $8, R7 - MOVD 0(R7), R2 - - // arg 3 --> R3 - CMP R8, $0 - BEQ docall - SUB $1, R8 - ADD $8, R7 - MOVD 0(R7), R3 - - CMP R8, $0 - BEQ docall - MOVD $2176+16, R6 // starting LE stack address-8 to store 4th argument - -repeat: - ADD $8, R7 - MOVD 0(R7), R0 // advance arg pointer by 8 byte - ADD $8, R6 // advance LE argument address by 8 byte - MOVD R0, (R4)(R6*1) // copy argument from go-slice to le-frame - SUB $1, R8 - CMP R8, $0 - BNE repeat - -docall: - MOVD funcdesc+0(FP), R8 // R8-> function descriptor - LMG 0(R8), R5, R6 - MOVD $0, 0(R9) // R9 address of SAVSTACK_ASYNC - LE_CALL // balr R7, R6 (return #1) - NOPH - MOVD R3, ret+32(FP) - CMP R3, $-1 // compare result to -1 - BNE done - - // retrieve errno and errno2 - MOVD zosLibVec<>(SB), R8 - ADD $(__errno), R8 - LMG 0(R8), R5, R6 - LE_CALL // balr R7, R6 __errno (return #3) - NOPH - MOVWZ 0(R3), R3 - MOVD R3, err+48(FP) - MOVD zosLibVec<>(SB), R8 - ADD $(__err2ad), R8 - LMG 0(R8), R5, R6 - LE_CALL // balr R7, R6 __err2ad (return #2) - NOPH - MOVW (R3), R2 // retrieve errno2 - MOVD R2, errno2+40(FP) // store in return area - -done: - MOVD R4, 0(R9) // Save stack pointer. - RET - + JMP runtime·CallLeFuncWithErr(SB) // // Call LE function, if the return is 0 // errno and errno2 is retrieved // TEXT ·CallLeFuncWithPtrReturn(SB), NOSPLIT, $0 - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD CAA(R8), R9 - MOVD g, GOCB(R9) - - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 // R9-> LE stack frame saving address - MOVD 0(R9), R4 // R4-> restore previously saved stack frame pointer - - MOVD parms_base+8(FP), R7 // R7 -> argument array - MOVD parms_len+16(FP), R8 // R8 number of arguments - - // arg 1 ---> R1 - CMP R8, $0 - BEQ docall - SUB $1, R8 - MOVD 0(R7), R1 - - // arg 2 ---> R2 - CMP R8, $0 - BEQ docall - SUB $1, R8 - ADD $8, R7 - MOVD 0(R7), R2 - - // arg 3 --> R3 - CMP R8, $0 - BEQ docall - SUB $1, R8 - ADD $8, R7 - MOVD 0(R7), R3 - - CMP R8, $0 - BEQ docall - MOVD $2176+16, R6 // starting LE stack address-8 to store 4th argument - -repeat: - ADD $8, R7 - MOVD 0(R7), R0 // advance arg pointer by 8 byte - ADD $8, R6 // advance LE argument address by 8 byte - MOVD R0, (R4)(R6*1) // copy argument from go-slice to le-frame - SUB $1, R8 - CMP R8, $0 - BNE repeat - -docall: - MOVD funcdesc+0(FP), R8 // R8-> function descriptor - LMG 0(R8), R5, R6 - MOVD $0, 0(R9) // R9 address of SAVSTACK_ASYNC - LE_CALL // balr R7, R6 (return #1) - NOPH - MOVD R3, ret+32(FP) - CMP R3, $0 // compare result to 0 - BNE done - - // retrieve errno and errno2 - MOVD zosLibVec<>(SB), R8 - ADD $(__errno), R8 - LMG 0(R8), R5, R6 - LE_CALL // balr R7, R6 __errno (return #3) - NOPH - MOVWZ 0(R3), R3 - MOVD R3, err+48(FP) - MOVD zosLibVec<>(SB), R8 - ADD $(__err2ad), R8 - LMG 0(R8), R5, R6 - LE_CALL // balr R7, R6 __err2ad (return #2) - NOPH - MOVW (R3), R2 // retrieve errno2 - MOVD R2, errno2+40(FP) // store in return area - XOR R2, R2 - MOVWZ R2, (R3) // clear errno2 - -done: - MOVD R4, 0(R9) // Save stack pointer. - RET - + JMP runtime·CallLeFuncWithPtrReturn(SB) // // function to test if a pointer can be safely dereferenced (content read) // return 0 for succces @@ -360,23 +197,4 @@ TEXT ·ptrtest(SB), NOSPLIT, $0-16 // // func safeload(ptr uintptr) ( value uintptr, error uintptr) TEXT ·safeload(SB), NOSPLIT, $0-24 - MOVD ptr+0(FP), R10 // test pointer in R10 - MOVD $0x0, R6 - BYTE $0xE3; BYTE $0x20; BYTE $0x04; BYTE $0xB8; BYTE $0x00; BYTE $0x17 // llgt 2,1208 - BYTE $0xB9; BYTE $0x17; BYTE $0x00; BYTE $0x22 // llgtr 2,2 - BYTE $0xA5; BYTE $0x26; BYTE $0x7F; BYTE $0xFF // nilh 2,32767 - BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x58; BYTE $0x00; BYTE $0x04 // lg 2,88(2) - BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x08; BYTE $0x00; BYTE $0x04 // lg 2,8(2) - BYTE $0x41; BYTE $0x22; BYTE $0x03; BYTE $0x68 // la 2,872(2) - BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x33 // xgr 3,3 - BYTE $0xA7; BYTE $0x55; BYTE $0x00; BYTE $0x04 // bras 5,lbl1 - BYTE $0xA7; BYTE $0x39; BYTE $0x00; BYTE $0x01 // lghi 3,1 - BYTE $0xB9; BYTE $0x02; BYTE $0x00; BYTE $0x33 // lbl1 ltgr 3,3 - BYTE $0xA7; BYTE $0x74; BYTE $0x00; BYTE $0x08 // brc b'0111',lbl2 - BYTE $0xE3; BYTE $0x52; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 5,0(2) - BYTE $0xE3; BYTE $0x6A; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x04 // lg 6,0(10) - BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x99 // lbl2 xgr 9,9 - BYTE $0xE3; BYTE $0x92; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 9,0(2) - MOVD R6, value+8(FP) // result in R6 - MOVD R3, error+16(FP) // error in R3 - RET + JMP runtime·ZosSafeLoad(SB) diff --git a/vendor/golang.org/x/sys/unix/bpxsvc_zos.s b/vendor/golang.org/x/sys/unix/bpxsvc_zos.s index 4bd4a17982..1236e1e903 100644 --- a/vendor/golang.org/x/sys/unix/bpxsvc_zos.s +++ b/vendor/golang.org/x/sys/unix/bpxsvc_zos.s @@ -20,15 +20,15 @@ TEXT ·bpxcall(SB), NOSPLIT|NOFRAME, $0 MOVD plist_base+0(FP), R1 // r1 points to plist MOVD bpx_offset+24(FP), R2 // r2 offset to BPX vector table MOVD R14, R7 // save r14 - MOVD R15, R8 // save r15 - MOVWZ 16(R0), R9 - MOVWZ 544(R9), R9 - MOVWZ 24(R9), R9 // call vector in r9 - ADD R2, R9 // add offset to vector table - MOVWZ (R9), R9 // r9 points to entry point - BYTE $0x0D // BL R14,R9 --> basr r14,r9 - BYTE $0xE9 // clobbers 0,1,14,15 - MOVD R8, R15 // restore 15 + MOVD R15, R9 // save r15 + MOVWZ 16(R0), R15 + MOVWZ 544(R15), R15 + MOVWZ 24(R15), R15 // call vector in r15 + ADD R2, R15 // add offset to vector table + MOVWZ (R15), R15 // r15 points to entry point + BYTE $0x0D // BL R14,R15 --> basr r14,r15 + BYTE $0xEF // clobbers 0,1,14,15 + MOVD R9, R15 // restore 15 JMP R7 // return via saved return address // func A2e(arr [] byte) diff --git a/vendor/golang.org/x/sys/unix/fcntl_darwin.go b/vendor/golang.org/x/sys/unix/fcntl_darwin.go index a9911c7c1d..78c28a3dc0 100644 --- a/vendor/golang.org/x/sys/unix/fcntl_darwin.go +++ b/vendor/golang.org/x/sys/unix/fcntl_darwin.go @@ -13,12 +13,12 @@ func FcntlInt(fd uintptr, cmd, arg int) (int, error) { // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { - _, err := fcntl(int(fd), cmd, int(uintptr(unsafe.Pointer(lk)))) + _, err := fcntlPtr(int(fd), cmd, unsafe.Pointer(lk)) return err } // FcntlFstore performs a fcntl syscall for the F_PREALLOCATE command. func FcntlFstore(fd uintptr, cmd int, fstore *Fstore_t) error { - _, err := fcntl(int(fd), cmd, int(uintptr(unsafe.Pointer(fstore)))) + _, err := fcntlPtr(int(fd), cmd, unsafe.Pointer(fstore)) return err } diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 9e907ac296..e95eecd53c 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -579,7 +579,7 @@ ccflags="$@" $2 ~ /^DIOC/ || $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ || - $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || + $2 ~ /^PRIO_(PROCESS|PGRP|USER|DARWIN_(THREAD|PROCESS|BG|NONUI))/ || $2 ~ /^CLONE_[A-Z_]+/ || $2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+|BPF_F_LINK)$/ && $2 ~ /^(BPF|DLT)_/ || diff --git a/vendor/golang.org/x/sys/unix/ptrace_zos.go b/vendor/golang.org/x/sys/unix/ptrace_zos.go new file mode 100644 index 0000000000..394fbd71b2 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/ptrace_zos.go @@ -0,0 +1,537 @@ +// Copyright 2026 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. + +//go:build zos + +package unix + +import "unsafe" + +// z/OS ptrace implementation notes: +// +// This file provides ptrace wrappers for z/OS that match the Linux API as closely +// as possible. However, there are fundamental differences in how z/OS implements +// process tracing compared to Linux: +// +// 1. SYSTEM CALL INTERFACE: +// - z/OS uses BPX4PTR (5 parameters) vs Linux ptrace syscall (4 parameters) +// - The 5th parameter (buffer) is used for block operations +// +// 2. MEMORY OPERATIONS: +// - z/OS: PT_READ_BLOCK/PT_WRITE_BLOCK for efficient block transfers +// - Linux: PTRACE_PEEKTEXT/POKETEXT for word-by-word access +// +// 3. REGISTER OPERATIONS: +// - z/OS: PT_READ_GPR/PT_WRITE_GPR with register number for 64-bit values +// - Linux: PTRACE_GETREGSET/SETREGSET with iovec structure +// +// 4. SINGLE-STEPPING: +// - z/OS: No native single-step; requires temporary breakpoints or PER +// - Linux: PTRACE_SINGLESTEP natively supported +// a) Read instruction at current PSW +// b) Calculate next instruction address (handle branches) +// c) Set temporary breakpoint (SVC 144 = 0x0A90) at next address +// d) Continue execution until breakpoint hit +// e) Restore original instruction and adjust PSW +// +// 5. SYSCALL TRACING: +// - z/OS: No PTRACE_SYSCALL equivalent; requires breakpoint-based approach +// - Linux: PTRACE_SYSCALL stops at syscall entry/exit +// a) Identify BPX syscall vector location +// b) Set breakpoints at syscall entry points +// c) Detect BASR instructions calling into syscall vector +// d) Parse arguments from registers before/after syscall +// +// 6. LIMITATIONS: +// - PtraceSetOptions: No equivalent (returns ENOSYS) +// - PtraceGetEventMsg: No equivalent (returns ENOSYS) +// - PtraceSingleStep: Requires complex implementation (returns ENOSYS) +// - PtraceInterrupt: No equivalent (returns ENOSYS) +// - PtracePokeUser: No PT_WRITE_U (returns ENOSYS) +// +// For reference implementations of single-stepping and syscall tracing on z/OS, + +// ptrace is the basic wrapper for BPX4PTR on z/OS. +// Note: z/OS ptrace (BPX4PTR) takes 5 parameters vs 4 on Linux/Darwin. +// The 5th parameter (buffer) is used for operations like PT_READ_BLOCK/PT_WRITE_BLOCK. +// +// data is an integer-valued argument (signal number, register index, byte count, +// or a target-process address). It is not a Go-managed pointer. We must not pass +// it to Bpx4ptr as unsafe.Pointer(data) because the garbage collector would treat +// that integer as a pointer and may crash trying to follow it. +// +// Instead we inline the parms array that Bpx4ptr would construct, placing &data +// at parms[3]. BPX4PTR dereferences parms[3] to obtain the data value, so it +// receives data unchanged while the GC only ever sees a valid stack pointer. +func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { + req32 := int32(request) + pid32 := int32(pid) + var rv, rc, rn int32 + var buffer unsafe.Pointer + parms := [8]unsafe.Pointer{ + unsafe.Pointer(&req32), + unsafe.Pointer(&pid32), + unsafe.Pointer(&addr), + unsafe.Pointer(&data), // &data, not unsafe.Pointer(data) + unsafe.Pointer(&buffer), + unsafe.Pointer(&rv), + unsafe.Pointer(&rc), + unsafe.Pointer(&rn), + } + bpxcall(parms[:], BPX4PTR) + if rv != 0 { + err = errnoErr2(Errno(rc), uintptr(rn)) + } + return +} + +// ptracePtr is a variant that accepts unsafe.Pointer for the data parameter. +// addr is a target-process address (a raw integer), not a Go-managed pointer. +// We must not pass it to Bpx4ptr as unsafe.Pointer(addr); instead we inline the +// parms array and place &addr at parms[2], exactly as ptrace() does for data. +func ptracePtr(request int, pid int, addr uintptr, data unsafe.Pointer) (err error) { + req32 := int32(request) + pid32 := int32(pid) + var rv, rc, rn int32 + var buffer unsafe.Pointer + parms := [8]unsafe.Pointer{ + unsafe.Pointer(&req32), + unsafe.Pointer(&pid32), + unsafe.Pointer(&addr), // &addr, not unsafe.Pointer(addr) + unsafe.Pointer(&data), + unsafe.Pointer(&buffer), + unsafe.Pointer(&rv), + unsafe.Pointer(&rc), + unsafe.Pointer(&rn), + } + bpxcall(parms[:], BPX4PTR) + if rv != 0 { + err = errnoErr2(Errno(rc), uintptr(rn)) + } + return +} + +// ptracePtrWithBuffer is used for operations that require the buffer parameter. +// addr is a target-process address; same &addr treatment as ptracePtr. +func ptracePtrWithBuffer(request int, pid int, addr uintptr, data unsafe.Pointer, buffer unsafe.Pointer) (err error) { + req32 := int32(request) + pid32 := int32(pid) + var rv, rc, rn int32 + parms := [8]unsafe.Pointer{ + unsafe.Pointer(&req32), + unsafe.Pointer(&pid32), + unsafe.Pointer(&addr), // &addr, not unsafe.Pointer(addr) + unsafe.Pointer(&data), + unsafe.Pointer(&buffer), + unsafe.Pointer(&rv), + unsafe.Pointer(&rc), + unsafe.Pointer(&rn), + } + bpxcall(parms[:], BPX4PTR) + if rv != 0 { + err = errnoErr2(Errno(rc), uintptr(rn)) + } + return +} + +// High-level convenience functions matching the Linux/Darwin API + +func PtraceAttach(pid int) (err error) { + return ptrace(PT_ATTACH, pid, 0, 0) +} + +func PtraceDetach(pid int) (err error) { + return ptrace(PT_DETACH, pid, 0, 0) +} + +func PtraceCont(pid int, signal int) (err error) { + // PT_CONTINUE can be interrupted by signals (EINTR), retry if needed + for { + err = ptrace(PT_CONTINUE, pid, 0, uintptr(signal)) + if err != EINTR { + break + } + } + return err +} + +func PtraceKill(pid int) (err error) { + return ptrace(PT_KILL, pid, 0, 0) +} + +// ptracePeek implements the peek operations using PT_READ_BLOCK. +// On z/OS, PT_READ_BLOCK can read arbitrary-length data efficiently. +// Unlike Linux which reads word-by-word, z/OS can read blocks directly. +func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) { + if len(out) == 0 { + return 0, nil + } + + // z/OS PT_READ_BLOCK can read blocks directly without word-by-word alignment + // The buffer parameter points to the output buffer + buffer := unsafe.Pointer(&out[0]) + err = ptracePtrWithBuffer(req, pid, addr, unsafe.Pointer(uintptr(len(out))), buffer) + if err != nil { + return 0, err + } + return len(out), nil +} + +// PtracePeekText reads from the traced process's text segment. +func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) { + return ptracePeek(PT_READ_BLOCK, pid, addr, out) +} + +// PtracePeekData reads from the traced process's data segment. +func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) { + return ptracePeek(PT_READ_BLOCK, pid, addr, out) +} + +// PtracePeekUser reads from the traced process's user area. +// On z/OS, PT_READ_U reads a 32-bit word from the user area at the specified offset. +// To match Linux behavior, we implement word-by-word reading for arbitrary lengths. +func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) { + if len(out) == 0 { + return 0, nil + } + + // PT_READ_U reads 32-bit words from user area + // We need to read word-by-word to handle arbitrary lengths + n := 0 + for n < len(out) { + var data uint32 + err = ptracePtr(PT_READ_U, pid, addr+uintptr(n), unsafe.Pointer(&data)) + if err != nil { + return n, err + } + + // Copy up to 4 bytes to output + remaining := len(out) - n + if remaining >= 4 { + out[n] = byte(data >> 24) + out[n+1] = byte(data >> 16) + out[n+2] = byte(data >> 8) + out[n+3] = byte(data) + n += 4 + } else { + // Handle partial word at the end + for i := 0; i < remaining; i++ { + out[n+i] = byte(data >> (24 - i*8)) + } + n += remaining + } + } + return n, nil +} + +// ptracePoke implements the poke operations using PT_WRITE_BLOCK. +func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) { + if len(data) == 0 { + return 0, nil + } + + // z/OS PT_WRITE_BLOCK can write blocks directly + buffer := unsafe.Pointer(&data[0]) + err = ptracePtrWithBuffer(pokeReq, pid, addr, unsafe.Pointer(uintptr(len(data))), buffer) + if err != nil { + return 0, err + } + return len(data), nil +} + +// PtracePokeText writes to the traced process's text segment. +func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) { + return ptracePoke(PT_WRITE_BLOCK, PT_READ_BLOCK, pid, addr, data) +} + +// PtracePokeData writes to the traced process's data segment. +func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) { + return ptracePoke(PT_WRITE_BLOCK, PT_READ_BLOCK, pid, addr, data) +} + +// PtracePokeUser writes to the traced process's user area. +// Note: z/OS does not have a direct PT_WRITE_U equivalent. +// This function returns ENOSYS to indicate it's not supported. +// DIFFERENCE FROM LINUX: Linux supports PTRACE_POKEUSR, z/OS does not. +func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) { + // z/OS doesn't have PT_WRITE_U + return 0, ENOSYS +} + +// PtraceGetRegs retrieves the general purpose registers from the traced process. +// On z/OS, PT_READ_GPR can read individual registers as 64-bit values when called +// with a register number, or read all registers when called with a buffer. +// This function reads each register individually to ensure full 64-bit values. +// DIFFERENCE FROM LINUX: Linux uses PTRACE_GETREGSET with iovec, z/OS uses PT_READ_GPR. +func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) { + // Use PT_REGHSET to enable reading high GPRs for AMODE 64 programs + rv, rc, rn := Bpx4ptr(int32(PT_REGHSET), int32(pid), nil, nil, nil) + _ = rv + _ = rc + _ = rn + + // Use PT_BLOCKREQ to read GPRs and PSW in one call + // dbx uses 3 requests: PT_READ_GPR, PT_READ_U, PT_READ_GPRH + // PT_READ_U is required for ptrace to populate PSW in GPR block + // + // IMPORTANT: z/OS ptrace always returns 64-bit ESA/390 format PSW in the Psw field. + // The 128-bit Pswg field is never populated, even with PSWG_Req bit set. + // We convert ESA/390 to z/Architecture format in software (matching DBX behavior). + const ( + numRequests = 3 + reqSize = int(unsafe.Sizeof(PtraceBlkReqReq{})) + gprSize = int(unsafe.Sizeof(PtraceBlkGpr{})) + uareaSize = int(unsafe.Sizeof(PtraceBlkUar{})) + 6*int(unsafe.Sizeof(PtraceBlkUarOcw{})) + totalSize = int(unsafe.Sizeof(PtraceBlkReq{})) + numRequests*reqSize + gprSize*2 + uareaSize + ) + + // Allocate buffer for block request + buf := make([]byte, totalSize) + + // Setup block request header + blkReq := (*PtraceBlkReq)(unsafe.Pointer(&buf[0])) + blkReq.Numreq = numRequests + + // Setup request array + reqOffset := int(unsafe.Sizeof(PtraceBlkReq{})) + reqs := (*[3]PtraceBlkReqReq)(unsafe.Pointer(&buf[reqOffset])) + + // Setup GPR block (lower 32 bits) + gprOffset := reqOffset + numRequests*reqSize + gprBlock := (*PtraceBlkGpr)(unsafe.Pointer(&buf[gprOffset])) + + // Setup user area block (required for PSW) + uareaOffset := gprOffset + gprSize + uareaBlock := (*PtraceBlkUar)(unsafe.Pointer(&buf[uareaOffset])) + uareaBlock.Num = 6 // Number of control info entries + + // Setup user area offset/control words + uareaOcw := (*[6]PtraceBlkUarOcw)(unsafe.Pointer(&buf[uareaOffset+int(unsafe.Sizeof(PtraceBlkUar{}))])) + uareaOcw[0].Ofs = 1025 // program interrupt code + uareaOcw[1].Ofs = 1026 // abend completion code + uareaOcw[2].Ofs = 1027 // abend reason code + uareaOcw[3].Ofs = 1028 // signal code + uareaOcw[4].Ofs = 1029 // instruction length code + uareaOcw[5].Ofs = 1030 // process flags + + // Setup high GPR block (upper 32 bits) + gprHighOffset := uareaOffset + uareaSize + gprHighBlock := (*PtraceBlkGpr)(unsafe.Pointer(&buf[gprHighOffset])) + + // Configure requests (order matters: GPR, U, GPRH) + // reqdata contains OFFSET from buffer start, not absolute address + // dbx: brr[0].reqdata=(unsigned long)brg; where brg is the offset + reqs[0].Reqtype = PT_READ_GPR + reqs[0].Reqdata = uint32(gprOffset) + reqs[1].Reqtype = PT_READ_U + reqs[1].Reqdata = uint32(uareaOffset) + reqs[2].Reqtype = PT_READ_GPRH + reqs[2].Reqdata = uint32(gprHighOffset) + + // Execute block request + rvBlk, rcBlk, rnBlk := Bpx4ptr(int32(PT_BLOCKREQ), int32(pid), + unsafe.Pointer(&buf[0]), unsafe.Pointer(uintptr(totalSize)), nil) + if rvBlk == -1 { + return errnoErr2(Errno(rcBlk), uintptr(rnBlk)) + } + + // Extract GPRs (combine low and high 32 bits) + for i := 0; i < 16; i++ { + low := uint64(gprBlock.Gpr[i]) + high := uint64(gprHighBlock.Gpr[i]) << 32 + regsout.Gprs[i] = high | low + } + + // Extract PSW from GPR block structure + // z/OS ptrace ALWAYS returns 8-byte ESA/390 format PSW at offset 144. + // The 16-byte PSWG field at offset 152 is NEVER populated (always zero). + // We must convert ESA/390 format to z/Architecture format in software (like DBX does). + // + // ESA/390 PSW format (8 bytes): + // Word 1 (bytes 0-3): Mask with bit 12 = 1 (ECMODE31BIT) + // Word 2 (bytes 4-7): Address with bit 0 = AMODE bit (1=31-bit, 0=64-bit) + // + // z/Architecture PSW format (16 bytes): + // Mask (bytes 0-7): Extended mask with bit 12 = 0, bits 31-32 = EA+BA (AMODE) + // Addr (bytes 8-15): Full 64-bit instruction address + + // Read ESA/390 PSW as two 32-bit words + pswWord1 := uint32(gprBlock.Psw[0])<<24 | uint32(gprBlock.Psw[1])<<16 | + uint32(gprBlock.Psw[2])<<8 | uint32(gprBlock.Psw[3]) + pswWord2 := uint32(gprBlock.Psw[4])<<24 | uint32(gprBlock.Psw[5])<<16 | + uint32(gprBlock.Psw[6])<<8 | uint32(gprBlock.Psw[7]) + + // Convert ESA/390 to z/Architecture format (matching DBX psw_ESA390_to_zArchitecture) + const ECMODE31BIT = uint64(0x0000000000080000) + const AMODE31BIT = uint64(0x0000000080000000) + const ADDR_MASK_31 = uint64(0x000000007FFFFFFF) + + // Extract AMODE bit from address word (bit 0 of word 2) + amode31 := uint64(pswWord2) & AMODE31BIT + + // Mask off AMODE bit from address + addr := uint64(pswWord2) & ADDR_MASK_31 + + // Convert mask: clear ECMODE31BIT, shift left 32 bits, add AMODE bit + mask := uint64(pswWord1) & ^ECMODE31BIT + mask = (mask << 32) | amode31 + + regsout.Psw.Mask = mask + regsout.Psw.Addr = addr + + // Note: Access registers (Acrs), floating point registers (Fp_regs), + // PER info (Per_info), and other fields would require additional + // PT_READ_* calls. For now, we focus on GPRs and PSW which are + // the most commonly used registers for debugging. + + return nil +} + +// ptraceWritePSW writes only the PSW address register. +// This is a lower-level function used internally for single-stepping. +// Based on ztrace's write_psw function. +func ptraceWritePSW(pid int, pswAddr uint32) error { + const PTRACE_REG_PSWA = 41 + rv, rc, rn := Bpx4ptr(int32(PT_WRITE_GPR), int32(pid), + unsafe.Pointer(uintptr(PTRACE_REG_PSWA)), + unsafe.Pointer(uintptr(pswAddr)), + nil) + if rv == -1 { + return errnoErr2(Errno(rc), uintptr(rn)) + } + return nil +} + +// PtraceSetRegs sets the general purpose registers in the traced process. +// Uses PT_BLOCKREQ to write GPRs and PSW in a single call, matching dbx implementation. +// DIFFERENCE FROM LINUX: Linux uses PTRACE_SETREGSET with iovec, z/OS uses PT_BLOCKREQ. +// NOTE: The process must be in a stopped state for register writes to succeed. +func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) { + // Use PT_REGHSET to enable writing high GPRs for AMODE 64 programs + rv, rc, rn := Bpx4ptr(int32(PT_REGHSET), int32(pid), nil, nil, nil) + _ = rv + _ = rc + _ = rn + + // Use PT_BLOCKREQ to write GPRs and PSW in one call + const ( + numRequests = 2 + reqSize = int(unsafe.Sizeof(PtraceBlkReqReq{})) + gprSize = int(unsafe.Sizeof(PtraceBlkGpr{})) + totalSize = int(unsafe.Sizeof(PtraceBlkReq{})) + numRequests*reqSize + gprSize*2 + ) + + // Allocate buffer for block request + buf := make([]byte, totalSize) + + // Setup block request header + blkReq := (*PtraceBlkReq)(unsafe.Pointer(&buf[0])) + blkReq.Numreq = numRequests + + // Setup request array + reqOffset := int(unsafe.Sizeof(PtraceBlkReq{})) + reqs := (*[2]PtraceBlkReqReq)(unsafe.Pointer(&buf[reqOffset])) + + // Setup GPR block (lower 32 bits) + gprOffset := reqOffset + numRequests*reqSize + gprBlock := (*PtraceBlkGpr)(unsafe.Pointer(&buf[gprOffset])) + + // Setup high GPR block (upper 32 bits) + gprHighOffset := gprOffset + gprSize + gprHighBlock := (*PtraceBlkGpr)(unsafe.Pointer(&buf[gprHighOffset])) + + // Mark all GPRs as modified (set all 16 bits) + gprBlock.Writebitflags = 0xFFFF + gprHighBlock.Writebitflags = 0xFFFF + + // Split 64-bit GPRs into low and high 32 bits + for i := 0; i < 16; i++ { + gprBlock.Gpr[i] = uint32(regs.Gprs[i] & 0xFFFFFFFF) + gprHighBlock.Gpr[i] = uint32(regs.Gprs[i] >> 32) + } + + // Pack PSW for 31-bit targets (current z/OS) + // Upper 32 bits = mask, lower 32 bits = address + gprBlock.Wpsw = 1 // Mark PSW as modified + // Write PSW in old format (8 bytes at offset 144) + // Word 1 (mask) at bytes 0-3, Word 2 (addr) at bytes 4-7 + pswMask := uint32(regs.Psw.Mask) + pswAddr := uint32(regs.Psw.Addr) + gprBlock.Psw[0] = byte(pswMask >> 24) + gprBlock.Psw[1] = byte(pswMask >> 16) + gprBlock.Psw[2] = byte(pswMask >> 8) + gprBlock.Psw[3] = byte(pswMask) + gprBlock.Psw[4] = byte(pswAddr >> 24) + gprBlock.Psw[5] = byte(pswAddr >> 16) + gprBlock.Psw[6] = byte(pswAddr >> 8) + gprBlock.Psw[7] = byte(pswAddr) + + // Clear extended PSWG (not used for 31-bit targets) + for i := 0; i < 16; i++ { + gprBlock.Pswg[i] = 0 + } + + // Configure requests + // reqdata contains OFFSET from buffer start, not absolute address + reqs[0].Reqtype = PT_WRITE_GPR + reqs[0].Reqdata = uint32(gprOffset) + reqs[1].Reqtype = PT_WRITE_GPRH + reqs[1].Reqdata = uint32(gprHighOffset) + + // Execute block request + rvBlk, rcBlk, rnBlk := Bpx4ptr(int32(PT_BLOCKREQ), int32(pid), + unsafe.Pointer(&buf[0]), unsafe.Pointer(uintptr(totalSize)), nil) + if rvBlk == -1 { + return errnoErr2(Errno(rcBlk), uintptr(rnBlk)) + } + + return nil +} + +// PtraceSetOptions sets ptrace options. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_SETOPTIONS equivalent. +// Returns ENOSYS to indicate this is not supported on z/OS. +func PtraceSetOptions(pid int, options int) (err error) { + return ENOSYS +} + +// PtraceGetEventMsg retrieves a message about the ptrace event. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_GETEVENTMSG equivalent. +// Returns ENOSYS to indicate this is not supported on z/OS. +func PtraceGetEventMsg(pid int) (msg uint, err error) { + return 0, ENOSYS +} + +// PtraceSyscall continues execution and stops at the next syscall entry/exit. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_SYSCALL equivalent. +// This function falls back to PT_CONTINUE and will NOT stop at syscalls. +// +// To trace syscalls on z/OS, applications must: +// 1. Set breakpoints at BPX syscall entry points (requires knowledge of syscall vector) +// 2. Detect BASR instructions that call into the BPX syscall vector +// 3. Use PT_LDINFO to identify loaded modules and their entry points +func PtraceSyscall(pid int, signal int) (err error) { + // z/OS doesn't have a direct PTRACE_SYSCALL equivalent + // Use PT_CONTINUE as a fallback (won't stop at syscalls) + return ptrace(PT_CONTINUE, pid, 0, uintptr(signal)) +} + +// Note: PtraceSingleStep is implemented in ptrace_zos_singlestep.go +// with full two-breakpoint emulation for branch instructions. + +// PtraceInterrupt interrupts the traced process. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_INTERRUPT equivalent. +// Returns ENOSYS to indicate this is not supported on z/OS. +func PtraceInterrupt(pid int) (err error) { + return ENOSYS +} + +// PtraceSeize attaches to a process without stopping it. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_SEIZE equivalent. +// Uses PT_ATTACH as a fallback, which will stop the process. +func PtraceSeize(pid int) (err error) { + // z/OS doesn't have PTRACE_SEIZE, use PT_ATTACH + // Note: This WILL stop the process, unlike Linux PTRACE_SEIZE + return ptrace(PT_ATTACH, pid, 0, 0) +} diff --git a/vendor/golang.org/x/sys/unix/ptrace_zos_singlestep.go b/vendor/golang.org/x/sys/unix/ptrace_zos_singlestep.go new file mode 100644 index 0000000000..7d7e2c8d30 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/ptrace_zos_singlestep.go @@ -0,0 +1,425 @@ +// Copyright 2024 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. + +//go:build zos + +package unix + +import ( + "sync" +) + +// Single-stepping emulation for z/OS +// +// z/OS does not have native single-step support like Linux's PTRACE_SINGLESTEP. +// Instead, single-stepping must be emulated using temporary breakpoints. +// +// This file provides a complete implementation of single-step emulation using +// temporary breakpoints at both the sequential next instruction and branch target. + +const ( + // NO_BRANCH_DEST indicates the instruction is not a branch or cannot branch + NO_BRANCH_DEST = 0xFFFFFFFF + + // SVC_144 is the breakpoint instruction (SVC 144 = 0x0A90) + SVC_144 = 0x0A90 + + // Maximum number of temporary breakpoints (one for next PC, one for branch dest) + MAX_TEMP_BREAKPOINTS = 2 + + // S/390 branch instruction opcodes + // RR format (Register-Register) + opBCR = 0x07 // Branch on Condition Register + opBALR = 0x05 // Branch and Link Register + opBASR = 0x0D // Branch and Save Register + opBASSM = 0x0C // Branch and Save and Set Mode + opBSM = 0x0B // Branch and Set Mode + opBCTR = 0x06 // Branch on Count Register + + // RX format (Register-Index-Storage) + opBC = 0x47 // Branch on Condition + opBAL = 0x45 // Branch and Link + opBCT = 0x46 // Branch on Count + opBAS = 0x4D // Branch and Save + + // RS format (Register-Storage) + opBXH = 0x86 // Branch on Index High + opBXLE = 0x87 // Branch on Index Low or Equal + + // Extended branch opcodes + opBA7 = 0xA7 // A7x series (BRC, BRAS, BRCT, BRCTG) + opBC0 = 0xC0 // C0x series (BRASL, BRCL) + opBEC = 0xEC // ECxx series (RIEc format: compare-and-branch) +) + +// tempBreakpoint represents a temporary breakpoint for single-stepping +type tempBreakpoint struct { + address uint64 + originalInsn [8]byte // Save up to 8 bytes (full instruction) + active bool +} + +// singleStepState manages temporary breakpoints for a process +type singleStepState struct { + mu sync.Mutex + breakpoints [MAX_TEMP_BREAKPOINTS]tempBreakpoint +} + +var ( + // Global map of process states (pid -> state) + processStates = make(map[int]*singleStepState) + processStatesMu sync.Mutex +) + +// getProcessState returns or creates the single-step state for a process +func getProcessState(pid int) *singleStepState { + processStatesMu.Lock() + defer processStatesMu.Unlock() + + state, exists := processStates[pid] + if !exists { + state = &singleStepState{} + processStates[pid] = state + } + return state +} + +// cleanupProcessState removes the state for a process (call on detach) +func cleanupProcessState(pid int) { + processStatesMu.Lock() + defer processStatesMu.Unlock() + delete(processStates, pid) +} + +// GetInstructionLength returns the length of an S/390 instruction in bytes. +func GetInstructionLength(firstByte byte) int { + switch (firstByte >> 6) & 0x03 { + case 0x00: + return 2 + case 0x01, 0x02: + return 4 + case 0x03: + return 6 + default: + return 2 + } +} + +// GetNextInstructionAddr returns the address of the next sequential instruction. +func GetNextInstructionAddr(pc uint64, instruction []byte) uint64 { + if len(instruction) < 1 { + return pc + 2 + } + insnLen := GetInstructionLength(instruction[0]) + return pc + uint64(insnLen) +} + +// CalculateBranchDest calculates the destination address for branch instructions. +func CalculateBranchDest(pid int, pc uint64, instruction []byte) uint64 { + if len(instruction) < 6 { + return NO_BRANCH_DEST + } + + inst0_15 := uint16(instruction[0])<<8 | uint16(instruction[1]) + inst16_31 := uint16(instruction[2])<<8 | uint16(instruction[3]) + inst32_47 := uint16(instruction[4])<<8 | uint16(instruction[5]) + opcode := instruction[0] + + var dest uint64 = NO_BRANCH_DEST + + // RR format branches + if opcode == opBCR || opcode == opBALR || opcode == opBASR || + opcode == opBASSM || opcode == opBSM || opcode == opBCTR { + + r2 := int(inst0_15 & 0x0F) + + if opcode == opBCR { + mask := int((inst0_15 >> 4) & 0x0F) + if mask == 0 || r2 == 0 { + return NO_BRANCH_DEST + } + } else { + if r2 == 0 { + return NO_BRANCH_DEST + } + } + + var regs PtraceRegs + if err := PtraceGetRegs(pid, ®s); err == nil { + if r2 >= 0 && r2 < 16 { + regVal := regs.Gprs[r2] + dest = regVal + } + } + } else if opcode == opBC || opcode == opBAL || opcode == opBCT || opcode == opBAS { + // RX format branches + if opcode == opBC { + mask := int((inst0_15 >> 4) & 0x0F) + if mask == 0 { + return NO_BRANCH_DEST + } + } + + index := int(inst0_15 & 0x0F) + base := int((inst16_31 >> 12) & 0x0F) + displacement := uint32(inst16_31 & 0x0FFF) + + var baseVal, indexVal uint64 + var regs PtraceRegs + if err := PtraceGetRegs(pid, ®s); err == nil { + if base != 0 && base < 16 { + baseVal = regs.Gprs[base] + } + if index != 0 && index < 16 { + indexVal = regs.Gprs[index] + } + } + + if base == 0 && index == 0 { + dest = pc + uint64(displacement) + } else { + dest = baseVal + indexVal + uint64(displacement) + } + } else if opcode == opBXH || opcode == opBXLE { + // RS format branches + base := int((inst16_31 >> 12) & 0x0F) + displacement := uint32(inst16_31 & 0x0FFF) + + var baseVal uint64 + var regs PtraceRegs + if err := PtraceGetRegs(pid, ®s); err == nil { + if base != 0 && base < 16 { + baseVal = regs.Gprs[base] + } + } + + dest = baseVal + uint64(displacement) + } else if opcode == opBA7 { + // RI format branches + subOp := int(inst0_15 & 0x0F) + + if subOp < 4 || subOp > 7 { + return NO_BRANCH_DEST + } + + if subOp == 0x04 { + mask := int((inst0_15 >> 4) & 0x0F) + if mask == 0 { + return NO_BRANCH_DEST + } + } + + relDispl := int16(inst16_31) + dest = uint64(int64(pc) + int64(relDispl)*2) + } else if opcode == opBC0 { + // RIL format branches + subOp := int(inst0_15 & 0x0F) + + if subOp == 0x04 || subOp == 0x05 { + if subOp == 0x04 { + mask := int((inst0_15 >> 4) & 0x0F) + if mask == 0 { + return NO_BRANCH_DEST + } + } + + inst16_47 := (uint32(inst16_31) << 16) | uint32(inst32_47) + relDispl4 := int32(inst16_47) + dest = uint64(int64(pc) + int64(relDispl4)*2) + } + } else if opcode == opBEC { + // RIEc format compare-and-branch + subOp := instruction[4] + + isCompareBranch := (subOp >= 0x64 && subOp <= 0x67) || + (subOp >= 0x76 && subOp <= 0x77) || + (subOp >= 0x7C && subOp <= 0x7F) + + if isCompareBranch { + ri4 := int16(inst16_31) + dest = uint64(int64(pc) + int64(ri4)*2) + } + } + + if dest < 0x2000 { + return NO_BRANCH_DEST + } + + return dest +} + +// setTempBreakpoint sets a temporary breakpoint at the specified address +func (s *singleStepState) setTempBreakpoint(pid int, addr uint64) error { + s.mu.Lock() + defer s.mu.Unlock() + + // Find free slot + slot := -1 + for i := 0; i < MAX_TEMP_BREAKPOINTS; i++ { + if !s.breakpoints[i].active { + slot = i + break + } + } + + if slot == -1 { + return ENOMEM // All slots in use + } + + // Read original instruction (up to 8 bytes for safety) + _, err := PtracePeekText(pid, uintptr(addr), s.breakpoints[slot].originalInsn[:]) + if err != nil { + return err + } + + // Write SVC 144 (0x0A90) as breakpoint + svc144 := []byte{0x0A, 0x90} + _, err = PtracePokeText(pid, uintptr(addr), svc144) + if err != nil { + return err + } + + s.breakpoints[slot].address = addr + s.breakpoints[slot].active = true + + return nil +} + +// removeTempBreakpoints removes all active temporary breakpoints +func (s *singleStepState) removeTempBreakpoints(pid int) error { + s.mu.Lock() + defer s.mu.Unlock() + + var lastErr error + for i := 0; i < MAX_TEMP_BREAKPOINTS; i++ { + if !s.breakpoints[i].active { + continue + } + + // Restore original instruction (first 2 bytes are enough for SVC 144) + _, err := PtracePokeText(pid, uintptr(s.breakpoints[i].address), s.breakpoints[i].originalInsn[:2]) + if err != nil { + lastErr = err + } + + s.breakpoints[i].active = false + } + + return lastErr +} + +// isTempBreakpoint checks if an address is a temporary breakpoint +func (s *singleStepState) isTempBreakpoint(addr uint64) bool { + s.mu.Lock() + defer s.mu.Unlock() + + for i := 0; i < MAX_TEMP_BREAKPOINTS; i++ { + if s.breakpoints[i].active && s.breakpoints[i].address == addr { + return true + } + } + return false +} + +// PtraceSingleStep executes a single instruction using temporary breakpoints. +// +// This function: +// 1. Reads the current instruction at PSW +// 2. Calculates the next instruction address (sequential) +// 3. If branch instruction, calculates branch destination +// 4. Sets temporary breakpoints at both addresses +// 5. Continues execution until breakpoint hit +// 6. Restores original instructions and adjusts PSW +// +// Returns nil on success, error on failure. +func PtraceSingleStep(pid int) error { + state := getProcessState(pid) + + // 1. Get current PSW + var regs PtraceRegs + if err := PtraceGetRegs(pid, ®s); err != nil { + return err + } + pc := regs.Psw.Addr + + // 2. Read instruction at PC + insn := make([]byte, 8) + if _, err := PtracePeekText(pid, uintptr(pc), insn); err != nil { + return err + } + + // 3. Calculate next instruction addresses + nextPC := GetNextInstructionAddr(pc, insn) + branchDest := CalculateBranchDest(pid, pc, insn) + + // 4. Set temporary breakpoints + if err := state.setTempBreakpoint(pid, nextPC); err != nil { + return err + } + + // If branch instruction, set breakpoint at branch destination too + if branchDest != NO_BRANCH_DEST && branchDest != nextPC { + if err := state.setTempBreakpoint(pid, branchDest); err != nil { + state.removeTempBreakpoints(pid) // Cleanup first breakpoint + return err + } + } + + // 5. Continue execution + if err := PtraceCont(pid, 0); err != nil { + state.removeTempBreakpoints(pid) + return err + } + + // 6. Wait for breakpoint hit (retry on EINTR) + var status WaitStatus + for { + _, err := Wait4(pid, &status, 0, nil) + if err == EINTR { + continue // Retry on interrupted system call + } + if err != nil { + state.removeTempBreakpoints(pid) + return err + } + break + } + + // Check if process stopped (should be at breakpoint) + if !status.Stopped() { + state.removeTempBreakpoints(pid) + return ECHILD // Process exited or error + } + + // 7. Get current PSW (should be at breakpoint + 2) + if err := PtraceGetRegs(pid, ®s); err != nil { + state.removeTempBreakpoints(pid) + return err + } + + // 8. Remove temporary breakpoints + if err := state.removeTempBreakpoints(pid); err != nil { + return err + } + + // 9. Back up PSW by 2 bytes (to point at original instruction, not SVC 144) + // Use direct PSW write like ztrace does, not full register set + hitAddr := regs.Psw.Addr + if state.isTempBreakpoint(hitAddr - 2) { + if err := ptraceWritePSW(pid, uint32(hitAddr-2)); err != nil { + return err + } + } + + return nil +} + +// PtraceDetachWithCleanup detaches from a process and cleans up single-step state. +// Use this instead of PtraceDetach when using PtraceSingleStep. +func PtraceDetachWithCleanup(pid int) error { + state := getProcessState(pid) + state.removeTempBreakpoints(pid) + cleanupProcessState(pid) + return PtraceDetach(pid) +} diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 38590ca81d..cb9d0a181c 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -369,6 +369,7 @@ func Flistxattr(fd int, dest []byte) (sz int, err error) { */ //sys fcntl(fd int, cmd int, arg int) (val int, err error) +//sys fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (val int, err error) = SYS_FCNTL //sys kill(pid int, signum int, posix int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go index 2b57e0f73b..495188996d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -369,6 +369,15 @@ func Dup3(oldfd, newfd, flags int) error { //sys ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) //sys ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) +//sys extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchdir(fd int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 6926057e9e..a31e2c71ad 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -1991,7 +1991,24 @@ func FsconfigReconfigure(fd int) (err error) { return fsconfig(fd, FSCONFIG_CMD_RECONFIGURE, nil, nil, 0) } -//sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64 +//sys getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64 + +// Getdents reads directory entries from fd into buf. +func Getdents(fd int, buf []byte) (n int, err error) { + // getdents64 stores d_ino with a 64-bit write, which faults on + // strict-alignment targets unless buf is 8-aligned. + if len(buf) > 0 { + if off := int(-uintptr(unsafe.Pointer(&buf[0])) & 7); off > 0 && off < len(buf) { + n, err = getdents(fd, buf[off:]) + if n > 0 { + copy(buf, buf[off:off+n]) + } + return n, err + } + } + return getdents(fd, buf) +} + //sysnb Getpgid(pid int) (pgid int, err error) func Getpgrp() (pid int) { @@ -2033,6 +2050,7 @@ func Getrandom(buf []byte, flags int) (n int, err error) { //sysnb Kill(pid int, sig syscall.Signal) (err error) //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG //sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error) +//sys Listns(req *NsIdReq, nsIds []uint64, flags uint) (n int, err error) //sys Listxattr(path string, dest []byte) (sz int, err error) //sys Llistxattr(path string, dest []byte) (sz int, err error) //sys Lremovexattr(path string, attr string) (err error) @@ -2046,6 +2064,7 @@ func Getrandom(buf []byte, flags int) (n int, err error) { //sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) +//sys PrctlArg5Ptr(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 unsafe.Pointer) (err error) = SYS_PRCTL //sys pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Removexattr(path string, attr string) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go index 4964119af8..cd50715c9d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go @@ -8,7 +8,7 @@ package unix //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) -//sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) @@ -19,7 +19,7 @@ package unix //sysnb Getuid() (uid int) //sys Lchown(path string, uid int, gid int) (err error) //sys Listen(s int, n int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) +//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys Pause() (err error) //sys pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 @@ -31,7 +31,7 @@ package unix //sys setfsuid(uid int) (prev int, err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) -//sys Stat(path string, stat *Stat_t) (err error) +//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go index 34a4676973..c8badc54c6 100644 --- a/vendor/golang.org/x/sys/unix/syscall_netbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_netbsd.go @@ -293,6 +293,15 @@ func Getvfsstat(buf []Statvfs_t, flags int) (n int, err error) { //sys ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) //sys ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) +//sys extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE //sys Fchdir(fd int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_unix_gc.go b/vendor/golang.org/x/sys/unix/syscall_unix_gc.go index 05c95bccfa..60c0d16cff 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix_gc.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix_gc.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build (darwin || dragonfly || freebsd || (linux && !ppc64 && !ppc64le) || netbsd || openbsd || solaris) && gc +//go:build (darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris) && gc package unix diff --git a/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go b/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go deleted file mode 100644 index 23f39b7af7..0000000000 --- a/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go +++ /dev/null @@ -1,22 +0,0 @@ -// 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. - -//go:build linux && (ppc64le || ppc64) && gc - -package unix - -import "syscall" - -func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { - return syscall.Syscall(trap, a1, a2, a3) -} -func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { - return syscall.Syscall6(trap, a1, a2, a3, a4, a5, a6) -} -func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { - return syscall.RawSyscall(trap, a1, a2, a3) -} -func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { - return syscall.RawSyscall6(trap, a1, a2, a3, a4, a5, a6) -} diff --git a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index 7bf5c04bb0..edabb6892a 100644 --- a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -27,14 +27,10 @@ import ( "unsafe" ) -//go:noescape -func initZosLibVec() - //go:noescape func GetZosLibVec() uintptr func init() { - initZosLibVec() r0, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS_____GETENV_A<<4, uintptr(unsafe.Pointer(&([]byte("__ZOS_XSYSTRACE\x00"))[0]))) if r0 != 0 { n, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___ATOI_A<<4, r0) diff --git a/vendor/golang.org/x/sys/unix/xattr_bsd.go b/vendor/golang.org/x/sys/unix/xattr_bsd.go index e168793961..d3d12c27c1 100644 --- a/vendor/golang.org/x/sys/unix/xattr_bsd.go +++ b/vendor/golang.org/x/sys/unix/xattr_bsd.go @@ -56,7 +56,7 @@ func Getxattr(file string, attr string, dest []byte) (sz int, err error) { return -1, err } - return ExtattrGetFile(file, nsid, a, uintptr(d), destsize) + return extattrGetFile(file, nsid, a, d, destsize) } func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { @@ -68,7 +68,7 @@ func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { return -1, err } - return ExtattrGetFd(fd, nsid, a, uintptr(d), destsize) + return extattrGetFd(fd, nsid, a, d, destsize) } func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { @@ -80,7 +80,7 @@ func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { return -1, err } - return ExtattrGetLink(link, nsid, a, uintptr(d), destsize) + return extattrGetLink(link, nsid, a, d, destsize) } // flags are unused on FreeBSD @@ -97,7 +97,7 @@ func Fsetxattr(fd int, attr string, data []byte, flags int) (err error) { return } - _, err = ExtattrSetFd(fd, nsid, a, uintptr(d), datasiz) + _, err = extattrSetFd(fd, nsid, a, d, datasiz) return } @@ -113,7 +113,7 @@ func Setxattr(file string, attr string, data []byte, flags int) (err error) { return } - _, err = ExtattrSetFile(file, nsid, a, uintptr(d), datasiz) + _, err = extattrSetFile(file, nsid, a, d, datasiz) return } @@ -129,7 +129,7 @@ func Lsetxattr(link string, attr string, data []byte, flags int) (err error) { return } - _, err = ExtattrSetLink(link, nsid, a, uintptr(d), datasiz) + _, err = extattrSetLink(link, nsid, a, d, datasiz) return } @@ -199,9 +199,9 @@ func ListxattrNS(file string, nsid int, dest []byte) (sz int, err error) { d := initxattrdest(dest, 0) destsiz := len(dest) - s, e := ExtattrListFile(file, nsid, uintptr(d), destsiz) + s, e := extattrListFile(file, nsid, d, destsiz) if e != nil { - return 0, err + return 0, e } return s, nil @@ -235,9 +235,9 @@ func FlistxattrNS(fd int, nsid int, dest []byte) (sz int, err error) { d := initxattrdest(dest, 0) destsiz := len(dest) - s, e := ExtattrListFd(fd, nsid, uintptr(d), destsiz) + s, e := extattrListFd(fd, nsid, d, destsiz) if e != nil { - return 0, err + return 0, e } return s, nil @@ -271,9 +271,9 @@ func LlistxattrNS(link string, nsid int, dest []byte) (sz int, err error) { d := initxattrdest(dest, 0) destsiz := len(dest) - s, e := ExtattrListLink(link, nsid, uintptr(d), destsiz) + s, e := extattrListLink(link, nsid, d, destsiz) if e != nil { - return 0, err + return 0, e } return s, nil diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go index d73c4652e6..01a3953320 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go @@ -1128,6 +1128,7 @@ const ( O_DSYNC = 0x400000 O_EVTONLY = 0x8000 O_EXCL = 0x800 + O_EXEC = 0x40000000 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 @@ -1138,6 +1139,7 @@ const ( O_POPUP = 0x80000000 O_RDONLY = 0x0 O_RDWR = 0x2 + O_SEARCH = 0x40100000 O_SHLOCK = 0x10 O_SYMLINK = 0x200000 O_SYNC = 0x80 @@ -1147,6 +1149,10 @@ const ( PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 + PRIO_DARWIN_BG = 0x1000 + PRIO_DARWIN_NONUI = 0x1001 + PRIO_DARWIN_PROCESS = 0x4 + PRIO_DARWIN_THREAD = 0x3 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go index 4a55a40058..d80b95f6bf 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go @@ -1128,6 +1128,7 @@ const ( O_DSYNC = 0x400000 O_EVTONLY = 0x8000 O_EXCL = 0x800 + O_EXEC = 0x40000000 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 @@ -1138,6 +1139,7 @@ const ( O_POPUP = 0x80000000 O_RDONLY = 0x0 O_RDWR = 0x2 + O_SEARCH = 0x40100000 O_SHLOCK = 0x10 O_SYMLINK = 0x200000 O_SYNC = 0x80 @@ -1147,6 +1149,10 @@ const ( PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 + PRIO_DARWIN_BG = 0x1000 + PRIO_DARWIN_NONUI = 0x1001 + PRIO_DARWIN_PROCESS = 0x4 + PRIO_DARWIN_THREAD = 0x3 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 45feb12453..aa68cb8d00 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -752,10 +752,12 @@ const ( CLONE_ARGS_SIZE_VER0 = 0x40 CLONE_ARGS_SIZE_VER1 = 0x50 CLONE_ARGS_SIZE_VER2 = 0x58 + CLONE_AUTOREAP = 0x400000000 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_CLEAR_SIGHAND = 0x100000000 CLONE_DETACHED = 0x400000 + CLONE_EMPTY_MNTNS = 0x2000000000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_INTO_CGROUP = 0x200000000 @@ -768,9 +770,11 @@ const ( CLONE_NEWTIME = 0x80 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 + CLONE_NNP = 0x800000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PIDFD = 0x1000 + CLONE_PIDFD_AUTOKILL = 0x1000000000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 @@ -803,12 +807,15 @@ const ( DEVLINK_GENL_MCGRP_CONFIG_NAME = "config" DEVLINK_GENL_NAME = "devlink" DEVLINK_GENL_VERSION = 0x1 + DEVLINK_INDEX_BUS_NAME = "devlink_index" DEVLINK_PORT_FN_CAP_IPSEC_CRYPTO = 0x4 DEVLINK_PORT_FN_CAP_IPSEC_PACKET = 0x8 DEVLINK_PORT_FN_CAP_MIGRATABLE = 0x2 DEVLINK_PORT_FN_CAP_ROCE = 0x1 DEVLINK_RATE_TCS_MAX = 0x8 DEVLINK_RATE_TC_INDEX_MAX = 0x7 + DEVLINK_RESOURCE_SCOPE_DEV = 0x1 + DEVLINK_RESOURCE_SCOPE_PORT = 0x2 DEVLINK_SB_THRESHOLD_TO_ALPHA_MAX = 0x14 DEVLINK_SUPPORTED_FLASH_OVERWRITE_SECTIONS = 0x3 DEVMEM_MAGIC = 0x454d444d @@ -1127,6 +1134,7 @@ const ( ETHTOOL_SWOL = 0x6 ETHTOOL_TEST = 0x1a ETH_P_1588 = 0x88f7 + ETH_P_8021AC = 0x8870 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 @@ -1170,6 +1178,7 @@ const ( ETH_P_ETHERCAT = 0x88a4 ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 + ETH_P_GRE_OSI = 0xfe ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 @@ -1198,6 +1207,7 @@ const ( ETH_P_MXLGSW = 0x88c3 ETH_P_NCSI = 0x88f8 ETH_P_NSH = 0x894f + ETH_P_NXP_NETC = 0xfd3a ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -1359,6 +1369,7 @@ const ( FAN_UNLIMITED_MARKS = 0x20 FAN_UNLIMITED_QUEUE = 0x10 FD_CLOEXEC = 0x1 + FD_NSFS_ROOT = -0x2713 FD_PIDFS_ROOT = -0x2712 FD_SETSIZE = 0x400 FF0 = 0x0 @@ -1427,6 +1438,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x7 + FS_SHUTDOWN_FLAGS_LOGFLUSH = 0x1 + FS_SHUTDOWN_FLAGS_NOLOGFLUSH = 0x2 FS_VERITY_FL = 0x100000 FS_VERITY_HASH_ALG_SHA256 = 0x1 FS_VERITY_HASH_ALG_SHA512 = 0x2 @@ -1441,6 +1454,7 @@ const ( F_DUPFD_CLOEXEC = 0x406 F_DUPFD_QUERY = 0x403 F_EXLCK = 0x4 + F_GETDELEG = 0x40f F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 @@ -1462,6 +1476,7 @@ const ( F_SEAL_SEAL = 0x1 F_SEAL_SHRINK = 0x2 F_SEAL_WRITE = 0x8 + F_SETDELEG = 0x410 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -1632,6 +1647,7 @@ const ( IN_UNMOUNT = 0x2000 IOCTL_MEI_CONNECT_CLIENT = 0xc0104801 IOCTL_MEI_CONNECT_CLIENT_VTAG = 0xc0144804 + IPPROTO_AGGFRAG = 0x90 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c @@ -1913,10 +1929,14 @@ const ( LANDLOCK_ACCESS_FS_REFER = 0x2000 LANDLOCK_ACCESS_FS_REMOVE_DIR = 0x10 LANDLOCK_ACCESS_FS_REMOVE_FILE = 0x20 + LANDLOCK_ACCESS_FS_RESOLVE_UNIX = 0x10000 LANDLOCK_ACCESS_FS_TRUNCATE = 0x4000 LANDLOCK_ACCESS_FS_WRITE_FILE = 0x2 LANDLOCK_ACCESS_NET_BIND_TCP = 0x1 + LANDLOCK_ACCESS_NET_BIND_UDP = 0x4 + LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP = 0x8 LANDLOCK_ACCESS_NET_CONNECT_TCP = 0x2 + LANDLOCK_ADD_RULE_QUIET = 0x1 LANDLOCK_CREATE_RULESET_ERRATA = 0x2 LANDLOCK_CREATE_RULESET_VERSION = 0x1 LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON = 0x2 @@ -3408,6 +3428,7 @@ const ( SCHED_FLAG_UTIL_CLAMP = 0x60 SCHED_FLAG_UTIL_CLAMP_MAX = 0x40 SCHED_FLAG_UTIL_CLAMP_MIN = 0x20 + SCHED_GETATTR_FLAG_DL_DYNAMIC = 0x1 SCHED_IDLE = 0x5 SCHED_NORMAL = 0x0 SCHED_RESET_ON_FORK = 0x40000000 @@ -3790,6 +3811,14 @@ const ( TCPOPT_TIMESTAMP = 0x8 TCPOPT_TSTAMP_HDR = 0x101080a TCPOPT_WINDOW = 0x3 + TCP_ACCECN_ACE_FAIL_RECV = 0x2 + TCP_ACCECN_ACE_FAIL_SEND = 0x1 + TCP_ACCECN_OPT_COUNTER_SEEN = 0x2 + TCP_ACCECN_OPT_EMPTY_SEEN = 0x1 + TCP_ACCECN_OPT_FAIL_RECV = 0x8 + TCP_ACCECN_OPT_FAIL_SEEN = 0x3 + TCP_ACCECN_OPT_FAIL_SEND = 0x4 + TCP_ACCECN_OPT_NOT_SEEN = 0x0 TCP_AO_KEYF_EXCLUDE_OPT = 0x2 TCP_AO_KEYF_IFINDEX = 0x1 TCP_AO_MAXKEYLEN = 0x50 @@ -3804,6 +3833,7 @@ const ( TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 + TCP_DELACK_MAX_US = 0x2e TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_FASTOPEN_KEY = 0x21 @@ -3836,6 +3866,8 @@ const ( TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d + TCP_RTO_MAX_MS = 0x2c + TCP_RTO_MIN_US = 0x2d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 6f74d4a0cf..5aaf4bc7a2 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -600,6 +600,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -840,6 +841,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index 36c1f0b68c..b8e6287a1c 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -600,6 +600,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -840,6 +841,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index c5512dbea6..464f821890 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -605,6 +605,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -845,6 +846,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 4dabfae071..735265b626 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -602,6 +602,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -842,6 +843,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index ea97930f1f..1970ce826a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -592,6 +592,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -832,6 +833,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index 0826a929e0..56de9aeb29 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -601,6 +601,7 @@ const ( EDQUOT = syscall.Errno(0x46d) EFSBADCRC = syscall.Errno(0x4d) EFSCORRUPTED = syscall.Errno(0x87) + EFTYPE = syscall.Errno(0xa9) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) @@ -845,6 +846,7 @@ var errorList = [...]struct { {166, "ENOTRECOVERABLE", "state not recoverable"}, {167, "ERFKILL", "operation not possible due to RF-kill"}, {168, "EHWPOISON", "memory page has hardware error"}, + {169, "EFTYPE", "unknown error 169"}, {1133, "EDQUOT", "disk quota exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index 139deedd95..26ca1caca3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -601,6 +601,7 @@ const ( EDQUOT = syscall.Errno(0x46d) EFSBADCRC = syscall.Errno(0x4d) EFSCORRUPTED = syscall.Errno(0x87) + EFTYPE = syscall.Errno(0xa9) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) @@ -845,6 +846,7 @@ var errorList = [...]struct { {166, "ENOTRECOVERABLE", "state not recoverable"}, {167, "ERFKILL", "operation not possible due to RF-kill"}, {168, "EHWPOISON", "memory page has hardware error"}, + {169, "EFTYPE", "unknown error 169"}, {1133, "EDQUOT", "disk quota exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index b8018af335..b19df2348c 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -601,6 +601,7 @@ const ( EDQUOT = syscall.Errno(0x46d) EFSBADCRC = syscall.Errno(0x4d) EFSCORRUPTED = syscall.Errno(0x87) + EFTYPE = syscall.Errno(0xa9) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) @@ -845,6 +846,7 @@ var errorList = [...]struct { {166, "ENOTRECOVERABLE", "state not recoverable"}, {167, "ERFKILL", "operation not possible due to RF-kill"}, {168, "EHWPOISON", "memory page has hardware error"}, + {169, "EFTYPE", "unknown error 169"}, {1133, "EDQUOT", "disk quota exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index deb5c2e6a9..9ba3c95099 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -601,6 +601,7 @@ const ( EDQUOT = syscall.Errno(0x46d) EFSBADCRC = syscall.Errno(0x4d) EFSCORRUPTED = syscall.Errno(0x87) + EFTYPE = syscall.Errno(0xa9) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) @@ -845,6 +846,7 @@ var errorList = [...]struct { {166, "ENOTRECOVERABLE", "state not recoverable"}, {167, "ERFKILL", "operation not possible due to RF-kill"}, {168, "EHWPOISON", "memory page has hardware error"}, + {169, "EFTYPE", "unknown error 169"}, {1133, "EDQUOT", "disk quota exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index 0603bf3a1a..62da59f96a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -657,6 +657,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -898,6 +899,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 5fa8a5d367..d18d4daed4 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -661,6 +661,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -902,6 +903,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 2733e99934..ba7767db53 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -661,6 +661,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -902,6 +903,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index 1470172fd9..76cb221111 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -602,6 +602,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -842,6 +843,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 1871579c5c..ffd12a97fc 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -661,6 +661,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -901,6 +902,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 10881cf6d3..f372aed328 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -704,6 +704,7 @@ const ( EDQUOT = syscall.Errno(0x45) EFSBADCRC = syscall.Errno(0x4c) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x88) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EHWPOISON = syscall.Errno(0x87) @@ -950,6 +951,7 @@ var errorList = [...]struct { {133, "ENOTRECOVERABLE", "state not recoverable"}, {134, "ERFKILL", "operation not possible due to RF-kill"}, {135, "EHWPOISON", "memory page has hardware error"}, + {136, "EFTYPE", "unknown error 136"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go index 813c05b664..7db9bf5f29 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -702,6 +702,17 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func kill(pid int, signum int, posix int) (err error) { _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go index e6f58f3c6f..2a658059df 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -702,6 +702,17 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func kill(pid int, signum int, posix int) (err error) { _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go index c0096391af..10b57ffb9c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go index 7664df7496..6a6fc3cc4b 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go index ae099182c9..4a15b4abf0 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go index 11fd5d45bb..f15331fb4c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go index c3d2d65307..faa562642e 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index 5788c2a58d..4c63b976be 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -943,7 +943,7 @@ func fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getdents(fd int, buf []byte) (n int, err error) { +func getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) @@ -1167,6 +1167,23 @@ func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Listns(req *NsIdReq, nsIds []uint64, flags uint) (n int, err error) { + var _p0 unsafe.Pointer + if len(nsIds) > 0 { + _p0 = unsafe.Pointer(&nsIds[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_LISTNS, uintptr(unsafe.Pointer(req)), uintptr(_p0), uintptr(len(nsIds)), uintptr(flags), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -1390,6 +1407,16 @@ func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PrctlArg5Ptr(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 unsafe.Pointer) (err error) { + _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go index 527637623d..b7aca54590 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go @@ -66,7 +66,7 @@ func Fchown(fd int, uid int, gid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } @@ -183,7 +183,7 @@ func Lstat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } @@ -338,7 +338,7 @@ func Stat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go index e91ebc14a1..1e136d12b6 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go @@ -802,6 +802,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go index be28babbcd..440db6ec58 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go @@ -802,6 +802,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go index fb587e8261..db963000e9 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go @@ -802,6 +802,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go index d576438bb0..c4bea6c89f 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go @@ -802,6 +802,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go index 5e8c263ca9..f09f844788 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go @@ -2848,5 +2848,18 @@ const ( SYS_____CHATTRAT64_A = 0xE39 // 3641 SYS_MADVISE = 0xE3A // 3642 SYS___AUTHENTICATE = 0xE3B // 3643 + SYS_GETPWENT_R = 0xE3C // 3644 + SYS___GETPWENT_R_A = 0xE3D // 3645 + SYS_STRNLEN = 0xE3E // 3646 + SYS_STPCPY = 0xE3F // 3647 + SYS_STPNCPY = 0xE40 // 3648 + SYS_STRSIGNAL = 0xE41 // 3649 + SYS_WCPCPY = 0xE42 // 3650 + SYS_WCPNCPY = 0xE43 // 3651 + SYS_WCSNLEN = 0xE44 // 3652 + SYS___STRSIGNAL_A = 0xE45 // 3653 + SYS_FDOPENDIR = 0xE46 // 3654 + SYS_FDCLOSEDIR = 0xE47 // 3655 + SYS_SYSCALL = 0xE48 // 3656 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 538a18f27c..2b3c00b9d8 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -933,6 +933,29 @@ type OpenHow struct { const SizeofOpenHow = 0x18 +type NsIdReq struct { + Size uint32 + Spare uint32 + Ns_id uint64 + Ns_type uint32 + Spare2 uint32 + User_ns_id uint64 +} + +const ( + NS_ID_REQ_SIZE_VER0 = 0x20 + LISTNS_CURRENT_USER = 0xffffffffffffffff + + TIME_NS = 0x80 + MNT_NS = 0x20000 + CGROUP_NS = 0x2000000 + UTS_NS = 0x4000000 + IPC_NS = 0x8000000 + USER_NS = 0x10000000 + PID_NS = 0x20000000 + NET_NS = 0x40000000 +) + const ( RESOLVE_BENEATH = 0x8 RESOLVE_IN_ROOT = 0x10 @@ -3579,7 +3602,7 @@ const ( DEVLINK_ATTR_LINECARD_SUPPORTED_TYPES = 0xae DEVLINK_ATTR_NESTED_DEVLINK = 0xaf DEVLINK_ATTR_SELFTESTS = 0xb0 - DEVLINK_ATTR_MAX = 0xb7 + DEVLINK_ATTR_MAX = 0xb9 DEVLINK_DPIPE_FIELD_MAPPING_TYPE_NONE = 0x0 DEVLINK_DPIPE_FIELD_MAPPING_TYPE_IFINDEX = 0x1 DEVLINK_DPIPE_MATCH_TYPE_FIELD_EXACT = 0x0 @@ -4101,7 +4124,7 @@ const ( ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL = 0x17 ETHTOOL_A_COALESCE_USE_CQE_MODE_TX = 0x18 ETHTOOL_A_COALESCE_USE_CQE_MODE_RX = 0x19 - ETHTOOL_A_COALESCE_MAX = 0x1e + ETHTOOL_A_COALESCE_MAX = 0x20 ETHTOOL_A_PAUSE_UNSPEC = 0x0 ETHTOOL_A_PAUSE_HEADER = 0x1 ETHTOOL_A_PAUSE_AUTONEG = 0x2 @@ -4113,7 +4136,7 @@ const ( ETHTOOL_A_PAUSE_STAT_PAD = 0x1 ETHTOOL_A_PAUSE_STAT_TX_FRAMES = 0x2 ETHTOOL_A_PAUSE_STAT_RX_FRAMES = 0x3 - ETHTOOL_A_PAUSE_STAT_MAX = 0x3 + ETHTOOL_A_PAUSE_STAT_MAX = 0x4 ETHTOOL_A_EEE_UNSPEC = 0x0 ETHTOOL_A_EEE_HEADER = 0x1 ETHTOOL_A_EEE_MODES_OURS = 0x2 @@ -4537,9 +4560,12 @@ const ( ) type LandlockRulesetAttr struct { - Access_fs uint64 - Access_net uint64 - Scoped uint64 + Handled_access_fs uint64 + Handled_access_net uint64 + Scoped uint64 + Quiet_access_fs uint64 + Quiet_access_net uint64 + Quiet_scoped uint64 } type LandlockPathBeneathAttr struct { @@ -4569,28 +4595,31 @@ const ( PIDFD_COREDUMP_USER = 0x4 PIDFD_COREDUMP_ROOT = 0x8 PIDFD_INFO_SIZE_VER0 = 0x40 - PIDFD_GET_INFO = 0xc048ff0b + PIDFD_GET_INFO = 0xc058ff0b ) -const SizeofPidfdInfo = 0x48 +const SizeofPidfdInfo = 0x58 type PidfdInfo struct { - Mask uint64 - Cgroupid uint64 - Pid uint32 - Tgid uint32 - Ppid uint32 - Ruid uint32 - Rgid uint32 - Euid uint32 - Egid uint32 - Suid uint32 - Sgid uint32 - Fsuid uint32 - Fsgid uint32 - Exit_code int32 - Coredump_mask uint32 - _ uint32 + Mask uint64 + Cgroupid uint64 + Pid uint32 + Tgid uint32 + Ppid uint32 + Ruid uint32 + Rgid uint32 + Euid uint32 + Egid uint32 + Suid uint32 + Sgid uint32 + Fsuid uint32 + Fsgid uint32 + Exit_code int32 + Coredump_mask uint32 + Coredump_signal uint32 + Coredump_code uint32 + Coredump_pad uint32 + Supported_mask uint64 } const ( @@ -4932,7 +4961,7 @@ const ( NL80211_ATTR_MAC_HINT = 0xc8 NL80211_ATTR_MAC_MASK = 0xd7 NL80211_ATTR_MAX_AP_ASSOC_STA = 0xca - NL80211_ATTR_MAX = 0x15c + NL80211_ATTR_MAX = 0x16e NL80211_ATTR_MAX_CRIT_PROT_DURATION = 0xb4 NL80211_ATTR_MAX_CSA_COUNTERS = 0xce NL80211_ATTR_MAX_HW_TIMESTAMP_PEERS = 0x143 @@ -5147,12 +5176,12 @@ const ( NL80211_ATTR_WOWLAN_TRIGGERS = 0x75 NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED = 0x76 NL80211_ATTR_WPA_VERSIONS = 0x4b - NL80211_AUTHTYPE_AUTOMATIC = 0x9 + NL80211_AUTHTYPE_AUTOMATIC = 0xa NL80211_AUTHTYPE_FILS_PK = 0x7 NL80211_AUTHTYPE_FILS_SK = 0x5 NL80211_AUTHTYPE_FILS_SK_PFS = 0x6 NL80211_AUTHTYPE_FT = 0x2 - NL80211_AUTHTYPE_MAX = 0x8 + NL80211_AUTHTYPE_MAX = 0x9 NL80211_AUTHTYPE_NETWORK_EAP = 0x3 NL80211_AUTHTYPE_OPEN_SYSTEM = 0x0 NL80211_AUTHTYPE_SAE = 0x4 @@ -5320,7 +5349,7 @@ const ( NL80211_CMD_LEAVE_MESH = 0x45 NL80211_CMD_LEAVE_OCB = 0x6d NL80211_CMD_LINKS_REMOVED = 0x9a - NL80211_CMD_MAX = 0x9f + NL80211_CMD_MAX = 0xa7 NL80211_CMD_MICHAEL_MIC_FAILURE = 0x29 NL80211_CMD_MODIFY_LINK_STA = 0x97 NL80211_CMD_NAN_MATCH = 0x78 @@ -5566,7 +5595,7 @@ const ( NL80211_FREQUENCY_ATTR_GO_CONCURRENT = 0xf NL80211_FREQUENCY_ATTR_INDOOR_ONLY = 0xe NL80211_FREQUENCY_ATTR_IR_CONCURRENT = 0xf - NL80211_FREQUENCY_ATTR_MAX = 0x27 + NL80211_FREQUENCY_ATTR_MAX = 0x29 NL80211_FREQUENCY_ATTR_MAX_TX_POWER = 0x6 NL80211_FREQUENCY_ATTR_NO_10MHZ = 0x11 NL80211_FREQUENCY_ATTR_NO_160MHZ = 0xc @@ -5639,7 +5668,7 @@ const ( NL80211_IFTYPE_AKM_ATTR_SUITES = 0x2 NL80211_IFTYPE_AP = 0x3 NL80211_IFTYPE_AP_VLAN = 0x4 - NL80211_IFTYPE_MAX = 0xc + NL80211_IFTYPE_MAX = 0xe NL80211_IFTYPE_MESH_POINT = 0x7 NL80211_IFTYPE_MONITOR = 0x6 NL80211_IFTYPE_NAN = 0xc @@ -5664,7 +5693,7 @@ const ( NL80211_KEY_DEFAULT_TYPES = 0x8 NL80211_KEY_DEFAULT_TYPE_UNICAST = 0x1 NL80211_KEY_IDX = 0x2 - NL80211_KEY_MAX = 0xa + NL80211_KEY_MAX = 0xb NL80211_KEY_MODE = 0x9 NL80211_KEY_NO_TX = 0x1 NL80211_KEY_RX_TX = 0x0 @@ -5822,7 +5851,7 @@ const ( NL80211_PMKSA_CANDIDATE_BSSID = 0x2 NL80211_PMKSA_CANDIDATE_INDEX = 0x1 NL80211_PMKSA_CANDIDATE_PREAUTH = 0x3 - NL80211_PMSR_ATTR_MAX = 0x5 + NL80211_PMSR_ATTR_MAX = 0x7 NL80211_PMSR_ATTR_MAX_PEERS = 0x1 NL80211_PMSR_ATTR_PEERS = 0x5 NL80211_PMSR_ATTR_RANDOMIZE_MAC_ADDR = 0x3 @@ -5831,7 +5860,7 @@ const ( NL80211_PMSR_FTM_CAPA_ATTR_ASAP = 0x1 NL80211_PMSR_FTM_CAPA_ATTR_BANDWIDTHS = 0x6 NL80211_PMSR_FTM_CAPA_ATTR_MAX_BURSTS_EXPONENT = 0x7 - NL80211_PMSR_FTM_CAPA_ATTR_MAX = 0x12 + NL80211_PMSR_FTM_CAPA_ATTR_MAX = 0x1f NL80211_PMSR_FTM_CAPA_ATTR_MAX_FTMS_PER_BURST = 0x8 NL80211_PMSR_FTM_CAPA_ATTR_NON_ASAP = 0x2 NL80211_PMSR_FTM_CAPA_ATTR_NON_TRIGGER_BASED = 0xa @@ -5853,7 +5882,7 @@ const ( NL80211_PMSR_FTM_REQ_ATTR_BURST_PERIOD = 0x4 NL80211_PMSR_FTM_REQ_ATTR_FTMS_PER_BURST = 0x6 NL80211_PMSR_FTM_REQ_ATTR_LMR_FEEDBACK = 0xc - NL80211_PMSR_FTM_REQ_ATTR_MAX = 0xe + NL80211_PMSR_FTM_REQ_ATTR_MAX = 0x17 NL80211_PMSR_FTM_REQ_ATTR_NON_TRIGGER_BASED = 0xb NL80211_PMSR_FTM_REQ_ATTR_NUM_BURSTS_EXP = 0x3 NL80211_PMSR_FTM_REQ_ATTR_NUM_FTMR_RETRIES = 0x7 @@ -5871,7 +5900,7 @@ const ( NL80211_PMSR_FTM_RESP_ATTR_FAIL_REASON = 0x1 NL80211_PMSR_FTM_RESP_ATTR_FTMS_PER_BURST = 0x8 NL80211_PMSR_FTM_RESP_ATTR_LCI = 0x13 - NL80211_PMSR_FTM_RESP_ATTR_MAX = 0x16 + NL80211_PMSR_FTM_RESP_ATTR_MAX = 0x21 NL80211_PMSR_FTM_RESP_ATTR_NUM_BURSTS_EXP = 0x6 NL80211_PMSR_FTM_RESP_ATTR_NUM_FTMR_ATTEMPTS = 0x3 NL80211_PMSR_FTM_RESP_ATTR_NUM_FTMR_SUCCESSES = 0x4 @@ -5885,7 +5914,7 @@ const ( NL80211_PMSR_FTM_RESP_ATTR_TX_RATE = 0xb NL80211_PMSR_PEER_ATTR_ADDR = 0x1 NL80211_PMSR_PEER_ATTR_CHAN = 0x2 - NL80211_PMSR_PEER_ATTR_MAX = 0x4 + NL80211_PMSR_PEER_ATTR_MAX = 0x5 NL80211_PMSR_PEER_ATTR_REQ = 0x3 NL80211_PMSR_PEER_ATTR_RESP = 0x4 NL80211_PMSR_REQ_ATTR_DATA = 0x1 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go index 38658a345b..c7ec66dc94 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -163,6 +163,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -178,6 +183,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go index 267ffe05f3..abe072e897 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -166,6 +166,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -181,6 +187,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go index ec459d5f3f..4ba7cea03e 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -169,6 +169,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -184,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go index fa45ab7d2c..3f55ca4afc 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go index 3da72ccdf8..445b2a2e97 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go index 78f8c6d555..6a52e254fc 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -168,6 +168,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -183,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go index bbd4c6c2b9..fafd89de21 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go index 644d31d6ae..5fb6f4cf8c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go index a976f62676..a50187bcec 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -168,6 +168,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -183,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go index 46324695f6..777b0228fe 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go @@ -169,6 +169,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -184,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go index cbc303974f..48a6a5ac38 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -168,6 +168,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -183,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go index b47f7b4984..1972c0125e 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -168,6 +168,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -183,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go index cb16add54c..87572ee086 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go index a57ab8fadd..f6a33e6803 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -166,6 +166,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -181,6 +187,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go index bf99635d8a..8b72614580 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go @@ -84,22 +84,20 @@ type Rusage struct { type Stat_t struct { Dev uint64 - _ uint16 Ino uint64 + Nlink uint64 Mode uint32 - Nlink uint32 Uid uint32 Gid uint32 + _ uint32 Rdev uint64 - _ uint16 Size int64 Blksize int64 Blocks int64 Atim Timespec Mtim Timespec Ctim Timespec - _ uint64 - _ uint64 + _ [3]int64 } type Dirent struct { @@ -170,6 +168,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -185,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go index 2e5d5a4435..80d4c9535c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go @@ -209,6 +209,84 @@ type TCPInfo struct { Total_retrans uint32 } +// Ptrace structures for z/OS + +type PtraceRegs struct { + Psw PtracePsw + Gprs [16]uint64 + Acrs [16]uint32 + Orig_gpr2 uint64 + Fp_regs PtraceFpregs + Per_info PtracePer + Ieee_instruction_pointer uint64 +} + +type PtracePsw struct { + Mask uint64 + Addr uint64 +} + +type PtraceFpregs struct { + Fpc uint32 + Fprs [16]float64 +} + +type PtracePer struct { + Control_regs [3]uint64 + _ [8]byte + Starting_addr uint64 + Ending_addr uint64 + Perc_atmid uint16 + Address uint64 + Access_id uint8 + _ [7]byte +} + +// PT_BLOCKREQ structures for block ptrace requests +// Layout matches BPXYPTRC HLASM macro (PtBR_GPR + PtBR_GPR_EXT): +// +// Offset 0-1: Writebitflags (PtBR_GPR_CntlGPR, 2 bytes) +// Offset 2-3: Wpsw (PtBR_GPR_CntlMisc, 2 bytes with WPSW bit flag) +// Offset 4-15: Reserved (12 bytes) +// Offset 16-79: Gpr (64 bytes, 16 GPRs) +// Offset 80-143: Ctl (64 bytes, 16 CRs) +// Offset 144-151: Psw old format (8 bytes, PtBR_GPR_PSW) +// Offset 152-167: Pswg extended (16 bytes, PtBR_GPR_PSWG for 64-bit) +// Total: 168 bytes (base 152 + extended 16) +type PtraceBlkGpr struct { + Writebitflags uint16 // 2 bytes at offset 0 (PtBR_GPR_CntlGPR) + Wpsw uint16 // 2 bytes at offset 2 (PtBR_GPR_CntlMisc with WPSW flag) + _ [12]byte // 12 bytes reserved (offset 4-15) + Gpr [16]uint32 // 64 bytes at offset 16 (GPRs) + Ctl [16]uint32 // 64 bytes at offset 80 (CRs) + Psw [8]byte // 8 bytes at offset 144 (old PSW format) + Pswg [16]byte // 16 bytes at offset 152 (extended PSWG) + // Total: 2+2+12+64+64+8+16 = 168 bytes +} + +type PtraceBlkReqReq struct { + Reqtype int32 + Reqstat int32 + Reqdata uint32 + _ [4]byte +} + +type PtraceBlkReq struct { + Numreq int32 + _ [12]byte +} + +// PT_READ_U structures for reading user area (control info) +type PtraceBlkUarOcw struct { + Ofs uint32 // Control information offset + Ctl uint32 // Control information +} + +type PtraceBlkUar struct { + Num uint32 // Number of entries + _ [4]byte +} + type _Gid_t uint32 type rusage_zos struct { diff --git a/vendor/golang.org/x/sys/windows/types_windows_arm.go b/vendor/golang.org/x/sys/windows/types_windows_arm.go deleted file mode 100644 index 321872c3e0..0000000000 --- a/vendor/golang.org/x/sys/windows/types_windows_arm.go +++ /dev/null @@ -1,35 +0,0 @@ -// 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 windows - -type WSAData struct { - Version uint16 - HighVersion uint16 - Description [WSADESCRIPTION_LEN + 1]byte - SystemStatus [WSASYS_STATUS_LEN + 1]byte - MaxSockets uint16 - MaxUdpDg uint16 - VendorInfo *byte -} - -type Servent struct { - Name *byte - Aliases **byte - Port uint16 - Proto *byte -} - -type JOBOBJECT_BASIC_LIMIT_INFORMATION struct { - PerProcessUserTimeLimit int64 - PerJobUserTimeLimit int64 - LimitFlags uint32 - MinimumWorkingSetSize uintptr - MaximumWorkingSetSize uintptr - ActiveProcessLimit uint32 - Affinity uintptr - PriorityClass uint32 - SchedulingClass uint32 - _ uint32 // pad to 8 byte boundary -} diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule.go b/vendor/golang.org/x/text/secure/bidirule/bidirule.go index 5386327308..399cb89697 100644 --- a/vendor/golang.org/x/text/secure/bidirule/bidirule.go +++ b/vendor/golang.org/x/text/secure/bidirule/bidirule.go @@ -10,6 +10,7 @@ package bidirule import ( "errors" + "sync" "unicode/utf8" "golang.org/x/text/transform" @@ -246,8 +247,9 @@ func (t *Transformer) Span(src []byte, atEOF bool) (n int, err error) { // Precomputing the ASCII values decreases running time for the ASCII fast path // by about 30%. var asciiTable [128]bidi.Properties +var asciiTableOnce sync.Once -func init() { +func initASCIITable() { for i := range asciiTable { p, _ := bidi.LookupRune(rune(i)) asciiTable[i] = p @@ -255,6 +257,8 @@ func init() { } func (t *Transformer) advance(s []byte) (n int, ok bool) { + asciiTableOnce.Do(initASCIITable) + var e bidi.Properties var sz int for n < len(s) { @@ -297,6 +301,8 @@ func (t *Transformer) advance(s []byte) (n int, ok bool) { } func (t *Transformer) advanceString(s string) (n int, ok bool) { + asciiTableOnce.Do(initASCIITable) + var e bidi.Properties var sz int for n < len(s) { diff --git a/vendor/golang.org/x/text/unicode/bidi/core.go b/vendor/golang.org/x/text/unicode/bidi/core.go index e28ac8c8aa..fe5a46ffe1 100644 --- a/vendor/golang.org/x/text/unicode/bidi/core.go +++ b/vendor/golang.org/x/text/unicode/bidi/core.go @@ -208,27 +208,23 @@ func (p *paragraph) determineMatchingIsolates() { p.matchingIsolateInitiator[i] = -1 } + var open []int for i := range p.matchingPDI { p.matchingPDI[i] = -1 - if t := p.resultTypes[i]; t.in(LRI, RLI, FSI) { - depthCounter := 1 - for j := i + 1; j < p.Len(); j++ { - if u := p.resultTypes[j]; u.in(LRI, RLI, FSI) { - depthCounter++ - } else if u == PDI { - if depthCounter--; depthCounter == 0 { - p.matchingPDI[i] = j - p.matchingIsolateInitiator[j] = i - break - } - } - } - if p.matchingPDI[i] == -1 { - p.matchingPDI[i] = p.Len() - } + switch t := p.resultTypes[i]; { + case t.in(LRI, RLI, FSI): + open = append(open, i) + case t == PDI && len(open) > 0: + j := open[len(open)-1] + open = open[:len(open)-1] + p.matchingPDI[j] = i + p.matchingIsolateInitiator[i] = j } } + for _, i := range open { + p.matchingPDI[i] = p.Len() + } } // determineParagraphEmbeddingLevel reports the resolved paragraph direction of @@ -496,16 +492,13 @@ func (s *isolatingRunSequence) resolveWeakTypes() { // Rule W2. // EN does not change at the start of the run, because sos != AL. + lastStrong := unknownClass for i, t := range s.types { - if t == EN { - for j := i - 1; j >= 0; j-- { - if t := s.types[j]; t.in(L, R, AL) { - if t == AL { - s.types[i] = AN - } - break - } - } + switch { + case t.in(L, R, AL): + lastStrong = t + case t == EN && lastStrong == AL: + s.types[i] = AN } } @@ -543,29 +536,30 @@ func (s *isolatingRunSequence) resolveWeakTypes() { } // Rule W5. - for i, t := range s.types { - if t == ET { - // locate end of sequence - runStart := i - runEnd := s.findRunLimit(runStart, ET) - - // check values at ends of sequence - t := s.sos - if runStart > 0 { - t = s.types[runStart-1] - } - if t != EN { - t = s.eos - if runEnd < len(s.types) { - t = s.types[runEnd] - } - } - if t == EN { - setTypes(s.types[runStart:runEnd], EN) + for i := 0; i < len(s.types); i++ { + if s.types[i] != ET { + continue + } + // locate end of sequence + runStart := i + runEnd := s.findRunLimit(runStart, ET) + + // check values at ends of sequence + t := s.sos + if runStart > 0 { + t = s.types[runStart-1] + } + if t != EN { + t = s.eos + if runEnd < len(s.types) { + t = s.types[runEnd] } - // continue at end of sequence - i = runEnd } + if t == EN { + setTypes(s.types[runStart:runEnd], EN) + } + // continue at end of sequence + i = runEnd } // Rule W6. @@ -576,20 +570,13 @@ func (s *isolatingRunSequence) resolveWeakTypes() { } // Rule W7. + prevStrongType := s.sos for i, t := range s.types { - if t == EN { - // set default if we reach start of run - prevStrongType := s.sos - for j := i - 1; j >= 0; j-- { - t = s.types[j] - if t == L || t == R { // AL's have been changed to R - prevStrongType = t - break - } - } - if prevStrongType == L { - s.types[i] = L - } + switch { + case t == L || t == R: // AL's have been changed to R + prevStrongType = t + case t == EN && prevStrongType == L: + s.types[i] = L } } } diff --git a/vendor/google.golang.org/api/iamcredentials/v1/iamcredentials-api.json b/vendor/google.golang.org/api/iamcredentials/v1/iamcredentials-api.json index 3694e4aebb..610501f1ea 100644 --- a/vendor/google.golang.org/api/iamcredentials/v1/iamcredentials-api.json +++ b/vendor/google.golang.org/api/iamcredentials/v1/iamcredentials-api.json @@ -151,7 +151,7 @@ ], "parameters": { "name": { - "description": "Required. Resource name of workforce pool.", + "description": "Required. Resource name of workforce pool. Format: `locations/global/workforcePools/{pool_id}`", "location": "path", "pattern": "^locations/[^/]+/workforcePools/[^/]+$", "required": true, @@ -183,7 +183,7 @@ ], "parameters": { "name": { - "description": "Required. Resource name of workload identity pool.", + "description": "Required. Resource name of workload identity pool. Format: `projects/{project_number}/locations/global/workloadIdentityPools/{pool_id}`", "location": "path", "pattern": "^projects/[^/]+/locations/[^/]+/workloadIdentityPools/[^/]+$", "required": true, @@ -267,7 +267,7 @@ ], "parameters": { "name": { - "description": "Required. Resource name of service account.", + "description": "Required. Resource name of service account. Format: `projects/-/serviceAccounts/{service_account_email}`", "location": "path", "pattern": "^projects/[^/]+/serviceAccounts/[^/]+$", "required": true, @@ -340,7 +340,7 @@ } } }, - "revision": "20251022", + "revision": "20260326", "rootUrl": "https://iamcredentials.googleapis.com/", "schemas": { "GenerateAccessTokenRequest": { diff --git a/vendor/google.golang.org/api/iamcredentials/v1/iamcredentials-gen.go b/vendor/google.golang.org/api/iamcredentials/v1/iamcredentials-gen.go index e9885ea2a4..95826774a7 100644 --- a/vendor/google.golang.org/api/iamcredentials/v1/iamcredentials-gen.go +++ b/vendor/google.golang.org/api/iamcredentials/v1/iamcredentials-gen.go @@ -609,7 +609,8 @@ type LocationsWorkforcePoolsGetAllowedLocationsCall struct { // GetAllowedLocations: Returns the trust boundary info for a given workforce // pool. // -// - name: Resource name of workforce pool. +// - name: Resource name of workforce pool. Format: +// `locations/global/workforcePools/{pool_id}`. func (r *LocationsWorkforcePoolsService) GetAllowedLocations(name string) *LocationsWorkforcePoolsGetAllowedLocationsCall { c := &LocationsWorkforcePoolsGetAllowedLocationsCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name @@ -720,7 +721,9 @@ type ProjectsLocationsWorkloadIdentityPoolsGetAllowedLocationsCall struct { // GetAllowedLocations: Returns the trust boundary info for a given workload // identity pool. // -// - name: Resource name of workload identity pool. +// - name: Resource name of workload identity pool. Format: +// `projects/{project_number}/locations/global/workloadIdentityPools/{pool_id} +// `. func (r *ProjectsLocationsWorkloadIdentityPoolsService) GetAllowedLocations(name string) *ProjectsLocationsWorkloadIdentityPoolsGetAllowedLocationsCall { c := &ProjectsLocationsWorkloadIdentityPoolsGetAllowedLocationsCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name @@ -1046,7 +1049,8 @@ type ProjectsServiceAccountsGetAllowedLocationsCall struct { // GetAllowedLocations: Returns the trust boundary info for a given service // account. // -// - name: Resource name of service account. +// - name: Resource name of service account. Format: +// `projects/-/serviceAccounts/{service_account_email}`. func (r *ProjectsServiceAccountsService) GetAllowedLocations(name string) *ProjectsServiceAccountsGetAllowedLocationsCall { c := &ProjectsServiceAccountsGetAllowedLocationsCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name diff --git a/vendor/google.golang.org/api/internal/version.go b/vendor/google.golang.org/api/internal/version.go index 1eef8553bc..5b40f19265 100644 --- a/vendor/google.golang.org/api/internal/version.go +++ b/vendor/google.golang.org/api/internal/version.go @@ -5,4 +5,4 @@ package internal // Version is the current tagged release of the library. -const Version = "0.274.0" +const Version = "0.278.0" diff --git a/vendor/google.golang.org/api/servicenetworking/v1/servicenetworking-api.json b/vendor/google.golang.org/api/servicenetworking/v1/servicenetworking-api.json index fa7ed39d39..1e70588858 100644 --- a/vendor/google.golang.org/api/servicenetworking/v1/servicenetworking-api.json +++ b/vendor/google.golang.org/api/servicenetworking/v1/servicenetworking-api.json @@ -1034,7 +1034,7 @@ } } }, - "revision": "20260223", + "revision": "20260406", "rootUrl": "https://servicenetworking.googleapis.com/", "schemas": { "AddDnsRecordSetMetadata": { @@ -1495,7 +1495,7 @@ "type": "object" }, "pathTranslation": { - "description": "no-lint", + "description": "Path translation specifies how to combine the backend address with the request path in order to produce the appropriate forwarding URL for the request. See PathTranslation for more details.", "enum": [ "PATH_TRANSLATION_UNSPECIFIED", "CONSTANT_ADDRESS", @@ -1777,7 +1777,7 @@ }, "selectiveGapicGeneration": { "$ref": "SelectiveGapicGeneration", - "description": "Configuration for which RPCs should be generated in the GAPIC client." + "description": "Configuration for which RPCs should be generated in the GAPIC client. Note: This field should not be used in most cases." } }, "type": "object" @@ -3523,7 +3523,8 @@ "STREET_VIEW", "SHOPPING", "GEO", - "GENERATIVE_AI" + "GENERATIVE_AI", + "HEALTH" ], "enumDescriptions": [ "Not useful.", @@ -3533,7 +3534,8 @@ "Street View Org.", "Shopping Org.", "Geo Org.", - "Generative AI - https://developers.generativeai.google" + "Generative AI - https://developers.generativeai.google", + "Health Org." ], "type": "string" }, @@ -3833,7 +3835,7 @@ "type": "object" }, "SelectiveGapicGeneration": { - "description": "This message is used to configure the generation of a subset of the RPCs in a service for client libraries.", + "description": "This message is used to configure the generation of a subset of the RPCs in a service for client libraries. Note: This feature should not be used in most cases.", "id": "SelectiveGapicGeneration", "properties": { "generateOmittedAsInternal": { @@ -3902,7 +3904,7 @@ "description": "Additional API documentation." }, "endpoints": { - "description": "Configuration for network endpoints. If this is empty, then an endpoint with the same name as the service is automatically generated to service all defined APIs. WARNING: Defining any entries in the `endpoints` list disables the automatic generation of default endpoint variations (e.g., `{service}.clients6.google.com`, `content-{service}.googleapis.com`, and mTLS variants like `{service}.mtls.googleapis.com`). To retain these default variations, you are required to explicitly include your main service endpoint (e.g., `myservice.googleapis.com`) in this list alongside any other custom endpoints (like REP, GFE, etc.).", + "description": "Configuration for network endpoints. If this is empty, then an endpoint with the same name as the service is automatically generated to service all defined APIs.", "items": { "$ref": "Endpoint" }, @@ -4266,7 +4268,7 @@ "id": "UsageRule", "properties": { "allowUnregisteredCalls": { - "description": " Use this rule to configure unregistered calls for the service. Unregistered calls are calls that do not contain consumer project identity. (Example: calls that do not contain an API key). WARNING: By default, API methods do not allow unregistered calls, and each method call must be identified by a consumer project identity.", + "description": "Use this rule to configure unregistered calls for the service. Unregistered calls are calls that do not contain consumer project identity. (Example: calls that do not contain an API key). WARNING: By default, API methods do not allow unregistered calls, and each method call must be identified by a consumer project identity.", "type": "boolean" }, "selector": { diff --git a/vendor/google.golang.org/api/servicenetworking/v1/servicenetworking-gen.go b/vendor/google.golang.org/api/servicenetworking/v1/servicenetworking-gen.go index 9cf31d4a70..cd8e9cf665 100644 --- a/vendor/google.golang.org/api/servicenetworking/v1/servicenetworking-gen.go +++ b/vendor/google.golang.org/api/servicenetworking/v1/servicenetworking-gen.go @@ -937,7 +937,9 @@ type BackendRule struct { // OverridesByRequestProtocol: The map between request protocol and the backend // address. OverridesByRequestProtocol map[string]BackendRule `json:"overridesByRequestProtocol,omitempty"` - // PathTranslation: no-lint + // PathTranslation: Path translation specifies how to combine the backend + // address with the request path in order to produce the appropriate forwarding + // URL for the request. See PathTranslation for more details. // // Possible values: // "PATH_TRANSLATION_UNSPECIFIED" @@ -1327,7 +1329,7 @@ type CommonLanguageSettings struct { // Example: https://cloud.google.com/nodejs/docs/reference/asset/latest ReferenceDocsUri string `json:"referenceDocsUri,omitempty"` // SelectiveGapicGeneration: Configuration for which RPCs should be generated - // in the GAPIC client. + // in the GAPIC client. Note: This field should not be used in most cases. SelectiveGapicGeneration *SelectiveGapicGeneration `json:"selectiveGapicGeneration,omitempty"` // ForceSendFields is a list of field names (e.g. "Destinations") to // unconditionally include in API requests. By default, fields with empty or @@ -4025,6 +4027,7 @@ type Publishing struct { // "SHOPPING" - Shopping Org. // "GEO" - Geo Org. // "GENERATIVE_AI" - Generative AI - https://developers.generativeai.google + // "HEALTH" - Health Org. Organization string `json:"organization,omitempty"` // ProtoReferenceDocumentationUri: Optional link to proto reference // documentation. Example: @@ -4498,7 +4501,8 @@ func (s SecondaryIpRangeSpec) MarshalJSON() ([]byte, error) { } // SelectiveGapicGeneration: This message is used to configure the generation -// of a subset of the RPCs in a service for client libraries. +// of a subset of the RPCs in a service for client libraries. Note: This +// feature should not be used in most cases. type SelectiveGapicGeneration struct { // GenerateOmittedAsInternal: Setting this to true indicates to the client // generators that methods that would be excluded from the generation should @@ -4573,13 +4577,7 @@ type Service struct { Documentation *Documentation `json:"documentation,omitempty"` // Endpoints: Configuration for network endpoints. If this is empty, then an // endpoint with the same name as the service is automatically generated to - // service all defined APIs. WARNING: Defining any entries in the `endpoints` - // list disables the automatic generation of default endpoint variations (e.g., - // `{service}.clients6.google.com`, `content-{service}.googleapis.com`, and - // mTLS variants like `{service}.mtls.googleapis.com`). To retain these default - // variations, you are required to explicitly include your main service - // endpoint (e.g., `myservice.googleapis.com`) in this list alongside any other - // custom endpoints (like REP, GFE, etc.). + // service all defined APIs. Endpoints []*Endpoint `json:"endpoints,omitempty"` // Enums: A list of all enum types included in this API service. Enums // referenced directly or indirectly by the `apis` are automatically included. @@ -5021,7 +5019,7 @@ func (s Usage) MarshalJSON() ([]byte, error) { // UsageRule: Usage configuration rules for the service. type UsageRule struct { - // AllowUnregisteredCalls: Use this rule to configure unregistered calls for + // AllowUnregisteredCalls: Use this rule to configure unregistered calls for // the service. Unregistered calls are calls that do not contain consumer // project identity. (Example: calls that do not contain an API key). WARNING: // By default, API methods do not allow unregistered calls, and each method diff --git a/vendor/google.golang.org/api/storage/v1/storage-api.json b/vendor/google.golang.org/api/storage/v1/storage-api.json index cb32e75a94..9bd7de921c 100644 --- a/vendor/google.golang.org/api/storage/v1/storage-api.json +++ b/vendor/google.golang.org/api/storage/v1/storage-api.json @@ -253,7 +253,7 @@ "location": "northamerica-south1" } ], - "etag": "\"31363539393037303230303637393438373935\"", + "etag": "\"3136383236333536383830353031333435373432\"", "icons": { "x16": "https://www.google.com/images/icons/product/cloud_storage-16.png", "x32": "https://www.google.com/images/icons/product/cloud_storage-32.png" @@ -521,7 +521,7 @@ ] }, "update": { - "description": "Updates the config(ttl and admissionPolicy) of an Anywhere Cache instance.", + "description": "Updates the config of an Anywhere Cache instance.", "httpMethod": "PATCH", "id": "storage.anywhereCaches.update", "parameterOrder": [ @@ -4605,7 +4605,7 @@ } } }, - "revision": "20260204", + "revision": "20260408", "rootUrl": "https://storage.googleapis.com/", "schemas": { "AdvanceRelocateBucketOperationRequest": { @@ -4650,6 +4650,10 @@ "description": "The ID of the resource, including the project number, bucket name and anywhere cache ID.", "type": "string" }, + "ingestOnWrite": { + "description": "Specifies whether objects are ingested into the cache upon write.", + "type": "boolean" + }, "kind": { "default": "storage#anywhereCache", "description": "The kind of item this is. For Anywhere Cache, this is always storage#anywhereCache.", diff --git a/vendor/google.golang.org/api/storage/v1/storage-gen.go b/vendor/google.golang.org/api/storage/v1/storage-gen.go index 5f2dd2ccee..e35ce697a4 100644 --- a/vendor/google.golang.org/api/storage/v1/storage-gen.go +++ b/vendor/google.golang.org/api/storage/v1/storage-gen.go @@ -384,6 +384,9 @@ type AnywhereCache struct { // Id: The ID of the resource, including the project number, bucket name and // anywhere cache ID. Id string `json:"id,omitempty"` + // IngestOnWrite: Specifies whether objects are ingested into the cache upon + // write. + IngestOnWrite bool `json:"ingestOnWrite,omitempty"` // Kind: The kind of item this is. For Anywhere Cache, this is always // storage#anywhereCache. Kind string `json:"kind,omitempty"` @@ -3726,8 +3729,7 @@ type AnywhereCachesUpdateCall struct { header_ http.Header } -// Update: Updates the config(ttl and admissionPolicy) of an Anywhere Cache -// instance. +// Update: Updates the config of an Anywhere Cache instance. // // - anywhereCacheId: The ID of requested Anywhere Cache instance. // - bucket: Name of the parent bucket. diff --git a/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go b/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go index 12479f6985..22dbc52287 100644 --- a/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go +++ b/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go @@ -39,27 +39,14 @@ import ( var randIntN = rand.IntN -// ChildState is the balancer state of a child along with the endpoint which -// identifies the child balancer. +// ChildState is the state of a child balancer. type ChildState struct { - Endpoint resolver.Endpoint - State balancer.State - - // Balancer exposes only the ExitIdler interface of the child LB policy. - // Other methods of the child policy are called only by endpointsharding. - Balancer ExitIdler -} - -// ExitIdler provides access to only the ExitIdle method of the child balancer. -type ExitIdler interface { - // ExitIdle instructs the LB policy to reconnect to backends / exit the - // IDLE state, if appropriate and possible. Note that SubConns that enter - // the IDLE state will not reconnect until SubConn.Connect is called. - ExitIdle() + Endpoint resolver.Endpoint // Endpoint of the child balancer. + State balancer.State // State of the child balancer. + ExitIdle func() // Function to exit the child balancer from IDLE state. } -// Options are the options to configure the behaviour of the -// endpointsharding balancer. +// Options configure the behaviour of the endpointsharding balancer. type Options struct { // DisableAutoReconnect allows the balancer to keep child balancer in the // IDLE state until they are explicitly triggered to exit using the @@ -77,14 +64,13 @@ type ChildBuilderFunc func(cc balancer.ClientConn, opts balancer.BuildOptions) b // policies each owning a single endpoint. The endpointsharding balancer // forwards the LoadBalancingConfig in ClientConn state updates to its children. func NewBalancer(cc balancer.ClientConn, opts balancer.BuildOptions, childBuilder ChildBuilderFunc, esOpts Options) balancer.Balancer { - es := &endpointSharding{ + return &endpointSharding{ cc: cc, bOpts: opts, esOpts: esOpts, childBuilder: childBuilder, + endpoints: resolver.NewEndpointMap[*endpointState](), } - es.children.Store(resolver.NewEndpointMap[*balancerWrapper]()) - return es } // endpointSharding is a balancer that wraps child balancers. It creates a child @@ -96,124 +82,129 @@ type endpointSharding struct { esOpts Options childBuilder ChildBuilderFunc - // childMu synchronizes calls to any single child. It must be held for all - // calls into a child. To avoid deadlocks, do not acquire childMu while - // holding mu. - childMu sync.Mutex - children atomic.Pointer[resolver.EndpointMap[*balancerWrapper]] - - // inhibitChildUpdates is set during UpdateClientConnState/ResolverError - // calls (calls to children will each produce an update, only want one - // update). - inhibitChildUpdates atomic.Bool - - // mu synchronizes access to the state stored in balancerWrappers in the - // children field. mu must not be held during calls into a child since - // synchronous calls back from the child may require taking mu, causing a - // deadlock. To avoid deadlocks, do not acquire childMu while holding mu. - mu sync.Mutex + // mu guards access to the below fields and guarantees mutual exclusion + // between top-down methods (like UpdateClientConnState, ResolverError etc, + // which are already serialized) and bottom-up methods (like UpdateState) + // that can be called concurrently. + // + // Lock ordering & deadlock prevention: + // Child callbacks (like UpdateState) acquire this mutex to push state updates + // to the parent. This establishes a strict lock ordering: + // [endpointState.childMu] -> [endpointSharding.mu] + // + // To prevent deadlocks, we must never invert this order. Therefore, we must + // never call any methods on a child balancer while holding this mutex. If we + // did, and that child balancer invoked UpdateState synchronously, it would + // attempt to re-acquire this mutex, causing a deadlock. + // + // Concurrency: + // Top-down operations need to iterate over all children. To ensure a + // single, clean aggregated update at the end of such operations, we inhibit + // intermediate updates from children. We grab this mutex briefly to set + // `inhibitChildUpdates = true` and immediately release it. This allows us + // to perform the potentially slow, top-down child updates without holding + // any parent locks. Once finished, we grab the mutex again to unset the + // flag and push the final aggregated state. An update from a child during + // this time will *only* update the child state, and will not access the + // endpoints map or push an aggregated state to the parent. + mu sync.Mutex + endpoints *resolver.EndpointMap[*endpointState] + inhibitChildUpdates bool } // rotateEndpoints returns a slice of all the input endpoints rotated a random // amount. func rotateEndpoints(es []resolver.Endpoint) []resolver.Endpoint { - les := len(es) - if les == 0 { + n := len(es) + if n == 0 { return es } - r := randIntN(les) + r := randIntN(n) + // Make a copy to avoid mutating data beyond the end of es. - ret := make([]resolver.Endpoint, les) + ret := make([]resolver.Endpoint, n) copy(ret, es[r:]) - copy(ret[les-r:], es[:r]) + copy(ret[n-r:], es[:r]) return ret } // UpdateClientConnState creates a child for new endpoints and deletes children // for endpoints that are no longer present. It also updates all the children, // and sends a single synchronous update of the childrens' aggregated state at -// the end of the UpdateClientConnState operation. If any endpoint has no -// addresses it will ignore that endpoint. Otherwise, returns first error found -// from a child, but fully processes the new update. +// the end of the UpdateClientConnState operation. +// +// Returns the first error found from a child, but fully processes the update. func (es *endpointSharding) UpdateClientConnState(state balancer.ClientConnState) error { - es.childMu.Lock() - defer es.childMu.Unlock() - - es.inhibitChildUpdates.Store(true) - defer func() { - es.inhibitChildUpdates.Store(false) - es.updateState() - }() - var ret error - - children := es.children.Load() - newChildren := resolver.NewEndpointMap[*balancerWrapper]() + es.inhibitUpdatesFromChildren() - // Update/Create new children. + // Update/create child balancers for each endpoint in the update. Note that we + // don't hold the mutex here, but this is fine because inhibitChildUpdates is + // true, and therefore UpdateState will not access es.endpoints. + var retErr error + newEndpoints := resolver.NewEndpointMap[*endpointState]() for _, endpoint := range rotateEndpoints(state.ResolverState.Endpoints) { - if _, ok := newChildren.Get(endpoint); ok { - // Endpoint child was already created, continue to avoid duplicate - // update. + if _, ok := newEndpoints.Get(endpoint); ok { + // Skip duplicate endpoints. continue } - childBalancer, ok := children.Get(endpoint) + epState, ok := es.endpoints.Get(endpoint) if ok { - // Endpoint attributes may have changed, update the stored endpoint. - es.mu.Lock() - childBalancer.childState.Endpoint = endpoint - es.mu.Unlock() + // Endpoint child already exists, update the stored endpoint. + epState.endpoint = endpoint } else { - childBalancer = &balancerWrapper{ - childState: ChildState{Endpoint: endpoint}, - ClientConn: es.cc, - es: es, + // Endpoint child does not exist, create a new one. + epState = &endpointState{ + ClientConn: es.cc, + parent: es, + endpoint: endpoint, + disableAutoReconnect: es.esOpts.DisableAutoReconnect, } - childBalancer.childState.Balancer = childBalancer - childBalancer.child = es.childBuilder(childBalancer, es.bOpts) + epState.childLB = es.childBuilder(epState, es.bOpts) } - newChildren.Set(endpoint, childBalancer) - if err := childBalancer.updateClientConnStateLocked(balancer.ClientConnState{ + // Update the endpoint state for the endpoint. + newEndpoints.Set(endpoint, epState) + + if err := epState.updateClientConnState(balancer.ClientConnState{ BalancerConfig: state.BalancerConfig, ResolverState: resolver.State{ Endpoints: []resolver.Endpoint{endpoint}, Attributes: state.ResolverState.Attributes, }, - }); err != nil && ret == nil { - // Return first error found, and always commit full processing of - // updating children. If desired to process more specific errors - // across all endpoints, caller should make these specific - // validations, this is a current limitation for simplicity sake. - ret = err + }); err != nil && retErr == nil { + // Keep the first error found from any child. + retErr = err } } + // Delete old children that are no longer present. - for e, child := range children.All() { - if _, ok := newChildren.Get(e); !ok { - child.closeLocked() + for e, child := range es.endpoints.All() { + if _, ok := newEndpoints.Get(e); !ok { + child.close() } } - es.children.Store(newChildren) - if newChildren.Len() == 0 { - return balancer.ErrBadResolverState + + if newEndpoints.Len() == 0 { + retErr = balancer.ErrBadResolverState } - return ret + + es.mu.Lock() + es.endpoints = newEndpoints + es.inhibitChildUpdates = false + es.updateStateLocked() + es.mu.Unlock() + + return retErr } // ResolverError forwards the resolver error to all of the endpointSharding's // children and sends a single synchronous update of the childStates at the end // of the ResolverError operation. func (es *endpointSharding) ResolverError(err error) { - es.childMu.Lock() - defer es.childMu.Unlock() - es.inhibitChildUpdates.Store(true) - defer func() { - es.inhibitChildUpdates.Store(false) - es.updateState() - }() - children := es.children.Load() - for _, child := range children.All() { - child.resolverErrorLocked(err) + es.inhibitUpdatesFromChildren() + for _, child := range es.endpoints.All() { + child.resolverError(err) } + es.allowUpdatesFromChildren() } func (es *endpointSharding) UpdateSubConnState(balancer.SubConn, balancer.SubConnState) { @@ -221,41 +212,49 @@ func (es *endpointSharding) UpdateSubConnState(balancer.SubConn, balancer.SubCon } func (es *endpointSharding) Close() { - es.childMu.Lock() - defer es.childMu.Unlock() - children := es.children.Load() - for _, child := range children.All() { - child.closeLocked() + es.inhibitUpdatesFromChildren() + for _, child := range es.endpoints.All() { + child.close() } } func (es *endpointSharding) ExitIdle() { - es.childMu.Lock() - defer es.childMu.Unlock() - for _, bw := range es.children.Load().All() { - if !bw.isClosed { - bw.child.ExitIdle() - } + es.inhibitUpdatesFromChildren() + for _, child := range es.endpoints.All() { + child.exitIdle() } + es.allowUpdatesFromChildren() } -// updateState updates this component's state. It sends the aggregated state, -// and a picker with round robin behavior with all the child states present if -// needed. -func (es *endpointSharding) updateState() { - if es.inhibitChildUpdates.Load() { - return - } - var readyPickers, connectingPickers, idlePickers, transientFailurePickers []balancer.Picker +func (es *endpointSharding) inhibitUpdatesFromChildren() { + es.mu.Lock() + es.inhibitChildUpdates = true + es.mu.Unlock() +} +func (es *endpointSharding) allowUpdatesFromChildren() { es.mu.Lock() - defer es.mu.Unlock() + es.inhibitChildUpdates = false + es.updateStateLocked() + es.mu.Unlock() +} - children := es.children.Load() - childStates := make([]ChildState, 0, children.Len()) +// updateStateLocked updates this component's state. It sends the aggregated +// state, and a picker with round robin behavior with all the child states +// present if needed. This method must only be called when inhibitChildUpdates +// is false. +// +// Caller must hold es.mu. +func (es *endpointSharding) updateStateLocked() { + var readyPickers, connectingPickers, idlePickers, transientFailurePickers []balancer.Picker - for _, child := range children.All() { - childState := child.childState + childStates := make([]ChildState, 0, es.endpoints.Len()) + for _, epState := range es.endpoints.All() { + childState := ChildState{ + Endpoint: epState.endpoint, + State: epState.state, + ExitIdle: func() { go epState.exitIdle() }, + } childStates = append(childStates, childState) childPicker := childState.State.Picker switch childState.State.ConnectivityState { @@ -292,14 +291,14 @@ func (es *endpointSharding) updateState() { aggState = connectivity.TransientFailure pickers = []balancer.Picker{base.NewErrPicker(errors.New("no children to pick from"))} } // No children (resolver error before valid update). - p := &pickerWithChildStates{ - pickers: pickers, - childStates: childStates, - next: uint32(randIntN(len(pickers))), - } + es.cc.UpdateState(balancer.State{ ConnectivityState: aggState, - Picker: p, + Picker: &pickerWithChildStates{ + pickers: pickers, + childStates: childStates, + next: uint32(randIntN(len(pickers))), + }, }) } @@ -328,61 +327,59 @@ func ChildStatesFromPicker(picker balancer.Picker) []ChildState { return p.childStates } -// balancerWrapper is a wrapper of a balancer. It ID's a child balancer by -// endpoint, and persists recent child balancer state. -type balancerWrapper struct { - // The following fields are initialized at build time and read-only after - // that and therefore do not need to be guarded by a mutex. - - // child contains the wrapped balancer. Access its methods only through - // methods on balancerWrapper to ensure proper synchronization - child balancer.Balancer - balancer.ClientConn // embed to intercept UpdateState, doesn't deal with SubConns +// endpointState is the internal state maintained for each endpoint. +type endpointState struct { + balancer.ClientConn // Embedded to intercept UpdateState - es *endpointSharding + parent *endpointSharding // Parent endpointsharding balancer. + endpoint resolver.Endpoint // Endpoint of the child balancer. + state balancer.State // State of the child balancer. + disableAutoReconnect bool // Whether to disable auto reconnect for this child. - // Access to the following fields is guarded by es.mu. - - childState ChildState - isClosed bool + childMu sync.Mutex // Guarantees mutual exclusion for Balancer API calls to the child balancer. + childLB balancer.Balancer // Child balancer. + closed bool // Tracks closure of the child balancer to ensure ExitIdle is not called after Close(). } -func (bw *balancerWrapper) UpdateState(state balancer.State) { - bw.es.mu.Lock() - bw.childState.State = state - bw.es.mu.Unlock() - if state.ConnectivityState == connectivity.Idle && !bw.es.esOpts.DisableAutoReconnect { - bw.ExitIdle() +func (es *endpointState) UpdateState(state balancer.State) { + es.parent.mu.Lock() + es.state = state + if !es.parent.inhibitChildUpdates { + es.parent.updateStateLocked() + } + es.parent.mu.Unlock() + + if state.ConnectivityState == connectivity.Idle && !es.disableAutoReconnect { + go es.exitIdle() } - bw.es.updateState() } -// ExitIdle pings an IDLE child balancer to exit idle in a new goroutine to -// avoid deadlocks due to synchronous balancer state updates. -func (bw *balancerWrapper) ExitIdle() { - go func() { - bw.es.childMu.Lock() - if !bw.isClosed { - bw.child.ExitIdle() - } - bw.es.childMu.Unlock() - }() +func (es *endpointState) updateClientConnState(state balancer.ClientConnState) error { + es.childMu.Lock() + err := es.childLB.UpdateClientConnState(state) + es.childMu.Unlock() + return err } -// updateClientConnStateLocked delivers the ClientConnState to the child -// balancer. Callers must hold the child mutex of the parent endpointsharding -// balancer. -func (bw *balancerWrapper) updateClientConnStateLocked(ccs balancer.ClientConnState) error { - return bw.child.UpdateClientConnState(ccs) +func (es *endpointState) resolverError(err error) { + es.childMu.Lock() + es.childLB.ResolverError(err) + es.childMu.Unlock() } -// closeLocked closes the child balancer. Callers must hold the child mutext of -// the parent endpointsharding balancer. -func (bw *balancerWrapper) closeLocked() { - bw.child.Close() - bw.isClosed = true +func (es *endpointState) close() { + es.childMu.Lock() + if !es.closed { + es.closed = true + es.childLB.Close() + } + es.childMu.Unlock() } -func (bw *balancerWrapper) resolverErrorLocked(err error) { - bw.child.ResolverError(err) +func (es *endpointState) exitIdle() { + es.childMu.Lock() + if !es.closed { + es.childLB.ExitIdle() + } + es.childMu.Unlock() } diff --git a/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go b/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go index d48bc304c2..ddd08f5373 100644 --- a/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go +++ b/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go @@ -36,7 +36,6 @@ import ( "google.golang.org/grpc/balancer/pickfirst/internal" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/experimental/balancer/weight" - expstats "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/envconfig" internalgrpclog "google.golang.org/grpc/internal/grpclog" @@ -56,30 +55,7 @@ const Name = "pick_first" // attributes to indicate whether the health listener usage is enabled. type enableHealthListenerKeyType struct{} -var ( - logger = grpclog.Component("pick-first-leaf-lb") - disconnectionsMetric = expstats.RegisterInt64Count(expstats.MetricDescriptor{ - Name: "grpc.lb.pick_first.disconnections", - Description: "EXPERIMENTAL. Number of times the selected subchannel becomes disconnected.", - Unit: "{disconnection}", - Labels: []string{"grpc.target"}, - Default: false, - }) - connectionAttemptsSucceededMetric = expstats.RegisterInt64Count(expstats.MetricDescriptor{ - Name: "grpc.lb.pick_first.connection_attempts_succeeded", - Description: "EXPERIMENTAL. Number of successful connection attempts.", - Unit: "{attempt}", - Labels: []string{"grpc.target"}, - Default: false, - }) - connectionAttemptsFailedMetric = expstats.RegisterInt64Count(expstats.MetricDescriptor{ - Name: "grpc.lb.pick_first.connection_attempts_failed", - Description: "EXPERIMENTAL. Number of failed connection attempts.", - Unit: "{attempt}", - Labels: []string{"grpc.target"}, - Default: false, - }) -) +var logger = grpclog.Component("pick-first-leaf-lb") const ( // TODO: change to pick-first when this becomes the default pick_first policy. @@ -101,11 +77,9 @@ const ( type pickfirstBuilder struct{} -func (pickfirstBuilder) Build(cc balancer.ClientConn, bo balancer.BuildOptions) balancer.Balancer { +func (pickfirstBuilder) Build(cc balancer.ClientConn, _ balancer.BuildOptions) balancer.Balancer { b := &pickfirstBalancer{ - cc: cc, - target: bo.Target.String(), - metricsRecorder: cc.MetricsRecorder(), + cc: cc, subConns: resolver.NewAddressMapV2[*scData](), state: connectivity.Connecting, @@ -185,10 +159,8 @@ func (b *pickfirstBalancer) newSCData(addr resolver.Address) (*scData, error) { type pickfirstBalancer struct { // The following fields are initialized at build time and read-only after // that and therefore do not need to be guarded by a mutex. - logger *internalgrpclog.PrefixLogger - cc balancer.ClientConn - target string - metricsRecorder expstats.MetricsRecorder // guaranteed to be non nil + logger *internalgrpclog.PrefixLogger + cc balancer.ClientConn // The mutex is used to ensure synchronization of updates triggered // from the idle picker and the already serialized resolver, @@ -633,14 +605,11 @@ func (b *pickfirstBalancer) updateSubConnState(sd *scData, newState balancer.Sub return } - // Record a connection attempt when exiting CONNECTING. if newState.ConnectivityState == connectivity.TransientFailure { sd.connectionFailedInFirstPass = true - connectionAttemptsFailedMetric.Record(b.metricsRecorder, 1, b.target) } if newState.ConnectivityState == connectivity.Ready { - connectionAttemptsSucceededMetric.Record(b.metricsRecorder, 1, b.target) b.shutdownRemainingLocked(sd) if !b.addressList.seekTo(sd.addr) { // This should not fail as we should have only one SubConn after @@ -689,15 +658,6 @@ func (b *pickfirstBalancer) updateSubConnState(sd *scData, newState balancer.Sub // the first address when the picker is used. b.shutdownRemainingLocked(sd) sd.effectiveState = newState.ConnectivityState - // READY SubConn interspliced in between CONNECTING and IDLE, need to - // account for that. - if oldState == connectivity.Connecting { - // A known issue (https://github.com/grpc/grpc-go/issues/7862) - // causes a race that prevents the READY state change notification. - // This works around it. - connectionAttemptsSucceededMetric.Record(b.metricsRecorder, 1, b.target) - } - disconnectionsMetric.Record(b.metricsRecorder, 1, b.target) b.addressList.reset() b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.Idle, diff --git a/vendor/google.golang.org/grpc/balancer/ringhash/picker.go b/vendor/google.golang.org/grpc/balancer/ringhash/picker.go index 96f72905ec..3f76917069 100644 --- a/vendor/google.golang.org/grpc/balancer/ringhash/picker.go +++ b/vendor/google.golang.org/grpc/balancer/ringhash/picker.go @@ -107,7 +107,7 @@ func (p *picker) Pick(info balancer.PickInfo) (balancer.PickResult, error) { // If the SubChannel is in idle state, initiate a connection but // continue to check other pickers to see if there is one in // ready state. - es.balancer.ExitIdle() + es.exitIdle() } } if requestedConnection { diff --git a/vendor/google.golang.org/grpc/balancer/ringhash/ringhash.go b/vendor/google.golang.org/grpc/balancer/ringhash/ringhash.go index 171cdd9647..384dedb3b0 100644 --- a/vendor/google.golang.org/grpc/balancer/ringhash/ringhash.go +++ b/vendor/google.golang.org/grpc/balancer/ringhash/ringhash.go @@ -142,10 +142,10 @@ func (b *ringhashBalancer) UpdateState(state balancer.State) { es, ok := b.endpointStates.Get(endpoint) if !ok { es := &endpointState{ - balancer: childState.Balancer, hashKey: hk, weight: newWeight, state: childState.State, + exitIdle: childState.ExitIdle, } b.endpointStates.Set(endpoint, es) b.shouldRegenerateRing = true @@ -261,26 +261,28 @@ func (b *ringhashBalancer) updatePickerLocked() { // non-deterministic, the list of `endpointState`s must be sorted to // ensure `ExitIdle` is called on the same child, preventing unnecessary // connections. - var endpointStates = make([]*endpointState, 0, b.endpointStates.Len()) + endpointStates := make([]*endpointState, 0, b.endpointStates.Len()) for _, s := range b.endpointStates.All() { endpointStates = append(endpointStates, s) } sort.Slice(endpointStates, func(i, j int) bool { return endpointStates[i].hashKey < endpointStates[j].hashKey }) - var idleBalancer endpointsharding.ExitIdler + + // Store the function to ExitIdle on the first IDLE endpoint. + var exitIdle func() for _, es := range endpointStates { connState := es.state.ConnectivityState if connState == connectivity.Connecting { - idleBalancer = nil + exitIdle = nil break } - if idleBalancer == nil && connState == connectivity.Idle { - idleBalancer = es.balancer + if exitIdle == nil && connState == connectivity.Idle { + exitIdle = es.exitIdle } } - if idleBalancer != nil { - idleBalancer.ExitIdle() + if exitIdle != nil { + exitIdle() } } @@ -399,7 +401,7 @@ type endpointState struct { // overridden, for example based on EDS endpoint metadata. hashKey string weight uint32 - balancer endpointsharding.ExitIdler + exitIdle func() // state is updated by the balancer while receiving resolver updates from // the channel and picker updates from its children. Access to it is guarded diff --git a/vendor/google.golang.org/grpc/balancer/rls/balancer.go b/vendor/google.golang.org/grpc/balancer/rls/balancer.go index 3e3c6fba9f..6d414dddf9 100644 --- a/vendor/google.golang.org/grpc/balancer/rls/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/rls/balancer.go @@ -140,7 +140,7 @@ func (rlsBB) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer. lbCfg: &lbConfig{}, pendingMap: make(map[cacheKey]*backoffState), childPolicies: make(map[string]*childPolicyWrapper), - updateCh: buffer.NewUnbounded(), + updateCh: buffer.NewUnbounded[any](), } lb.logger = internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf("[rls-experimental-lb %p] ", lb)) lb.dataCache = newDataCache(maxCacheSize, lb.logger, opts.Target.String()) @@ -204,7 +204,7 @@ type rlsBalancer struct { inhibitPickerUpdates bool // Channel on which all updates are pushed. Processed in run(). - updateCh *buffer.Unbounded + updateCh *buffer.Unbounded[any] } type resumePickerUpdates struct { diff --git a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go index 296123e20d..6c249fdaf2 100644 --- a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go +++ b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go @@ -679,7 +679,7 @@ func (x *Message) GetData() []byte { // A list of metadata pairs, used in the payload of client header, // server header, and server trailer. // Implementations may omit some entries to honor the header limits -// of GRPC_BINARY_LOG_CONFIG. +// of GRPC_BINARY_LOG_FILTER. // // Header keys added by gRPC are omitted. To be more specific, // implementations will not log the following entries, and this is @@ -689,7 +689,9 @@ func (x *Message) GetData() []byte { // or keys like 'lb-token' // - transport specific entries, including but not limited to: // ':path', ':authority', 'content-encoding', 'user-agent', 'te', etc -// - entries added for call credentials +// - entries added for call credentials (on client side, excludes all +// such headers; on server side, excludes only the "authorization" +// header) // // Implementations must always log grpc-trace-bin if it is present. // Practically speaking it will only be visible on server side because diff --git a/vendor/google.golang.org/grpc/call.go b/vendor/google.golang.org/grpc/call.go index 788c89c16f..2079bf4ed7 100644 --- a/vendor/google.golang.org/grpc/call.go +++ b/vendor/google.golang.org/grpc/call.go @@ -20,6 +20,10 @@ package grpc import ( "context" + "io" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // Invoke sends the RPC request on the wire and returns after response is @@ -67,8 +71,27 @@ func invoke(ctx context.Context, method string, req, reply any, cc *ClientConn, if err != nil { return err } - if err := cs.SendMsg(req); err != nil { + // In case of nil or io.EOF error, call RecvMsg. + if err := cs.SendMsg(req); err != nil && err != io.EOF { + return err + } + // CloseSend is needed because in some scenarios (e.g., xDS), the same + // interceptors are used to process both unary and streaming RPCs. Calling + // CloseSend signals to those interceptors that no more messages are on the + // way. + if err := cs.CloseSend(); err != nil && err != io.EOF { return err } - return cs.RecvMsg(reply) + if err := cs.RecvMsg(reply); err != nil { + return err + } + // Call RecvMsg again to get the trailers. + err = cs.RecvMsg(reply) + if err == io.EOF { + return nil + } + if err == nil { + return status.Error(codes.Internal, "cardinality violation: expected for non server-streaming RPCs, but received another message") + } + return err } diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index b27c7e84a3..f5ce071970 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -553,6 +553,7 @@ func chainStreamClientInterceptors(cc *ClientConn) { if cc.dopts.streamInt != nil { interceptors = append([]StreamClientInterceptor{cc.dopts.streamInt}, interceptors...) } + interceptors = append(interceptors, defaultStreamInterceptor) var chainedInt StreamClientInterceptor if len(interceptors) == 0 { chainedInt = nil diff --git a/vendor/google.golang.org/grpc/credentials/alts/internal/conn/record.go b/vendor/google.golang.org/grpc/credentials/alts/internal/conn/record.go index 022416b260..bf33b7511d 100644 --- a/vendor/google.golang.org/grpc/credentials/alts/internal/conn/record.go +++ b/vendor/google.golang.org/grpc/credentials/alts/internal/conn/record.go @@ -65,8 +65,7 @@ const ( altsRecordDefaultLength = 4 * 1024 // 4KiB // Message type value included in ALTS record framing. altsRecordMsgType = uint32(0x06) - // The maximum write buffer size. This *must* be multiple of - // altsRecordDefaultLength. + // The maximum write buffer size, which can hold multiple ALTS frames. altsWriteBufferMaxSize = 512 * 1024 // 512KiB // The initial buffer used to read from the network. // It includes an additional 512 Bytes to hold two 16KiB records plus @@ -137,6 +136,12 @@ type conn struct { // NewConn creates a new secure channel instance given the other party role and // handshaking result. func NewConn(c net.Conn, side core.Side, recordProtocol string, key []byte, protected []byte) (net.Conn, error) { + return NewConnWithMaxFrameSize(c, side, recordProtocol, key, protected, 0) +} + +// NewConnWithMaxFrameSize creates a new secure channel instance given the +// other party role, handshaking result, and negotiated maximum frame size. +func NewConnWithMaxFrameSize(c net.Conn, side core.Side, recordProtocol string, key []byte, protected []byte, negotiatedMaxFrameSize int) (net.Conn, error) { newCrypto := protocols[recordProtocol] if newCrypto == nil { return nil, fmt.Errorf("negotiated unknown next_protocol %q", recordProtocol) @@ -146,7 +151,10 @@ func NewConn(c net.Conn, side core.Side, recordProtocol string, key []byte, prot return nil, fmt.Errorf("protocol %q: %v", recordProtocol, err) } overhead := MsgLenFieldSize + msgTypeFieldSize + crypto.EncryptionOverhead() - payloadLengthLimit := altsRecordDefaultLength - overhead + + // Clamp maxRecordLen to be at least altsRecordDefaultLength. + maxRecordLen := max(altsRecordDefaultLength, negotiatedMaxFrameSize) + payloadLengthLimit := maxRecordLen - overhead // We pre-allocate protected to be of size 32KB during initialization. // We increase the size of the buffer by the required amount if it can't // hold a complete encrypted record. @@ -321,7 +329,8 @@ func (p *conn) Write(b []byte) (n int, err error) { partialBSize := len(b) if size > altsWriteBufferMaxSize { size = altsWriteBufferMaxSize - const numOfFramesInMaxWriteBuf = altsWriteBufferMaxSize / altsRecordDefaultLength + frameLen := p.payloadLengthLimit + p.overhead + numOfFramesInMaxWriteBuf := altsWriteBufferMaxSize / frameLen partialBSize = numOfFramesInMaxWriteBuf * p.payloadLengthLimit } // Get a writeBuf of the required length. @@ -363,7 +372,7 @@ func (p *conn) Write(b []byte) (n int, err error) { // written. This means we need to remove header, // encryption overheads, and any partially-written // frame data. - numOfWrittenFrames := int(math.Floor(float64(nn) / float64(altsRecordDefaultLength))) + numOfWrittenFrames := int(math.Floor(float64(nn) / float64(p.payloadLengthLimit+p.overhead))) return partialBStart + numOfWrittenFrames*p.payloadLengthLimit, err } } diff --git a/vendor/google.golang.org/grpc/credentials/alts/internal/handshaker/handshaker.go b/vendor/google.golang.org/grpc/credentials/alts/internal/handshaker/handshaker.go index f4974b504b..f2a1e36f73 100644 --- a/vendor/google.golang.org/grpc/credentials/alts/internal/handshaker/handshaker.go +++ b/vendor/google.golang.org/grpc/credentials/alts/internal/handshaker/handshaker.go @@ -289,7 +289,11 @@ func (h *altsHandshaker) doHandshake(req *altspb.HandshakerReq) (net.Conn, *alts if !ok { return nil, nil, fmt.Errorf("unknown resulted record protocol %v", result.RecordProtocol) } - sc, err := conn.NewConn(h.conn, h.side, result.GetRecordProtocol(), result.KeyData[:keyLen], extra) + maxFrameSize := int(envconfig.ALTSMaxFrameSize) + if peerMax := int(result.GetMaxFrameSize()); peerMax > 0 { + maxFrameSize = min(peerMax, maxFrameSize) + } + sc, err := conn.NewConnWithMaxFrameSize(h.conn, h.side, result.GetRecordProtocol(), result.KeyData[:keyLen], extra, maxFrameSize) if err != nil { return nil, nil, err } diff --git a/vendor/google.golang.org/grpc/internal/buffer/unbounded.go b/vendor/google.golang.org/grpc/internal/buffer/unbounded.go index 467392b8d4..d1f4b634b9 100644 --- a/vendor/google.golang.org/grpc/internal/buffer/unbounded.go +++ b/vendor/google.golang.org/grpc/internal/buffer/unbounded.go @@ -27,32 +27,29 @@ import ( // extra goroutines. This is typically used for passing updates from one entity // to another within gRPC. // +// To avoid extra memory allocations and type assertions, using any on +// performance-critical code paths is discouraged. Use concrete types wherever +// possible when instantiating Unbounded. +// // All methods on this type are thread-safe and don't block on anything except // the underlying mutex used for synchronization. -// -// Unbounded supports values of any type to be stored in it by using a channel -// of `any`. This means that a call to Put() incurs an extra memory allocation, -// and also that users need a type assertion while reading. For performance -// critical code paths, using Unbounded is strongly discouraged and defining a -// new type specific implementation of this buffer is preferred. See -// internal/transport/transport.go for an example of this. -type Unbounded struct { - c chan any +type Unbounded[T any] struct { + c chan T closed bool closing bool mu sync.Mutex - backlog []any + backlog []T } // NewUnbounded returns a new instance of Unbounded. -func NewUnbounded() *Unbounded { - return &Unbounded{c: make(chan any, 1)} +func NewUnbounded[T any]() *Unbounded[T] { + return &Unbounded[T]{c: make(chan T, 1)} } var errBufferClosed = errors.New("Put called on closed buffer.Unbounded") // Put adds t to the unbounded buffer. -func (b *Unbounded) Put(t any) error { +func (b *Unbounded[T]) Put(t T) error { b.mu.Lock() defer b.mu.Unlock() if b.closing { @@ -72,13 +69,14 @@ func (b *Unbounded) Put(t any) error { // Load sends the earliest buffered data, if any, onto the read channel returned // by Get(). Users are expected to call this every time they successfully read a // value from the read channel. -func (b *Unbounded) Load() { +func (b *Unbounded[T]) Load() { b.mu.Lock() defer b.mu.Unlock() if len(b.backlog) > 0 { select { case b.c <- b.backlog[0]: - b.backlog[0] = nil + var zero T + b.backlog[0] = zero b.backlog = b.backlog[1:] default: } @@ -96,14 +94,14 @@ func (b *Unbounded) Load() { // // If the unbounded buffer is closed, the read channel returned by this method // is closed after all data is drained. -func (b *Unbounded) Get() <-chan any { +func (b *Unbounded[T]) Get() <-chan T { return b.c } // Close closes the unbounded buffer. No subsequent data may be Put(), and the // channel returned from Get() will be closed after all the data is read and // Load() is called for the final time. -func (b *Unbounded) Close() { +func (b *Unbounded[T]) Close() { b.mu.Lock() defer b.mu.Unlock() if b.closing { diff --git a/vendor/google.golang.org/grpc/internal/credentials/xds/handshake_info.go b/vendor/google.golang.org/grpc/internal/credentials/xds/handshake_info.go index 404b9cc9e2..dd4cdb9bfe 100644 --- a/vendor/google.golang.org/grpc/internal/credentials/xds/handshake_info.go +++ b/vendor/google.golang.org/grpc/internal/credentials/xds/handshake_info.go @@ -33,6 +33,7 @@ import ( "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/credentials/spiffe" "google.golang.org/grpc/internal/envconfig" + "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/xds/matcher" "google.golang.org/grpc/resolver" ) @@ -66,42 +67,18 @@ func Hostname(attr *attributes.Attributes) string { return hn } -// Equal reports whether the handshake info structs are identical. -func (hi *HandshakeInfo) Equal(other *HandshakeInfo) bool { - if hi == nil && other == nil { - return true - } - if hi == nil || other == nil { - return false - } - if hi.rootProvider != other.rootProvider || - hi.identityProvider != other.identityProvider || - hi.requireClientCert != other.requireClientCert || - hi.sni != other.sni || - hi.validateSANUsingSNI != other.validateSANUsingSNI || - hi.useAutoHostSNI != other.useAutoHostSNI || - len(hi.sanMatchers) != len(other.sanMatchers) { - return false - } - for i := range hi.sanMatchers { - if !hi.sanMatchers[i].Equal(other.sanMatchers[i]) { - return false - } - } - return true -} - // SetHandshakeInfo returns a copy of addr in which the Attributes field is // updated with hiPtr. -func SetHandshakeInfo(addr resolver.Address, hiPtr *atomic.Pointer[HandshakeInfo]) resolver.Address { +func SetHandshakeInfo(addr resolver.Address, hiPtr *atomic.Pointer[grpcsync.RefCounted[*HandshakeInfo]]) resolver.Address { addr.Attributes = addr.Attributes.WithValue(handshakeAttrKey{}, hiPtr) return addr } -// HandshakeInfoFromAttributes returns a pointer to the *HandshakeInfo stored in attr. -func HandshakeInfoFromAttributes(attr *attributes.Attributes) *atomic.Pointer[HandshakeInfo] { +// HandshakeInfoFromAttributes returns the atomic pointer to the +// reference-counted HandshakeInfo stored in attr. +func HandshakeInfoFromAttributes(attr *attributes.Attributes) *atomic.Pointer[grpcsync.RefCounted[*HandshakeInfo]] { v := attr.Value(handshakeAttrKey{}) - hi, _ := v.(*atomic.Pointer[HandshakeInfo]) + hi, _ := v.(*atomic.Pointer[grpcsync.RefCounted[*HandshakeInfo]]) return hi } @@ -109,29 +86,98 @@ func HandshakeInfoFromAttributes(attr *attributes.Attributes) *atomic.Pointer[Ha // server handshake methods in xds credentials. The xDS implementation will be // responsible for populating these fields. type HandshakeInfo struct { - // All fields written at init time and read only after that, so no - // synchronization needed. - rootProvider certprovider.Provider - identityProvider certprovider.Provider + // The fields below are initialized when the HandshakeInfo is created, and are + // not changed thereafter. sanMatchers []matcher.StringMatcher // Only on the client side. requireClientCert bool // Only on server side. sni string // Only on client side, used for Server Name Indication in TLS handshake. validateSANUsingSNI bool // Only on client side, indicates whether to perform validation of SANs based on SNI value. useAutoHostSNI bool // Only on client side, indicates whether to use endpoint hostname as SNI. + + rootProvider certprovider.Provider + identityProvider certprovider.Provider } -// NewHandshakeInfo returns a new handshake info configured with the provided -// options. -func NewHandshakeInfo(rootProvider certprovider.Provider, identityProvider certprovider.Provider, sanMatchers []matcher.StringMatcher, requireClientCert bool, sni string, validateSANUsingSNI bool, useAutoHostSNI bool) *HandshakeInfo { - return &HandshakeInfo{ +// NewHandshakeInfo returns a new reference counted HandshakeInfo configured +// with the provided options. +func NewHandshakeInfo(rootProvider, identityProvider certprovider.Provider, sanMatchers []matcher.StringMatcher, sni string, requireClientCert, validateSANUsingSNI, useAutoHostSNI bool) *grpcsync.RefCounted[*HandshakeInfo] { + hi := &HandshakeInfo{ rootProvider: rootProvider, identityProvider: identityProvider, sanMatchers: sanMatchers, - requireClientCert: requireClientCert, sni: sni, + requireClientCert: requireClientCert, validateSANUsingSNI: validateSANUsingSNI, useAutoHostSNI: useAutoHostSNI, } + + return grpcsync.NewRefCounted(hi, hi.close) +} + +func (hi *HandshakeInfo) close() { + if hi.rootProvider != nil { + hi.rootProvider.Close() + } + if hi.identityProvider != nil { + hi.identityProvider.Close() + } +} + +// ClientSideTLSConfig loads the HandshakeInfo from hiPtr, marks it as in-use, +// and returns the tls.Config along with a done callback that MUST be invoked +// when the handshake completes. If no HandshakeInfo is stored in hiPtr or if +// fallback credentials should be used, useFallback returns true. +func ClientSideTLSConfig(ctx context.Context, hiPtr *atomic.Pointer[grpcsync.RefCounted[*HandshakeInfo]], hostname string) (cfg *tls.Config, useFallback bool, done func(), err error) { + if hiPtr == nil { + return nil, true, func() {}, nil + } + for { + hiRC := hiPtr.Load() + if hiRC == nil { + return nil, false, func() {}, errors.New("xds: connection closed or HandshakeInfo dead") + } + if !hiRC.TryIncrement() { + if hiPtr.Load() != hiRC { + continue + } + return nil, false, func() {}, errors.New("xds: connection closed or HandshakeInfo dead") + } + + hi := hiRC.Value() + if hi == nil || hi.UseFallbackCreds() { + hiRC.Decrement() + return nil, true, func() {}, nil + } + cfg, err := hi.clientSideTLSConfigInternal(ctx, hostname) + if err != nil { + hiRC.Decrement() + return nil, false, func() {}, err + } + return cfg, false, hiRC.Decrement, nil + } +} + +// ServerSideTLSConfig checks if hi is configured and marks it as in-use, +// returning the tls.Config along with a done callback that MUST be invoked when +// the handshake completes. If hi is nil or fallback credentials should be used, +// useFallback returns true. +func ServerSideTLSConfig(ctx context.Context, hiRC *grpcsync.RefCounted[*HandshakeInfo]) (cfg *tls.Config, useFallback bool, done func(), err error) { + if hiRC == nil { + return nil, true, func() {}, nil + } + hi := hiRC.Value() + if hi == nil || hi.UseFallbackCreds() { + return nil, true, func() {}, nil + } + if !hiRC.TryIncrement() { + return nil, false, func() {}, errors.New("xds: connection closed or HandshakeInfo dead") + } + cfg, err = hi.serverSideTLSConfigInternal(ctx) + if err != nil { + hiRC.Decrement() + return nil, false, func() {}, err + } + return cfg, false, hiRC.Decrement, nil } // UseFallbackCreds returns true when fallback credentials are to be used based @@ -149,23 +195,20 @@ func (hi *HandshakeInfo) GetSANMatchersForTesting() []matcher.StringMatcher { return append([]matcher.StringMatcher{}, hi.sanMatchers...) } -// ClientSideTLSConfig constructs a tls.Config to be used in a client-side -// handshake based on the contents of the HandshakeInfo. +// clientSideTLSConfigInternal constructs a tls.Config to be used in a +// client-side handshake based on the contents of the HandshakeInfo. // // hostname is passed as a parameter here instead of being part of the // HandshakeInfo because HandshakeInfo contains cluster-level security // configuration that applies to all endpoints in the cluster, while hostname is // specific to each endpoint. This allows sharing a single HandshakeInfo // instance across multiple endpoints in the same cluster. -func (hi *HandshakeInfo) ClientSideTLSConfig(ctx context.Context, hostname string) (*tls.Config, error) { +func (hi *HandshakeInfo) clientSideTLSConfigInternal(ctx context.Context, hostname string) (*tls.Config, error) { // On the client side, rootProvider is mandatory. IdentityProvider is // optional based on whether the client is doing TLS or mTLS. if hi.rootProvider == nil { return nil, errors.New("xds: CertificateProvider to fetch trusted roots is missing, cannot perform TLS handshake. Please check configuration on the management server") } - // Since the call to KeyMaterial() can block, we read the providers under - // the lock but call the actual function after releasing the lock. - rootProv, idProv := hi.rootProvider, hi.identityProvider // InsecureSkipVerify needs to be set to true because we need to perform // custom verification to check the SAN on the received certificate. @@ -177,7 +220,7 @@ func (hi *HandshakeInfo) ClientSideTLSConfig(ctx context.Context, hostname strin NextProtos: []string{"h2"}, } - km, err := rootProv.KeyMaterial(ctx) + km, err := hi.rootProvider.KeyMaterial(ctx) if err != nil { return nil, fmt.Errorf("xds: fetching trusted roots from CertificateProvider failed: %v", err) } @@ -194,8 +237,8 @@ func (hi *HandshakeInfo) ClientSideTLSConfig(ctx context.Context, hostname strin cfg.VerifyPeerCertificate = hi.buildVerifyFunc(km, true, sni) - if idProv != nil { - km, err := idProv.KeyMaterial(ctx) + if hi.identityProvider != nil { + km, err := hi.identityProvider.KeyMaterial(ctx) if err != nil { return nil, fmt.Errorf("xds: fetching identity certificates from CertificateProvider failed: %v", err) } @@ -279,9 +322,9 @@ func (hi *HandshakeInfo) buildVerifyFunc(km *certprovider.KeyMaterial, isClient } } -// ServerSideTLSConfig constructs a tls.Config to be used in a server-side -// handshake based on the contents of the HandshakeInfo. -func (hi *HandshakeInfo) ServerSideTLSConfig(ctx context.Context) (*tls.Config, error) { +// serverSideTLSConfigInternal constructs a tls.Config to be used in a +// server-side handshake based on the contents of the HandshakeInfo. +func (hi *HandshakeInfo) serverSideTLSConfigInternal(ctx context.Context) (*tls.Config, error) { cfg := &tls.Config{ ClientAuth: tls.NoClientCert, NextProtos: []string{"h2"}, @@ -291,22 +334,19 @@ func (hi *HandshakeInfo) ServerSideTLSConfig(ctx context.Context) (*tls.Config, if hi.identityProvider == nil { return nil, errors.New("xds: CertificateProvider to fetch identity certificate is missing, cannot perform TLS handshake. Please check configuration on the management server") } - // Since the call to KeyMaterial() can block, we read the providers under - // the lock but call the actual function after releasing the lock. - rootProv, idProv := hi.rootProvider, hi.identityProvider if hi.requireClientCert { cfg.ClientAuth = tls.RequireAndVerifyClientCert } // identityProvider is mandatory on the server side. - km, err := idProv.KeyMaterial(ctx) + km, err := hi.identityProvider.KeyMaterial(ctx) if err != nil { return nil, fmt.Errorf("xds: fetching identity certificates from CertificateProvider failed: %v", err) } cfg.Certificates = km.Certs - if rootProv != nil { - km, err := rootProv.KeyMaterial(ctx) + if hi.rootProvider != nil { + km, err := hi.rootProvider.KeyMaterial(ctx) if err != nil { return nil, fmt.Errorf("xds: fetching trusted roots from CertificateProvider failed: %v", err) } diff --git a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go index 3334481274..dc6fc0c4cb 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go @@ -153,6 +153,13 @@ var ( // TODO: Remove this env var once v1.83.0 is released. ControlBufferThrottleLimit = uint64FromEnv("GRPC_GO_EXPERIMENTAL_CONTROL_BUFFER_THROTTLE_LIMIT", 100, 1, 10000) + // ALTSMaxFrameSize is the maximum frame size for ALTS in bytes. + // This can be overridden by setting the environment variable + // "GRPC_GO_EXPERIMENTAL_ALTS_MAX_FRAME_SIZE" (min: 4096, max: 512*1024, capped at + // 512KiB to match altsWriteBufferMaxSize in + // credentials/alts/internal/conn/record.go). + ALTSMaxFrameSize = uint64FromEnv("GRPC_GO_EXPERIMENTAL_ALTS_MAX_FRAME_SIZE", 4096, 4096, 512*1024) + // EnableReceiveBufferCompaction enables the compaction of data buffers // to reduce the number of buffers in the receive buffer. // diff --git a/vendor/google.golang.org/grpc/internal/envconfig/xds.go b/vendor/google.golang.org/grpc/internal/envconfig/xds.go index e4b6919138..5ec39bd756 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/xds.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/xds.go @@ -98,4 +98,9 @@ var ( // filter. For more details, see: // https://github.com/grpc/proposal/blob/master/A83-xds-gcp-authn-filter.md GCPAuthenticationFilterEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_GCP_AUTHENTICATION_FILTER", false) + + // XDSClientExtAuthzEnabled indicates whether the external authorization + // filter is enabled on the client side. For more details, see: + // https://github.com/grpc/proposal/blob/master/A92-xds-ext-authz.md + XDSClientExtAuthzEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_EXT_AUTHZ_ON_CLIENT", false) ) diff --git a/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go b/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go index d4999fcca8..caa9dd68ea 100644 --- a/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go +++ b/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go @@ -41,7 +41,7 @@ type CallbackSerializer struct { // its resources. done chan struct{} - callbacks *buffer.Unbounded + callbacks *buffer.Unbounded[func(context.Context)] } // NewCallbackSerializer returns a new CallbackSerializer instance. The provided @@ -52,7 +52,7 @@ type CallbackSerializer struct { func NewCallbackSerializer(ctx context.Context) *CallbackSerializer { cs := &CallbackSerializer{ done: make(chan struct{}), - callbacks: buffer.NewUnbounded(), + callbacks: buffer.NewUnbounded[func(context.Context)](), } go cs.run(ctx) return cs @@ -113,7 +113,7 @@ func (cs *CallbackSerializer) run(ctx context.Context) { // Run all callbacks. for cb := range cs.callbacks.Get() { cs.callbacks.Load() - cb.(func(context.Context))(ctx) + cb(ctx) } } diff --git a/vendor/google.golang.org/grpc/internal/grpcsync/refcounted.go b/vendor/google.golang.org/grpc/internal/grpcsync/refcounted.go new file mode 100644 index 0000000000..bca9b83754 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpcsync/refcounted.go @@ -0,0 +1,109 @@ +/* + * + * Copyright 2026 gRPC 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 grpcsync + +import ( + "sync/atomic" + + "google.golang.org/grpc/grpclog" +) + +var logger = grpclog.Component("grpcsync") + +// RefCounted is a reference counted wrapper of type T. It tracks the number of +// active references and runs a cleanup when the last reference is released. +type RefCounted[T any] struct { + val T + refCount atomic.Int32 + onZero func() +} + +// NewRefCounted creates a new RefCounted instance wrapping the given value with +// initial refcount of one. +// +// The value should typically be a pointer, interface, or handle rather than a +// plain value type (such as a struct or primitive value). +// +// The provided onZero callback must not be nil, and is executed exactly once +// when the reference count drops to zero. Panics if onZero is nil. +// +// WARNING: onZero runs synchronously inside Decrement; it must not acquire +// locks held by Decrement callers. +func NewRefCounted[T any](val T, onZero func()) *RefCounted[T] { + if onZero == nil { + panic("grpcsync: onZero callback cannot be nil") + } + rc := &RefCounted[T]{ + val: val, + onZero: onZero, + } + rc.refCount.Store(1) + return rc +} + +// Value returns the encapsulated resource. +func (rc *RefCounted[T]) Value() T { + return rc.val +} + +// TryIncrement attempts to increment the reference count, returning true if +// successful. It returns false if the count has already reached 0, indicating +// the resource has been cleaned up and cannot be resurrected. +// +// WARNING: Avoid calling TryIncrement on hot paths when an active reference is +// already guaranteed by the caller; use Increment instead to bypass the +// CompareAndSwap loop overhead. TryIncrement should be reserved for speculative +// lookups (such as fetching from a cache or map) where the resource might be +// dead. +func (rc *RefCounted[T]) TryIncrement() bool { + // Utilize a CompareAndSwap loop to prevent race conditions where a concurrent + // decrement could drop the count to zero between the read and the increment + // operation, which would otherwise inadvertently resurrect a closed resource. + for { + count := rc.refCount.Load() + if count <= 0 { + return false // Already dead or dying + } + if rc.refCount.CompareAndSwap(count, count+1) { + return true + } + } +} + +// Increment increments the reference count. +// +// WARNING: Call Increment only when there is a guarantee that an active +// reference is already present, ensuring the resource is not dead. If there is +// a possibility that the resource is dead or its reference count might have +// reached zero, call TryIncrement instead. +func (rc *RefCounted[T]) Increment() { + if rc.refCount.Add(1) <= 1 { + logger.Errorf("Resource already closed or dead") + } +} + +// Decrement decrements the reference count. If it drops to zero, the onZero +// callback is executed synchronously before this method returns. +func (rc *RefCounted[T]) Decrement() { + if v := rc.refCount.Add(-1); v < 0 { + logger.Errorf("Refcount cannot be negative") + } else if v == 0 { + rc.onZero() + } +} diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go index 4b3d563f8d..2b7fa6b08b 100644 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ b/vendor/google.golang.org/grpc/internal/internal.go @@ -245,6 +245,10 @@ var ( AsyncReporterCleanupDelegate = func(cleanup func()) func() { return cleanup } + + // XDSFilterWrapperOption returns a ServerOption that sets the internal + // stream wrapper used for server-side xDS HTTP filters. + XDSFilterWrapperOption any // func(func(grpc.ServerStream) (grpc.ServerStream, error)) grpc.ServerOption ) // HealthChecker defines the signature of the client-side LB channel health diff --git a/vendor/google.golang.org/grpc/internal/optional/optional.go b/vendor/google.golang.org/grpc/internal/optional/optional.go new file mode 100644 index 0000000000..218794af6a --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/optional/optional.go @@ -0,0 +1,47 @@ +/* + * + * Copyright 2026 gRPC 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 optional implements a generic optional type. +package optional + +// Optional represents an optional value of type T. The zero value is usable and +// indicates that no value is set. This type is not safe for concurrent access. +type Optional[T any] struct { + val T + set bool +} + +// New creates a new Optional type with the provided value. +func New[T any](value T) Optional[T] { + return Optional[T]{ + val: value, + set: true, + } +} + +// Value returns the underlying value and a boolean indicating if the value is +// set. If the value is not set, it returns the zero value of T and false. +func (o *Optional[T]) Value() (T, bool) { + return o.val, o.set +} + +// SetValue updates or adds the value to Optional. +func (o *Optional[T]) SetValue(v T) { + o.val = v + o.set = true +} diff --git a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go index 238950bbbf..ead6dda4e9 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go +++ b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go @@ -42,6 +42,10 @@ type RPCInfo struct { // efficiency reasons. SelectConfig should not be blocking. Context context.Context Method string // i.e. "/Service/Method" + // Authority is the target authority (host) name of the RPC. This is required + // for HTTP filters (such as external processing) to populate request + // attributes. + Authority string } // RPCConfig describes the configuration to use for each RPC. @@ -54,17 +58,6 @@ type RPCConfig struct { Interceptor any } -// ServerInterceptor is an interceptor for incoming RPC's on gRPC server side. -type ServerInterceptor interface { - // AllowRPC checks if an incoming RPC is allowed to proceed based on - // information about connection RPC was received on, and HTTP Headers. This - // information will be piped into context. - AllowRPC(ctx context.Context) error // TODO: Make this a real interceptor for filters such as rate limiting. - // Close closes the interceptor. Once called, no new calls to NewStream are - // accepted. Ongoing calls to NewStream are allowed to complete. - Close() -} - type csKeyType string const csKey = csKeyType("grpc.internal.resolver.configSelector") diff --git a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go index b9bae02498..89c938fdb5 100644 --- a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go +++ b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go @@ -219,6 +219,17 @@ type outFlowControlSizeRequest struct { resp chan uint32 } +// outStreamRequestForTesting is used by tests to retrieve a pointer to an outStream +// safely inside the loopyWriter goroutine without racing on loopyWriter.estdStreams. +// By holding the *outStream pointer while streams and transports close down, tests +// can inspect settled accounting values (such as bytesOutStanding) after loopyWriter +// has run to completion without any data races. +type outStreamRequestForTesting struct { + throttledItem + streamID uint32 + resp chan *outStream +} + // closeConnection is an instruction to tell the loopy writer to flush the // framer and exit, which will cause the transport's connection to be closed // (by the client or server). The transport itself will close after the reader @@ -799,6 +810,10 @@ func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequ o.resp <- l.sendQuota } +func (l *loopyWriter) outStreamRequestHandler(o *outStreamRequestForTesting) { + o.resp <- l.estdStreams[o.streamID] +} + func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error { c.onWrite() if str, ok := l.estdStreams[c.streamID]; ok { @@ -896,6 +911,8 @@ func (l *loopyWriter) handle(i any) error { return l.goAwayHandler(i) case *outFlowControlSizeRequest: l.outFlowControlSizeRequestHandler(i) + case *outStreamRequestForTesting: + l.outStreamRequestHandler(i) case closeConnection: // Just return a non-I/O error and run() will flush and close the // connection. diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/vendor/google.golang.org/grpc/internal/transport/http2_client.go index 10d1977415..720fc4e5b0 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -554,8 +554,6 @@ func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) if err != nil { return nil, err } - // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields - // first and create a slice of that exact size. // Make the slice of certain predictable size to reduce allocations made by append. hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te hfLen += len(authData) + len(callAuthData) @@ -575,6 +573,21 @@ func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) if _, ok := ctx.Deadline(); ok { hfLen++ } + // Count the metadata header fields as well so the slice is not reallocated + // while they are appended below. Reserved headers are dropped when writing, + // so this may slightly over-count, which is preferable to growing the slice. + md, added, mdOK := metadataFromOutgoingContextRaw(ctx) + if mdOK { + for _, vv := range md { + hfLen += len(vv) + } + for _, vv := range added { + hfLen += len(vv) / 2 + } + } + for _, vv := range t.md { + hfLen += len(vv) + } headerFields := make([]hpack.HeaderField, 0, hfLen) headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"}) headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme}) @@ -619,7 +632,7 @@ func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } - if md, added, ok := metadataFromOutgoingContextRaw(ctx); ok { + if mdOK { var k string for k, vv := range md { // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. @@ -648,6 +661,9 @@ func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) if isReservedHeader(k) { continue } + if err := imetadata.ValidatePair(k, vv...); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } for _, v := range vv { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } @@ -691,6 +707,9 @@ func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[s for k, v := range data { // Capital header names are illegal in HTTP/2. k = strings.ToLower(k) + if err := imetadata.ValidatePair(k, v); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } authData[k] = v } } @@ -724,6 +743,9 @@ func (t *http2Client) getCallAuthData(ctx context.Context, audience string, call for k, v := range data { // Capital header names are illegal in HTTP/2 k = strings.ToLower(k) + if err := imetadata.ValidatePair(k, v); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } callAuthData[k] = v } } @@ -1226,23 +1248,26 @@ func (t *http2Client) handleData(f *parsedDataFrame) { t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false) return } + } - if s.nonGRPCStatus != nil { - // The frame should be handled as a non-gRPC response body - st := s.handleNonGRPCData(f) - if st != nil { - t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, true) - return - } - if w := s.fc.onRead(size); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: s.id, - increment: w, - }) - } + if s.nonGRPCStatus != nil { + // The frame should be handled as a non-gRPC response body. A non-nil + // status also covers END_STREAM, so no separate handling is needed below. + st := s.handleNonGRPCData(f) + if st != nil { + t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, true) return } + if w := s.fc.onRead(size); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: s.id, + increment: w, + }) + } + return + } + if size > 0 { dataLen := f.data.Len() if f.Header().Flags.Has(http2.FlagDataPadded) { if w := s.fc.onRead(size - uint32(dataLen)); w > 0 { diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/vendor/google.golang.org/grpc/internal/transport/http2_server.go index 82e13e64aa..f11e88cc5b 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -531,6 +531,7 @@ func (t *http2Server) operateHeaders(ctx context.Context, frame *http2.MetaHeade if frame.StreamEnded() { // s is just created by the caller. No lock needed. s.state = streamReadDone + s.write(recvMsg{err: io.EOF}) } if timeoutSet { s.ctx, s.cancel = context.WithTimeout(ctx, timeout) diff --git a/vendor/google.golang.org/grpc/internal/transport/http_util.go b/vendor/google.golang.org/grpc/internal/transport/http_util.go index c34975ffef..faa42f8cad 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http_util.go +++ b/vendor/google.golang.org/grpc/internal/transport/http_util.go @@ -300,24 +300,29 @@ func decodeGrpcMessageUnchecked(msg string) string { type bufWriter struct { pool *imem.SimpleBufferPool - buf []byte + bufHandle *[]byte offset int batchSize int conn io.Writer err error } +// unsharedBufWriter keeps the unshared slice header in the writer allocation. +type unsharedBufWriter struct { + bufWriter + buf []byte +} + func newBufWriter(conn io.Writer, batchSize int, pool *imem.SimpleBufferPool) *bufWriter { - w := &bufWriter{ - batchSize: batchSize, - conn: conn, - pool: pool, - } - // this indicates that we should use non shared buf - if pool == nil { - w.buf = make([]byte, batchSize) + if pool == nil && batchSize > 0 { + w := &unsharedBufWriter{ + bufWriter: bufWriter{batchSize: batchSize, conn: conn}, + buf: make([]byte, batchSize), + } + w.bufHandle = &w.buf + return &w.bufWriter } - return w + return &bufWriter{batchSize: batchSize, conn: conn, pool: pool} } func (w *bufWriter) Write(b []byte) (int, error) { @@ -328,13 +333,13 @@ func (w *bufWriter) Write(b []byte) (int, error) { n, err := w.conn.Write(b) return n, toIOError(err) } - if w.buf == nil { - b := w.pool.Get(w.batchSize) - w.buf = *b + if w.bufHandle == nil { + w.bufHandle = w.pool.Get(w.batchSize) } + buf := *w.bufHandle written := 0 for len(b) > 0 { - copied := copy(w.buf[w.offset:], b) + copied := copy(buf[w.offset:], b) b = b[copied:] written += copied w.offset += copied @@ -350,15 +355,17 @@ func (w *bufWriter) Write(b []byte) (int, error) { func (w *bufWriter) Flush() error { err := w.flushKeepBuffer() - // Only release the buffer if we are in a "shared" mode - if w.buf != nil && w.pool != nil { - b := w.buf - w.pool.Put(&b) - w.buf = nil - } + w.releaseBuffer() return err } +func (w *bufWriter) releaseBuffer() { + if w.pool != nil && w.bufHandle != nil { + w.pool.Put(w.bufHandle) + w.bufHandle = nil + } +} + func (w *bufWriter) flushKeepBuffer() error { if w.err != nil { return w.err @@ -366,9 +373,13 @@ func (w *bufWriter) flushKeepBuffer() error { if w.offset == 0 { return nil } - _, w.err = w.conn.Write(w.buf[:w.offset]) + buf := *w.bufHandle + _, w.err = w.conn.Write(buf[:w.offset]) w.err = toIOError(w.err) w.offset = 0 + if w.err != nil { + w.releaseBuffer() + } return w.err } diff --git a/vendor/google.golang.org/grpc/internal/transport/transport.go b/vendor/google.golang.org/grpc/internal/transport/transport.go index 5fc901e5cf..fc656b36c9 100644 --- a/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -89,10 +89,10 @@ type recvMsg struct { // recvBuffer is an unbounded channel of recvMsg structs. // -// Note: recvBuffer differs from buffer.Unbounded only in the fact that it -// holds a channel of recvMsg structs instead of objects implementing "item" -// interface. recvBuffer is written to much more often and using strict recvMsg -// structs helps avoid allocation in "recvBuffer.put" +// Note: recvBuffer differs from buffer.Unbounded in that it provides in-place +// value initialization (via init) to avoid struct pointer allocations on +// streams, and automatically frees pooled mem.Buffer payloads when stream +// errors occur. type recvBuffer struct { c chan recvMsg mu sync.Mutex @@ -466,15 +466,18 @@ func (s *Stream) ReadMessageHeader(header []byte) (err error) { return er } s.readRequester.requestRead(len(header)) + bytesRead := 0 for len(header) != 0 { n, err := s.trReader.ReadMessageHeader(header) + bytesRead += n header = header[n:] if len(header) == 0 { err = nil } if err != nil { - if n > 0 && err == io.EOF { + if bytesRead > 0 && err == io.EOF { err = io.ErrUnexpectedEOF + s.trReader.er = err } return err } @@ -505,19 +508,22 @@ func (s *Stream) read(n int) (data mem.BufferSlice, err error) { allocCap := min(ceil(n, http2MaxFrameLen), 128) data = make(mem.BufferSlice, 0, allocCap) s.readRequester.requestRead(n) + bytesRead := 0 for n != 0 { buf, err := s.trReader.Read(n) var bufLen int if buf != nil { bufLen = buf.Len() } + bytesRead += bufLen n -= bufLen if n == 0 { err = nil } if err != nil { - if bufLen > 0 && err == io.EOF { + if bytesRead > 0 && err == io.EOF { err = io.ErrUnexpectedEOF + s.trReader.er = err } data.Free() return nil, err diff --git a/vendor/google.golang.org/grpc/internal/xds/balancer/clusterimpl/clusterimpl.go b/vendor/google.golang.org/grpc/internal/xds/balancer/clusterimpl/clusterimpl.go index 73247d4d00..36b84c049c 100644 --- a/vendor/google.golang.org/grpc/internal/xds/balancer/clusterimpl/clusterimpl.go +++ b/vendor/google.golang.org/grpc/internal/xds/balancer/clusterimpl/clusterimpl.go @@ -41,6 +41,7 @@ import ( "google.golang.org/grpc/internal/balancer/gracefulswitch" "google.golang.org/grpc/internal/credentials/xds" "google.golang.org/grpc/internal/grpclog" + "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/pretty" xdsinternal "google.golang.org/grpc/internal/xds" @@ -82,7 +83,7 @@ func (bb) Build(cc balancer.ClientConn, bOpts balancer.BuildOptions) balancer.Ba loadWrapper: loadstore.NewWrapper(), requestCountMax: defaultRequestCountMax, } - b.xdsHIPtr.Store(xds.NewHandshakeInfo(nil, nil, nil, false, "", false, false)) + b.xdsHIPtr.Store(xds.NewHandshakeInfo(nil, nil, nil, "", false, false, false)) b.logger = prefixLogger(b) b.child = gracefulswitch.NewBalancer(b, bOpts) b.logger.Infof("Created") @@ -127,13 +128,11 @@ type clusterImplBalancer struct { lrsServer *bootstrap.ServerConfig // Load reporting server configuration. dropCategories []DropConfig // The categories for drops. child *gracefulswitch.Balancer - xdsHIPtr atomic.Pointer[xds.HandshakeInfo] // Accessed atomically as it is shared between the balancer and the transport. + xdsHIPtr atomic.Pointer[grpcsync.RefCounted[*xds.HandshakeInfo]] // Accessed atomically as it is shared between the balancer and the transport. xdsCredsInUse bool - // The certificate providers are cached here to that they can be closed when - // a new provider is to be created. - cachedRoot certprovider.Provider - cachedIdentity certprovider.Provider + // The active security configuration received from the control plane. + securityConfig *xdsresource.SecurityConfig // The following fields are protected by mu, since they are accessed in // balancer API methods and in methods called from the child policy. @@ -151,6 +150,19 @@ type clusterImplBalancer struct { lrsReportEndpointMetrics *xdsresource.LRSReportEndpointMetricsConfig // LRS metrics to propagate. } +// dropRequestsPerMillion scales a drop overload's numerator and denominator to +// a number of requests to drop per million. numerator can be as large as a +// million (a 100% drop), so the multiplication is done in uint64 to avoid +// overflowing a uint32, and the result is capped at a million because a drop +// ratio above 100% is treated as 100%. +func dropRequestsPerMillion(numerator, denominator uint32) uint32 { + rpm := uint64(numerator) * million / uint64(denominator) + if rpm > million { + rpm = million + } + return uint32(rpm) +} + // handleClusterConfigLocked updates the internal state of the balancer with the // new cluster configuration. It returns true if a new picker needs to be // generated as a result of these changes. It must be called with b.mu held. @@ -172,7 +184,7 @@ func (b *clusterImplBalancer) handleClusterConfigLocked(clusterConfig xdsresourc for _, d := range edsUpdate.Drops { newDrops = append(newDrops, DropConfig{ Category: d.Category, - RequestsPerMillion: d.Numerator * million / d.Denominator, + RequestsPerMillion: dropRequestsPerMillion(d.Numerator, d.Denominator), }) } if !slices.Equal(b.dropCategories, newDrops) { @@ -313,6 +325,33 @@ func buildProviderFunc(configs map[string]*certprovider.BuildableConfig, instanc return provider, nil } +func (b *clusterImplBalancer) buildProviders(config *xdsresource.SecurityConfig) (certprovider.Provider, certprovider.Provider, error) { + cpc := b.xdsClient.BootstrapConfig().CertProviderConfigs() + var rootProvider certprovider.Provider + if config.UseSystemRootCerts { + rootProvider = systemRootCertsProvider{} + } else { + rp, err := buildProvider(cpc, config.RootInstanceName, config.RootCertName, false, true) + if err != nil { + return nil, nil, err + } + rootProvider = rp + } + + var identityProvider certprovider.Provider + if name, cert := config.IdentityInstanceName, config.IdentityCertName; name != "" { + ip, err := buildProvider(cpc, name, cert, true, false) + if err != nil { + if rootProvider != nil { + rootProvider.Close() + } + return nil, nil, err + } + identityProvider = ip + } + return rootProvider, identityProvider, nil +} + // handleSecurityConfig processes the security configuration received from the // management server, creates appropriate certificate provider plugins, and // updates the HandshakeInfo which is added as an address attribute in @@ -321,7 +360,7 @@ func (b *clusterImplBalancer) handleSecurityConfig(config *xdsresource.SecurityC // If xdsCredentials are not in use, i.e, the user did not want to get // security configuration from an xDS server, we should not be acting on the // received security config here. Doing so poses a security threat. - if !b.xdsCredsInUse { + if !b.xdsCredsInUse || config.Equal(b.securityConfig) { return nil } @@ -329,48 +368,25 @@ func (b *clusterImplBalancer) handleSecurityConfig(config *xdsresource.SecurityC // not sent any security configuration. The xdsCredentials implementation // handles this by delegating to its fallback credentials. if config == nil { - // We need to explicitly set the fields to nil here since this might be - // a case of switching from a good security configuration to an empty - // one where fallback credentials are to be used. - b.xdsHIPtr.Store(xds.NewHandshakeInfo(nil, nil, nil, false, "", false, false)) - return nil - - } - - // A root provider is required whether we are using TLS or mTLS. - cpc := b.xdsClient.BootstrapConfig().CertProviderConfigs() - var rootProvider certprovider.Provider - if config.UseSystemRootCerts { - rootProvider = systemRootCertsProvider{} - } else { - rp, err := buildProvider(cpc, config.RootInstanceName, config.RootCertName, false, true) - if err != nil { - return err + b.securityConfig = nil + oldHI := b.xdsHIPtr.Swap(xds.NewHandshakeInfo(nil, nil, nil, "", false, false, false)) + if oldHI != nil { + oldHI.Decrement() } - rootProvider = rp + return nil } - // The identity provider is only present when using mTLS. - var identityProvider certprovider.Provider - if name, cert := config.IdentityInstanceName, config.IdentityCertName; name != "" { - var err error - identityProvider, err = buildProvider(cpc, name, cert, true, false) - if err != nil { - return err - } + rootProvider, identityProvider, err := b.buildProviders(config) + if err != nil { + return err } - // Close the old providers and cache the new ones. - if b.cachedRoot != nil { - b.cachedRoot.Close() - } - if b.cachedIdentity != nil { - b.cachedIdentity.Close() + newHI := xds.NewHandshakeInfo(rootProvider, identityProvider, config.SubjectAltNameMatchers, config.SNI, false, config.AutoSNISANValidation, config.UseAutoHostSNI) + b.securityConfig = config + oldHI := b.xdsHIPtr.Swap(newHI) + if oldHI != nil { + oldHI.Decrement() } - b.cachedRoot = rootProvider - b.cachedIdentity = identityProvider - - b.xdsHIPtr.Store(xds.NewHandshakeInfo(rootProvider, identityProvider, config.SubjectAltNameMatchers, false, config.SNI, config.AutoSNISANValidation, config.UseAutoHostSNI)) return nil } @@ -499,12 +515,11 @@ func (b *clusterImplBalancer) Close() { b.cancelLoadReport(stopCtx) b.cancelLoadReport = nil } - if b.cachedRoot != nil { - b.cachedRoot.Close() - } - if b.cachedIdentity != nil { - b.cachedIdentity.Close() + oldHI := b.xdsHIPtr.Swap(nil) + if oldHI != nil { + oldHI.Decrement() } + b.securityConfig = nil b.logger.Infof("Shutdown") } diff --git a/vendor/google.golang.org/grpc/internal/xds/balancer/outlierdetection/balancer.go b/vendor/google.golang.org/grpc/internal/xds/balancer/outlierdetection/balancer.go index e47ac40671..0904c5d6b4 100644 --- a/vendor/google.golang.org/grpc/internal/xds/balancer/outlierdetection/balancer.go +++ b/vendor/google.golang.org/grpc/internal/xds/balancer/outlierdetection/balancer.go @@ -83,8 +83,8 @@ func (bb) Build(cc balancer.ClientConn, bOpts balancer.BuildOptions) balancer.Ba closed: grpcsync.NewEvent(), done: grpcsync.NewEvent(), addrs: make(map[string]*endpointInfo), - scUpdateCh: buffer.NewUnbounded(), - pickerUpdateCh: buffer.NewUnbounded(), + scUpdateCh: buffer.NewUnbounded[any](), + pickerUpdateCh: buffer.NewUnbounded[any](), channelzParent: bOpts.ChannelzParent, endpoints: resolver.NewEndpointMap[*endpointInfo](), metricsRecorder: cc.MetricsRecorder(), // we use an explicit field instead of using cc.MetricsRecorder() so we can override the metric recorder in tests. @@ -229,8 +229,8 @@ type outlierDetectionBalancer struct { updateUnconditionally bool numEndpointsEjected int // For fast calculations of percentage of endpoints ejected - scUpdateCh *buffer.Unbounded - pickerUpdateCh *buffer.Unbounded + scUpdateCh *buffer.Unbounded[any] + pickerUpdateCh *buffer.Unbounded[any] } // noopConfig returns whether this balancer is configured with a logical no-op diff --git a/vendor/google.golang.org/grpc/internal/xds/balancer/outlierdetection/subconn_wrapper.go b/vendor/google.golang.org/grpc/internal/xds/balancer/outlierdetection/subconn_wrapper.go index bff6774199..ed9d963f97 100644 --- a/vendor/google.golang.org/grpc/internal/xds/balancer/outlierdetection/subconn_wrapper.go +++ b/vendor/google.golang.org/grpc/internal/xds/balancer/outlierdetection/subconn_wrapper.go @@ -40,7 +40,7 @@ type subConnWrapper struct { listener func(balancer.SubConnState) - scUpdateCh *buffer.Unbounded + scUpdateCh *buffer.Unbounded[any] // The following fields are only referenced in the context of a work // serializing buffer and don't need to be protected by a mutex. diff --git a/vendor/google.golang.org/grpc/internal/xds/balancer/priority/balancer.go b/vendor/google.golang.org/grpc/internal/xds/balancer/priority/balancer.go index e842920ffc..7ce430eb28 100644 --- a/vendor/google.golang.org/grpc/internal/xds/balancer/priority/balancer.go +++ b/vendor/google.golang.org/grpc/internal/xds/balancer/priority/balancer.go @@ -61,7 +61,7 @@ func (bb) Build(cc balancer.ClientConn, bOpts balancer.BuildOptions) balancer.Ba cc: cc, done: grpcsync.NewEvent(), children: make(map[string]*childBalancer), - childBalancerStateUpdate: buffer.NewUnbounded(), + childBalancerStateUpdate: buffer.NewUnbounded[any](), } b.logger = prefixLogger(b) @@ -97,7 +97,7 @@ type priorityBalancer struct { cc balancer.ClientConn bg *balancergroup.BalancerGroup done *grpcsync.Event - childBalancerStateUpdate *buffer.Unbounded + childBalancerStateUpdate *buffer.Unbounded[any] mu sync.Mutex childInUse string diff --git a/vendor/google.golang.org/grpc/internal/xds/bootstrap/bootstrap.go b/vendor/google.golang.org/grpc/internal/xds/bootstrap/bootstrap.go index 79fb79020c..f866da0e8e 100644 --- a/vendor/google.golang.org/grpc/internal/xds/bootstrap/bootstrap.go +++ b/vendor/google.golang.org/grpc/internal/xds/bootstrap/bootstrap.go @@ -120,6 +120,176 @@ func (ccs CallCredsConfigs) String() string { return strings.Join(creds, ",") } +// AllowedGRPCService contains credentials config for an allowed gRPC service. +type AllowedGRPCService struct { + // targetURI is the fully-qualified side-channel target this entry + // applies to. It is the map key under which the service is stored, + // copied in during parsing so the service is self-describing. + targetURI string + // channelCreds is the list of channel-credential configs from the + // bootstrap JSON. Kept for Equal and MarshalJSON. + channelCreds []ChannelCreds + // callCredsConfigs is the list of call-credential configs from the + // bootstrap JSON. Kept for Equal and MarshalJSON. + callCredsConfigs []CallCredsConfig + // selectedChannelCreds is the first channel-creds entry whose type the + // client supports; it is the one used to build the side channel. + selectedChannelCreds ChannelCreds + // dialOptions are built from the selected channel and call credentials + // and passed to grpc.NewClient when creating the side channel. + dialOptions []grpc.DialOption + // cleanups release resources (credential bundles, file watchers) built + // for this service; run when the owning Config is no longer needed. + cleanups []func() +} + +// TargetURI returns the fully-qualified target URI this service applies to. +func (a *AllowedGRPCService) TargetURI() string { + return a.targetURI +} + +// DialOptions returns the dial options built from this service's selected +// channel and call credentials, for use when creating the side channel. +func (a *AllowedGRPCService) DialOptions() []grpc.DialOption { + return a.dialOptions +} + +// Cleanups returns cleanups to run when the service is no longer needed. +func (a *AllowedGRPCService) Cleanups() []func() { + return a.cleanups +} + +// Equal reports whether a and other are considered equal. +func (a *AllowedGRPCService) Equal(other *AllowedGRPCService) bool { + if a == nil && other == nil { + return true + } + if a == nil || other == nil { + return false + } + if a.targetURI != other.targetURI { + return false + } + if !slices.EqualFunc(a.channelCreds, other.channelCreds, ChannelCreds.Equal) { + return false + } + return slices.EqualFunc(a.callCredsConfigs, other.callCredsConfigs, CallCredsConfig.Equal) +} + +type allowedGRPCServiceJSON struct { + ChannelCreds []ChannelCreds `json:"channel_creds,omitempty"` + CallCredsConfigs []CallCredsConfig `json:"call_creds,omitempty"` +} + +// allowedGRPCServicesEnabled reports whether any feature that consumes the +// allowed_grpc_services field is enabled. Per gRFC A102 the field has no +// dedicated env var; it is guarded by the env vars of its consuming features +// (currently only ext_proc on the client; OR in ext_authz/RLQS guards as +// those features are implemented). +func allowedGRPCServicesEnabled() bool { + return envconfig.XDSClientExtProcEnabled +} + +// AllowedGRPCServices maps a target URI to the credentials gRPC may use for +// that side channel when the xDS server that configured it is untrusted +// (gRFC A102). +type AllowedGRPCServices map[string]*AllowedGRPCService + +// UnmarshalJSON parses and validates the allowed_grpc_services field. The +// field is parsed only when a consuming feature is enabled, so a disabled +// feature can neither build credentials nor fail bootstrap. +func (s *AllowedGRPCServices) UnmarshalJSON(data []byte) error { + if !allowedGRPCServicesEnabled() { + return nil + } + services := make(map[string]*AllowedGRPCService) + if err := json.Unmarshal(data, &services); err != nil { + return err + } + // A JSON null decodes to a nil entry without calling UnmarshalJSON; reject + // it since channel_creds is required, and stamp the target on each service. + for target, svc := range services { + if svc == nil { + return fmt.Errorf("xds: allowed_grpc_services entry %q has no configuration in bootstrap config", target) + } + svc.targetURI = target + } + *s = services + return nil +} + +// UnmarshalJSON parses the JSON data and validates its credentials. +func (a *AllowedGRPCService) UnmarshalJSON(data []byte) (err error) { + var jsonS allowedGRPCServiceJSON + if err := json.Unmarshal(data, &jsonS); err != nil { + return err + } + + // Build into locals and assign the receiver only on success, so a + // mid-parse error never leaves the receiver partially mutated. Credentials + // built before a failure are released by this deferred cleanup. + var cleanups []func() + defer func() { + if err != nil { + for _, f := range cleanups { + f() + } + } + }() + + var credsDialOption grpc.DialOption + var selectedChannelCreds ChannelCreds + for _, cc := range jsonS.ChannelCreds { + c := bootstrap.GetChannelCredentials(cc.Type) + if c == nil { + continue + } + bundle, cancel, err := c.Build(cc.Config) + if err != nil { + return fmt.Errorf("xds: failed to build credentials bundle from bootstrap for allowed grpc service: type %q, err: %v", cc.Type, err) + } + selectedChannelCreds = cc + credsDialOption = grpc.WithCredentialsBundle(bundle) + cleanups = append(cleanups, cancel) + break + } + + // If no channel-creds type in the list was supported, credsDialOption is + // still nil after the loop; that is a validation error. + if credsDialOption == nil { + return fmt.Errorf("xds: no supported channel credentials found for allowed grpc service in config:\n%s", string(data)) + } + dialOptions := []grpc.DialOption{credsDialOption} + + for _, cfg := range jsonS.CallCredsConfigs { + c := bootstrap.GetCallCredentials(cfg.Type) + if c == nil { + continue + } + callCreds, cancel, err := c.Build(cfg.Config) + if err != nil { + return fmt.Errorf("xds: failed to build call credentials from bootstrap for allowed grpc service: type %q, err: %v", cfg.Type, err) + } + dialOptions = append(dialOptions, grpc.WithPerRPCCredentials(callCreds)) + cleanups = append(cleanups, cancel) + } + + a.channelCreds = jsonS.ChannelCreds + a.callCredsConfigs = jsonS.CallCredsConfigs + a.selectedChannelCreds = selectedChannelCreds + a.dialOptions = dialOptions + a.cleanups = cleanups + return nil +} + +// MarshalJSON marshals the allowed gRPC service into JSON format. +func (a *AllowedGRPCService) MarshalJSON() ([]byte, error) { + return json.Marshal(allowedGRPCServiceJSON{ + ChannelCreds: a.channelCreds, + CallCredsConfigs: a.callCredsConfigs, + }) +} + // ServerConfigs represents a collection of server configurations. type ServerConfigs []*ServerConfig @@ -461,6 +631,16 @@ type Config struct { // A map from certprovider instance names to parsed buildable configs. certProviderConfigs map[string]*certprovider.BuildableConfig + + // allowedGRPCServices is the side-channel allowlist parsed from the + // allowed_grpc_services field (gRFC A102). + allowedGRPCServices AllowedGRPCServices +} + +// AllowedGRPCServices returns the allowlist of gRPC services. +// Callers must not modify the returned map. +func (c *Config) AllowedGRPCServices() AllowedGRPCServices { + return c.allowedGRPCServices } // XDSServers returns the top-level list of management servers to connect to, @@ -550,7 +730,9 @@ func (c *Config) Equal(other *Config) bool { return false case c.clientDefaultListenerResourceNameTemplate != other.clientDefaultListenerResourceNameTemplate: return false - case !maps.EqualFunc(c.authorities, other.authorities, func(a, b *Authority) bool { return a.Equal(b) }): + case !maps.EqualFunc(c.authorities, other.authorities, (*Authority).Equal): + return false + case !maps.EqualFunc(c.allowedGRPCServices, other.allowedGRPCServices, (*AllowedGRPCService).Equal): return false case !c.node.Equal(other.node): return false @@ -572,6 +754,7 @@ type configJSON struct { ClientDefaultListenerResourceNameTemplate string `json:"client_default_listener_resource_name_template,omitempty"` Authorities map[string]*Authority `json:"authorities,omitempty"` Node node `json:"node,omitempty"` + AllowedGRPCServices AllowedGRPCServices `json:"allowed_grpc_services,omitempty"` } // MarshalJSON returns marshaled JSON bytes corresponding to this config. @@ -583,6 +766,7 @@ func (c *Config) MarshalJSON() ([]byte, error) { ClientDefaultListenerResourceNameTemplate: c.clientDefaultListenerResourceNameTemplate, Authorities: c.authorities, Node: c.node, + AllowedGRPCServices: c.allowedGRPCServices, } return json.MarshalIndent(config, " ", " ") } @@ -594,6 +778,12 @@ func (c *Config) UnmarshalJSON(data []byte) error { // even if the bootstrap configuration did not contain the node field, we // will have a node field with client controlled fields alone. config := configJSON{Node: newNode()} + + // Credentials (bundles, file watchers) eagerly built during unmarshaling + // are intentionally not released if parsing fails below: a failed + // bootstrap is parsed once per process (the xDS client pool memoizes + // GetConfiguration via sync.OnceValues) and is treated as fatal, so the + // leak is bounded and one-time. if err := json.Unmarshal(data, &config); err != nil { return fmt.Errorf("xds: json.Unmarshal(%s) failed during bootstrap: %v", string(data), err) } @@ -604,6 +794,7 @@ func (c *Config) UnmarshalJSON(data []byte) error { c.clientDefaultListenerResourceNameTemplate = config.ClientDefaultListenerResourceNameTemplate c.authorities = config.Authorities c.node = config.Node + c.allowedGRPCServices = config.AllowedGRPCServices // Build the certificate providers configuration to ensure that it is valid. cpcCfgs := make(map[string]*certprovider.BuildableConfig) @@ -723,6 +914,8 @@ type ConfigOptionsForTesting struct { // Node identifies the gRPC client/server node in the // proxyless service mesh. Node json.RawMessage + // AllowedGRPCServices is the allowlist of gRPC services. + AllowedGRPCServices json.RawMessage } // NewContentsForTesting creates a new bootstrap configuration from the passed in @@ -754,6 +947,23 @@ func NewContentsForTesting(opts ConfigOptionsForTesting) ([]byte, error) { if err := json.Unmarshal(opts.Node, &node); err != nil { return nil, fmt.Errorf("failed to unmarshal node configuration %s: %v", string(opts.Node), err) } + allowedGRPCServices := make(AllowedGRPCServices) + if len(opts.AllowedGRPCServices) > 0 { + if err := json.Unmarshal(opts.AllowedGRPCServices, &allowedGRPCServices); err != nil { + return nil, fmt.Errorf("failed to unmarshal allowed_grpc_services configuration: %v", err) + } + // Only the parsed config is needed to marshal the bootstrap JSON below; + // release the credentials built during unmarshal so this test helper + // does not leak file watchers. + for _, svc := range allowedGRPCServices { + if svc == nil { + continue + } + for _, cleanup := range svc.Cleanups() { + cleanup() + } + } + } cfgJSON := configJSON{ XDSServers: servers, CertificateProviders: certProviders, @@ -761,6 +971,7 @@ func NewContentsForTesting(opts ConfigOptionsForTesting) ([]byte, error) { ClientDefaultListenerResourceNameTemplate: opts.ClientDefaultListenerResourceNameTemplate, Authorities: authorities, Node: node, + AllowedGRPCServices: allowedGRPCServices, } contents, err := json.MarshalIndent(cfgJSON, " ", " ") if err != nil { diff --git a/vendor/google.golang.org/grpc/internal/xds/clients/internal/buffer/unbounded.go b/vendor/google.golang.org/grpc/internal/xds/clients/internal/buffer/unbounded.go index 52b8dab892..4d3527d596 100644 --- a/vendor/google.golang.org/grpc/internal/xds/clients/internal/buffer/unbounded.go +++ b/vendor/google.golang.org/grpc/internal/xds/clients/internal/buffer/unbounded.go @@ -27,32 +27,29 @@ import ( // extra goroutines. This is typically used for passing updates from one entity // to another within gRPC. // +// To avoid extra memory allocations and type assertions, using any on +// performance-critical code paths is discouraged. Use concrete types wherever +// possible when instantiating Unbounded. +// // All methods on this type are thread-safe and don't block on anything except // the underlying mutex used for synchronization. -// -// Unbounded supports values of any type to be stored in it by using a channel -// of `any`. This means that a call to Put() incurs an extra memory allocation, -// and also that users need a type assertion while reading. For performance -// critical code paths, using Unbounded is strongly discouraged and defining a -// new type specific implementation of this buffer is preferred. See -// internal/transport/transport.go for an example of this. -type Unbounded struct { - c chan any +type Unbounded[T any] struct { + c chan T closed bool closing bool mu sync.Mutex - backlog []any + backlog []T } // NewUnbounded returns a new instance of Unbounded. -func NewUnbounded() *Unbounded { - return &Unbounded{c: make(chan any, 1)} +func NewUnbounded[T any]() *Unbounded[T] { + return &Unbounded[T]{c: make(chan T, 1)} } var errBufferClosed = errors.New("Put() called on closed buffer.Unbounded") // Put adds t to the unbounded buffer. -func (b *Unbounded) Put(t any) error { +func (b *Unbounded[T]) Put(t T) error { b.mu.Lock() defer b.mu.Unlock() if b.closing { @@ -72,13 +69,14 @@ func (b *Unbounded) Put(t any) error { // Load sends the earliest buffered data, if any, onto the read channel returned // by Get(). Users are expected to call this every time they successfully read a // value from the read channel. -func (b *Unbounded) Load() { +func (b *Unbounded[T]) Load() { b.mu.Lock() defer b.mu.Unlock() if len(b.backlog) > 0 { select { case b.c <- b.backlog[0]: - b.backlog[0] = nil + var zero T + b.backlog[0] = zero b.backlog = b.backlog[1:] default: } @@ -96,14 +94,14 @@ func (b *Unbounded) Load() { // // If the unbounded buffer is closed, the read channel returned by this method // is closed after all data is drained. -func (b *Unbounded) Get() <-chan any { +func (b *Unbounded[T]) Get() <-chan T { return b.c } // Close closes the unbounded buffer. No subsequent data may be Put(), and the // channel returned from Get() will be closed after all the data is read and // Load() is called for the final time. -func (b *Unbounded) Close() { +func (b *Unbounded[T]) Close() { b.mu.Lock() defer b.mu.Unlock() if b.closing { diff --git a/vendor/google.golang.org/grpc/internal/xds/clients/internal/syncutil/callback_serializer.go b/vendor/google.golang.org/grpc/internal/xds/clients/internal/syncutil/callback_serializer.go index baab133f24..54dc6e4746 100644 --- a/vendor/google.golang.org/grpc/internal/xds/clients/internal/syncutil/callback_serializer.go +++ b/vendor/google.golang.org/grpc/internal/xds/clients/internal/syncutil/callback_serializer.go @@ -36,7 +36,7 @@ type CallbackSerializer struct { // its resources. done chan struct{} - callbacks *buffer.Unbounded + callbacks *buffer.Unbounded[func(context.Context)] } // NewCallbackSerializer returns a new CallbackSerializer instance. The provided @@ -47,7 +47,7 @@ type CallbackSerializer struct { func NewCallbackSerializer(ctx context.Context) *CallbackSerializer { cs := &CallbackSerializer{ done: make(chan struct{}), - callbacks: buffer.NewUnbounded(), + callbacks: buffer.NewUnbounded[func(context.Context)](), } go cs.run(ctx) return cs @@ -87,7 +87,7 @@ func (cs *CallbackSerializer) run(ctx context.Context) { // Run all callbacks. for cb := range cs.callbacks.Get() { cs.callbacks.Load() - cb.(func(context.Context))(ctx) + cb(ctx) } } diff --git a/vendor/google.golang.org/grpc/internal/xds/clients/xdsclient/authority.go b/vendor/google.golang.org/grpc/internal/xds/clients/xdsclient/authority.go index 3b5666bf1b..f5d78eb094 100644 --- a/vendor/google.golang.org/grpc/internal/xds/clients/xdsclient/authority.go +++ b/vendor/google.golang.org/grpc/internal/xds/clients/xdsclient/authority.go @@ -347,7 +347,7 @@ func (a *authority) handleADSResourceUpdate(serverConfig *ServerConfig, rType Re onDone() } } - funcsToSchedule := []func(context.Context){} + var funcsToSchedule []func(context.Context) defer func() { if len(funcsToSchedule) == 0 { // When there are no watchers for the resources received as part of @@ -368,26 +368,35 @@ func (a *authority) handleADSResourceUpdate(serverConfig *ServerConfig, rType Re continue } - // On error, keep previous version of the resource. But update status - // and error. - if uErr.Err != nil { + if err := uErr.Err; err != nil { if a.metricsReporter != nil { a.metricsReporter.ReportMetric(&metrics.ResourceUpdateInvalid{ ServerURI: serverConfig.ServerIdentifier.ServerURI, ResourceType: rType.TypeName, }) } - state.md.ErrState = md.ErrState - state.md.Status = md.Status - for watcher := range state.watchers { - watcher := watcher - err := uErr.Err - watcherCnt.Add(1) - if state.cache == nil { - funcsToSchedule = append(funcsToSchedule, func(context.Context) { watcher.ResourceError(err, done) }) - } else { - funcsToSchedule = append(funcsToSchedule, func(context.Context) { watcher.AmbientError(err, done) }) + + // Notify watchers only if this is not a duplicated error from the previous update. + if errState := state.md.ErrState; errState == nil || errState.Err == nil || state.md.ErrState.Err.Error() != err.Error() { + for watcher := range state.watchers { + watcherCnt.Add(1) + if state.cache == nil { + funcsToSchedule = append(funcsToSchedule, func(context.Context) { watcher.ResourceError(err, done) }) + } else { + funcsToSchedule = append(funcsToSchedule, func(context.Context) { watcher.AmbientError(err, done) }) + } } } + + // On error, keep previous version of the resource. But update + // status to NACKed and capture the specific per-resource error (and + // not the overall error for the update) in the ErrState field. + state.md.Status = xdsresource.ServiceStatusNACKed + state.md.ErrState = &xdsresource.UpdateErrorMetadata{ + Version: md.ErrState.Version, + Err: err, + Timestamp: md.ErrState.Timestamp, + } + continue } @@ -414,7 +423,6 @@ func (a *authority) handleADSResourceUpdate(serverConfig *ServerConfig, rType Re state.cache = uErr.Resource for watcher := range state.watchers { - watcher := watcher resource := uErr.Resource watcherCnt.Add(1) funcsToSchedule = append(funcsToSchedule, func(context.Context) { watcher.ResourceChanged(resource, done) }) @@ -492,7 +500,6 @@ func (a *authority) handleADSResourceUpdate(serverConfig *ServerConfig, rType Re state.cache = nil state.md = xdsresource.UpdateMetadata{Status: xdsresource.ServiceStatusNotExist} for watcher := range state.watchers { - watcher := watcher watcherCnt.Add(1) funcsToSchedule = append(funcsToSchedule, func(context.Context) { watcher.ResourceError(xdsresource.NewErrorf(xdsresource.ErrorTypeResourceNotFound, "xds: resource %q of type %q has been removed", name, rType.TypeName), done) diff --git a/vendor/google.golang.org/grpc/internal/xds/httpfilter/extconfig.go b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extconfig.go index f93ab5bfa1..cd68714b2a 100644 --- a/vendor/google.golang.org/grpc/internal/xds/httpfilter/extconfig.go +++ b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extconfig.go @@ -19,15 +19,24 @@ package httpfilter import ( + "encoding/base64" "fmt" "regexp" + "strings" + imetadata "google.golang.org/grpc/internal/metadata" "google.golang.org/grpc/internal/xds/matcher" + "google.golang.org/grpc/metadata" v3mutationpb "github.com/envoyproxy/go-control-plane/envoy/config/common/mutation_rules/v3" + v3corepb "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" v3matcherpb "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3" ) +// maxHeaderSize is the maximum length, in bytes, of a header key or value in a +// mutation received from an external processing server. +const maxHeaderSize = 16384 + // HeaderMutationRules specifies the rules for what modifications an external // processing server may make to headers sent on the data plane RPC. type HeaderMutationRules struct { @@ -86,3 +95,232 @@ func HeaderMutationRulesFromProto(mr *v3mutationpb.HeaderMutationRules) (HeaderM rules.DisallowIsError = mr.GetDisallowIsError().GetValue() return rules, nil } + +// ApplyAdditions takes a set of header mutations (for additions and +// modifications) received from an external server and applies them to the +// provided metadata, subject to the rules defined in hmr. +// +// If the DisallowAll field is true, no mutations are performed, and the input +// metadata is returned unmodified. +// +// It iterates through each header mutation, performs validation on the header +// key and value, and checks if the mutation is permitted by the AllowExpr and +// DisallowExpr regular expressions. +// +// A mutation for any of the following headers fails validation and an error is +// returned: +// - Pseudo-headers (keys starting with ':'). +// - The 'host' header. +// - Headers with keys in the reserved 'grpc-' space. +// - Headers with non-lowercase keys. +// - Headers with keys or values exceeding 16384 bytes. +// - Headers with an invalid gRPC header name or header value. +// +// If a mutation is disallowed by the mutation rules and DisallowIsError is +// true, an error is returned. Otherwise, the disallowed mutation is silently +// ignored. +// +// The input metadata must not be nil. +func (hmr *HeaderMutationRules) ApplyAdditions(hvos []*v3corepb.HeaderValueOption, input metadata.MD) error { + if hmr == nil { + hmr = &HeaderMutationRules{} + } + if input == nil { + return fmt.Errorf("input metadata is nil") + } + if hmr.DisallowAll { + return nil + } + + for _, hvo := range hvos { + header := hvo.GetHeader() + key := header.GetKey() + if err := validateHeaderKey(key); err != nil { + return fmt.Errorf("invalid header mutation: %v", err) + } + + value := header.GetValue() + if strings.HasSuffix(key, "-bin") { + value = string(header.GetRawValue()) + } + if len(value) > maxHeaderSize { + return fmt.Errorf("invalid header mutation: value for header key %q exceeds the maximum length of %d bytes", key, maxHeaderSize) + } + // ValidatePair rejects values carrying bytes outside %x20-%x7E. It + // skips the value check for "-bin" keys, whose values the transport + // base64 encodes. + if err := imetadata.ValidatePair(key, value); err != nil { + return fmt.Errorf("invalid header mutation: %v", err) + } + + if !hmr.allow(key) { + if hmr.DisallowIsError { + return fmt.Errorf("header mutation disallowed by headerMutationRules for header key %q", key) + } + continue + } + + // Perform the mutation on output metadata using the append_action + // field from the header value option. + switch hvo.GetAppendAction() { + case v3corepb.HeaderValueOption_APPEND_IF_EXISTS_OR_ADD: + input.Append(key, value) + case v3corepb.HeaderValueOption_ADD_IF_ABSENT: + if input.Get(key) == nil { + input.Set(key, value) + } + case v3corepb.HeaderValueOption_OVERWRITE_IF_EXISTS_OR_ADD: + input.Set(key, value) + case v3corepb.HeaderValueOption_OVERWRITE_IF_EXISTS: + if input.Get(key) != nil { + input.Set(key, value) + } + } + } + return nil +} + +// ApplyRemovals takes a set of headers (for removal) received from an external +// processing server and applies them to the provided metadata, subject to the +// rules defined in hmr. +// +// This method is very similar to ApplyAdditions, except that headers are +// removed here instead of added or mutated as is the case in the latter. See +// ApplyAdditions for more details. +// +// The input metadata must not be nil. +func (hmr *HeaderMutationRules) ApplyRemovals(headersToRemove []string, input metadata.MD) error { + if hmr == nil { + hmr = &HeaderMutationRules{} + } + if input == nil { + return fmt.Errorf("input metadata is nil") + } + if hmr.DisallowAll { + return nil + } + + for _, header := range headersToRemove { + if err := validateHeaderKey(header); err != nil { + return fmt.Errorf("invalid header mutation: %v", err) + } + if !hmr.allow(header) { + if hmr.DisallowIsError { + return fmt.Errorf("header mutation disallowed by headerMutationRules for header %q", header) + } + continue + } + input.Delete(header) + } + return nil +} + +// validateHeaderKey returns a non-nil error if key may not be mutated by an +// external processing server, either because the key is reserved or because it +// is not a valid gRPC header name. +func validateHeaderKey(key string) error { + switch { + case len(key) == 0: + return fmt.Errorf("header key is empty") + case key[0] == ':': + return fmt.Errorf("header key %q is a pseudo-header", key) + case key == "host": + return fmt.Errorf("header key %q is reserved", key) + case strings.HasPrefix(key, "grpc-"): + return fmt.Errorf("header key %q is in the reserved 'grpc-' space", key) + case key != strings.ToLower(key): + return fmt.Errorf("header key %q is not lowercase", key) + case len(key) > maxHeaderSize: + return fmt.Errorf("header key exceeds the maximum length of %d bytes", maxHeaderSize) + } + return imetadata.ValidateKey(key) +} + +func (hmr *HeaderMutationRules) allow(key string) bool { + if hmr.DisallowExpr != nil && hmr.DisallowExpr.MatchString(key) { + return false + } + if hmr.AllowExpr != nil && hmr.AllowExpr.MatchString(key) { + return true + } + if hmr.AllowExpr != nil { + return false + } + return true +} + +// ConstructHeaderMap constructs a HeaderMap from the given metadata and raw +// appended metadata slice, using the following rules: +// - if the header is matched by the disallowed_headers config field, it will +// not be added to the map, otherwise, +// - if the allowed_headers config field is unset or matches the header, the +// header will be added to the map, otherwise, +// - the header will be excluded from the map. +func ConstructHeaderMap(md metadata.MD, added [][]string, allowedHeaders, disallowedHeaders []matcher.StringMatcher) *v3corepb.HeaderMap { + headerMap := &v3corepb.HeaderMap{} + // Process the base metadata map. + for key, values := range md { + if isDisallowedHeader(key, disallowedHeaders) { + continue + } + if isAllowedHeader(key, allowedHeaders) { + for _, value := range values { + headerMap.Headers = append(headerMap.Headers, constructHeader(key, value)) + } + } + } + // Process the raw appended metadata slice. + for _, kvs := range added { + for i := 0; i < len(kvs); i += 2 { + key := strings.ToLower(kvs[i]) + if isDisallowedHeader(key, disallowedHeaders) { + continue + } + if isAllowedHeader(key, allowedHeaders) { + headerMap.Headers = append(headerMap.Headers, constructHeader(key, kvs[i+1])) + } + } + } + if len(headerMap.Headers) == 0 { + return nil + } + return headerMap +} + +func constructHeader(key, value string) *v3corepb.HeaderValue { + rawValue := []byte(value) + if strings.HasSuffix(key, "-bin") { + encoded := make([]byte, base64.StdEncoding.EncodedLen(len(rawValue))) + base64.StdEncoding.Encode(encoded, rawValue) + rawValue = encoded + } + return &v3corepb.HeaderValue{ + Key: key, + RawValue: rawValue, + } +} + +// isDisallowedHeader returns true if the given header key matches any of the +// provided disallowed header matchers. +func isDisallowedHeader(key string, matchers []matcher.StringMatcher) bool { + for _, m := range matchers { + if m.Match(key) { + return true + } + } + return false +} + +// isAllowedHeader returns true if the allowed header matchers list is empty, or +// if the given header key matches any of the provided allowed header matchers. +func isAllowedHeader(key string, matchers []matcher.StringMatcher) bool { + if len(matchers) == 0 { + return true + } + for _, m := range matchers { + if m.Match(key) { + return true + } + } + return false +} diff --git a/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/config.go b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/config.go new file mode 100644 index 0000000000..e3300d3c1d --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/config.go @@ -0,0 +1,184 @@ +/* + * + * Copyright 2026 gRPC 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 extproc + +import ( + "time" + + "google.golang.org/grpc/internal/optional" + "google.golang.org/grpc/internal/xds/httpfilter" + "google.golang.org/grpc/internal/xds/matcher" + "google.golang.org/grpc/internal/xds/xdsclient/xdsresource" + + v3procfilterpb "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ext_proc/v3" +) + +// baseConfig contains the configuration for the external processing +// interceptor. +type baseConfig struct { + httpfilter.FilterConfig + + // The following fields can be set either in the filter config or the override + // config. If both are set, the override config will be used. + + // server is the configuration for the external processing server. + server xdsresource.GRPCServiceConfig + // processingModes specifies the processing mode for each dataplane event. + processingModes processingModes + // failureModeAllow specifies the behavior when the RPC to the external + // processing server fails. If true, the dataplane RPC will be allowed to + // continue. If false, the data plane RPC will be failed with a grpc status + // code of INTERNAL. + failureModeAllow bool + // Attributes to be sent to the external processing server along with the + // request and response dataplane events. + requestAttributes []string + responseAttributes []string + + // The following fields can only be set in the base config. + + // mutationRules specifies the rules for what modifications an external + // processing server may make to headers/trailers sent to it. + mutationRules httpfilter.HeaderMutationRules + // allowedHeaders specifies the headers that are allowed to be sent to the + // external processing server. If unset, all headers are allowed. + allowedHeaders []matcher.StringMatcher + // disallowedHeaders specifies the headers that will not be sent to the + // external processing server. This overrides the above allowedHeaders if a + // header matches both. + disallowedHeaders []matcher.StringMatcher + // disableImmediateResponse specifies whether to disable immediate responses + // from the external processing server. When true, any immediate response + // received from the server is treated as an error (causing the stream to fail + // with an Internal error, or to be bypassed if failureModeAllow is true). + // When false, the immediate response is honored, and the stream is aborted + // with the specified status code and details provided by the external + // processing server. + disableImmediateResponse bool + // observabilityMode determines if the filter waits for the external + // processing server. If true, events are sent to the server in + // "observation-only" mode; the filter does not wait for a response. If false, + // the filter waits for a response, allowing the server to modify events + // before they reach the dataplane. + observabilityMode bool + // deferredCloseTimeout is the duration the filter waits before closing the + // external processing stream after the dataplane RPC completes. This is only + // applicable when observabilityMode is true; otherwise, it is ignored. The + // default value is 5 seconds. + deferredCloseTimeout time.Duration +} + +// overrideConfig contains the configuration for the external processing +// interceptor used for overriding the base config. If a particular field is +// set, that will be used instead of the base config. The fields are similar to +// base config. +type overrideConfig struct { + httpfilter.FilterConfig + server optional.Optional[xdsresource.GRPCServiceConfig] + processingModes optional.Optional[processingModes] + failureModeAllow optional.Optional[bool] + requestAttributes []string + responseAttributes []string +} + +// processingMode defines how headers, trailers, and bodies are handled in +// relation to the external processing server. +type processingMode int + +const ( + // modeSkip indicates that the header/trailer/body should not be sent. + modeSkip processingMode = iota + // modeSend indicates that the header/trailer/body should be sent. + modeSend +) + +type processingModes struct { + requestHeaderMode processingMode + requestBodyMode processingMode + responseHeaderMode processingMode + responseTrailerMode processingMode + responseBodyMode processingMode +} + +// resolveHeaderMode resolves the processing mode for headers based on the +// protobuf enum value. If the mode is not set or set to Default processing +// mode, it returns the provided defaultMode. +func resolveHeaderMode(mode v3procfilterpb.ProcessingMode_HeaderSendMode, defaultMode processingMode) processingMode { + switch mode { + case v3procfilterpb.ProcessingMode_SEND: + return modeSend + case v3procfilterpb.ProcessingMode_SKIP: + return modeSkip + case v3procfilterpb.ProcessingMode_DEFAULT: + return defaultMode + default: + return defaultMode + } +} + +// resolveBodyMode resolves the processing mode for body based on the protobuf +// enum value. If the mode is not set (i.e., default), it returns modeSkip, as +// the default for body is to skip. +func resolveBodyMode(mode v3procfilterpb.ProcessingMode_BodySendMode) processingMode { + switch mode { + case v3procfilterpb.ProcessingMode_GRPC: + return modeSend + case v3procfilterpb.ProcessingMode_NONE: + return modeSkip + default: + return modeSkip + } +} + +// processingModesFromProto converts a protobuf ProcessingMode message +// to a processingModes struct. +func processingModesFromProto(pm *v3procfilterpb.ProcessingMode) processingModes { + return processingModes{ + requestHeaderMode: resolveHeaderMode(pm.GetRequestHeaderMode(), modeSend), + requestBodyMode: resolveBodyMode(pm.GetRequestBodyMode()), + responseHeaderMode: resolveHeaderMode(pm.GetResponseHeaderMode(), modeSend), + responseBodyMode: resolveBodyMode(pm.GetResponseBodyMode()), + responseTrailerMode: resolveHeaderMode(pm.GetResponseTrailerMode(), modeSkip), + } +} + +// newInterceptorConfig creates the interceptor config from the base and +// override filter configs. If a field is set in both the base and override +// configs, the value from the override config will be used. +func newInterceptorConfig(base baseConfig, override overrideConfig) baseConfig { + ic := base + + // Apply overrides if present. + if val, ok := override.server.Value(); ok { + ic.server = val + } + if val, ok := override.failureModeAllow.Value(); ok { + ic.failureModeAllow = val + } + if override.requestAttributes != nil { + ic.requestAttributes = override.requestAttributes + } + if override.responseAttributes != nil { + ic.responseAttributes = override.responseAttributes + } + if val, ok := override.processingModes.Value(); ok { + ic.processingModes = val + } + return ic +} diff --git a/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/ext_proc.go b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/ext_proc.go new file mode 100644 index 0000000000..2afe59b293 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/ext_proc.go @@ -0,0 +1,2012 @@ +/* + * + * Copyright 2026 gRPC 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 extproc implements the Envoy external processing HTTP filter. +package extproc + +import ( + "context" + "errors" + "fmt" + "io" + "strings" + "sync" + "sync/atomic" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + estats "google.golang.org/grpc/experimental/stats" + "google.golang.org/grpc/internal" + "google.golang.org/grpc/internal/buffer" + "google.golang.org/grpc/internal/envconfig" + "google.golang.org/grpc/internal/grpcsync" + "google.golang.org/grpc/internal/optional" + "google.golang.org/grpc/internal/resolver" + "google.golang.org/grpc/internal/xds/httpfilter" + iextproc "google.golang.org/grpc/internal/xds/httpfilter/extproc/internal" + "google.golang.org/grpc/internal/xds/matcher" + "google.golang.org/grpc/internal/xds/xdsclient/xdsresource" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/known/anypb" + "google.golang.org/protobuf/types/known/structpb" + + v3procfilterpb "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ext_proc/v3" + v3procservicegrpc "github.com/envoyproxy/go-control-plane/envoy/service/ext_proc/v3" + v3procservicepb "github.com/envoyproxy/go-control-plane/envoy/service/ext_proc/v3" +) + +func init() { + if envconfig.XDSClientExtProcEnabled { + httpfilter.Register(builder{}) + } + iextproc.RegisterForTesting = func() { + httpfilter.Register(builder{}) + } + iextproc.UnregisterForTesting = func() { + for _, typeURL := range builder.TypeURLs(builder{}) { + httpfilter.UnregisterForTesting(typeURL) + } + } + iextproc.TimeNowFunc = time.Now + iextproc.TimeSinceFunc = time.Since +} + +var metadataFromOutgoingContextRaw = internal.FromOutgoingContextRaw.(func(context.Context) (metadata.MD, [][]string, bool)) + +const defaultDeferredCloseTimeout = 5 * time.Second + +func timeNow() time.Time { + return iextproc.TimeNowFunc() +} + +func timeSince(t time.Time) time.Duration { + return iextproc.TimeSinceFunc(t) +} + +type builder struct{} + +func (builder) TypeURLs() []string { + return []string{ + "type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExternalProcessor", + "type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExtProcPerRoute", + } +} + +// validateBodyProcessingMode ensures that the body processing mode is either +// NONE or GRPC. Also ensures that if response body mode is GRPC then response +// trailer mode must be SEND. +func validateBodyProcessingMode(mode *v3procfilterpb.ProcessingMode) error { + if m := mode.GetRequestBodyMode(); m != v3procfilterpb.ProcessingMode_NONE && m != v3procfilterpb.ProcessingMode_GRPC { + return fmt.Errorf("extproc: invalid request body mode %v: want %q or %q", m, "NONE", "GRPC") + } + if m := mode.GetResponseBodyMode(); m != v3procfilterpb.ProcessingMode_NONE && m != v3procfilterpb.ProcessingMode_GRPC { + return fmt.Errorf("extproc: invalid response body mode %v: want %q or %q", m, "NONE", "GRPC") + } + if mode.GetResponseBodyMode() == v3procfilterpb.ProcessingMode_GRPC && mode.GetResponseTrailerMode() != v3procfilterpb.ProcessingMode_SEND { + return fmt.Errorf("extproc: invalid response trailer mode %v: must be %q when response body mode is %q", mode.GetResponseTrailerMode(), "SEND", "GRPC") + } + return nil +} + +func (builder) ParseFilterConfig(cfg proto.Message, _ httpfilter.ParseOptions) (httpfilter.FilterConfig, error) { + m, ok := cfg.(*anypb.Any) + if !ok { + return nil, fmt.Errorf("extproc: error parsing config %v: unknown type %T, want *anypb.Any", cfg, cfg) + } + msg := new(v3procfilterpb.ExternalProcessor) + if err := m.UnmarshalTo(msg); err != nil { + return nil, fmt.Errorf("extproc: failed to unmarshal config %v: %v", cfg, err) + } + if msg.GetProcessingMode() == nil { + return nil, fmt.Errorf("extproc: missing processing_mode in config %v", cfg) + } + if err := validateBodyProcessingMode(msg.GetProcessingMode()); err != nil { + return nil, err + } + + if msg.GetGrpcService() == nil { + return nil, fmt.Errorf("extproc: empty grpc_service provided in config %v", cfg) + } + server, err := iextproc.ParseGRPCServiceConfig(msg.GetGrpcService()) + if err != nil { + return nil, fmt.Errorf("extproc: failed to parse grpc_service %v", err) + } + + mutationRules, err := httpfilter.HeaderMutationRulesFromProto(msg.GetMutationRules()) + if err != nil { + return nil, err + } + + var allowedHeaders, disallowedHeaders []matcher.StringMatcher + if allowed := msg.GetForwardRules().GetAllowedHeaders(); allowed != nil { + allowedHeaders, err = httpfilter.ConvertStringMatchers(allowed.GetPatterns()) + if err != nil { + return nil, err + } + } + + if disallowed := msg.GetForwardRules().GetDisallowedHeaders(); disallowed != nil { + disallowedHeaders, err = httpfilter.ConvertStringMatchers(disallowed.GetPatterns()) + if err != nil { + return nil, err + } + } + + deferredCloseTimeout := defaultDeferredCloseTimeout + if msg.GetDeferredCloseTimeout() != nil { + deferredCloseTimeout = msg.GetDeferredCloseTimeout().AsDuration() + } + + return baseConfig{ + processingModes: processingModesFromProto(msg.GetProcessingMode()), + requestAttributes: msg.GetRequestAttributes(), + responseAttributes: msg.GetResponseAttributes(), + disableImmediateResponse: msg.GetDisableImmediateResponse(), + observabilityMode: msg.GetObservabilityMode(), + failureModeAllow: msg.GetFailureModeAllow(), + server: server, + mutationRules: mutationRules, + allowedHeaders: allowedHeaders, + disallowedHeaders: disallowedHeaders, + deferredCloseTimeout: deferredCloseTimeout, + }, nil +} + +func (builder) ParseFilterConfigOverride(ov proto.Message, _ httpfilter.ParseOptions) (httpfilter.FilterConfig, error) { + m, ok := ov.(*anypb.Any) + if !ok { + return nil, fmt.Errorf("extproc: error parsing override %v: unknown type %T, want *anypb.Any", ov, ov) + } + msg := new(v3procfilterpb.ExtProcPerRoute) + if err := m.UnmarshalTo(msg); err != nil { + return nil, fmt.Errorf("extproc: failed to unmarshal override %v: %v", ov, err) + } + override := msg.GetOverrides() + + var processingModesOpt optional.Optional[processingModes] + if pm := override.GetProcessingMode(); pm != nil { + if err := validateBodyProcessingMode(pm); err != nil { + return nil, err + } + processingModesOpt = optional.New(processingModesFromProto(pm)) + } + + var serverOpt optional.Optional[xdsresource.GRPCServiceConfig] + if override.GetGrpcService() != nil { + server, err := iextproc.ParseGRPCServiceConfig(override.GetGrpcService()) + if err != nil { + return nil, fmt.Errorf("extproc: failed to parse grpc_service: %v", err) + } + serverOpt = optional.New(server) + } + + var failureModeAllowOpt optional.Optional[bool] + if override.GetFailureModeAllow() != nil { + failureModeAllowOpt = optional.New(override.GetFailureModeAllow().GetValue()) + } + + return overrideConfig{ + server: serverOpt, + processingModes: processingModesOpt, + failureModeAllow: failureModeAllowOpt, + requestAttributes: override.GetRequestAttributes(), + responseAttributes: override.GetResponseAttributes(), + }, nil +} + +func (builder) IsTerminal() bool { + return false +} + +func (builder) BuildClientFilter(opts httpfilter.ClientFilterOptions) httpfilter.ClientFilter { + return &clientFilter{ + metricsRecorder: opts.MetricsRecorder, + target: opts.Target, + procChannels: make(map[grpcServiceKey]*grpcsync.RefCounted[v3procservicegrpc.ExternalProcessorClient]), + } +} + +var _ httpfilter.ClientFilterBuilder = builder{} + +// grpcServiceKey uniquely identifies an external processor server configuration +// by its target URI, channel credentials, and call credentials. It is used as a +// map key in clientFilter to share and reuse the external processor channels. +type grpcServiceKey struct { + targetURI string + channelCredentials string + callCredentials string +} + +type clientFilter struct { + metricsRecorder estats.MetricsRecorder + target string + + mu sync.Mutex + procChannels map[grpcServiceKey]*grpcsync.RefCounted[v3procservicegrpc.ExternalProcessorClient] +} + +func (*clientFilter) Close() {} + +// getProcChannel returns an existing refcounted client from the map if present +// and its refcount is incremented successfully. +func (cf *clientFilter) getProcChannel(key grpcServiceKey) *grpcsync.RefCounted[v3procservicegrpc.ExternalProcessorClient] { + cf.mu.Lock() + defer cf.mu.Unlock() + if rc, ok := cf.procChannels[key]; ok && rc.TryIncrement() { + return rc + } + return nil +} + +// storeProcChannel stores the created channel in the map if no valid channel +// exists for the key. If another goroutine already stored a channel while +// unlocked, it increments the existing channel's refcount and returns it. +func (cf *clientFilter) storeProcChannel(key grpcServiceKey, rc *grpcsync.RefCounted[v3procservicegrpc.ExternalProcessorClient]) *grpcsync.RefCounted[v3procservicegrpc.ExternalProcessorClient] { + cf.mu.Lock() + defer cf.mu.Unlock() + if existing, ok := cf.procChannels[key]; ok && existing.TryIncrement() { + return existing + } + cf.procChannels[key] = rc + return rc +} + +// removeProcChannel removes rc from the map if it is still associated with key. +// +// We check (cf.procChannels[key] == rc) before deleting because: +// 1. When a channel's reference count drops to 0, this cleanup callback runs +// asynchronously on a background goroutine. +// 2. Before this callback acquires cf.mu, a subsequent call to +// getOrCreateExtProcChannel could see that the old channel has refcount 0, +// ignore it, and store a newly created channel in cf.procChannels[key]. +// 3. The equality check ensures we only delete from the map if it still points +// to this expiring channel, preventing us from accidentally deleting a new +// replacement channel. +func (cf *clientFilter) removeProcChannel(key grpcServiceKey, rc *grpcsync.RefCounted[v3procservicegrpc.ExternalProcessorClient]) { + cf.mu.Lock() + defer cf.mu.Unlock() + // Only delete from the map if it hasn't already been replaced by a newer channel. + if cf.procChannels[key] == rc { + delete(cf.procChannels, key) + } +} + +// getOrCreateExtProcChannel retrieves an existing refcounted external processor +// client from the procChannels map and increases its refcount or creates a new +// one if it doesn't exist. +func (cf *clientFilter) getOrCreateExtProcChannel(server xdsresource.GRPCServiceConfig) (*grpcsync.RefCounted[v3procservicegrpc.ExternalProcessorClient], error) { + // Create the grpcServiceKey. + key := grpcServiceKey{ + targetURI: server.TargetURI, + channelCredentials: server.ChannelCredentials, + callCredentials: server.CallCredentials, + } + + // If the channel for the key is present in the map and its refcount is + // greater than 0, increment the refcount and return the channel. + if rc := cf.getProcChannel(key); rc != nil { + return rc, nil + } + + // Create the external processor channel without holding the lock. + cc, cancel, err := iextproc.CreateExtProcChannel(server) + if err != nil { + return nil, fmt.Errorf("extproc: failed to create channel to the external processor server %q: %v", server.TargetURI, err) + } + + client := v3procservicegrpc.NewExternalProcessorClient(cc) + // Create a new refcounted client. The onZero cleanup function will remove the + // client from the map and close the underlying channel. + var rc *grpcsync.RefCounted[v3procservicegrpc.ExternalProcessorClient] + rc = grpcsync.NewRefCounted(client, func() { + cf.removeProcChannel(key, rc) + cancel() + }) + + // Double-check if another goroutine created and stored a channel for this + // key while we were unlocked. + if existing := cf.storeProcChannel(key, rc); existing != rc { + rc.Decrement() + return existing, nil + } + return rc, nil +} + +func (cf *clientFilter) BuildClientInterceptor(base, override httpfilter.FilterConfig) (httpfilter.ClientInterceptor, error) { + b, ok := base.(baseConfig) + if !ok { + return nil, fmt.Errorf("extproc: incorrect config type provided (%T): %v", base, base) + } + + var ov overrideConfig + if override != nil { + ov, ok = override.(overrideConfig) + if !ok { + return nil, fmt.Errorf("extproc: incorrect override config type provided (%T): %v", override, override) + } + } + + config := newInterceptorConfig(b, ov) + + // Create or reuse a refcounted channel to the external processor server. + rc, err := cf.getOrCreateExtProcChannel(config.server) + if err != nil { + return nil, err + } + return &clientInterceptor{ + config: config, + procClient: rc, + metricsRecorder: cf.metricsRecorder, + target: cf.target, + }, nil +} + +type clientInterceptor struct { + config baseConfig + procClient *grpcsync.RefCounted[v3procservicegrpc.ExternalProcessorClient] + metricsRecorder estats.MetricsRecorder + target string +} + +func (i *clientInterceptor) Close() { + i.procClient.Decrement() +} + +// createProcContext creates a new child context for the RPC to the external +// processor server to be able to cancel it independently. This context has a +// deadline of the timeout specified in the config, if present, and contains the +// initial metadata specified in the config. +func createProcContext(ctx context.Context, server xdsresource.GRPCServiceConfig) (procCtx context.Context, cancel context.CancelFunc) { + if server.Timeout != 0 { + procCtx, cancel = context.WithTimeout(ctx, server.Timeout) + } else { + procCtx, cancel = context.WithCancel(ctx) + } + procCtx = metadata.NewOutgoingContext(procCtx, server.InitialMetadata) + return procCtx, cancel +} + +func (i *clientInterceptor) NewStream(ctx context.Context, ri resolver.RPCInfo, newStream func(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStream, error), opts ...grpc.CallOption) (grpc.ClientStream, error) { + // Increment procClient's refcount so this RPC stream keeps the connection + // open even if the interceptor is closed. Decremented when the Process + // stream finishes (via grpc.OnFinish) or fails to start. + i.procClient.Increment() + outgoingMD, added, _ := metadataFromOutgoingContextRaw(ctx) + // Create a cancelable context to cancel the dataplane stream and close any + // goroutines in case of error. + cancelCtx, cancel := context.WithCancel(ctx) + procCtx, procCancel := createProcContext(cancelCtx, i.config.server) + + // Collect OnFinishCallOption functions from the call options. + var onFinish []func(error) + for _, o := range opts { + if onFinishOpt, ok := o.(grpc.OnFinishCallOption); ok && onFinishOpt.OnFinish != nil { + onFinish = append(onFinish, onFinishOpt.OnFinish) + } + } + + csCommon := &commonStream{ + ctx: cancelCtx, + cancel: cancel, + procCancel: procCancel, + config: i.config, + metricsRecorder: i.metricsRecorder, + target: i.target, + clientHeadersStartTime: timeNow(), + // Construct request attributes once during stream initialization to capture + // the original, unmutated request metadata and RPC info. For streaming + // RPCs, where stream creation and message transmission are separable, + // initializing attributes upfront avoids repeated protobuf construction on + // subsequent SendMsg and RecvMsg calls. + reqAttrs: constructRequestAttributes(ri, outgoingMD, added, i.config.requestAttributes), + onFinish: onFinish, + } + + // In the ClientStream API, outgoing headers are sent immediately when the + // stream is created. Because we need to send or mutate these headers before + // they go over the wire, we must establish the ext_proc stream now rather + // than deferring it. + var err error + procClient := i.procClient.Value() + if csCommon.procStream, err = procClient.Process(procCtx, grpc.OnFinish(func(error) { + i.procClient.Decrement() + })); err != nil { + return csCommon.handleInitError(fmt.Errorf("failed to create a stream to external processor: %w", err), newStream, opts...) + } + + // Observability mode. + if i.config.observabilityMode { + ocs := &observabilityClientStream{ + commonStream: csCommon, + procRecvDone: make(chan struct{}), + } + + // Defer the closing of ext proc stream by the defined deferred close + // timeout to allow the server to read all messages from the proc stream. + onFinishFunc := func(error) { + time.AfterFunc(ocs.config.deferredCloseTimeout, ocs.procCancel) + } + newOpts := append(opts, grpc.OnFinish(onFinishFunc)) + + if ocs.dataplaneStream, err = newStream(ocs.ctx, newOpts...); err != nil { + ocs.cancel() + return nil, ocs.streamError(err) + } + ocs.recordMetric(clientHeadersDurationMetric, timeSince(ocs.clientHeadersStartTime).Seconds()) + // Start background goroutine to receive any messages from the external + // processor server and discard them. + go ocs.discardProcessorResponsesLoop() + + // If the request header processing mode is set to "Send", forward the + // headers to the external processor server. + if i.config.processingModes.requestHeaderMode == modeSend { + if err = ocs.sendToProcessor(ocs.requestHeaders(outgoingMD, added)); err != nil { + return ocs.handleInitError(fmt.Errorf("failed to send client headers to external processor server: %w", err), newStream, opts...) + } + } + + return ocs, nil + } + + // Normal mode. + cs := &clientStream{ + commonStream: csCommon, + procStreamFailed: grpcsync.NewEvent(), + procStreamBypass: grpcsync.NewEvent(), + mutatedReqBuffer: buffer.NewUnbounded[*v3procservicepb.StreamedBodyResponse](), + mutatedRespBuffer: buffer.NewUnbounded[*v3procservicepb.StreamedBodyResponse](), + responseHeadersReady: grpcsync.NewEvent(), + responseTrailerReady: grpcsync.NewEvent(), + dataplaneSetup: make(chan struct{}), + procSendCh: make(chan *v3procservicepb.ProcessingRequest), + requestForwardLoopDoneCh: make(chan struct{}), + procRecvLoopDone: grpcsync.NewEvent(), + } + + // When request header processing is "Send", defer creating the dataplane + // stream until the external processor responds, because gRPC transmits + // outgoing headers immediately upon stream creation and we must apply any + // header mutations first. If header processing is skipped, create the + // dataplane stream immediately. + if i.config.processingModes.requestHeaderMode == modeSend { + if err = cs.procStream.Send(cs.requestHeaders(outgoingMD, added)); err != nil { + if err == io.EOF { + _, err = cs.procStream.Recv() + } + return cs.handleInitError(fmt.Errorf("failed to send client headers to external processor server: %w", err), newStream, opts...) + } + } else { + if err = cs.createDataplaneStream(cs.ctx, newStream, opts); err != nil { + return nil, err + } + } + + // Start a background loop for sending messages to the external processor + // server. Use a single goroutine to ensure no concurrent sends. + go cs.sendToProcServerLoop() + + // Start a background loop to receive messages from the external processor + // server and send them on the dataplane stream in either direction. + go cs.recvFromProcServerLoop(newStream, opts) + + return cs, nil +} + +// commonStream contains state and synchronization primitives shared between the +// normal and observability mode client stream implementations. +type commonStream struct { + // ctx is stored to allow blocking ClientStream interface methods (which do + // not accept context parameters) to respect context cancellation/timeout and + // retrieve ctx.Err() for returning the correct gRPC status error. This + // context is directly derived from the dataplane RPC's context. + ctx context.Context + cancel context.CancelFunc + procCancel context.CancelFunc + config baseConfig + + dataplaneStream grpc.ClientStream // underlying gRPC stream to the backend + procStream v3procservicegrpc.ExternalProcessor_ProcessClient // bidirectional stream to the external processor + procStreamClosed atomic.Bool // ensures the stream closure logic is executed exactly once + procStreamErr atomic.Value // holds the terminal error causing the external processor stream to fail + + reqAttrs map[string]*structpb.Struct // attributes to be sent to proc server with client message + reqAttrsSent atomic.Bool // tracks whether the first client message has been sent to ensure request attributes are sent only once + protocolConfigSent atomic.Bool // tracks whether the protocol configuration has been sent to the processor + trailersOnly bool // tracks whether the backend response is trailers-only + responseHeaderOnce atomic.Bool // ensures response headers are forwarded to the external processor only once + responseTrailerOnce atomic.Bool // ensures response trailers are forwarded to the external processor only once + + metricsRecorder estats.MetricsRecorder + target string + clientHeadersStartTime time.Time // holds the start time of client headers processing for metrics and relative timestamp calculations + + // onFinish stores OnFinishCallOption callbacks to execute if calling the + // delegate (newStream) fails or if the RPC fails before delegating. + onFinish []func(err error) + dataplaneRecvCalled atomic.Bool // tracks if RecvMsg has been called on dataplaneStream by the application +} + +func (cs *commonStream) recordMetric(handle *estats.Float64HistoHandle, duration float64) { + if cs.metricsRecorder == nil { + return + } + handle.Record(cs.metricsRecorder, duration, cs.target) +} + +// handleInitError handles failures during the initialization of the external +// processor stream in NewStream. In deny mode, it returns an internal error. In +// allow mode, it bypasses the external processor and creates and returns the +// dataplane stream directly. +// +// The error passed into handleInitError is a wrapped error and must not be +// returned directly to the caller to avoid exposing it as part of the public +// API. +func (cs *commonStream) handleInitError(err error, newStream func(context.Context, ...grpc.CallOption) (grpc.ClientStream, error), opts ...grpc.CallOption) (grpc.ClientStream, error) { + cs.procCancel() + + if !errors.Is(err, io.EOF) && !cs.config.failureModeAllow { + cs.cancel() + return nil, status.Errorf(codes.Internal, "extproc: %v", err) + } + cs.recordMetric(clientHeadersDurationMetric, timeSince(cs.clientHeadersStartTime).Seconds()) + if cs.dataplaneStream, err = newStream(cs.ctx, opts...); err != nil { + cs.cancel() + return nil, err + } + cs.recordMetric(clientHeadersDurationMetric, timeSince(cs.clientHeadersStartTime).Seconds()) + return cs.dataplaneStream, nil +} + +// callOnFinish executes all registered OnFinish CallOption callbacks. +func (cs *commonStream) callOnFinish(err error) { + for _, f := range cs.onFinish { + f(err) + } +} + +// cleanupDataplane cancels the dataplane stream's context to immediately tear +// down the active dataplane connection and unblock any pending client I/O. +// +// Additionally, after context cancellation, if the application has not called +// RecvMsg on the dataplane stream, it invokes a dummy RecvMsg on it. In +// gRPC-Go, unary RPCs do not start a background goroutine waiting for context +// expiration to call cs.finish(err). If an application or interceptor layer +// abandons an RPC after NewStream without calling SendMsg, CloseSend, or +// RecvMsg on the dataplane stream, calling RecvMsg on the canceled stream +// forces gRPC-Go's internal clientStream to encounter context.Canceled and +// execute cleanup. This guarantees that all registered OnFinish CallOption +// callbacks are executed and reference counts are decremented so that channels +// do not leak. +// +// For streaming RPCs where RecvMsg has already been called by the application, +// we avoid invoking a dummy RecvMsg because ClientStream.RecvMsg is not safe +// for concurrent calls by multiple goroutines on the same stream. Multiple +// goroutines may enter here concurrently; mutual exclusion is not required +// because cs.cancel() makes subsequent RecvMsg calls after context cancellation +// are idempotent. +func (cs *commonStream) cleanupDataplane() { + cs.cancel() + if cs.dataplaneStream != nil && !cs.dataplaneRecvCalled.Load() { + cs.dataplaneStream.RecvMsg(new(any)) + } +} + +// newProcessingRequest creates a new ProcessingRequest with ObservabilityMode, +// ProtocolConfig, and Attributes fields initialized. +func (cs *commonStream) newProcessingRequest(isClientMessage bool) *v3procservicepb.ProcessingRequest { + req := &v3procservicepb.ProcessingRequest{ + ObservabilityMode: cs.config.observabilityMode, + } + + if cs.protocolConfigSent.CompareAndSwap(false, true) { + req.ProtocolConfig = &v3procservicepb.ProtocolConfiguration{ + RequestBodyMode: convertBodyMode(cs.config.processingModes.requestBodyMode), + ResponseBodyMode: convertBodyMode(cs.config.processingModes.responseBodyMode), + } + } + + if isClientMessage && cs.reqAttrsSent.CompareAndSwap(false, true) { + req.Attributes = cs.reqAttrs + } + return req +} + +// requestHeaders creates a ProcessingRequest for sending request headers. +func (cs *commonStream) requestHeaders(md metadata.MD, added [][]string) *v3procservicepb.ProcessingRequest { + req := cs.newProcessingRequest(true) + req.Request = &v3procservicepb.ProcessingRequest_RequestHeaders{ + RequestHeaders: &v3procservicepb.HttpHeaders{ + Headers: httpfilter.ConstructHeaderMap(md, added, cs.config.allowedHeaders, cs.config.disallowedHeaders), + }, + } + return req +} + +// responseHeaders creates a ProcessingRequest for sending response +// headers. +func (cs *commonStream) responseHeaders(header metadata.MD) *v3procservicepb.ProcessingRequest { + req := cs.newProcessingRequest(false) + req.Request = &v3procservicepb.ProcessingRequest_ResponseHeaders{ResponseHeaders: &v3procservicepb.HttpHeaders{ + Headers: httpfilter.ConstructHeaderMap(header, nil, cs.config.allowedHeaders, cs.config.disallowedHeaders), + EndOfStream: cs.trailersOnly, + }} + return req +} + +// responseTrailers creates a ProcessingRequest for sending response +// trailers. +func (cs *commonStream) responseTrailers(trailers metadata.MD) *v3procservicepb.ProcessingRequest { + req := cs.newProcessingRequest(false) + req.Request = &v3procservicepb.ProcessingRequest_ResponseTrailers{ResponseTrailers: &v3procservicepb.HttpTrailers{ + Trailers: httpfilter.ConstructHeaderMap(trailers, nil, cs.config.allowedHeaders, cs.config.disallowedHeaders), + }} + return req +} + +// halfClose creates a ProcessingRequest indicating end of stream without +// a message body. +func (cs *commonStream) halfClose() *v3procservicepb.ProcessingRequest { + req := cs.newProcessingRequest(true) + req.Request = &v3procservicepb.ProcessingRequest_RequestBody{ + RequestBody: &v3procservicepb.HttpBody{ + EndOfStreamWithoutMessage: true, + EndOfStream: true, + }, + } + return req +} + +// marshalAndCreateBodyReq marshals the message and creates a request or +// response body ProcessingRequest. +func (cs *commonStream) marshalAndCreateBodyReq(m any, isClientMessage bool) (*v3procservicepb.ProcessingRequest, error) { + msg, ok := m.(proto.Message) + if !ok { + return nil, status.Errorf(codes.Internal, "extproc: message does not implement proto.Message") + } + bodyBytes, err := proto.Marshal(msg) + if err != nil { + return nil, status.Errorf(codes.Internal, "extproc: failed to marshal message: %v", err) + } + + req := cs.newProcessingRequest(isClientMessage) + if isClientMessage { + req.Request = &v3procservicepb.ProcessingRequest_RequestBody{ + RequestBody: &v3procservicepb.HttpBody{Body: bodyBytes}, + } + return req, nil + } + req.Request = &v3procservicepb.ProcessingRequest_ResponseBody{ + ResponseBody: &v3procservicepb.HttpBody{Body: bodyBytes}, + } + return req, nil +} + +// observabilityClientStream implements resolver.ClientStream to coordinate +// message exchanges between the application client, the external processor, and +// the backend dataplane in observability mode. +type observabilityClientStream struct { + *commonStream + + procStreamBypass atomic.Bool // set to true when the external processor stream should be bypassed + procRecvDone chan struct{} // closed when discardProcessorResponsesLoop detects stream closure/failure + + responseRecvStarted bool // tracks whether RecvMsg has started processing response messages + responseHeader metadata.MD // stores response headers received from dataplane + responseHeaderErr error // stores response header error received from dataplane + mu sync.Mutex // guards concurrent writes to the external processor stream +} + +// streamError returns the appropriate error when a stream operation fails. +// It prioritizes the external processor stream's terminal error. +func (ocs *observabilityClientStream) streamError(err error) error { + if fatalErr, ok := ocs.procStreamErr.Load().(error); ok { + return fatalErr + } + return err +} + +func (ocs *observabilityClientStream) Header() (metadata.MD, error) { + if fatalErr, ok := ocs.procStreamErr.Load().(error); ok { + return nil, fatalErr + } + return ocs.initiateResponseHeaderProcessing() +} + +func (ocs *observabilityClientStream) Trailer() metadata.MD { + if _, ok := ocs.procStreamErr.Load().(error); ok { + return nil + } + + // If trailer is not yet ready, return nil. This may happen when Trailer() is + // called before the server sends trailers, or before the entire response has + // been received. + if tr := ocs.dataplaneStream.Trailer(); tr != nil { + ocs.initiateResponseTrailerProcessing(tr) + return tr + } + return nil +} + +func (ocs *observabilityClientStream) CloseSend() error { + if fatalErr, ok := ocs.procStreamErr.Load().(error); ok { + return fatalErr + } + startTime := timeNow() + if !ocs.procStreamBypass.Load() && ocs.config.processingModes.requestBodyMode == modeSend { + if err := ocs.sendToProcessor(ocs.halfClose()); err != nil { + return err + } + } + err := ocs.dataplaneStream.CloseSend() + ocs.recordMetric(clientHalfCloseDurationMetric, timeSince(startTime).Seconds()) + return ocs.streamError(err) +} + +func (ocs *observabilityClientStream) Context() context.Context { + return ocs.dataplaneStream.Context() +} + +func (ocs *observabilityClientStream) SendMsg(m any) error { + if fatalErr, ok := ocs.procStreamErr.Load().(error); ok { + return fatalErr + } + if ocs.config.processingModes.requestBodyMode == modeSend && !ocs.procStreamBypass.Load() { + if err := ocs.sendBodyToProcessor(m, true); err != nil { + return err + } + } + err := ocs.dataplaneStream.SendMsg(m) + return ocs.streamError(err) +} + +func (ocs *observabilityClientStream) RecvMsg(m any) error { + if fatalErr, ok := ocs.procStreamErr.Load().(error); ok { + return fatalErr + } + + // If this is the first time RecvMsg is called, initiate response header + // processing. + if !ocs.responseRecvStarted { + ocs.responseRecvStarted = true + if _, err := ocs.initiateResponseHeaderProcessing(); err != nil { + return err + } + } + + if !ocs.dataplaneRecvCalled.Load() { + ocs.dataplaneRecvCalled.Store(true) + } + if err := ocs.dataplaneStream.RecvMsg(m); err != nil { + if trerr := ocs.initiateResponseTrailerProcessing(ocs.dataplaneStream.Trailer()); trerr != nil { + return trerr + } + return ocs.streamError(err) + } + + if ocs.config.processingModes.responseBodyMode == modeSend && !ocs.procStreamBypass.Load() { + if err := ocs.sendBodyToProcessor(m, false); err != nil { + return err + } + } + return ocs.streamError(nil) +} + +// sendBodyToProcessor marshals the given message and forwards it as a request +// or response body ProcessingRequest to the external processor stream. +func (ocs *observabilityClientStream) sendBodyToProcessor(m any, isClientMessage bool) error { + req, err := ocs.marshalAndCreateBodyReq(m, isClientMessage) + if err != nil { + return err + } + return ocs.sendToProcessor(req) +} + +// initiateResponseTrailerProcessing fetches response trailers from the +// dataplane stream and forwards them to the external processor if configured. +// It is guarded by responseTrailerOnce to run at most once. +func (ocs *observabilityClientStream) initiateResponseTrailerProcessing(trailers metadata.MD) error { + if ocs.responseTrailerOnce.Load() || !ocs.responseTrailerOnce.CompareAndSwap(false, true) { + return nil + } + startTime := timeNow() + if ocs.config.processingModes.responseTrailerMode == modeSend && !ocs.procStreamBypass.Load() && !ocs.trailersOnly { + if err := ocs.sendToProcessor(ocs.responseTrailers(trailers)); err != nil { + return err + } + } + ocs.recordMetric(serverTrailersDurationMetric, timeSince(startTime).Seconds()) + + // Half-close the external processor stream immediately so the server can + // shut down gracefully. + if !ocs.procStreamBypass.Load() { + ocs.mu.Lock() + ocs.procStream.CloseSend() + ocs.mu.Unlock() + } + return nil +} + +// initiateResponseHeaderProcessing fetches response headers from the dataplane +// stream, detects if the response is trailers-only, and forwards the response +// headers to the external processor if configured. It is guarded by +// responseHeaderOnce to run at most once. +func (ocs *observabilityClientStream) initiateResponseHeaderProcessing() (metadata.MD, error) { + if ocs.responseHeaderOnce.Load() || !ocs.responseHeaderOnce.CompareAndSwap(false, true) { + return ocs.responseHeader, ocs.streamError(ocs.responseHeaderErr) + } + ocs.responseHeader, ocs.responseHeaderErr = ocs.dataplaneStream.Header() + if ocs.responseHeaderErr != nil { + return nil, ocs.streamError(ocs.responseHeaderErr) + } + startTime := timeNow() + // A trailers-only response returns nil from dataplaneStream.Header(). + procHeader := ocs.responseHeader + if ocs.responseHeader == nil { + procHeader = ocs.dataplaneStream.Trailer() + if len(procHeader) > 0 { + ocs.trailersOnly = true + } + } + + if ocs.config.processingModes.responseHeaderMode == modeSend && !ocs.procStreamBypass.Load() { + if err := ocs.sendToProcessor(ocs.responseHeaders(procHeader)); err != nil { + return nil, err + } + } + ocs.recordMetric(serverHeadersDurationMetric, timeSince(startTime).Seconds()) + return ocs.responseHeader, nil +} + +// sendToProcessor sends a ProcessingRequest to the external processor stream. +// If the write fails, it waits for the receive background loop to process the +// closure and returns the resulting error. +func (ocs *observabilityClientStream) sendToProcessor(req *v3procservicepb.ProcessingRequest) error { + ocs.mu.Lock() + err := ocs.procStream.Send(req) + ocs.mu.Unlock() + if err != nil { + select { + case <-ocs.procRecvDone: + case <-ocs.ctx.Done(): + } + if fatalErr, ok := ocs.procStreamErr.Load().(error); ok { + return fatalErr + } + if ocs.procStreamBypass.Load() { + return nil + } + return err + } + return nil +} + +// discardProcessorResponsesLoop runs in a background goroutine to continuously +// read and discard messages from the external processor server, while also +// monitoring the stream for closure or failure. +// +// Per the Envoy ExtProc protobuf specification for observability mode, +// "External processor should not send back processing response, as any +// responses will be ignored." +func (ocs *observabilityClientStream) discardProcessorResponsesLoop() { + for { + if _, err := ocs.procStream.Recv(); err != nil { + ocs.failObsProcStream(err) + return + } + } +} + +// failObsProcStream handles proc stream closure or failure by updating the +// stream state. If the failure is a non-EOF error and failure mode is deny, it +// stores the error to fail the dataplane RPC. Otherwise, it enables bypass +// mode. +func (ocs *observabilityClientStream) failObsProcStream(err error) { + if !ocs.procStreamClosed.CompareAndSwap(false, true) { + return + } + defer close(ocs.procRecvDone) + ocs.procCancel() + if err != io.EOF && !ocs.config.failureModeAllow { + ocs.procStreamErr.Store(status.Errorf(codes.Internal, "extproc: external processor RPC failed: %v", err)) + ocs.cleanupDataplane() + return + } + ocs.procStreamBypass.Store(true) +} + +// clientStream implements resolver.ClientStream to coordinate bidirectional +// message exchanges between the application client, the external processor, and +// the backend dataplane. +type clientStream struct { + *commonStream + + procStreamFailed *grpcsync.Event // fired when external processor stream has closed and RPC should be failed + procStreamBypass *grpcsync.Event // fired when the external processor stream should be bypassed or drained + + ignoreFailureMode atomic.Bool // tracks whether the failureModeAllow setting should be ignored (e.g. after sending body messages) + discardRequests atomic.Bool // set when ext_proc server signals end_of_stream to stop client sends + mutatedReqBuffer *buffer.Unbounded[*v3procservicepb.StreamedBodyResponse] // buffers mutated request body messages from the ext_proc server + reqForwardingStarted bool // tracks whether request forwarding loop to the dataplane has started + procSendCh chan *v3procservicepb.ProcessingRequest // serializes writes to the external processor stream to ensure thread-safety + + responseHeader metadata.MD // stores headers received from the dataplane stream + responseHeadersReady *grpcsync.Event // signals that response headers are ready for client + responseHeaderSent atomic.Bool // tracks whether response headers have been dispatched to external processor + responseTrailers metadata.MD // stores trailers received from the dataplane stream + responseTrailerReady *grpcsync.Event // signals that response trailers are ready for client + trailerSent atomic.Bool // tracks whether response trailers have been dispatched + trailerErr atomic.Value // holds any terminal status returned upon processing response trailers (e.g. ImmediateResponse) + mutatedRespBuffer *buffer.Unbounded[*v3procservicepb.StreamedBodyResponse] // buffers mutated response body messages from the ext_proc server + responseDrained atomic.Bool // tracks whether all buffered response body messages from the ext_proc server have been drained + dataplaneSetup chan struct{} // closed once dataplaneStream creation attempt is complete + dataplaneCreationErr error // stores the error from the dataplane stream creation attempt + respForwardingStarted bool // tracks whether response forwarding loop to the external processor has started + + requestForwardLoopDoneCh chan struct{} // closed when request forwarding loop finishes draining + procRecvLoopDone *grpcsync.Event // fires when external processor stream receive loop finishes + + // The following start times are accessed concurrently across goroutines + // during the stream lifetime. We store them as atomic.Int64 nanosecond + // offsets from clientHeadersStartTime instead of time.Time because time.Time + // cannot be accessed atomically without a mutex and atomic.Int64 provides + // lock-free atomic operations. + clientHalfCloseStartTime atomic.Int64 + serverHeadersStartTime atomic.Int64 + serverTrailersStartTime atomic.Int64 +} + +// recordDuration records the elapsed time since the event start timestamp +// stored in val to the histogram metric. val holds the start timestamp as a +// nanosecond offset from cs.clientHeadersStartTime. It is a no-op if val has +// not been set (value is 0). +func (cs *clientStream) recordDuration(handle *estats.Float64HistoHandle, val *atomic.Int64) { + if offsetNs := val.Load(); offsetNs != 0 { + startTime := cs.clientHeadersStartTime.Add(time.Duration(offsetNs)) + cs.recordMetric(handle, timeSince(startTime).Seconds()) + } +} + +// fireResponseHeadersReady fires the responseHeadersReady event, and records +// the server_headers_duration metric exactly once upon firing. +func (cs *clientStream) fireResponseHeadersReady() { + if cs.responseHeadersReady.Fire() { + cs.recordDuration(serverHeadersDurationMetric, &cs.serverHeadersStartTime) + } +} + +// fireResponseTrailerReady fires the responseTrailerReady event, and records +// the server_trailers_duration metric exactly once upon firing. +func (cs *clientStream) fireResponseTrailerReady() { + if cs.responseTrailerReady.Fire() { + cs.recordDuration(serverTrailersDurationMetric, &cs.serverTrailersStartTime) + } +} + +// Header returns the response headers received from the backend, potentially +// modified by the external processor if configured. It blocks until header +// processing is complete, or returns nil if the response is trailers-only. +func (cs *clientStream) Header() (metadata.MD, error) { + if err := cs.initiateResponseHeaderProcessing(); err != nil { + return nil, err + } + // Wait for the response headers to be modified. + select { + case <-cs.responseHeadersReady.Done(): + if cs.trailersOnly { + return nil, nil + } + return cs.responseHeader, nil + case <-cs.procStreamFailed.Done(): + return nil, cs.streamError() + case <-cs.ctx.Done(): + return nil, cs.streamError() + } +} + +// Trailer returns the trailer metadata received from the server, potentially +// modified by the external processor if configured. It returns nil or empty map +// immediately if trailers are not yet received from the backend. If backend +// trailers are available, it blocks until any configured trailer processing by +// the external processor completes. +func (cs *clientStream) Trailer() metadata.MD { + // If trailers are already modified and ready, return them immediately. + if cs.responseTrailerReady.HasFired() { + return cs.responseTrailers + } + // Checking if backend stream has trailers ready now. + s, err := cs.waitForDataplaneStream(cs.ctx) + // Since Trailer is not supposed to be a blocking function and should be + // called after CloseRecv or after Recv() returns an error, it should have the + // dataplane stream created. If it does not, then Trailer has been called + // prematurely, which means we need to return nil and not block here. + if err != nil { + return nil + } + // If no backend trailers are ready yet, return nil to preserve standard + // non-blocking behaviour. + if len(s.Trailer()) == 0 { + return nil + } + + cs.initiateResponseTrailerProcessing() + select { + case <-cs.responseTrailerReady.Done(): + return cs.responseTrailers + case <-cs.procStreamFailed.Done(): + return nil + case <-cs.ctx.Done(): + return nil + } +} + +func (cs *clientStream) CloseSend() error { + if cs.discardRequests.Load() { + return nil + } + if cs.clientHalfCloseStartTime.Load() == 0 { + offset := timeSince(cs.clientHeadersStartTime) + cs.clientHalfCloseStartTime.CompareAndSwap(0, int64(offset)) + } + + s, err := cs.bypassProcStreamForClientMsg() + if err != nil { + return err + } + if s != nil { + cs.recordDuration(clientHalfCloseDurationMetric, &cs.clientHalfCloseStartTime) + err = s.CloseSend() + return err + } + // If external processor stream is active, client CloseSend is sent to the + // processor server as request message with `EndOfStreamWithoutMessage` set. + s, err = cs.sendClientReqToProcServer(cs.halfClose()) + if s != nil { + cs.recordDuration(clientHalfCloseDurationMetric, &cs.clientHalfCloseStartTime) + err = s.CloseSend() + return err + } + return err +} + +func (cs *clientStream) Context() context.Context { + s, err := cs.waitForDataplaneStream(cs.ctx) + if err != nil { + return cs.ctx + } + return s.Context() +} + +func (cs *clientStream) RecvMsg(m any) error { + // Initiate response header processing because external processor requires the + // events to be sent in the correct order, i.e. response header before + // response message. And if Header() has not already been called, send the + // response headers to external processor server first. + if err := cs.initiateResponseHeaderProcessing(); err != nil { + return err + } + + // If all the responses from external processor server have been drained or if + // the external processor is bypassed, or if the response body mode is skip, + // then receive directly from the dataplane stream. + if cs.responseDrained.Load() || (cs.procStreamBypass.HasFired() && !cs.respForwardingStarted) || cs.config.processingModes.responseBodyMode == modeSkip { + return cs.recvFromDataplane(m) + } + + msg, ok := m.(proto.Message) + if !ok { + return fmt.Errorf("extproc: response message does not implement proto.Message") + } + + // Start the background receiving loop on the first RecvMsg call to capture + // the type of message to be received. + if !cs.respForwardingStarted { + cs.respForwardingStarted = true + go cs.responseForwardingToProcServerLoop(msg.ProtoReflect().Type()) + } + + // Pull response messages from mutatedRespBuffer. + select { + case streamedResp, ok := <-cs.mutatedRespBuffer.Get(): + cs.mutatedRespBuffer.Load() + if !ok { + // Closed channel implies that all messages from the external processor + // have been received. Start receiving directly from dataplane stream. + cs.responseDrained.Store(true) + return cs.recvFromDataplane(m) + } + return proto.Unmarshal(streamedResp.GetBody(), msg) + case <-cs.ctx.Done(): + return cs.streamError() + case <-cs.procStreamFailed.Done(): + return cs.streamError() + } +} + +func (cs *clientStream) SendMsg(m any) error { + s, err := cs.bypassProcStreamForClientMsg() + if err != nil { + return err + } + if s != nil { + return s.SendMsg(m) + } + + req, err := cs.marshalAndCreateBodyReq(m, true) + if err != nil { + return err + } + msg := m.(proto.Message) + + // Start request forwarding loop on the first send because we need the message + // type to send the data to the dataplane server. + if !cs.reqForwardingStarted { + cs.reqForwardingStarted = true + go cs.requestForwardingToDataplaneLoop(msg.ProtoReflect().Type()) + } + + // If the ExtProc server has already signaled end_of_stream, discard any + // subsequent client messages. + if cs.discardRequests.Load() { + return nil + } + + s, err = cs.sendClientReqToProcServer(req) + if s != nil { + return s.SendMsg(m) + } + return err +} + +// recvFromDataplane receives directly from the dataplane stream. If the +// dataplane stream returns an error, it initiates and waits for response +// trailers. +func (cs *clientStream) recvFromDataplane(m any) error { + if cs.procStreamFailed.HasFired() { + return cs.procStreamErr.Load().(error) + } + s, err := cs.waitForDataplaneStream(cs.ctx) + if err != nil { + return err + } + if !cs.dataplaneRecvCalled.Load() { + cs.dataplaneRecvCalled.Store(true) + } + if err := s.RecvMsg(m); err != nil { + // If RecvMsg returns error, fail the RPC in case external processor stream + // has failed. Otherwise process the trailers. + if cs.procStreamFailed.HasFired() { + return cs.procStreamErr.Load().(error) + } + cs.initiateResponseTrailerProcessing() + // Wait for trailer processing to be done to make sure we are able to return + // correct error and fail RPC if the trailer processing fails. This needs to + // be done because Trailer() does not return an error. TODO: Verify if the + // wait is acceptable. + return cs.waitForTrailerProcessing(err) + } + return nil +} + +// sendClientReqToProcServer attempts to send the given request for client to +// server msg to the external processor. If the processor stream is bypassed +// while waiting, it blocks until all queued messages are forwarded, and returns +// the dataplane stream so the caller can send the message directly to the +// dataplane stream instead. +func (cs *clientStream) sendClientReqToProcServer(req *v3procservicepb.ProcessingRequest) (grpc.ClientStream, error) { + // Ignoring the failureMode as we will be sending the request to proc server. + if !cs.ignoreFailureMode.Load() { + cs.ignoreFailureMode.Store(true) + } + + select { + case cs.procSendCh <- req: + return nil, nil + case <-cs.procStreamBypass.Done(): + if cs.reqForwardingStarted { + // When the drain is triggered, wait for all the queued requests to be sent + // to dataplane server before forwarding current request directly to + // dataplane server. + if err := cs.waitChannel(cs.requestForwardLoopDoneCh); err != nil { + return nil, err + } + } + return cs.waitForDataplaneStream(cs.ctx) + case <-cs.procStreamFailed.Done(): + return nil, cs.streamError() + case <-cs.ctx.Done(): + return nil, cs.streamError() + } +} + +// bypassProcStreamForClientMsg checks if the external processor should be +// bypassed for the current request message or CloseSend. If so, it returns the +// dataplane stream to be used directly. It blocks until all client messages +// received from the proc server are forwarded to ensure correct sequence. It +// also blocks to wait for stream creation if necessary. If the message needs to +// be sent to the external processor server, it returns (nil, nil). +func (cs *clientStream) bypassProcStreamForClientMsg() (grpc.ClientStream, error) { + if cs.procStreamFailed.HasFired() { + return nil, cs.procStreamErr.Load().(error) + } + + bypass := cs.procStreamBypass.HasFired() + if bypass && cs.reqForwardingStarted { + // We started forwarding messages to the proc server and then it + // initiated a drain. We must wait until all messages received from + // the proc server are sent on the dataplane stream, before + // unblocking the application's Send() or CloseSend(), to ensure + // correct message sequencing. + if err := cs.waitChannel(cs.requestForwardLoopDoneCh); err != nil { + return nil, err + } + } + + if bypass || cs.config.processingModes.requestBodyMode == modeSkip { + return cs.waitForDataplaneStream(cs.ctx) + } + + return nil, nil // Do not bypass. +} + +// responseForwardingToProcServerLoop continuously receives response messages +// from the underlying dataplane stream, marshals them, and forwards them to the +// external processor server via procSendCh. +func (cs *clientStream) responseForwardingToProcServerLoop(msgType protoreflect.MessageType) { + defer func() { + // Once the external processor server receive loop finishes, close the + // buffer to signal end of processed responses. + cs.waitChannel(cs.procRecvLoopDone.Done()) + cs.mutatedRespBuffer.Close() + }() + + dataplaneStream, err := cs.waitForDataplaneStream(cs.ctx) + if err != nil { + return + } + + for { + // If the processor stream has closed or the receive loop finishes, we can + // stop receiving messages in the background and Recv should now directly be + // called from the cs.RecvMsg() function. + if cs.procStreamBypass.HasFired() || cs.procRecvLoopDone.HasFired() { + return + } + + newMsg := msgType.New().Interface() + if !cs.dataplaneRecvCalled.Load() { + cs.dataplaneRecvCalled.Store(true) + } + if err := dataplaneStream.RecvMsg(newMsg); err != nil { + cs.initiateResponseTrailerProcessing() + return + } + + req, err := cs.marshalAndCreateBodyReq(newMsg, false) + if err != nil { + cs.failProcStream(err) + return + } + + if !cs.ignoreFailureMode.Load() { + cs.ignoreFailureMode.Store(true) + } + + select { + case cs.procSendCh <- req: + case <-cs.procStreamBypass.Done(): + // If drain is triggered, wait for external processor server receive loop + // to finish before pushing this message on the mutatedRespBuffer + // to ensure correct order of messages. + if err := cs.waitChannel(cs.procRecvLoopDone.Done()); err != nil { + return + } + resp := &v3procservicepb.StreamedBodyResponse{Body: req.GetResponseBody().GetBody()} + cs.mutatedRespBuffer.Put(resp) + return + case <-cs.procStreamFailed.Done(): + return + case <-cs.ctx.Done(): + return + } + } +} + +// requestForwardingToDataplaneLoop continuously consumes mutated request body +// from mutatedReqBuffer (populated by the external processor server), +// unmarshals them, and forwards the final messages to the backend server. +func (cs *clientStream) requestForwardingToDataplaneLoop(msgType protoreflect.MessageType) { + defer close(cs.requestForwardLoopDoneCh) + dataplaneStream, err := cs.waitForDataplaneStream(cs.ctx) + if err != nil { + return + } + for { + select { + case streamedResp, ok := <-cs.mutatedReqBuffer.Get(): + if !ok { + return + } + cs.mutatedReqBuffer.Load() + + // As per gRFC A93, ignore `end_of_stream_without_message` if + // `end_of_stream` is false. + if streamedResp.GetEndOfStream() && streamedResp.GetEndOfStreamWithoutMessage() { + cs.recordDuration(clientHalfCloseDurationMetric, &cs.clientHalfCloseStartTime) + dataplaneStream.CloseSend() + return + } + + newMsg := msgType.New().Interface() + if err := proto.Unmarshal(streamedResp.GetBody(), newMsg); err != nil { + cs.failProcStream(err) + return + } + if err := dataplaneStream.SendMsg(newMsg); err != nil { + cs.cancelStream(err) + return + } + + if streamedResp.GetEndOfStream() { + cs.recordDuration(clientHalfCloseDurationMetric, &cs.clientHalfCloseStartTime) + dataplaneStream.CloseSend() + return + } + case <-cs.ctx.Done(): + return + case <-cs.procStreamFailed.Done(): + return + } + } +} + +// recvFromProcServerLoop continuously receives messages from the external +// processor server and redirects them according to the response type. +func (cs *clientStream) recvFromProcServerLoop(newStream func(context.Context, ...grpc.CallOption) (grpc.ClientStream, error), opts []grpc.CallOption) { + defer func() { + cs.procRecvLoopDone.Fire() + // Close mutatedReqBuffer to indicate completion of receiving + // the mutated requests. Do not close mutatedResponseBuffer because we + // might push the message that has been read when drain is triggered. + cs.mutatedReqBuffer.Close() + }() + + // If request header mode is send, the first response should be the mutation + // for request header. Create the dataplane stream using the mutated header. + if cs.config.processingModes.requestHeaderMode == modeSend { + if !cs.processInitialHeaders(cs.ctx, newStream, opts) { + return + } + } + + // If header mode is not send or if we receive the header and create the + // dataplane stream, start receiving from the external processor server. + for { + resp, err := cs.procStream.Recv() + if err != nil { + cs.failProcStream(err) + return + } + if resp.GetRequestDrain() { + // Trigger the drain but continue receiving the drained messages until we + // get io.EOF. + cs.triggerBypass() + } + + if resp.GetImmediateResponse() != nil { + cs.handleImmediateResponse(resp.GetImmediateResponse(), newStream, opts) + return + } + + switch { + case resp.GetRequestBody() != nil: + if cs.config.processingModes.requestBodyMode == modeSkip { + cs.failProcStream(fmt.Errorf("external processor unexpectedly sent request body when request body processing is disabled")) + return + } + + streamedResp, ok := cs.validateBodyResponse(resp.GetRequestBody()) + if !ok { + return + } + if streamedResp.GetEndOfStream() { + cs.discardRequests.Store(true) + } + cs.mutatedReqBuffer.Put(streamedResp) + + case resp.GetResponseBody() != nil: + if cs.config.processingModes.responseBodyMode == modeSkip { + cs.failProcStream(fmt.Errorf("external processor unexpectedly sent response body when response body processing is disabled")) + return + } + + // If response headers have been sent and mutated response headers have + // not been received before receiving the response body message, fail the + // RPC. + if cs.config.processingModes.responseHeaderMode == modeSend && !cs.responseHeadersReady.HasFired() { + cs.failProcStream(fmt.Errorf("external processor sent response body before sending response headers")) + return + } + + // If mutated response trailers have been received before receiving the + // response body message, fail the RPC. + if cs.config.processingModes.responseTrailerMode == modeSend && cs.responseTrailerReady.HasFired() { + cs.failProcStream(fmt.Errorf("external processor sent response body after response trailers were already processed")) + return + } + + streamedResp, ok := cs.validateBodyResponse(resp.GetResponseBody()) + if !ok { + return + } + if streamedResp.GetEndOfStream() { + cs.failProcStream(fmt.Errorf("external processor unexpectedly set end of stream in response body mutation")) + return + } + cs.mutatedRespBuffer.Put(streamedResp) + + case resp.GetResponseHeaders() != nil: + if cs.config.processingModes.responseHeaderMode == modeSkip { + cs.failProcStream(fmt.Errorf("external processor unexpectedly sent response headers when response header processing is disabled")) + return + } + if !cs.responseHeaderSent.Load() { + cs.failProcStream(fmt.Errorf("external processor sent response headers before response headers were sent to it")) + return + } + if cs.responseHeadersReady.HasFired() { + cs.failProcStream(fmt.Errorf("external processor unexpectedly sent duplicate response headers after response headers were already processed")) + return + } + + header := resp.GetResponseHeaders() + // Check if the status in the header response is CONTINUE; if not, fail + // the stream. + if status := header.GetResponse().GetStatus(); status != v3procservicepb.CommonResponse_CONTINUE { + cs.failProcStream(fmt.Errorf("external processor returned unexpected status %v for response headers, expected %v", status, v3procservicepb.CommonResponse_CONTINUE)) + return + } + if err = cs.applyMutations(header.GetResponse().GetHeaderMutation(), cs.responseHeader); err != nil { + cs.failProcStream(err) + return + } + // Signal that the response header is modified and ready to be sent to the + // client, so that if there is any buffered response body, it can be sent + // after the header. + cs.fireResponseHeadersReady() + + case resp.GetResponseTrailers() != nil: + if cs.config.processingModes.responseTrailerMode == modeSkip { + cs.failProcStream(fmt.Errorf("external processor unexpectedly sent response trailers when response trailer processing is disabled")) + return + } + if !cs.trailerSent.Load() { + cs.failProcStream(fmt.Errorf("external processor sent response trailers before response trailers were sent to it")) + return + } + if cs.responseTrailerReady.HasFired() { + cs.failProcStream(fmt.Errorf("external processor unexpectedly sent duplicate response trailers after response trailers were already processed")) + return + } + trailer := resp.GetResponseTrailers() + if err = cs.applyMutations(trailer.GetHeaderMutation(), cs.responseTrailers); err != nil { + cs.failProcStream(err) + return + } + // Signal that the response trailer is modified and ready to be sent to + // the client. + cs.fireResponseTrailerReady() + } + } +} + +func (cs *clientStream) validateBodyResponse(bodyResp *v3procservicepb.BodyResponse) (*v3procservicepb.StreamedBodyResponse, bool) { + if status := bodyResp.GetResponse().GetStatus(); status != v3procservicepb.CommonResponse_CONTINUE { + cs.failProcStream(fmt.Errorf("external processor returned unexpected status %v for body response, expected %v", status, v3procservicepb.CommonResponse_CONTINUE)) + return nil, false + } + streamedResp := bodyResp.GetResponse().GetBodyMutation().GetStreamedResponse() + if streamedResp == nil { + cs.failProcStream(fmt.Errorf("external processor returned invalid body mutation in body response")) + return nil, false + } + if streamedResp.GetGrpcMessageCompressed() { + cs.failProcStream(fmt.Errorf("external processor returned compressed grpc message which is not supported")) + return nil, false + } + return streamedResp, true +} + +func (cs *clientStream) applyMutations(mutation *v3procservicepb.HeaderMutation, md metadata.MD) error { + if mutation == nil { + return nil + } + if err := cs.config.mutationRules.ApplyAdditions(mutation.GetSetHeaders(), md); err != nil { + return err + } + return cs.config.mutationRules.ApplyRemovals(mutation.GetRemoveHeaders(), md) +} + +// closeProcSend gracefully half-closes the external processor stream across the +// background send goroutine by pushing a nil sentinel onto procSendCh. +func (cs *clientStream) closeProcSend() { + select { + case cs.procSendCh <- nil: + case <-cs.ctx.Done(): + case <-cs.procStreamFailed.Done(): + case <-cs.procStreamBypass.Done(): + } +} + +// sendToProcServer runs as a dedicated background goroutine that serializes all +// outbound messages to the external processor server. It listens on procSendCh +// for messages to forward. It actively monitors stream lifecycle events: +// - Drain/Bypass: If procStreamBypass fires, it initiates a graceful shutdown +// by sending a half-close (CloseSend) to the external processor server and +// returning so that no more messages can be sent to the external processor. +// - Cancellation/Failure: It aborts immediately if the context is canceled or +// the underlying stream fails. +func (cs *clientStream) sendToProcServerLoop() { + for { + select { + case req := <-cs.procSendCh: + if req == nil { + // A nil request is used as a sentinel message to gracefully half-close + // the processor stream from this background thread. This ensures that + // CloseSend is called sequentially after all preceding requests in the + // channel are successfully sent, avoiding out-of-order data races. + cs.procStream.CloseSend() + return + } + if req.GetResponseHeaders() != nil { + cs.responseHeaderSent.Store(true) + } + if req.GetResponseTrailers() != nil { + cs.trailerSent.Store(true) + } + if err := cs.procStream.Send(req); err != nil { + if err != io.EOF { + // For non-EOF client-side send errors, fail the stream immediately. + cs.failProcStream(err) + } + // If Send returned io.EOF, the server closed the stream early. Let + // the Recv loop retrieve the actual status error from the server and + // propagate it. + return + } + case <-cs.procStreamBypass.Done(): + cs.procStream.CloseSend() + return + case <-cs.procStreamFailed.Done(): + return + case <-cs.ctx.Done(): + return + } + } +} + +// streamError returns the appropriate error when a stream operation is +// preempted by a stream failure or context cancellation. It prioritizes the +// external processor stream's terminal error over the context error. +func (cs *clientStream) streamError() error { + if cs.procStreamFailed.HasFired() { + return cs.procStreamErr.Load().(error) + } + return status.FromContextError(cs.ctx.Err()).Err() +} + +// waitChannel waits for the provided channel to be closed, while also +// respecting context cancellation and stream failures. +func (cs *clientStream) waitChannel(ch <-chan struct{}) error { + select { + case <-ch: + return nil + case <-cs.ctx.Done(): + return cs.streamError() + case <-cs.procStreamFailed.Done(): + return cs.streamError() + } +} + +// createDataplaneStream initializes the underlying gRPC dataplane stream using +// the provided newStream function. If dataplane stream creation fails, the +// top-level context used by the extproc filter is canceled and thereby all +// spawned goroutines terminate. +func (cs *clientStream) createDataplaneStream(ctx context.Context, newStream func(context.Context, ...grpc.CallOption) (grpc.ClientStream, error), opts []grpc.CallOption) error { + defer close(cs.dataplaneSetup) + cs.dataplaneStream, cs.dataplaneCreationErr = newStream(ctx, opts...) + if cs.dataplaneCreationErr != nil { + // Execute the OnFinish call options if the delegate failed. + cs.callOnFinish(cs.dataplaneCreationErr) + cs.cancel() + return cs.dataplaneCreationErr + } + cs.recordMetric(clientHeadersDurationMetric, timeSince(cs.clientHeadersStartTime).Seconds()) + return nil +} + +// failProcStream handles stream failures, recording errors or bypassing the +// external processor based on failureModeAllow configuration. It returns true +// if the stream is bypassed, and false if the connection is torn down. +func (cs *clientStream) failProcStream(err error) bool { + if !cs.procStreamClosed.CompareAndSwap(false, true) { + return cs.procStreamBypass.HasFired() + } + cs.procCancel() + if err != io.EOF && (cs.ignoreFailureMode.Load() || !cs.config.failureModeAllow) { + // Execute the OnFinish call options if the delegate is never called. + if cs.dataplaneStream == nil { + cs.callOnFinish(err) + } + cs.procStreamErr.Store(status.Errorf(codes.Internal, "extproc: %v", err)) + cs.procStreamFailed.Fire() + cs.cleanupDataplane() + return false + } + cs.triggerBypass() + return true +} + +// cancelStream immediately terminates the stream with the specified error and +// fires the failure event. It does not respect the failure mode. +func (cs *clientStream) cancelStream(err error) { + if !cs.procStreamClosed.CompareAndSwap(false, true) { + return + } + // Execute the OnFinish call options if the delegate is never called. + if cs.dataplaneStream == nil { + cs.callOnFinish(err) + } + cs.procStreamErr.Store(err) + cs.procStreamFailed.Fire() + cs.cleanupDataplane() +} + +// handleHeaderError handles failures that occur during receiving or processing +// the initial request headers. If the failure mode allows it, the external +// processor is bypassed and the direct dataplane stream is created. +func (cs *clientStream) handleHeaderError(err error, newStream func(context.Context, ...grpc.CallOption) (grpc.ClientStream, error), opts []grpc.CallOption) { + if cs.failProcStream(err) { + cs.createDataplaneStream(cs.ctx, newStream, opts) + } +} + +// processInitialHeaders waits for the initial header response from the external +// processor server, applies any requested header mutations to the outgoing +// context, and initializes the data plane stream. It returns true if the +// headers were processed successfully and dataplane stream was created. It +// returns false if the proc stream needs to be bypassed, or failed due to an +// error, or aborted early by a processor-initiated immediate response. +func (cs *clientStream) processInitialHeaders(ctx context.Context, newStream func(context.Context, ...grpc.CallOption) (grpc.ClientStream, error), opts []grpc.CallOption) bool { + resp, err := cs.procStream.Recv() + if err != nil { + cs.handleHeaderError(err, newStream, opts) + return false + } + if resp.GetRequestDrain() { + cs.triggerBypass() + } + if resp.GetImmediateResponse() != nil { + cs.handleImmediateResponse(resp.GetImmediateResponse(), newStream, opts) + return false + } + + header := resp.GetRequestHeaders() + if header == nil { + err := fmt.Errorf("external processor returned an unexpected message type %T, expected request headers response", resp.GetResponse()) + cs.handleHeaderError(err, newStream, opts) + return false + } + // Check if status in header response is CONTINUE; if not, fail the stream. + if status := header.GetResponse().GetStatus(); status != v3procservicepb.CommonResponse_CONTINUE { + cs.handleHeaderError(fmt.Errorf("external processor returned unexpected status %v for request headers, expected %v", status, v3procservicepb.CommonResponse_CONTINUE), newStream, opts) + return false + } + // Mutate the outgoing headers with additions and removals received from the + // external processor. + outgoingMD, _ := metadata.FromOutgoingContext(ctx) + if outgoingMD == nil { + outgoingMD = metadata.MD{} + } + if err = cs.applyMutations(header.GetResponse().GetHeaderMutation(), outgoingMD); err != nil { + cs.handleHeaderError(err, newStream, opts) + return false + } + dataplaneCtx := metadata.NewOutgoingContext(ctx, outgoingMD) + if err = cs.createDataplaneStream(dataplaneCtx, newStream, opts); err != nil { + return false + } + return true +} + +func (cs *clientStream) handleImmediateResponse(imm *v3procservicepb.ImmediateResponse, newStream func(context.Context, ...grpc.CallOption) (grpc.ClientStream, error), opts []grpc.CallOption) { + if cs.config.disableImmediateResponse { + err := fmt.Errorf("external processor sent an immediate response but immediate responses are disabled in configuration") + if cs.dataplaneStream == nil { + cs.handleHeaderError(err, newStream, opts) + } else { + cs.failProcStream(err) + } + return + } + + statusCode := codes.Internal + if imm.GetGrpcStatus() != nil { + statusCode = codes.Code(imm.GetGrpcStatus().GetStatus()) + if statusCode > codes.Code(16) { + statusCode = codes.Unknown + } + } + err := status.Error(statusCode, imm.GetDetails()) + + if cs.trailerSent.Load() { + if mutation := imm.GetHeaders(); mutation != nil { + cs.applyMutations(mutation, cs.responseTrailers) + } + cs.trailerErr.Store(err) + cs.fireResponseTrailerReady() + } else { + cs.cancelStream(err) + } +} + +func (cs *clientStream) triggerBypass() { + if cs.procStreamBypass.Fire() { + cs.fireResponseHeadersReady() + cs.fireResponseTrailerReady() + } +} + +// waitForDataplaneStream waits for the dataplane stream to be created or for +// the context to be done. It also checks if the processor stream has not ended +// abruptly with a non-io.EOF error. +func (cs *clientStream) waitForDataplaneStream(ctx context.Context) (grpc.ClientStream, error) { + select { + case <-cs.dataplaneSetup: + if cs.dataplaneCreationErr != nil { + return nil, cs.dataplaneCreationErr + } + return cs.dataplaneStream, nil + case <-ctx.Done(): + // Prioritize returning the underlying dataplane creation failure or + // external processor error over the context cancellation error. + if cs.dataplaneCreationErr != nil { + return nil, cs.dataplaneCreationErr + } + return nil, cs.streamError() + case <-cs.procStreamFailed.Done(): + return nil, cs.procStreamErr.Load().(error) + } +} + +// initiateResponseHeaderProcessing receives initial response headers exactly +// once, forwards them to the external processor if configured, or unblocks +// readers immediately. +func (cs *clientStream) initiateResponseHeaderProcessing() error { + if cs.procStreamFailed.HasFired() { + return cs.procStreamErr.Load().(error) + } + if cs.responseHeaderOnce.Load() || !cs.responseHeaderOnce.CompareAndSwap(false, true) { + return nil + } + dataplaneStream, err := cs.waitForDataplaneStream(cs.ctx) + if err != nil { + return err + } + header, err := dataplaneStream.Header() + if err != nil { + // If the processor stream failed first and canceled cs.ctx, prefer + // that root error over the secondary dataplaneStream.Header() failure. + if cs.procStreamFailed.HasFired() { + return cs.procStreamErr.Load().(error) + } + return err + } + // Capture the start time for response headers after they have been + // successfully retrieved from the dataplane stream. + cs.serverHeadersStartTime.Store(int64(timeSince(cs.clientHeadersStartTime))) + + if header == nil { + // A trailers-only response returns nil from dataplaneStream.Header(). + header = dataplaneStream.Trailer() + if len(header) > 0 { + cs.trailersOnly = true + // For trailers-only, the trailers are retrieved during the header + // phase. Start timing them now since they will be processed as part + // of the header phase. + cs.serverTrailersStartTime.Store(int64(timeSince(cs.clientHeadersStartTime))) + } + } + cs.responseHeader = header + if cs.config.processingModes.responseHeaderMode != modeSend || cs.procStreamBypass.HasFired() { + // If header does not need to be sent to the external processor, unblock + // the functions waiting on header modifications. + cs.fireResponseHeadersReady() + return nil + } + + select { + case cs.procSendCh <- cs.responseHeaders(header): + return nil + case <-cs.procStreamBypass.Done(): + return nil + case <-cs.procStreamFailed.Done(): + return cs.streamError() + case <-cs.ctx.Done(): + return cs.streamError() + } +} + +func (cs *clientStream) initiateResponseTrailerProcessing() { + if cs.responseTrailerOnce.Load() || !cs.responseTrailerOnce.CompareAndSwap(false, true) { + return + } + if cs.trailersOnly { + // For trailers-only response, the trailers metadata map is processed and + // mutated during the response header phase. Wait for those mutations to + // be received and applied. + select { + case <-cs.responseHeadersReady.Done(): + case <-cs.procStreamFailed.Done(): + case <-cs.ctx.Done(): + } + cs.responseTrailers = cs.responseHeader + cs.fireResponseTrailerReady() + // Gracefully half-close the external processor stream for trailers-only + // responses once header modifications finish. + cs.closeProcSend() + return + } + cs.responseTrailers = cs.dataplaneStream.Trailer() + // Capture the start time for response trailers after they have been + // successfully retrieved from the dataplane stream. + offset := timeSince(cs.clientHeadersStartTime) + cs.serverTrailersStartTime.Store(int64(offset)) + + if cs.config.processingModes.responseTrailerMode == modeSend && !cs.procStreamBypass.HasFired() { + select { + case cs.procSendCh <- cs.commonStream.responseTrailers(cs.responseTrailers): + case <-cs.ctx.Done(): + case <-cs.procStreamFailed.Done(): + case <-cs.procStreamBypass.Done(): + } + } else { + cs.fireResponseTrailerReady() + } + // Gracefully half-close the external processor stream after forwarding response + // trailers to signal that all responses have completely processed. + cs.closeProcSend() +} + +func (cs *clientStream) waitForTrailerProcessing(recvErr error) error { + select { + case <-cs.responseTrailerReady.Done(): + if val := cs.trailerErr.Load(); val != nil { + return val.(error) + } + if cs.procStreamFailed.HasFired() { + return cs.procStreamErr.Load().(error) + } + return recvErr + case <-cs.procStreamBypass.Done(): + return recvErr + case <-cs.procStreamFailed.Done(): + return cs.streamError() + case <-cs.ctx.Done(): + return cs.streamError() + } +} + +// convertBodyMode converts the body mode from processingMode to +// v3procfilterpb.ProcessingMode_BodySendMode. +func convertBodyMode(mode processingMode) v3procfilterpb.ProcessingMode_BodySendMode { + if mode == modeSend { + return v3procfilterpb.ProcessingMode_GRPC + } + return v3procfilterpb.ProcessingMode_NONE +} + +func getHeader(md metadata.MD, added [][]string, key string) string { + var vals []string + if md != nil { + vals = append(vals, md.Get(key)...) + } + for _, kvs := range added { + for i := 0; i < len(kvs); i += 2 { + if strings.EqualFold(kvs[i], key) { + vals = append(vals, kvs[i+1]) + } + } + } + return strings.Join(vals, ",") +} + +// constructRequestAttributes builds a map of request attributes specified in +// the interceptor config. +func constructRequestAttributes(rpcInfo resolver.RPCInfo, md metadata.MD, added [][]string, requestedAttributes []string) map[string]*structpb.Struct { + if len(requestedAttributes) == 0 { + return nil + } + + reqFields := make(map[string]any) + for _, attr := range requestedAttributes { + switch attr { + case "request.path", "request.url_path": + reqFields[attr] = rpcInfo.Method + case "request.host": + reqFields[attr] = rpcInfo.Authority + case "request.method": + reqFields[attr] = "POST" + case "request.headers": + headers := make(map[string]any) + for k, values := range md { + headers[strings.ToLower(k)] = strings.Join(values, ",") + } + for _, kvs := range added { + for i := 0; i < len(kvs); i += 2 { + k := strings.ToLower(kvs[i]) + v := kvs[i+1] + if prev, ok := headers[k].(string); ok { + headers[k] = prev + "," + v + } else { + headers[k] = v + } + } + } + reqFields[attr] = headers + case "request.referer": + if val := getHeader(md, added, "referer"); val != "" { + reqFields[attr] = val + } + case "request.useragent": + if val := getHeader(md, added, "user-agent"); val != "" { + reqFields[attr] = val + } + case "request.id": + if val := getHeader(md, added, "x-request-id"); val != "" { + reqFields[attr] = val + } + case "request.query": + reqFields[attr] = "" + default: + // Unknown/unsupported attributes are ignored. + } + } + + reqStruct := &structpb.Struct{Fields: make(map[string]*structpb.Value)} + for k, v := range reqFields { + val, err := structpb.NewValue(v) + if err != nil { + // Skip values that cannot be represented in a structpb.Value to + // match Envoy's behavior of encoding as many attributes as possible. + continue + } + reqStruct.Fields[k] = val + } + + if len(reqStruct.Fields) == 0 { + return nil + } + + return map[string]*structpb.Struct{ + "envoy.filters.http.ext_proc": reqStruct, + } +} diff --git a/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/internal/internal.go b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/internal/internal.go new file mode 100644 index 0000000000..a6812f01d3 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/internal/internal.go @@ -0,0 +1,59 @@ +/* + * + * Copyright 2026 gRPC 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 internal contains functionality internal to the extproc package. +package internal + +import ( + "fmt" + "time" + + v3corepb "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" + "google.golang.org/grpc" + "google.golang.org/grpc/internal/xds/xdsclient/xdsresource" +) + +var ( + // RegisterForTesting registers the external processor HTTP Filter for testing + // purposes. + RegisterForTesting func() + + // UnregisterForTesting unregisters the external processor HTTP Filter for + // testing purposes. + UnregisterForTesting func() + + // ParseGRPCServiceConfig parses the gRPC service configuration from the given + // protobuf message. + ParseGRPCServiceConfig = func(*v3corepb.GrpcService) (xdsresource.GRPCServiceConfig, error) { + return xdsresource.GRPCServiceConfig{}, fmt.Errorf("extproc: ParseGRPCServiceConfig not implemented") + } + + // CreateExtProcChannel creates a gRPC client channel to the external + // processing server. + CreateExtProcChannel = func(xdsresource.GRPCServiceConfig) (grpc.ClientConnInterface, func() error, error) { + return nil, nil, fmt.Errorf("extproc: dialing external processor server not implemented") + } + + // TimeNowFunc returns the current time.Time, and can be overridden for + // testing purposes. + TimeNowFunc func() time.Time + + // TimeSinceFunc returns the time elapsed, and can be overridden for testing + // purposes. + TimeSinceFunc func(t time.Time) time.Duration +) diff --git a/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/metrics.go b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/metrics.go new file mode 100644 index 0000000000..40dd49e9de --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/xds/httpfilter/extproc/metrics.go @@ -0,0 +1,54 @@ +/* + * + * Copyright 2026 gRPC 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 extproc + +import ( + estats "google.golang.org/grpc/experimental/stats" +) + +var ( + clientHeadersDurationMetric = estats.RegisterFloat64Histo(estats.MetricDescriptor{ + Name: "grpc.client_ext_proc.client_headers_duration", + Description: "Time between when the ext_proc filter sees the client's headers and when it allows those headers to continue on to the next filter.", + Unit: "s", + Labels: []string{"grpc.target"}, + Default: false, + }) + clientHalfCloseDurationMetric = estats.RegisterFloat64Histo(estats.MetricDescriptor{ + Name: "grpc.client_ext_proc.client_half_close_duration", + Description: "Time between when the ext_proc filter sees the client's half-close and when it allows that half-close to continue on to the next filter.", + Unit: "s", + Labels: []string{"grpc.target"}, + Default: false, + }) + serverHeadersDurationMetric = estats.RegisterFloat64Histo(estats.MetricDescriptor{ + Name: "grpc.client_ext_proc.server_headers_duration", + Description: "Time between when the ext_proc filter sees the server's headers and when it allows those headers to continue on to the next filter.", + Unit: "s", + Labels: []string{"grpc.target"}, + Default: false, + }) + serverTrailersDurationMetric = estats.RegisterFloat64Histo(estats.MetricDescriptor{ + Name: "grpc.client_ext_proc.server_trailers_duration", + Description: "Time between when the ext_proc filter sees the server's trailers and when it allows those trailers to continue on to the next filter.", + Unit: "s", + Labels: []string{"grpc.target"}, + Default: false, + }) +) diff --git a/vendor/google.golang.org/grpc/internal/xds/httpfilter/fault/fault.go b/vendor/google.golang.org/grpc/internal/xds/httpfilter/fault/fault.go index 58f3486369..3bb7aa5e6c 100644 --- a/vendor/google.golang.org/grpc/internal/xds/httpfilter/fault/fault.go +++ b/vendor/google.golang.org/grpc/internal/xds/httpfilter/fault/fault.go @@ -93,11 +93,11 @@ func parseConfig(cfg proto.Message) (httpfilter.FilterConfig, error) { return config{config: msg}, nil } -func (builder) ParseFilterConfig(cfg proto.Message) (httpfilter.FilterConfig, error) { +func (builder) ParseFilterConfig(cfg proto.Message, _ httpfilter.ParseOptions) (httpfilter.FilterConfig, error) { return parseConfig(cfg) } -func (builder) ParseFilterConfigOverride(override proto.Message) (httpfilter.FilterConfig, error) { +func (builder) ParseFilterConfigOverride(override proto.Message, _ httpfilter.ParseOptions) (httpfilter.FilterConfig, error) { return parseConfig(override) } diff --git a/vendor/google.golang.org/grpc/internal/xds/httpfilter/httpfilter.go b/vendor/google.golang.org/grpc/internal/xds/httpfilter/httpfilter.go index cc31e755ea..0a0f259e36 100644 --- a/vendor/google.golang.org/grpc/internal/xds/httpfilter/httpfilter.go +++ b/vendor/google.golang.org/grpc/internal/xds/httpfilter/httpfilter.go @@ -24,7 +24,9 @@ import ( "context" "google.golang.org/grpc" + estats "google.golang.org/grpc/experimental/stats" iresolver "google.golang.org/grpc/internal/resolver" + "google.golang.org/grpc/internal/xds/bootstrap" "google.golang.org/protobuf/proto" ) @@ -34,6 +36,17 @@ type FilterConfig interface { isFilterConfig() } +// ParseOptions contains additional information passed to the HTTP filter's +// config parsing methods. +type ParseOptions struct { + // BootstrapConfig contains the complete bootstrap configuration used by the + // xDS client that received the resource being parsed. + BootstrapConfig *bootstrap.Config + // ServerConfig contains the configuration of the xDS management server that + // sent the resource being parsed. + ServerConfig *bootstrap.ServerConfig +} + // DisabledFilterConfig represents a disabled filter override. It implements the // FilterConfig interface and can be returned by ParseFilterConfigOverride to // indicate that the filter should be disabled. It is not used as a config for @@ -57,13 +70,13 @@ type Builder interface { // udpa.type.v1.TypedStruct, or an xds.type.v3.TypedStruct for filters that // do not accept a custom type. The resulting FilterConfig will later be // passed to Build. - ParseFilterConfig(proto.Message) (FilterConfig, error) + ParseFilterConfig(proto.Message, ParseOptions) (FilterConfig, error) // ParseFilterConfigOverride parses the provided override configuration // proto.Message from the RDS override configuration of this filter. This // may be an anypb.Any, a udpa.type.v1.TypedStruct, or an // xds.type.v3.TypedStruct for filters that do not accept a custom type. // The resulting FilterConfig will later be passed to Build. - ParseFilterConfigOverride(proto.Message) (FilterConfig, error) + ParseFilterConfigOverride(proto.Message, ParseOptions) (FilterConfig, error) // IsTerminal returns whether this Filter is terminal or not (i.e. it must // be last filter in the filter chain). IsTerminal() bool @@ -82,14 +95,16 @@ type ClientInterceptor interface { // Note: RPCInfo.Context is currently unused and will be nil. NewStream(ctx context.Context, ri iresolver.RPCInfo, newStream func(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStream, error), opts ...grpc.CallOption) (grpc.ClientStream, error) - // Close closes the interceptor. Once called, no new calls to NewStream are - // accepted. Ongoing calls to NewStream are allowed to complete. + // Close closes the interceptor. No new RPCs will be dispatched to this + // interceptor, but ongoing calls to NewStream are allowed to complete. Close() } // ClientFilterOptions contains options for building a client filter. type ClientFilterOptions struct { - FilterName string // FilterName is the filter name from the xDS configuration. + FilterName string // FilterName is the filter name from the xDS configuration. + MetricsRecorder estats.MetricsRecorder // MetricsRecorder is the metrics recorder to capture metrics for the filter. + Target string // Target is the target string of the channel. } // ClientFilterBuilder is an optional interface that a Builder can implement to @@ -116,6 +131,25 @@ type ClientFilter interface { Close() } +// ServerInterceptor is an interceptor for incoming RPC's on gRPC server side. +type ServerInterceptor interface { + // InterceptRPC intercepts an incoming RPC on the server side. + // + // On success, implementations must return either the original ServerStream + // or a wrapped ServerStream, with a nil error. + // + // Returning a non-nil error will terminate the RPC with that error. + // Implementations are expected to return an error created using the status + // package; otherwise, the RPC will fail with an UNKNOWN status code. + // + // Implementations should never return (nil, nil). + InterceptRPC(ss grpc.ServerStream) (grpc.ServerStream, error) + + // Close closes the interceptor. No new RPCs will be dispatched to this + // interceptor, but ongoing calls to InterceptRPC are allowed to complete. + Close() +} + // ServerFilterBuilder is an optional interface that a Builder can implement to // indicate its capability to build server-side filters. type ServerFilterBuilder interface { @@ -134,7 +168,7 @@ type ServerFilter interface { // // It is valid for this method to return a nil Interceptor and a nil error. // In this case, the RPC will not be intercepted by this filter. - BuildServerInterceptor(config, override FilterConfig) (iresolver.ServerInterceptor, error) + BuildServerInterceptor(config, override FilterConfig) (ServerInterceptor, error) // Close is called when the filter is no longer needed. Close() diff --git a/vendor/google.golang.org/grpc/internal/xds/httpfilter/rbac/rbac.go b/vendor/google.golang.org/grpc/internal/xds/httpfilter/rbac/rbac.go index 1af2c2065b..761eb3b77b 100644 --- a/vendor/google.golang.org/grpc/internal/xds/httpfilter/rbac/rbac.go +++ b/vendor/google.golang.org/grpc/internal/xds/httpfilter/rbac/rbac.go @@ -20,12 +20,11 @@ package rbac import ( - "context" "errors" "fmt" "strings" - "google.golang.org/grpc/internal/resolver" + "google.golang.org/grpc" "google.golang.org/grpc/internal/xds/httpfilter" "google.golang.org/grpc/internal/xds/rbac" "google.golang.org/protobuf/proto" @@ -192,7 +191,7 @@ func normalizeHeaderMatcher(header *v3routepb.HeaderMatcher) error { return nil } -func (builder) ParseFilterConfig(cfg proto.Message) (httpfilter.FilterConfig, error) { +func (builder) ParseFilterConfig(cfg proto.Message, _ httpfilter.ParseOptions) (httpfilter.FilterConfig, error) { if cfg == nil { return nil, fmt.Errorf("rbac: nil configuration message provided") } @@ -207,7 +206,7 @@ func (builder) ParseFilterConfig(cfg proto.Message) (httpfilter.FilterConfig, er return parseConfig(msg) } -func (builder) ParseFilterConfigOverride(override proto.Message) (httpfilter.FilterConfig, error) { +func (builder) ParseFilterConfigOverride(override proto.Message, _ httpfilter.ParseOptions) (httpfilter.FilterConfig, error) { if override == nil { return nil, fmt.Errorf("rbac: nil configuration message provided") } @@ -236,7 +235,7 @@ type serverFilter struct{} func (serverFilter) Close() {} -func (serverFilter) BuildServerInterceptor(cfg httpfilter.FilterConfig, override httpfilter.FilterConfig) (resolver.ServerInterceptor, error) { +func (serverFilter) BuildServerInterceptor(cfg httpfilter.FilterConfig, override httpfilter.FilterConfig) (httpfilter.ServerInterceptor, error) { if cfg == nil { return nil, fmt.Errorf("rbac: nil config provided") } @@ -270,8 +269,11 @@ type interceptor struct { chainEngine *rbac.ChainEngine } -func (i *interceptor) AllowRPC(ctx context.Context) error { - return i.chainEngine.IsAuthorized(ctx) +func (i *interceptor) InterceptRPC(ss grpc.ServerStream) (grpc.ServerStream, error) { + if err := i.chainEngine.IsAuthorized(ss.Context()); err != nil { + return nil, err + } + return ss, nil } func (i *interceptor) Close() {} diff --git a/vendor/google.golang.org/grpc/internal/xds/httpfilter/router/router.go b/vendor/google.golang.org/grpc/internal/xds/httpfilter/router/router.go index 954528227a..4864197fef 100644 --- a/vendor/google.golang.org/grpc/internal/xds/httpfilter/router/router.go +++ b/vendor/google.golang.org/grpc/internal/xds/httpfilter/router/router.go @@ -22,7 +22,6 @@ package router import ( "fmt" - iresolver "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/xds/httpfilter" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" @@ -48,7 +47,7 @@ type builder struct { func (builder) TypeURLs() []string { return []string{TypeURL} } -func (builder) ParseFilterConfig(cfg proto.Message) (httpfilter.FilterConfig, error) { +func (builder) ParseFilterConfig(cfg proto.Message, _ httpfilter.ParseOptions) (httpfilter.FilterConfig, error) { // The gRPC router filter does not currently use any fields from the // config. Verify type only. if cfg == nil { @@ -65,7 +64,7 @@ func (builder) ParseFilterConfig(cfg proto.Message) (httpfilter.FilterConfig, er return config{}, nil } -func (builder) ParseFilterConfigOverride(override proto.Message) (httpfilter.FilterConfig, error) { +func (builder) ParseFilterConfigOverride(override proto.Message, _ httpfilter.ParseOptions) (httpfilter.FilterConfig, error) { if override != nil { return nil, fmt.Errorf("router: unexpected config override specified: %v", override) } @@ -104,7 +103,7 @@ func (filter) BuildClientInterceptor(cfg, override httpfilter.FilterConfig) (htt return nil, nil } -func (filter) BuildServerInterceptor(cfg, override httpfilter.FilterConfig) (iresolver.ServerInterceptor, error) { +func (filter) BuildServerInterceptor(cfg, override httpfilter.FilterConfig) (httpfilter.ServerInterceptor, error) { if _, ok := cfg.(config); !ok { return nil, fmt.Errorf("router: incorrect config type provided (%T): %v", cfg, cfg) } diff --git a/vendor/google.golang.org/grpc/internal/xds/rbac/matchers.go b/vendor/google.golang.org/grpc/internal/xds/rbac/matchers.go index cf6fbcead4..f5b064d526 100644 --- a/vendor/google.golang.org/grpc/internal/xds/rbac/matchers.go +++ b/vendor/google.golang.org/grpc/internal/xds/rbac/matchers.go @@ -365,7 +365,7 @@ type remoteIPMatcher struct { func newRemoteIPMatcher(cidrRange *v3corepb.CidrRange) (*remoteIPMatcher, error) { // Convert configuration to a cidrRangeString, as Go standard library has // methods that parse cidr string. - cidrRangeString := fmt.Sprintf("%s/%d", cidrRange.AddressPrefix, cidrRange.PrefixLen.Value) + cidrRangeString := fmt.Sprintf("%s/%d", cidrRange.GetAddressPrefix(), cidrRange.GetPrefixLen().GetValue()) ipNet, err := netip.ParsePrefix(cidrRangeString) if err != nil { return nil, err @@ -391,7 +391,7 @@ type localIPMatcher struct { } func newLocalIPMatcher(cidrRange *v3corepb.CidrRange) (*localIPMatcher, error) { - cidrRangeString := fmt.Sprintf("%s/%d", cidrRange.AddressPrefix, cidrRange.PrefixLen.Value) + cidrRangeString := fmt.Sprintf("%s/%d", cidrRange.GetAddressPrefix(), cidrRange.GetPrefixLen().GetValue()) ipNet, err := netip.ParsePrefix(cidrRangeString) if err != nil { return nil, err diff --git a/vendor/google.golang.org/grpc/internal/xds/resolver/serviceconfig.go b/vendor/google.golang.org/grpc/internal/xds/resolver/serviceconfig.go index 94801b77de..bdbaea6999 100644 --- a/vendor/google.golang.org/grpc/internal/xds/resolver/serviceconfig.go +++ b/vendor/google.golang.org/grpc/internal/xds/resolver/serviceconfig.go @@ -24,10 +24,12 @@ import ( "math/bits" rand "math/rand/v2" "strings" + "sync" "time" xxhash "github.com/cespare/xxhash/v2" "google.golang.org/grpc/codes" + "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/grpcutil" iresolver "google.golang.org/grpc/internal/resolver" iringhash "google.golang.org/grpc/internal/ringhash" @@ -110,10 +112,10 @@ type routeCluster struct { } type route struct { - m *xdsresource.CompositeMatcher // converted from route matchers - actionType xdsresource.RouteActionType // holds route action type - clusters wrr.WRR // holds *routeCluster entries - interceptors []httpfilter.ClientInterceptor // Interceptors across clusters belonging to this route + m *xdsresource.CompositeMatcher // converted from route matchers + actionType xdsresource.RouteActionType // holds route action type + clusters wrr.WRR // holds *routeCluster entries + routeClusters []*grpcsync.RefCounted[*routeCluster] // Route clusters belonging to this route maxStreamDuration time.Duration retryConfig *xdsresource.RetryConfig hashPolicies []*xdsresource.HashPolicy @@ -175,9 +177,20 @@ func annotateErrorWithNodeID(err error, nodeID string) error { func (cs *configSelector) SelectConfig(rpcInfo iresolver.RPCInfo) (*iresolver.RPCConfig, error) { var rt *route + md, _ := metadata.FromOutgoingContext(rpcInfo.Context) + if extraMD, ok := grpcutil.ExtraMetadata(rpcInfo.Context); ok { + md = metadata.Join(md, extraMD) + // Remove all binary headers. They are hard to match with. May need + // to add back if asked by users. + for k := range md { + if strings.HasSuffix(k, "-bin") { + delete(md, k) + } + } + } // Loop through routes in order and select first match. for _, r := range cs.routes { - if r.m.Match(rpcInfo) { + if r.m.Match(rpcInfo.Method, md) { rt = &r break } @@ -191,19 +204,11 @@ func (cs *configSelector) SelectConfig(rpcInfo iresolver.RPCInfo) (*iresolver.RP return nil, annotateErrorWithNodeID(errUnsupportedClientRouteAction, cs.xdsNodeID) } - cluster, ok := rt.clusters.Next().(*routeCluster) + rc, ok := rt.clusters.Next().(*grpcsync.RefCounted[*routeCluster]) if !ok { - return nil, annotateErrorWithNodeID(status.Errorf(codes.Internal, "error retrieving cluster for match: %v (%T)", cluster, cluster), cs.xdsNodeID) - } - - // Add a ref to the selected cluster/plugin, as this RPC needs this - // cluster/plugin until it is committed. - if info, ok := cs.clusters[cluster.name]; ok { - info.refCount.Add(1) - } else if info, ok := cs.plugins[cluster.name]; ok { - info.refCount.Add(1) + return nil, annotateErrorWithNodeID(status.Errorf(codes.Internal, "error retrieving cluster for match: %v (%T)", rc, rc), cs.xdsNodeID) } - + cluster := rc.Value() lbCtx := clustermanager.SetPickedCluster(rpcInfo.Context, cluster.name) lbCtx = xdsresource.NewContextWithXDSConfig(lbCtx, cs.xdsConfig) lbCtx = iringhash.SetXDSRequestHash(lbCtx, cs.generateHash(rpcInfo, rt.hashPolicies)) @@ -212,31 +217,48 @@ func (cs *configSelector) SelectConfig(rpcInfo iresolver.RPCInfo) (*iresolver.RP } config := &iresolver.RPCConfig{ - // Communicate to the LB policy the chosen cluster and request hash, if Ring Hash LB policy. - Context: lbCtx, - OnCommitted: func() { - // When the RPC is committed, the cluster is no longer required. - // Decrease its ref. - if info, ok := cs.clusters[cluster.name]; ok { - if v := info.refCount.Add(-1); v == 0 { - // We call unsubscribe rather than sendNewServiceConfig to - // prevent redundant updates. If the reference count in the - // dependency manager drops to zero, it will automatically - // trigger a service config update with this cluster - // removed. Calling unsubscribe allows the dependency - // manager to handle the update flow once and for all. - info.unsubscribe() - } + Context: lbCtx, + Interceptor: cluster.interceptor, + } + // Add a ref to the selected cluster to keep the interceptors alive until RPC + // is committed. + rc.Increment() + if info, ok := cs.clusters[cluster.name]; ok { + // Add a ref to the selected cluster, as this RPC needs this + // cluster until it is committed. + info.refCount.Add(1) + config.OnCommitted = sync.OnceFunc(func() { + if v := info.refCount.Add(-1); v == 0 { + // We call unsubscribe rather than sendNewServiceConfig to + // prevent redundant updates. If the reference count in the + // dependency manager drops to zero, it will automatically + // trigger a service config update with this cluster + // removed. Calling unsubscribe allows the dependency + // manager to handle the update flow once and for all. + info.unsubscribe() } - if info, ok := cs.plugins[cluster.name]; ok { - if v := info.refCount.Add(-1); v == 0 { - // This entry will be removed from activePlugins when - // producing a new service config update. - cs.sendNewServiceConfig() - } + // Decrement the refcount of the route cluster and close the interceptor + // if refcount goes to zero. + rc.Decrement() + }) + } else if info, ok := cs.plugins[cluster.name]; ok { + // Add a ref to the selected plugin, as this RPC needs this + // plugin until it is committed. + info.refCount.Add(1) + config.OnCommitted = sync.OnceFunc(func() { + if v := info.refCount.Add(-1); v == 0 { + // This entry will be removed from activePlugins when + // producing a new service config update. + cs.sendNewServiceConfig() } - }, - Interceptor: cluster.interceptor, + // Decrement the refcount of the route cluster and close the interceptor + // if refcount goes to zero. + rc.Decrement() + }) + } else { + // This should be unreachable because all route clusters are normalized + // into cs.clusters or cs.plugins during config selector creation. + panic(fmt.Sprintf("matched cluster %q not found in ConfigSelector", cluster.name)) } if rt.maxStreamDuration != 0 { @@ -333,10 +355,12 @@ func (cs *configSelector) stop() { return } - // Stop all interceptors associated with this config selector. + // Decrement the refcount of all the route clusters associated with this + // config selector and close the interceptors of the route cluster if it's + // refcount goes to zero. for _, r := range cs.routes { - for _, i := range r.interceptors { - i.Close() + for _, rc := range r.routeClusters { + rc.Decrement() } } diff --git a/vendor/google.golang.org/grpc/internal/xds/resolver/xds_resolver.go b/vendor/google.golang.org/grpc/internal/xds/resolver/xds_resolver.go index 8dfa684a5f..b9feb55bc8 100644 --- a/vendor/google.golang.org/grpc/internal/xds/resolver/xds_resolver.go +++ b/vendor/google.golang.org/grpc/internal/xds/resolver/xds_resolver.go @@ -142,6 +142,8 @@ func (b *xdsResolverBuilder) Build(target resolver.Target, cc resolver.ClientCon httpFilters: make(map[clientFilterKey]httpfilter.ClientFilter), channelID: rand.Uint64(), ldsResourceName: ldsResourceName, + target: target.String(), + metricsRecorder: opts.MetricsRecorder, // serializer used to synchronize the following: // - updates from the dependency manager. This could lead to generation @@ -233,6 +235,9 @@ type xdsResolver struct { xdsClient xdsclient.XDSClient xdsClientClose func() channelID uint64 // Unique random ID for the channel owning this resolver. + target string + metricsRecorder estats.MetricsRecorder + // All methods on the xdsResolver type except for the ones invoked by gRPC, // i.e ResolveNow() and Close(), are guaranteed to execute in the context of // this serializer's callback. We use the serializer because these shared @@ -312,13 +317,7 @@ func (r *xdsResolver) Update(config *xdsresource.XDSConfig) { r.onResourceError(err) return } - if !r.sendNewServiceConfig(cs) { - // Channel didn't like the update we provided (unexpected); erase - // this config selector and ignore this update, continuing with - // the previous config selector. - cs.stop() - return - } + r.sendNewServiceConfig(cs) if r.curConfigSelector != nil { r.curConfigSelector.stop() @@ -335,11 +334,12 @@ func (r *xdsResolver) Error(err error) { // sendNewServiceConfig prunes active clusters, generates a new service config // based on the current set of active clusters, and sends an update to the -// channel with that service config and the provided config selector. Returns -// false if an error occurs while sending an update to the channel. +// channel with that service config and the provided config selector. It is safe +// to ignore the error from `cc.UpdateState` because the clientconn uses the +// given configSelector even if it returns an error. // // Only executed in the context of a serializer callback. -func (r *xdsResolver) sendNewServiceConfig(cs stoppableConfigSelector) bool { +func (r *xdsResolver) sendNewServiceConfig(cs stoppableConfigSelector) { // Delete entries from r.activeClusters with zero references; // otherwise serviceConfigJSON will generate a config including // them. @@ -357,7 +357,7 @@ func (r *xdsResolver) sendNewServiceConfig(cs stoppableConfigSelector) bool { // more meaningful error, as opposed to one that says that pick_first // received no addresses. r.cc.ReportError(errCS.err) - return true + return } sc := serviceConfigJSON(r.activeClusters, r.activePlugins) @@ -371,13 +371,7 @@ func (r *xdsResolver) sendNewServiceConfig(cs stoppableConfigSelector) bool { }, cs) state = xdsresource.SetXDSConfig(state, r.xdsConfig) state = xdsdepmgr.SetXDSClusterSubscriber(state, r.dm) - if err := r.cc.UpdateState(xdsclient.SetClient(state, r.xdsClient)); err != nil { - if r.logger.V(2) { - r.logger.Infof("Channel rejected new state: %+v with error: %v", state, err) - } - return false - } - return true + r.cc.UpdateState(xdsclient.SetClient(state, r.xdsClient)) } // newConfigSelector creates a new config selector using the most recently @@ -431,11 +425,13 @@ func (r *xdsResolver) newConfigSelector() (_ *configSelector, err error) { } return nil, err } - clusters.Add(&routeCluster{ + routeCluster := &routeCluster{ name: clusterName, interceptor: interceptor, - }, 1) - interceptors = append(interceptors, interceptor) + } + rc := grpcsync.NewRefCounted(routeCluster, func() { interceptor.Close() }) + cs.routes[i].routeClusters = append(cs.routes[i].routeClusters, rc) + clusters.Add(rc, 1) ci := r.addOrGetActiveClusterInfo(clusterName, "") ci.cfg = xdsChildConfig{ChildPolicy: balancerConfig(r.xdsConfig.RouteConfig.ClusterSpecifierPlugins[rt.ClusterSpecifierPlugin])} cs.plugins[clusterName] = ci @@ -453,18 +449,19 @@ func (r *xdsResolver) newConfigSelector() (_ *configSelector, err error) { } return nil, err } - clusters.Add(&routeCluster{ + routeCluster := &routeCluster{ name: clusterName, interceptor: interceptor, - }, int64(wc.Weight)) - interceptors = append(interceptors, interceptor) + } + rc := grpcsync.NewRefCounted(routeCluster, func() { interceptor.Close() }) + cs.routes[i].routeClusters = append(cs.routes[i].routeClusters, rc) + clusters.Add(rc, int64(wc.Weight)) ci := r.addOrGetActiveClusterInfo(clusterName, wc.Name) ci.cfg = xdsChildConfig{ChildPolicy: newBalancerConfig(cdsName, cdsBalancerConfig{Cluster: wc.Name})} cs.clusters[clusterName] = ci } } cs.routes[i].clusters = clusters - cs.routes[i].interceptors = interceptors cs.routes[i].m = xdsresource.RouteToMatcher(rt) cs.routes[i].actionType = rt.ActionType if rt.MaxStreamDuration == nil { @@ -685,7 +682,11 @@ func (r *xdsResolver) getOrCreateClientFilter(builder httpfilter.ClientFilterBui return clientFilter } - cf := builder.BuildClientFilter(httpfilter.ClientFilterOptions{FilterName: key.name}) + cf := builder.BuildClientFilter(httpfilter.ClientFilterOptions{ + FilterName: key.name, + MetricsRecorder: r.metricsRecorder, + Target: r.target, + }) r.httpFilters[key] = cf return cf } diff --git a/vendor/google.golang.org/grpc/internal/xds/server/conn_wrapper.go b/vendor/google.golang.org/grpc/internal/xds/server/conn_wrapper.go index b2f707fabe..104e6f8235 100644 --- a/vendor/google.golang.org/grpc/internal/xds/server/conn_wrapper.go +++ b/vendor/google.golang.org/grpc/internal/xds/server/conn_wrapper.go @@ -26,7 +26,8 @@ import ( "time" "google.golang.org/grpc/credentials/tls/certprovider" - xdsinternal "google.golang.org/grpc/internal/credentials/xds" + "google.golang.org/grpc/internal/credentials/xds" + "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/transport" ) @@ -49,9 +50,6 @@ type connWrapper struct { // A reference to the listenerWrapper on which this connection was accepted. parent *listenerWrapper - // The certificate providers created for this connection. - rootProvider, identityProvider certprovider.Provider - // The connection deadline as configured by the grpc.Server on the rawConn // that is returned by a call to Accept(). This is set to the connection // timeout value configured by the user (or to a default value) before @@ -63,6 +61,8 @@ type connWrapper struct { mu sync.Mutex st transport.ServerTransport draining bool + closed bool + hi *grpcsync.RefCounted[*xds.HandshakeInfo] // The virtual hosts with matchable routes and instantiated HTTP Filters per // route, or an error. @@ -91,13 +91,13 @@ func (c *connWrapper) GetDeadline() time.Time { // XDSHandshakeInfo returns a HandshakeInfo with appropriate security // configuration for this connection. This method is invoked by the // ServerHandshake() method of the XdsCredentials. -func (c *connWrapper) XDSHandshakeInfo() (*xdsinternal.HandshakeInfo, error) { +func (c *connWrapper) XDSHandshakeInfo() (*grpcsync.RefCounted[*xds.HandshakeInfo], error) { if c.filterChain.securityCfg == nil { // If the security config is empty, this means that the control plane // did not provide any security configuration and therefore we should - // return an empty HandshakeInfo here so that the xdsCreds can use the - // configured fallback credentials. - return xdsinternal.NewHandshakeInfo(nil, nil, nil, false, "", false, false), nil + // return nil here so that the xdsCreds can use the configured fallback + // credentials. + return nil, nil } cpc := c.parent.xdsC.BootstrapConfig().CertProviderConfigs() @@ -113,13 +113,27 @@ func (c *connWrapper) XDSHandshakeInfo() (*xdsinternal.HandshakeInfo, error) { if instance, cert := secCfg.RootInstanceName, secCfg.RootCertName; instance != "" { rp, err = buildProviderFunc(cpc, instance, cert, false, true) if err != nil { + ip.Close() return nil, err } } - c.identityProvider = ip - c.rootProvider = rp - return xdsinternal.NewHandshakeInfo(c.rootProvider, c.identityProvider, nil, secCfg.RequireClientCert, "", false, false), nil + // Note that this method is invoked when a connection is accepted, and the + // xdsCredentials are doing a handshake on it. This can only ever be called + // once per connection. So, we do not need to worry about decrementing the + // reference count for the existing HandshakeInfo, which will always be nil. + // The reference count will be decremented when the connection is closed. + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + if rp != nil { + rp.Close() + } + ip.Close() + return nil, fmt.Errorf("xds: connection closed") + } + c.hi = xds.NewHandshakeInfo(rp, ip, nil, "", secCfg.RequireClientCert, false, false) + return c.hi, nil } // PassServerTransport drains the passed in ServerTransport if draining is set, @@ -148,12 +162,19 @@ func (c *connWrapper) Drain() { // Close closes the providers and the underlying connection. func (c *connWrapper) Close() error { - if c.identityProvider != nil { - c.identityProvider.Close() + c.mu.Lock() + if c.closed { + c.mu.Unlock() + return nil } - if c.rootProvider != nil { - c.rootProvider.Close() + c.closed = true + hi := c.hi + c.mu.Unlock() + + if hi != nil { + hi.Decrement() } + c.parent.removeConn(c) return c.Conn.Close() } diff --git a/vendor/google.golang.org/grpc/internal/xds/server/filter_chain_manager.go b/vendor/google.golang.org/grpc/internal/xds/server/filter_chain_manager.go index f3d0143c24..88c648e119 100644 --- a/vendor/google.golang.org/grpc/internal/xds/server/filter_chain_manager.go +++ b/vendor/google.golang.org/grpc/internal/xds/server/filter_chain_manager.go @@ -18,7 +18,6 @@ package server import ( - "context" "errors" "fmt" "net/netip" @@ -26,8 +25,8 @@ import ( "strings" "sync/atomic" + "google.golang.org/grpc" "google.golang.org/grpc/codes" - "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/xds/httpfilter" "google.golang.org/grpc/internal/xds/xdsclient/xdsresource" "google.golang.org/grpc/status" @@ -209,7 +208,7 @@ type virtualHostWithInterceptors struct { type routeWithInterceptors struct { matcher *xdsresource.CompositeMatcher actionType xdsresource.RouteActionType - interceptor resolver.ServerInterceptor + interceptor httpfilter.ServerInterceptor } type lookupParams struct { @@ -500,9 +499,9 @@ func (rc *usableRouteConfiguration) statusErrWithNodeID(c codes.Code, msg string return status.Error(c, fmt.Sprintf("[xDS node id: %v]: %s", rc.nodeID, fmt.Sprintf(msg, args...))) } -func (fc *filterChain) newInterceptor(routeOverride, virtualHostOverride map[string]httpfilter.FilterConfig, provider serverFilterProvider) (_ resolver.ServerInterceptor, _ []httpfilter.ServerFilter, err error) { +func (fc *filterChain) newInterceptor(routeOverride, virtualHostOverride map[string]httpfilter.FilterConfig, provider serverFilterProvider) (_ httpfilter.ServerInterceptor, _ []httpfilter.ServerFilter, err error) { serverFilters := []httpfilter.ServerFilter{} - interceptors := make([]resolver.ServerInterceptor, 0, len(fc.httpFilters)) + interceptors := make([]httpfilter.ServerInterceptor, 0, len(fc.httpFilters)) defer func() { if err != nil { for _, sf := range serverFilters { @@ -549,16 +548,18 @@ func (fc *filterChain) newInterceptor(routeOverride, virtualHostOverride map[str } type interceptorList struct { - interceptors []resolver.ServerInterceptor + interceptors []httpfilter.ServerInterceptor } -func (il *interceptorList) AllowRPC(ctx context.Context) error { +func (il *interceptorList) InterceptRPC(ss grpc.ServerStream) (grpc.ServerStream, error) { + var err error for _, i := range il.interceptors { - if err := i.AllowRPC(ctx); err != nil { - return err + ss, err = i.InterceptRPC(ss) + if err != nil { + return nil, err } } - return nil + return ss, nil } func (il *interceptorList) Close() { diff --git a/vendor/google.golang.org/grpc/internal/xds/server/routing.go b/vendor/google.golang.org/grpc/internal/xds/server/routing.go index 706872585e..36f4af1d45 100644 --- a/vendor/google.golang.org/grpc/internal/xds/server/routing.go +++ b/vendor/google.golang.org/grpc/internal/xds/server/routing.go @@ -19,28 +19,25 @@ package server import ( - "context" "errors" - "fmt" "strings" "google.golang.org/grpc" "google.golang.org/grpc/codes" - iresolver "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/internal/xds/xdsclient/xdsresource" "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" ) // RouteAndProcess routes the incoming RPC to a configured route in the route // table and also processes the RPC by running the incoming RPC through any HTTP // Filters configured. -func RouteAndProcess(ctx context.Context) error { +func RouteAndProcess(ss grpc.ServerStream) (grpc.ServerStream, error) { + ctx := ss.Context() conn := transport.GetConnection(ctx) cw, ok := conn.(*connWrapper) if !ok { - return errors.New("missing virtual hosts in incoming context") + return nil, errors.New("missing virtual hosts in incoming context") } rc := cw.urc.Load() @@ -51,16 +48,16 @@ func RouteAndProcess(ctx context.Context) error { if logger.V(2) { logger.Infof("RPC on connection with xDS Configuration error: %v", rc.err) } - return status.Error(codes.Unavailable, fmt.Sprintf("error from xDS configuration for matched route configuration: %v", rc.err)) + return nil, rc.statusErrWithNodeID(codes.Unavailable, "error from xDS configuration for matched route configuration: %v", rc.err) } mn, ok := grpc.Method(ctx) if !ok { - return errors.New("missing method name in incoming context") + return nil, rc.statusErrWithNodeID(codes.Internal, "missing method name in incoming context") } md, ok := metadata.FromIncomingContext(ctx) if !ok { - return errors.New("missing metadata in incoming context") + return nil, rc.statusErrWithNodeID(codes.Internal, "missing metadata in incoming context") } // A41 added logic to the core grpc implementation to guarantee that once the // RPC gets to this point, there will be a single, unambiguous authority @@ -68,37 +65,33 @@ func RouteAndProcess(ctx context.Context) error { // header is present. authority := md.Get(":authority") if len(authority) == 0 { - return rc.statusErrWithNodeID(codes.Internal, "no :authority header present") + return nil, rc.statusErrWithNodeID(codes.Internal, "no :authority header present") } vh := findBestMatchingVirtualHostServer(authority[0], rc.vhs) if vh == nil { - return rc.statusErrWithNodeID(codes.Unavailable, "the incoming RPC did not match a configured Virtual Host") + return nil, rc.statusErrWithNodeID(codes.Unavailable, "the incoming RPC did not match a configured Virtual Host") } var rwi *routeWithInterceptors - rpcInfo := iresolver.RPCInfo{ - Context: ctx, - Method: mn, - } for _, r := range vh.routes { - if r.matcher.Match(rpcInfo) { + if r.matcher.Match(mn, md) { // "NonForwardingAction is expected for all Routes used on // server-side; a route with an inappropriate action causes RPCs // matching that route to fail with UNAVAILABLE." - A36 if r.actionType != xdsresource.RouteActionNonForwardingAction { - return rc.statusErrWithNodeID(codes.Unavailable, "the incoming RPC matched to a route that was not of action type non forwarding") + return nil, rc.statusErrWithNodeID(codes.Unavailable, "the incoming RPC matched to a route that was not of action type non forwarding") } rwi = &r break } } if rwi == nil { - return rc.statusErrWithNodeID(codes.Unavailable, "the incoming RPC did not match a configured Route") + return nil, rc.statusErrWithNodeID(codes.Unavailable, "the incoming RPC did not match a configured Route") } - if err := rwi.interceptor.AllowRPC(ctx); err != nil { - return rc.statusErrWithNodeID(codes.PermissionDenied, "Incoming RPC is not allowed: %v", err) + if rwi.interceptor != nil { + return rwi.interceptor.InterceptRPC(ss) } - return nil + return ss, nil } // findBestMatchingVirtualHostServer returns the virtual host whose domains field best diff --git a/vendor/google.golang.org/grpc/internal/xds/xdsclient/resource_types.go b/vendor/google.golang.org/grpc/internal/xds/xdsclient/resource_types.go index 29d1ed4cbf..547e2a4b25 100644 --- a/vendor/google.golang.org/grpc/internal/xds/xdsclient/resource_types.go +++ b/vendor/google.golang.org/grpc/internal/xds/xdsclient/resource_types.go @@ -30,13 +30,13 @@ func supportedResourceTypes(config *bootstrap.Config, gServerCfgMap map[xdsclien TypeURL: version.V3ListenerURL, TypeName: xdsresource.ListenerResourceTypeName, AllResourcesRequiredInSotW: true, - Decoder: xdsresource.NewListenerResourceTypeDecoder(config), + Decoder: xdsresource.NewListenerResourceTypeDecoder(config, gServerCfgMap), }, version.V3RouteConfigURL: { TypeURL: version.V3RouteConfigURL, TypeName: xdsresource.RouteConfigTypeName, AllResourcesRequiredInSotW: false, - Decoder: xdsresource.NewRouteConfigResourceTypeDecoder(config), + Decoder: xdsresource.NewRouteConfigResourceTypeDecoder(config, gServerCfgMap), }, version.V3ClusterURL: { TypeURL: version.V3ClusterURL, diff --git a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/filter_chain.go b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/filter_chain.go index 8d69422d2e..fdf87d3235 100644 --- a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/filter_chain.go +++ b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/filter_chain.go @@ -21,6 +21,7 @@ import ( "fmt" "net/netip" + "google.golang.org/grpc/internal/xds/bootstrap" "google.golang.org/grpc/internal/xds/xdsclient/xdsresource/version" v3listenerpb "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" @@ -80,7 +81,7 @@ func (n NetworkFilterChainConfig) IsEmpty() bool { return n.SecurityCfg == nil && n.HTTPConnMgr == nil } -func processNetworkFilters(filters []*v3listenerpb.Filter) (*HTTPConnectionManagerConfig, error) { +func processNetworkFilters(filters []*v3listenerpb.Filter, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (*HTTPConnectionManagerConfig, error) { hcmConfig := &HTTPConnectionManagerConfig{} seenNames := make(map[string]bool, len(filters)) seenHCM := false @@ -120,7 +121,7 @@ func processNetworkFilters(filters []*v3listenerpb.Filter) (*HTTPConnectionManag // "Any filters after HttpConnectionManager should be ignored during // connection processing but still be considered for validity. // HTTPConnectionManager must have valid http_filters." - A36 - filters, err := processHTTPFilters(hcm.GetHttpFilters(), true) + filters, err := processHTTPFilters(hcm.GetHttpFilters(), true, bc, sc) if err != nil { return nil, fmt.Errorf("network filters {%+v} had invalid server side HTTP Filters {%+v}: %v", filters, hcm.GetHttpFilters(), err) } @@ -157,7 +158,7 @@ func processNetworkFilters(filters []*v3listenerpb.Filter) (*HTTPConnectionManag // server-side." - A36 // Can specify v3 here, as will never get to this function // if v2. - routeU, err := generateRDSUpdateFromRouteConfiguration(hcm.GetRouteConfig(), nil) + routeU, err := generateRDSUpdateFromRouteConfiguration(hcm.GetRouteConfig(), bc, sc) if err != nil { return nil, fmt.Errorf("failed to parse inline RDS resp: %v", err) } diff --git a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/listener_resource_type.go b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/listener_resource_type.go index 71d529f92f..b694ba7d11 100644 --- a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/listener_resource_type.go +++ b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/listener_resource_type.go @@ -33,10 +33,15 @@ const ListenerResourceTypeName = "ListenerResource" // interface for listener resources. type listenerResourceDecoder struct { bootstrapConfig *bootstrap.Config + serverConfigs map[xdsclient.ServerConfig]*bootstrap.ServerConfig } func (d *listenerResourceDecoder) Decode(resource *xdsclient.AnyProto, opts xdsclient.DecodeOptions) (*xdsclient.DecodeResult, error) { - name, listener, err := unmarshalListenerResource(resource.ToAny(), &opts) + var serverCfg *bootstrap.ServerConfig + if opts.ServerConfig != nil { + serverCfg = d.serverConfigs[*opts.ServerConfig] + } + name, listener, err := unmarshalListenerResource(resource.ToAny(), d.bootstrapConfig, serverCfg) if name == "" { // Name is unset only when protobuf deserialization fails. return nil, err @@ -175,6 +180,6 @@ func WatchListener(p Producer, name string, w ListenerWatcher) (cancel func()) { // NewListenerResourceTypeDecoder returns a xdsclient.Decoder that wraps // the xdsresource.listenerType. -func NewListenerResourceTypeDecoder(bc *bootstrap.Config) xdsclient.Decoder { - return &listenerResourceDecoder{bootstrapConfig: bc} +func NewListenerResourceTypeDecoder(bc *bootstrap.Config, gServerCfgMap map[xdsclient.ServerConfig]*bootstrap.ServerConfig) xdsclient.Decoder { + return &listenerResourceDecoder{bootstrapConfig: bc, serverConfigs: gServerCfgMap} } diff --git a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/matcher.go b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/matcher.go index 3eef12f23c..a1c15c21e8 100644 --- a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/matcher.go +++ b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/matcher.go @@ -22,8 +22,6 @@ import ( rand "math/rand/v2" "strings" - "google.golang.org/grpc/internal/grpcutil" - iresolver "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/xds/matcher" "google.golang.org/grpc/metadata" ) @@ -84,27 +82,11 @@ func newCompositeMatcher(pm pathMatcher, hms []matcher.HeaderMatcher, fm *fracti } // Match returns true if all matchers return true. -func (a *CompositeMatcher) Match(info iresolver.RPCInfo) bool { - if a.pm != nil && !a.pm.match(info.Method) { +func (a *CompositeMatcher) Match(method string, md metadata.MD) bool { + if a.pm != nil && !a.pm.match(method) { return false } - // Call headerMatchers even if md is nil, because routes may match - // non-presence of some headers. - var md metadata.MD - if info.Context != nil { - md, _ = metadata.FromOutgoingContext(info.Context) - if extraMD, ok := grpcutil.ExtraMetadata(info.Context); ok { - md = metadata.Join(md, extraMD) - // Remove all binary headers. They are hard to match with. May need - // to add back if asked by users. - for k := range md { - if strings.HasSuffix(k, "-bin") { - delete(md, k) - } - } - } - } for _, m := range a.hms { if !m.Match(md) { return false diff --git a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/route_config_resource_type.go b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/route_config_resource_type.go index 1104fe9f2b..2b392b831b 100644 --- a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/route_config_resource_type.go +++ b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/route_config_resource_type.go @@ -35,10 +35,15 @@ const ( // interface for route configuration resources. type routeConfigResourceDecoder struct { bootstrapConfig *bootstrap.Config + serverConfigs map[xdsclient.ServerConfig]*bootstrap.ServerConfig } func (d *routeConfigResourceDecoder) Decode(resource *xdsclient.AnyProto, opts xdsclient.DecodeOptions) (*xdsclient.DecodeResult, error) { - name, rc, err := unmarshalRouteConfigResource(resource.ToAny(), &opts) + var serverCfg *bootstrap.ServerConfig + if opts.ServerConfig != nil { + serverCfg = d.serverConfigs[*opts.ServerConfig] + } + name, rc, err := unmarshalRouteConfigResource(resource.ToAny(), d.bootstrapConfig, serverCfg) if name == "" { // Name is unset only when protobuf deserialization fails. return nil, err @@ -122,6 +127,6 @@ func WatchRouteConfig(p Producer, name string, w RouteConfigWatcher) (cancel fun // NewRouteConfigResourceTypeDecoder returns a xdsclient.Decoder that wraps // the xdsresource.routeConfigType. -func NewRouteConfigResourceTypeDecoder(bc *bootstrap.Config) xdsclient.Decoder { - return &routeConfigResourceDecoder{bootstrapConfig: bc} +func NewRouteConfigResourceTypeDecoder(bc *bootstrap.Config, gServerCfgMap map[xdsclient.ServerConfig]*bootstrap.ServerConfig) xdsclient.Decoder { + return &routeConfigResourceDecoder{bootstrapConfig: bc, serverConfigs: gServerCfgMap} } diff --git a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_eds.go b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_eds.go index 22eb8500db..3327d6751e 100644 --- a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_eds.go +++ b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_eds.go @@ -77,7 +77,7 @@ func parseAddress(socketAddress *v3corepb.SocketAddress) string { return net.JoinHostPort(socketAddress.GetAddress(), strconv.Itoa(int(socketAddress.GetPortValue()))) } -func parseDropPolicy(dropPolicy *v3endpointpb.ClusterLoadAssignment_Policy_DropOverload) OverloadDropConfig { +func parseDropPolicy(dropPolicy *v3endpointpb.ClusterLoadAssignment_Policy_DropOverload) (OverloadDropConfig, error) { percentage := dropPolicy.GetDropPercentage() var ( numerator = percentage.GetNumerator() @@ -90,12 +90,14 @@ func parseDropPolicy(dropPolicy *v3endpointpb.ClusterLoadAssignment_Policy_DropO denominator = 10000 case v3typepb.FractionalPercent_MILLION: denominator = 1000000 + default: + return OverloadDropConfig{}, fmt.Errorf("EDS response contains a drop policy with unsupported denominator: %v", percentage.GetDenominator()) } return OverloadDropConfig{ Category: dropPolicy.GetCategory(), Numerator: numerator, Denominator: denominator, - } + }, nil } func parseEndpoints(lbEndpoints []*v3endpointpb.LbEndpoint, uniqueEndpointAddrs map[string]bool) ([]Endpoint, error) { @@ -179,7 +181,11 @@ func hashKeyFromMetadata(metadata map[string]any) string { func parseEDSRespProto(m *v3endpointpb.ClusterLoadAssignment) (EndpointsUpdate, error) { ret := EndpointsUpdate{} for _, dropPolicy := range m.GetPolicy().GetDropOverloads() { - ret.Drops = append(ret.Drops, parseDropPolicy(dropPolicy)) + drop, err := parseDropPolicy(dropPolicy) + if err != nil { + return EndpointsUpdate{}, err + } + ret.Drops = append(ret.Drops, drop) } priorities := make(map[uint32]map[string]bool) sumOfWeights := make(map[uint32]uint64) diff --git a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_lds.go b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_lds.go index e4c8bfd5c7..9994d7a6a6 100644 --- a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_lds.go +++ b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_lds.go @@ -31,14 +31,14 @@ import ( v3httppb "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" v3tlspb "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3" "google.golang.org/grpc/internal/envconfig" - "google.golang.org/grpc/internal/xds/clients/xdsclient" + "google.golang.org/grpc/internal/xds/bootstrap" "google.golang.org/grpc/internal/xds/httpfilter" "google.golang.org/grpc/internal/xds/xdsclient/xdsresource/version" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" ) -func unmarshalListenerResource(r *anypb.Any, opts *xdsclient.DecodeOptions) (string, ListenerUpdate, error) { +func unmarshalListenerResource(r *anypb.Any, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (string, ListenerUpdate, error) { r, err := UnwrapResource(r) if err != nil { return "", ListenerUpdate{}, fmt.Errorf("failed to unwrap resource: %v", err) @@ -56,7 +56,7 @@ func unmarshalListenerResource(r *anypb.Any, opts *xdsclient.DecodeOptions) (str return "", ListenerUpdate{}, fmt.Errorf("empty resource name in listener resource") } - lu, err := processListener(lis, opts) + lu, err := processListener(lis, bc, sc) if err != nil { return lis.GetName(), ListenerUpdate{}, err } @@ -65,16 +65,16 @@ func unmarshalListenerResource(r *anypb.Any, opts *xdsclient.DecodeOptions) (str return lis.GetName(), *lu, nil } -func processListener(lis *v3listenerpb.Listener, opts *xdsclient.DecodeOptions) (*ListenerUpdate, error) { +func processListener(lis *v3listenerpb.Listener, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (*ListenerUpdate, error) { if lis.GetApiListener() != nil { - return processClientSideListener(lis, opts) + return processClientSideListener(lis, bc, sc) } - return processServerSideListener(lis) + return processServerSideListener(lis, bc, sc) } // processClientSideListener checks if the provided Listener proto meets // the expected criteria. If so, it returns a non-empty routeConfigName. -func processClientSideListener(lis *v3listenerpb.Listener, opts *xdsclient.DecodeOptions) (*ListenerUpdate, error) { +func processClientSideListener(lis *v3listenerpb.Listener, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (*ListenerUpdate, error) { apiLisAny := lis.GetApiListener().GetApiListener() if !IsHTTPConnManagerResource(apiLisAny.GetTypeUrl()) { return nil, fmt.Errorf("unexpected http connection manager resource type: %q", apiLisAny.GetTypeUrl()) @@ -105,7 +105,7 @@ func processClientSideListener(lis *v3listenerpb.Listener, opts *xdsclient.Decod } hcm.RouteConfigName = name case *v3httppb.HttpConnectionManager_RouteConfig: - routeU, err := generateRDSUpdateFromRouteConfiguration(apiLis.GetRouteConfig(), opts) + routeU, err := generateRDSUpdateFromRouteConfiguration(apiLis.GetRouteConfig(), bc, sc) if err != nil { return nil, fmt.Errorf("failed to parse inline RDS resp: %v", err) } @@ -121,7 +121,7 @@ func processClientSideListener(lis *v3listenerpb.Listener, opts *xdsclient.Decod hcm.MaxStreamDuration = apiLis.GetCommonHttpProtocolOptions().GetMaxStreamDuration().AsDuration() var err error - if hcm.HTTPFilters, err = processHTTPFilters(apiLis.GetHttpFilters(), false); err != nil { + if hcm.HTTPFilters, err = processHTTPFilters(apiLis.GetHttpFilters(), false, bc, sc); err != nil { return nil, err } @@ -149,7 +149,7 @@ func unwrapHTTPFilterConfig(config *anypb.Any) (proto.Message, string, error) { } } -func validateHTTPFilterConfig(cfg *anypb.Any, lds, optional bool) (httpfilter.Builder, httpfilter.FilterConfig, error) { +func validateHTTPFilterConfig(cfg *anypb.Any, lds, optional bool, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (httpfilter.Builder, httpfilter.FilterConfig, error) { config, typeURL, err := unwrapHTTPFilterConfig(cfg) if err != nil { return nil, nil, err @@ -165,14 +165,14 @@ func validateHTTPFilterConfig(cfg *anypb.Any, lds, optional bool) (httpfilter.Bu if !lds { parseFunc = filterBuilder.ParseFilterConfigOverride } - filterConfig, err := parseFunc(config) + filterConfig, err := parseFunc(config, httpfilter.ParseOptions{BootstrapConfig: bc, ServerConfig: sc}) if err != nil { return nil, nil, fmt.Errorf("error parsing config for filter %q: %v", typeURL, err) } return filterBuilder, filterConfig, nil } -func processHTTPFilterOverrides(cfgs map[string]*anypb.Any) (map[string]httpfilter.FilterConfig, error) { +func processHTTPFilterOverrides(cfgs map[string]*anypb.Any, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (map[string]httpfilter.FilterConfig, error) { if len(cfgs) == 0 { return nil, nil } @@ -187,7 +187,7 @@ func processHTTPFilterOverrides(cfgs map[string]*anypb.Any) (map[string]httpfilt } cfg = s.GetConfig() optional = s.GetIsOptional() - if envconfig.XDSClientExtProcEnabled { + if envconfig.XDSClientExtProcEnabled || envconfig.XDSClientExtAuthzEnabled { disabled = s.GetDisabled() } } @@ -197,7 +197,7 @@ func processHTTPFilterOverrides(cfgs map[string]*anypb.Any) (map[string]httpfilt continue } - httpFilter, config, err := validateHTTPFilterConfig(cfg, false, optional) + httpFilter, config, err := validateHTTPFilterConfig(cfg, false, optional, bc, sc) if err != nil { return nil, fmt.Errorf("filter override %q: %v", name, err) } @@ -210,7 +210,7 @@ func processHTTPFilterOverrides(cfgs map[string]*anypb.Any) (map[string]httpfilt return m, nil } -func processHTTPFilters(filters []*v3httppb.HttpFilter, server bool) ([]HTTPFilter, error) { +func processHTTPFilters(filters []*v3httppb.HttpFilter, server bool, bc *bootstrap.Config, sc *bootstrap.ServerConfig) ([]HTTPFilter, error) { ret := make([]HTTPFilter, 0, len(filters)) seenNames := make(map[string]bool, len(filters)) for _, filter := range filters { @@ -223,7 +223,7 @@ func processHTTPFilters(filters []*v3httppb.HttpFilter, server bool) ([]HTTPFilt } seenNames[name] = true - httpFilter, config, err := validateHTTPFilterConfig(filter.GetTypedConfig(), true, filter.GetIsOptional()) + httpFilter, config, err := validateHTTPFilterConfig(filter.GetTypedConfig(), true, filter.GetIsOptional(), bc, sc) if err != nil { return nil, err } @@ -246,7 +246,7 @@ func processHTTPFilters(filters []*v3httppb.HttpFilter, server bool) ([]HTTPFilt } disabled := false - if envconfig.XDSClientExtProcEnabled { + if envconfig.XDSClientExtProcEnabled || envconfig.XDSClientExtAuthzEnabled { disabled = filter.GetDisabled() } // Save name/config @@ -269,7 +269,7 @@ func processHTTPFilters(filters []*v3httppb.HttpFilter, server bool) ([]HTTPFilt return ret, nil } -func processServerSideListener(lis *v3listenerpb.Listener) (*ListenerUpdate, error) { +func processServerSideListener(lis *v3listenerpb.Listener, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (*ListenerUpdate, error) { if n := len(lis.ListenerFilters); n != 0 { return nil, fmt.Errorf("unsupported field 'listener_filters' contains %d entries", n) } @@ -293,7 +293,7 @@ func processServerSideListener(lis *v3listenerpb.Listener) (*ListenerUpdate, err // Populate the default filter chain. if dfc := lis.GetDefaultFilterChain(); dfc != nil { - fc, err := filterChainFromProto(dfc) + fc, err := filterChainFromProto(dfc, bc, sc) if err != nil { return nil, fmt.Errorf("failed to unmarshal default filter chain: %v", err) } @@ -301,7 +301,7 @@ func processServerSideListener(lis *v3listenerpb.Listener) (*ListenerUpdate, err } // Populated the filter chain map. - fcm, err := buildFilterChainMap(lis.GetFilterChains()) + fcm, err := buildFilterChainMap(lis.GetFilterChains(), bc, sc) if err != nil { return nil, fmt.Errorf("failed to unmarshal filter chains: %v", err) } @@ -316,10 +316,10 @@ func processServerSideListener(lis *v3listenerpb.Listener) (*ListenerUpdate, err return lu, nil } -func filterChainFromProto(fc *v3listenerpb.FilterChain) (NetworkFilterChainConfig, error) { +func filterChainFromProto(fc *v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (NetworkFilterChainConfig, error) { var emptyFilterChain NetworkFilterChainConfig - hcmConfig, err := processNetworkFilters(fc.GetFilters()) + hcmConfig, err := processNetworkFilters(fc.GetFilters(), bc, sc) if err != nil { return emptyFilterChain, err } @@ -353,16 +353,16 @@ func filterChainFromProto(fc *v3listenerpb.FilterChain) (NetworkFilterChainConfi if downstreamCtx.GetCommonTlsContext() == nil { return emptyFilterChain, errors.New("DownstreamTlsContext in LDS response does not contain a CommonTlsContext") } - sc, err := securityConfigFromCommonTLSContext(downstreamCtx.GetCommonTlsContext(), true) + secCfg, err := securityConfigFromCommonTLSContext(downstreamCtx.GetCommonTlsContext(), true) if err != nil { return emptyFilterChain, err } - if sc != nil { - sc.RequireClientCert = downstreamCtx.GetRequireClientCertificate().GetValue() - if sc.RequireClientCert && sc.RootInstanceName == "" { + if secCfg != nil { + secCfg.RequireClientCert = downstreamCtx.GetRequireClientCertificate().GetValue() + if secCfg.RequireClientCert && secCfg.RootInstanceName == "" { return emptyFilterChain, errors.New("security configuration on the server-side does not contain root certificate provider instance name, but require_client_cert field is set") } - fcc.SecurityCfg = sc + fcc.SecurityCfg = secCfg } return fcc, nil } @@ -373,7 +373,7 @@ type dstPrefixEntry struct { rawBufferSeen bool } -func buildFilterChainMap(fcs []*v3listenerpb.FilterChain) (NetworkFilterChainMap, error) { +func buildFilterChainMap(fcs []*v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (NetworkFilterChainMap, error) { dstPrefixEntries := []*dstPrefixEntry{} for _, fc := range fcs { fcMatch := fc.GetFilterChainMatch() @@ -385,7 +385,7 @@ func buildFilterChainMap(fcs []*v3listenerpb.FilterChain) (NetworkFilterChainMap } var err error - dstPrefixEntries, err = addFilterChainsForDestPrefixes(dstPrefixEntries, fc) + dstPrefixEntries, err = addFilterChainsForDestPrefixes(dstPrefixEntries, fc, bc, sc) if err != nil { return NetworkFilterChainMap{}, err } @@ -413,7 +413,7 @@ func buildFilterChainMap(fcs []*v3listenerpb.FilterChain) (NetworkFilterChainMap return NetworkFilterChainMap{DstPrefixes: entries}, nil } -func addFilterChainsForDestPrefixes(dstPrefixEntries []*dstPrefixEntry, fc *v3listenerpb.FilterChain) ([]*dstPrefixEntry, error) { +func addFilterChainsForDestPrefixes(dstPrefixEntries []*dstPrefixEntry, fc *v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) ([]*dstPrefixEntry, error) { ranges := fc.GetFilterChainMatch().GetPrefixRanges() dstPrefixes, err := parsePrefixRanges(ranges) if err != nil { @@ -425,14 +425,14 @@ func addFilterChainsForDestPrefixes(dstPrefixEntries []*dstPrefixEntry, fc *v3li // Use the unspecified entry when destination prefix is unspecified, and // set the `prefix` field to nil. dstPrefixEntries, entry = getOrCreateDestPrefixEntry(dstPrefixEntries, netip.Prefix{}) - if err := addFilterChainsForServerNames(entry, fc); err != nil { + if err := addFilterChainsForServerNames(entry, fc, bc, sc); err != nil { return nil, err } return dstPrefixEntries, nil } for _, prefix := range dstPrefixes { dstPrefixEntries, entry = getOrCreateDestPrefixEntry(dstPrefixEntries, prefix) - if err := addFilterChainsForServerNames(entry, fc); err != nil { + if err := addFilterChainsForServerNames(entry, fc, bc, sc); err != nil { return nil, err } } @@ -454,7 +454,7 @@ func getOrCreateDestPrefixEntry(dstPrefixEntries []*dstPrefixEntry, prefix netip return dstPrefixEntries, entry } -func addFilterChainsForServerNames(dstEntry *dstPrefixEntry, fc *v3listenerpb.FilterChain) error { +func addFilterChainsForServerNames(dstEntry *dstPrefixEntry, fc *v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) error { // Filter chains specifying server names in their match criteria always fail // a match at connection time. So, these filter chains can be dropped now. if len(fc.GetFilterChainMatch().GetServerNames()) != 0 { @@ -462,10 +462,10 @@ func addFilterChainsForServerNames(dstEntry *dstPrefixEntry, fc *v3listenerpb.Fi return nil } - return addFilterChainsForTransportProtocols(dstEntry, fc) + return addFilterChainsForTransportProtocols(dstEntry, fc, bc, sc) } -func addFilterChainsForTransportProtocols(dstEntry *dstPrefixEntry, fc *v3listenerpb.FilterChain) error { +func addFilterChainsForTransportProtocols(dstEntry *dstPrefixEntry, fc *v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) error { tp := fc.GetFilterChainMatch().GetTransportProtocol() switch { case tp != "" && tp != "raw_buffer": @@ -486,15 +486,15 @@ func addFilterChainsForTransportProtocols(dstEntry *dstPrefixEntry, fc *v3listen dstEntry.rawBufferSeen = true dstEntry.entry.SourceTypeArr = [3]SourcePrefixes{} } - return addFilterChainsForApplicationProtocols(dstEntry, fc) + return addFilterChainsForApplicationProtocols(dstEntry, fc, bc, sc) } -func addFilterChainsForApplicationProtocols(dstEntry *dstPrefixEntry, fc *v3listenerpb.FilterChain) error { +func addFilterChainsForApplicationProtocols(dstEntry *dstPrefixEntry, fc *v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) error { if len(fc.GetFilterChainMatch().GetApplicationProtocols()) != 0 { logger.Warningf("Dropping filter chain %q since it contains unsupported application_protocols match field", fc.GetName()) return nil } - return addFilterChainsForSourceType(&dstEntry.entry, fc) + return addFilterChainsForSourceType(&dstEntry.entry, fc, bc, sc) } // sourceType specifies the connection source IP match type. @@ -509,7 +509,7 @@ const ( sourceTypeExternal ) -func addFilterChainsForSourceType(entry *DestinationPrefixEntry, fc *v3listenerpb.FilterChain) error { +func addFilterChainsForSourceType(entry *DestinationPrefixEntry, fc *v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) error { var srcType sourceType switch st := fc.GetFilterChainMatch().GetSourceType(); st { case v3listenerpb.FilterChainMatch_ANY: @@ -522,10 +522,10 @@ func addFilterChainsForSourceType(entry *DestinationPrefixEntry, fc *v3listenerp return fmt.Errorf("unsupported source type: %v", st) } - return addFilterChainsForSourcePrefixes(&entry.SourceTypeArr[srcType], fc) + return addFilterChainsForSourcePrefixes(&entry.SourceTypeArr[srcType], fc, bc, sc) } -func addFilterChainsForSourcePrefixes(srcPrefixes *SourcePrefixes, fc *v3listenerpb.FilterChain) error { +func addFilterChainsForSourcePrefixes(srcPrefixes *SourcePrefixes, fc *v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) error { ranges := fc.GetFilterChainMatch().GetSourcePrefixRanges() prefixes, err := parsePrefixRanges(ranges) if err != nil { @@ -533,10 +533,10 @@ func addFilterChainsForSourcePrefixes(srcPrefixes *SourcePrefixes, fc *v3listene } if len(prefixes) == 0 { - return getOrCreateSourcePrefixEntry(srcPrefixes, netip.Prefix{}, fc) + return getOrCreateSourcePrefixEntry(srcPrefixes, netip.Prefix{}, fc, bc, sc) } for _, prefix := range prefixes { - if err := getOrCreateSourcePrefixEntry(srcPrefixes, prefix, fc); err != nil { + if err := getOrCreateSourcePrefixEntry(srcPrefixes, prefix, fc, bc, sc); err != nil { return err } } @@ -571,10 +571,10 @@ func parsePrefixRanges(ranges []*v3corepb.CidrRange) ([]netip.Prefix, error) { // SourcePrefixes, the provided filter chain is added to the new entry, and nil // is returned. If there are multiple filter chains with overlapping matching // rules, an error is returned. -func getOrCreateSourcePrefixEntry(srcPrefixes *SourcePrefixes, prefix netip.Prefix, fc *v3listenerpb.FilterChain) error { +func getOrCreateSourcePrefixEntry(srcPrefixes *SourcePrefixes, prefix netip.Prefix, fc *v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) error { for i := range srcPrefixes.Entries { if srcPrefixes.Entries[i].Prefix == prefix { - return addFilterChainsForSourcePorts(&srcPrefixes.Entries[i], fc) + return addFilterChainsForSourcePorts(&srcPrefixes.Entries[i], fc, bc, sc) } } @@ -583,10 +583,10 @@ func getOrCreateSourcePrefixEntry(srcPrefixes *SourcePrefixes, prefix netip.Pref Prefix: prefix, PortMap: make(map[int]NetworkFilterChainConfig), }) - return addFilterChainsForSourcePorts(&srcPrefixes.Entries[len(srcPrefixes.Entries)-1], fc) + return addFilterChainsForSourcePorts(&srcPrefixes.Entries[len(srcPrefixes.Entries)-1], fc, bc, sc) } -func addFilterChainsForSourcePorts(entry *SourcePrefixEntry, fc *v3listenerpb.FilterChain) error { +func addFilterChainsForSourcePorts(entry *SourcePrefixEntry, fc *v3listenerpb.FilterChain, bc *bootstrap.Config, sc *bootstrap.ServerConfig) error { ports := fc.GetFilterChainMatch().GetSourcePorts() srcPorts := make([]int, 0, len(ports)) for _, port := range ports { @@ -597,7 +597,7 @@ func addFilterChainsForSourcePorts(entry *SourcePrefixEntry, fc *v3listenerpb.Fi if !entry.PortMap[0].IsEmpty() { return errors.New("multiple filter chains with overlapping matching rules are defined") } - fcc, err := filterChainFromProto(fc) + fcc, err := filterChainFromProto(fc, bc, sc) if err != nil { return err } @@ -608,7 +608,7 @@ func addFilterChainsForSourcePorts(entry *SourcePrefixEntry, fc *v3listenerpb.Fi if !entry.PortMap[port].IsEmpty() { return errors.New("multiple filter chains with overlapping matching rules are defined") } - fcc, err := filterChainFromProto(fc) + fcc, err := filterChainFromProto(fc, bc, sc) if err != nil { return err } diff --git a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_rds.go b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_rds.go index a053db2235..865cc24ed4 100644 --- a/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_rds.go +++ b/vendor/google.golang.org/grpc/internal/xds/xdsclient/xdsresource/unmarshal_rds.go @@ -26,7 +26,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/internal/envconfig" - "google.golang.org/grpc/internal/xds/clients/xdsclient" + "google.golang.org/grpc/internal/xds/bootstrap" "google.golang.org/grpc/internal/xds/clusterspecifier" "google.golang.org/grpc/internal/xds/matcher" "google.golang.org/protobuf/proto" @@ -37,7 +37,7 @@ import ( v3typepb "github.com/envoyproxy/go-control-plane/envoy/type/v3" ) -func unmarshalRouteConfigResource(r *anypb.Any, opts *xdsclient.DecodeOptions) (string, RouteConfigUpdate, error) { +func unmarshalRouteConfigResource(r *anypb.Any, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (string, RouteConfigUpdate, error) { r, err := UnwrapResource(r) if err != nil { return "", RouteConfigUpdate{}, fmt.Errorf("failed to unwrap resource: %v", err) @@ -55,7 +55,7 @@ func unmarshalRouteConfigResource(r *anypb.Any, opts *xdsclient.DecodeOptions) ( return "", RouteConfigUpdate{}, fmt.Errorf("empty resource name in route config resource") } - u, err := generateRDSUpdateFromRouteConfiguration(rc, opts) + u, err := generateRDSUpdateFromRouteConfiguration(rc, bc, sc) if err != nil { return rc.GetName(), RouteConfigUpdate{}, err } @@ -80,7 +80,7 @@ func unmarshalRouteConfigResource(r *anypb.Any, opts *xdsclient.DecodeOptions) ( // field must be empty and whose route field must be set. Inside that route // message, the cluster field will contain the clusterName or weighted clusters // we are looking for. -func generateRDSUpdateFromRouteConfiguration(rc *v3routepb.RouteConfiguration, opts *xdsclient.DecodeOptions) (RouteConfigUpdate, error) { +func generateRDSUpdateFromRouteConfiguration(rc *v3routepb.RouteConfiguration, bc *bootstrap.Config, sc *bootstrap.ServerConfig) (RouteConfigUpdate, error) { vhs := make([]*VirtualHost, 0, len(rc.GetVirtualHosts())) csps, err := processClusterSpecifierPlugins(rc.ClusterSpecifierPlugins) if err != nil { @@ -91,7 +91,7 @@ func generateRDSUpdateFromRouteConfiguration(rc *v3routepb.RouteConfiguration, o // ignored and not emitted by the xdsclient. var cspNames = make(map[string]bool) for _, vh := range rc.GetVirtualHosts() { - routes, cspNs, err := routesProtoToSlice(vh.Routes, csps, opts) + routes, cspNs, err := routesProtoToSlice(vh.Routes, csps, bc, sc) if err != nil { return RouteConfigUpdate{}, fmt.Errorf("received route is invalid: %v", err) } @@ -107,7 +107,7 @@ func generateRDSUpdateFromRouteConfiguration(rc *v3routepb.RouteConfiguration, o Routes: routes, RetryConfig: rc, } - cfgs, err := processHTTPFilterOverrides(vh.GetTypedPerFilterConfig()) + cfgs, err := processHTTPFilterOverrides(vh.GetTypedPerFilterConfig(), bc, sc) if err != nil { return RouteConfigUpdate{}, fmt.Errorf("virtual host %+v: %v", vh, err) } @@ -214,7 +214,7 @@ func generateRetryConfig(rp *v3routepb.RetryPolicy) (*RetryConfig, error) { return cfg, nil } -func routesProtoToSlice(routes []*v3routepb.Route, csps map[string]clusterspecifier.BalancerConfig, opts *xdsclient.DecodeOptions) ([]*Route, map[string]bool, error) { +func routesProtoToSlice(routes []*v3routepb.Route, csps map[string]clusterspecifier.BalancerConfig, bc *bootstrap.Config, sc *bootstrap.ServerConfig) ([]*Route, map[string]bool, error) { var routesRet []*Route var cspNames = make(map[string]bool) for _, r := range routes { @@ -323,7 +323,7 @@ func routesProtoToSlice(routes []*v3routepb.Route, csps map[string]clusterspecif action := r.GetRoute() if envconfig.XDSAuthorityRewrite { - if opts != nil && opts.ServerConfig != nil && opts.ServerConfig.SupportsServerFeature(xdsclient.ServerFeatureTrustedXDSServer) { + if sc != nil && sc.ServerFeaturesTrustedXDSServer() { route.AutoHostRewrite = action.GetAutoHostRewrite().GetValue() } } @@ -351,7 +351,7 @@ func routesProtoToSlice(routes []*v3routepb.Route, csps map[string]clusterspecif return nil, nil, fmt.Errorf("xds: total weight of clusters exceeds MaxUint32") } wc := WeightedCluster{Name: c.GetName(), Weight: w} - cfgs, err := processHTTPFilterOverrides(c.GetTypedPerFilterConfig()) + cfgs, err := processHTTPFilterOverrides(c.GetTypedPerFilterConfig(), bc, sc) if err != nil { return nil, nil, fmt.Errorf("route %+v, action %+v: %v", r, a, err) } @@ -417,7 +417,7 @@ func routesProtoToSlice(routes []*v3routepb.Route, csps map[string]clusterspecif route.ActionType = RouteActionUnsupported } - cfgs, err := processHTTPFilterOverrides(r.GetTypedPerFilterConfig()) + cfgs, err := processHTTPFilterOverrides(r.GetTypedPerFilterConfig(), bc, sc) if err != nil { return nil, nil, fmt.Errorf("route %+v: %v", r, err) } diff --git a/vendor/google.golang.org/grpc/metadata/metadata.go b/vendor/google.golang.org/grpc/metadata/metadata.go index d2e15253bb..2b79204b48 100644 --- a/vendor/google.golang.org/grpc/metadata/metadata.go +++ b/vendor/google.golang.org/grpc/metadata/metadata.go @@ -24,6 +24,7 @@ package metadata // import "google.golang.org/grpc/metadata" import ( "context" "fmt" + "sort" "strings" "google.golang.org/grpc/internal" @@ -90,6 +91,76 @@ func Pairs(kv ...string) MD { return md } +// loggableMetadataKeys is the set of metadata keys whose values are known not +// to carry credentials or other sensitive data, and are therefore safe to print +// verbatim in String. Values for any key not in this set are redacted. Keys are +// in metadata's canonical lowercase form. +// +// The list is intentionally restricted to standardized gRPC and HTTP/2 protocol +// headers. Everything else, including all application-defined keys, is +// censored. +// Note that this list might change as we add/remove support for +// metadata types. +var loggableMetadataKeys = map[string]bool{ + "content-type": true, + "te": true, + "user-agent": true, + "grpc-encoding": true, + "grpc-accept-encoding": true, + "grpc-timeout": true, + "grpc-status": true, + "grpc-message-type": true, + "grpc-previous-rpc-attempts": true, + "grpc-retry-pushback-ms": true, +} + +// String implements fmt.Stringer to allow metadata to be printed when stored in +// a context. +// +// To avoid accidentally leaking credentials or other sensitive data (for +// example via log(md), or by logging a value that happens to contain metadata), +// String reports only keys on an allowlist of standardized, non-sensitive +// protocol headers (see loggableMetadataKeys). Every other key is omitted +// entirely, along with its values, because a key name may itself be sensitive; +// only the number of omitted keys is reported, as "". This is a +// best-effort guard against accidents, not a security boundary: a caller that +// genuinely wants the full contents can still print map[string][]string(md) +// directly. +// +// Note that this only affects verbs that use the Stringer, such as %v and %s. +// The %#v verb prints the underlying map with all values and is not redacted. +// Users should not rely on the output of this method to be stable +// # Experimental +// +// Notice: This API is EXPERIMENTAL and may be changed or removed in a later +// release. +func (md MD) String() string { + keys := make([]string, 0, len(md)) + for k := range md { + if loggableMetadataKeys[strings.ToLower(k)] { + keys = append(keys, k) + } + } + sort.Strings(keys) + + var sb strings.Builder + sb.WriteString("map[") + for i, k := range keys { + if i > 0 { + sb.WriteByte(' ') + } + fmt.Fprintf(&sb, "%s:%v", k, md[k]) + } + if redacted := len(md) - len(keys); redacted > 0 { + if len(keys) > 0 { + sb.WriteByte(' ') + } + fmt.Fprintf(&sb, "<%d redacted>", redacted) + } + sb.WriteByte(']') + return sb.String() +} + // Len returns the number of items in md. func (md MD) Len() int { return len(md) diff --git a/vendor/google.golang.org/grpc/resolver_wrapper.go b/vendor/google.golang.org/grpc/resolver_wrapper.go index 6e61376437..f8b0fd38fd 100644 --- a/vendor/google.golang.org/grpc/resolver_wrapper.go +++ b/vendor/google.golang.org/grpc/resolver_wrapper.go @@ -188,7 +188,7 @@ func (ccr *ccResolverWrapper) ParseServiceConfig(scJSON string) *serviceconfig.P // addChannelzTraceEvent adds a channelz trace event containing the new // state received from resolver implementations. func (ccr *ccResolverWrapper) addChannelzTraceEvent(s resolver.State) { - if !logger.V(0) && !channelz.IsOn() { + if !logger.V(2) && !channelz.IsOn() { return } var updates []string diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index cf0a206719..4ab54115b4 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -89,6 +89,7 @@ func init() { internal.MetricsRecorderForServer = func(srv *Server) estats.MetricsRecorder { return istats.NewMetricsRecorderList(srv.opts.statsHandlers) } + internal.XDSFilterWrapperOption = xdsFilterWrapperOption } var statusOK = status.New(codes.OK, "") @@ -117,10 +118,8 @@ type ServiceDesc struct { // serviceInfo wraps information about a service. It is very similar to // ServiceDesc and is constructed from it for internal purposes. type serviceInfo struct { - // Contains the implementation for the methods in this service. - serviceImpl any - methods map[string]*MethodDesc - streams map[string]*StreamDesc + serviceImpl any // Implementation for the methods in this service. + streams map[string]*StreamDesc // Streaming descriptors and wrapped unary descriptors for this service. mdata any } @@ -183,6 +182,7 @@ type serverOptions struct { bufferPool mem.BufferPool waitForHandlers bool staticWindowSize bool + streamWrapper func(ServerStream) (ServerStream, error) } var defaultServerOptions = serverOptions{ @@ -663,6 +663,14 @@ func bufferPool(bufferPool mem.BufferPool) ServerOption { }) } +// xdsFilterWrapperOption returns a ServerOption that sets the server-level +// stream wrapper (used internally by xDS server filters). +func xdsFilterWrapperOption(w func(ServerStream) (ServerStream, error)) ServerOption { + return newFuncServerOption(func(o *serverOptions) { + o.streamWrapper = w + }) +} + // serverWorkerResetThreshold defines how often the stack must be reset. Every // N requests, by spawning a new goroutine in its place, a worker can reset its // stack so that large stacks don't live in memory forever. 2^16 should allow @@ -790,18 +798,22 @@ func (s *Server) register(sd *ServiceDesc, ss any) { } info := &serviceInfo{ serviceImpl: ss, - methods: make(map[string]*MethodDesc), streams: make(map[string]*StreamDesc), mdata: sd.Metadata, } - for i := range sd.Methods { - d := &sd.Methods[i] - info.methods[d.MethodName] = d - } for i := range sd.Streams { d := &sd.Streams[i] info.streams[d.StreamName] = d } + for i := range sd.Methods { + d := &sd.Methods[i] + info.streams[d.MethodName] = &StreamDesc{ + StreamName: d.MethodName, + Handler: s.wrapUnaryHandler(d), + ServerStreams: false, + ClientStreams: false, + } + } s.services[sd.ServiceName] = info } @@ -827,20 +839,26 @@ type ServiceInfo struct { func (s *Server) GetServiceInfo() map[string]ServiceInfo { ret := make(map[string]ServiceInfo) for n, srv := range s.services { - methods := make([]MethodInfo, 0, len(srv.methods)+len(srv.streams)) - for m := range srv.methods { - methods = append(methods, MethodInfo{ - Name: m, - IsClientStream: false, - IsServerStream: false, - }) + methods := make([]MethodInfo, 0, len(srv.streams)) + // Iterate over unary methods first to maintain backward compatibility of order. + for m, d := range srv.streams { + if !d.ClientStreams && !d.ServerStreams { + methods = append(methods, MethodInfo{ + Name: m, + IsClientStream: false, + IsServerStream: false, + }) + } } + // Iterate over streaming methods. for m, d := range srv.streams { - methods = append(methods, MethodInfo{ - Name: m, - IsClientStream: d.ClientStreams, - IsServerStream: d.ServerStreams, - }) + if d.ClientStreams || d.ServerStreams { + methods = append(methods, MethodInfo{ + Name: m, + IsClientStream: d.ClientStreams, + IsServerStream: d.ServerStreams, + }) + } } ret[n] = ServiceInfo{ @@ -1185,42 +1203,6 @@ func (s *Server) incrCallsFailed() { s.channelz.ServerMetrics.CallsFailed.Add(1) } -func (s *Server) sendResponse(ctx context.Context, stream *transport.ServerStream, msg any, cp Compressor, opts *transport.WriteOptions, comp encoding.Compressor) error { - data, err := encode(s.getCodec(stream.ContentSubtype()), msg) - if err != nil { - channelz.Error(logger, s.channelz, "grpc: server failed to encode response: ", err) - return err - } - - compData, pf, err := compress(data, cp, comp, s.opts.bufferPool) - if err != nil { - data.Free() - channelz.Error(logger, s.channelz, "grpc: server failed to compress response: ", err) - return err - } - - hdr, payload := msgHeader(data, compData, pf) - - defer func() { - compData.Free() - data.Free() - // payload does not need to be freed here, it is either data or compData, both of - // which are already freed. - }() - - dataLen := data.Len() - payloadLen := payload.Len() - // TODO(dfawley): should we be checking len(data) instead? - if payloadLen > s.opts.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", payloadLen, s.opts.maxSendMessageSize) - } - err = stream.Write(hdr, payload, opts) - if err == nil && s.statsHandler != nil { - s.statsHandler.HandleRPC(ctx, outPayload(false, msg, dataLen, payloadLen, time.Now())) - } - return err -} - // chainUnaryServerInterceptors chains all unary server interceptors into one. func chainUnaryServerInterceptors(s *Server) { // Prepend opts.unaryInt to the chaining interceptors if it exists, since unaryInt will @@ -1257,300 +1239,6 @@ func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info } } -func (s *Server) processUnaryRPC(ctx context.Context, stream *transport.ServerStream, info *serviceInfo, md *MethodDesc, trInfo *traceInfo) (err error) { - sh := s.statsHandler - if sh != nil || trInfo != nil || channelz.IsOn() { - if channelz.IsOn() { - s.incrCallsStarted() - } - var statsBegin *stats.Begin - if sh != nil { - statsBegin = &stats.Begin{ - BeginTime: time.Now(), - IsClientStream: false, - IsServerStream: false, - } - sh.HandleRPC(ctx, statsBegin) - } - if trInfo != nil { - trInfo.tr.LazyLog(&trInfo.firstLine, false) - } - // The deferred error handling for tracing, stats handler and channelz are - // combined into one function to reduce stack usage -- a defer takes ~56-64 - // bytes on the stack, so overflowing the stack will require a stack - // re-allocation, which is expensive. - // - // To maintain behavior similar to separate deferred statements, statements - // should be executed in the reverse order. That is, tracing first, stats - // handler second, and channelz last. Note that panics *within* defers will - // lead to different behavior, but that's an acceptable compromise; that - // would be undefined behavior territory anyway. - defer func() { - if trInfo != nil { - if err != nil && err != io.EOF { - trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true) - trInfo.tr.SetError() - } - trInfo.tr.Finish() - } - - if sh != nil { - end := &stats.End{ - BeginTime: statsBegin.BeginTime, - EndTime: time.Now(), - } - if err != nil && err != io.EOF { - end.Error = toRPCErr(err) - } - sh.HandleRPC(ctx, end) - } - - if channelz.IsOn() { - if err != nil && err != io.EOF { - s.incrCallsFailed() - } else { - s.incrCallsSucceeded() - } - } - }() - } - var binlogs []binarylog.MethodLogger - if ml := binarylog.GetMethodLogger(stream.Method()); ml != nil { - binlogs = append(binlogs, ml) - } - if s.opts.binaryLogger != nil { - if ml := s.opts.binaryLogger.GetMethodLogger(stream.Method()); ml != nil { - binlogs = append(binlogs, ml) - } - } - if len(binlogs) != 0 { - md, _ := metadata.FromIncomingContext(ctx) - logEntry := &binarylog.ClientHeader{ - Header: md, - MethodName: stream.Method(), - PeerAddr: nil, - } - if deadline, ok := ctx.Deadline(); ok { - logEntry.Timeout = time.Until(deadline) - if logEntry.Timeout < 0 { - logEntry.Timeout = 0 - } - } - if a := md[":authority"]; len(a) > 0 { - logEntry.Authority = a[0] - } - if peer, ok := peer.FromContext(ctx); ok { - logEntry.PeerAddr = peer.Addr - } - for _, binlog := range binlogs { - binlog.Log(ctx, logEntry) - } - } - - // comp and cp are used for compression. decomp and dc are used for - // decompression. If comp and decomp are both set, they are the same; - // however they are kept separate to ensure that at most one of the - // compressor/decompressor variable pairs are set for use later. - var comp, decomp encoding.Compressor - var cp Compressor - var dc Decompressor - var sendCompressorName string - - // If dc is set and matches the stream's compression, use it. Otherwise, try - // to find a matching registered compressor for decomp. - if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { - dc = s.opts.dc - } else if rc != "" && rc != encoding.Identity { - decomp = encoding.GetCompressor(rc) - if decomp == nil { - st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) - stream.WriteStatus(st) - return st.Err() - } - } - - // If cp is set, use it. Otherwise, attempt to compress the response using - // the incoming message compression method. - // - // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. - if s.opts.cp != nil { - cp = s.opts.cp - sendCompressorName = cp.Type() - } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { - // Legacy compressor not specified; attempt to respond with same encoding. - comp = encoding.GetCompressor(rc) - if comp != nil { - sendCompressorName = comp.Name() - } - } - - if sendCompressorName != "" { - if err := stream.SetSendCompress(sendCompressorName); err != nil { - return status.Errorf(codes.Internal, "grpc: failed to set send compressor: %v", err) - } - } - - var payInfo *payloadInfo - if sh != nil || len(binlogs) != 0 { - payInfo = &payloadInfo{} - defer payInfo.free() - } - - d, err := recvAndDecompress(&parser{r: stream, bufferPool: s.opts.bufferPool}, stream, dc, s.opts.maxReceiveMessageSize, payInfo, decomp, true) - if err != nil { - if e := stream.WriteStatus(status.Convert(err)); e != nil { - channelz.Warningf(logger, s.channelz, "grpc: Server.processUnaryRPC failed to write status: %v", e) - } - return err - } - freed := false - dataFree := func() { - if !freed { - d.Free() - freed = true - } - } - defer dataFree() - df := func(v any) error { - defer dataFree() - if err := s.getCodec(stream.ContentSubtype()).Unmarshal(d, v); err != nil { - return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err) - } - - if sh != nil { - sh.HandleRPC(ctx, &stats.InPayload{ - RecvTime: time.Now(), - Payload: v, - Length: d.Len(), - WireLength: payInfo.compressedLength + headerLen, - CompressedLength: payInfo.compressedLength, - }) - } - if len(binlogs) != 0 { - cm := &binarylog.ClientMessage{ - Message: d.Materialize(), - } - for _, binlog := range binlogs { - binlog.Log(ctx, cm) - } - } - if trInfo != nil { - trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true) - } - return nil - } - ctx = NewContextWithServerTransportStream(ctx, stream) - reply, appErr := md.Handler(info.serviceImpl, ctx, df, s.opts.unaryInt) - if appErr != nil { - appStatus, ok := status.FromError(appErr) - if !ok { - // Convert non-status application error to a status error with code - // Unknown, but handle context errors specifically. - appStatus = status.FromContextError(appErr) - appErr = appStatus.Err() - } - if trInfo != nil { - trInfo.tr.LazyLog(stringer(appStatus.Message()), true) - trInfo.tr.SetError() - } - if e := stream.WriteStatus(appStatus); e != nil { - channelz.Warningf(logger, s.channelz, "grpc: Server.processUnaryRPC failed to write status: %v", e) - } - if len(binlogs) != 0 { - if h, _ := stream.Header(); h.Len() > 0 { - // Only log serverHeader if there was header. Otherwise it can - // be trailer only. - sh := &binarylog.ServerHeader{ - Header: h, - } - for _, binlog := range binlogs { - binlog.Log(ctx, sh) - } - } - st := &binarylog.ServerTrailer{ - Trailer: stream.Trailer(), - Err: appErr, - } - for _, binlog := range binlogs { - binlog.Log(ctx, st) - } - } - return appErr - } - if trInfo != nil { - trInfo.tr.LazyLog(stringer("OK"), false) - } - opts := &transport.WriteOptions{Last: true} - - // Server handler could have set new compressor by calling SetSendCompressor. - // In case it is set, we need to use it for compressing outbound message. - if stream.SendCompress() != sendCompressorName { - comp = encoding.GetCompressor(stream.SendCompress()) - } - if err := s.sendResponse(ctx, stream, reply, cp, opts, comp); err != nil { - if err == io.EOF { - // The entire stream is done (for unary RPC only). - return err - } - if sts, ok := status.FromError(err); ok { - if e := stream.WriteStatus(sts); e != nil { - channelz.Warningf(logger, s.channelz, "grpc: Server.processUnaryRPC failed to write status: %v", e) - } - } else { - switch st := err.(type) { - case transport.ConnectionError: - // Nothing to do here. - default: - panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st)) - } - } - if len(binlogs) != 0 { - h, _ := stream.Header() - sh := &binarylog.ServerHeader{ - Header: h, - } - st := &binarylog.ServerTrailer{ - Trailer: stream.Trailer(), - Err: appErr, - } - for _, binlog := range binlogs { - binlog.Log(ctx, sh) - binlog.Log(ctx, st) - } - } - return err - } - if len(binlogs) != 0 { - h, _ := stream.Header() - sh := &binarylog.ServerHeader{ - Header: h, - } - sm := &binarylog.ServerMessage{ - Message: reply, - } - for _, binlog := range binlogs { - binlog.Log(ctx, sh) - binlog.Log(ctx, sm) - } - } - if trInfo != nil { - trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true) - } - // TODO: Should we be logging if writing status failed here, like above? - // Should the logging be in WriteStatus? Should we ignore the WriteStatus - // error or allow the stats handler to see it? - if len(binlogs) != 0 { - st := &binarylog.ServerTrailer{ - Trailer: stream.Trailer(), - Err: appErr, - } - for _, binlog := range binlogs { - binlog.Log(ctx, st) - } - } - return stream.WriteStatus(statusOK) -} - // chainStreamServerInterceptors chains all stream server interceptors into one. func chainStreamServerInterceptors(s *Server) { // Prepend opts.streamInt to the chaining interceptors if it exists, since streamInt will @@ -1587,7 +1275,21 @@ func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, inf } } -func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.ServerStream, info *serviceInfo, sd *StreamDesc, trInfo *traceInfo) (err error) { +// wrapUnaryHandler converts a standard Unary Method Descriptor into a +// StreamHandler, allowing Unary RPCs to be processed via the same unified +// pipeline as Streaming RPCs. +func (s *Server) wrapUnaryHandler(md *MethodDesc) StreamHandler { + return func(srv any, stream ServerStream) error { + df := func(v any) error { return stream.RecvMsg(v) } + reply, err := md.Handler(srv, stream.Context(), df, s.opts.unaryInt) + if err != nil { + return err + } + return stream.SendMsg(reply) + } +} + +func (s *Server) processRPC(ctx context.Context, stream *transport.ServerStream, info *serviceInfo, sd *StreamDesc, trInfo *traceInfo) (err error) { if channelz.IsOn() { s.incrCallsStarted() } @@ -1615,7 +1317,16 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv } if sh != nil || trInfo != nil || channelz.IsOn() { - // See comment in processUnaryRPC on defers. + // The deferred error handling for tracing, stats handler and channelz are + // combined into one function to reduce stack usage -- a defer takes ~56-64 + // bytes on the stack, so overflowing the stack will require a stack + // re-allocation, which is expensive. + // + // To maintain behavior similar to separate deferred statements, statements + // should be executed in the reverse order. That is, tracing first, stats + // handler second, and channelz last. Note that panics *within* defers will + // lead to different behavior, but that's an acceptable compromise; that + // would be undefined behavior territory anyway. defer func() { if trInfo != nil { ss.mu.Lock() @@ -1689,7 +1400,7 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv ss.decompressorV1 = encoding.GetCompressor(rc) if ss.decompressorV1 == nil { st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) - ss.s.WriteStatus(st) + ss.writeStatus(st) return st.Err() } } @@ -1717,23 +1428,34 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv ss.ctx = newContextWithRPCInfo(ss.ctx, false, ss.codec, ss.compressorV0, ss.compressorV1) - if trInfo != nil { - trInfo.tr.LazyLog(&trInfo.firstLine, false) - } + // Execute the xDS HTTP filter interceptors. var appErr error - var server any - if info != nil { - server = info.serviceImpl + var wrappedStream ServerStream = ss + if s.opts.streamWrapper != nil { + wrappedStream, appErr = s.opts.streamWrapper(ss) } - if s.opts.streamInt == nil { - appErr = sd.Handler(server, ss) - } else { - info := &StreamServerInfo{ - FullMethod: stream.Method(), - IsClientStream: sd.ClientStreams, - IsServerStream: sd.ServerStreams, + + if appErr == nil { + if trInfo != nil { + trInfo.tr.LazyLog(&trInfo.firstLine, false) + } + var server any + if info != nil { + server = info.serviceImpl + } + if s.opts.streamInt == nil || (!sd.ClientStreams && !sd.ServerStreams) { + // If there is no stream interceptor, or if this is a unary RPC, call + // the handler directly. The wrapped unary handler will call the unary + // interceptor if it exists. + appErr = sd.Handler(server, wrappedStream) + } else { + info := &StreamServerInfo{ + FullMethod: stream.Method(), + IsClientStream: sd.ClientStreams, + IsServerStream: sd.ServerStreams, + } + appErr = s.opts.streamInt(server, wrappedStream, info, sd.Handler) } - appErr = s.opts.streamInt(server, ss, info, sd.Handler) } if appErr != nil { appStatus, ok := status.FromError(appErr) @@ -1750,6 +1472,17 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv ss.mu.Unlock() } if len(ss.binlogs) != 0 { + if !ss.serverHeaderBinlogged { + if h, _ := ss.s.Header(); h.Len() > 0 { + sh := &binarylog.ServerHeader{ + Header: h, + } + ss.serverHeaderBinlogged = true + for _, binlog := range ss.binlogs { + binlog.Log(ctx, sh) + } + } + } st := &binarylog.ServerTrailer{ Trailer: ss.s.Trailer(), Err: appErr, @@ -1758,8 +1491,9 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv binlog.Log(ctx, st) } } - ss.s.WriteStatus(appStatus) - // TODO: Should we log an error from WriteStatus here and below? + if err := ss.writeStatus(appStatus); err != nil { + channelz.Warningf(logger, s.channelz, "grpc: Server.processRPC failed to write status: %v", err) + } return appErr } if trInfo != nil { @@ -1776,7 +1510,10 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv binlog.Log(ctx, st) } } - return ss.s.WriteStatus(statusOK) + if err := ss.writeStatus(statusOK); err != nil { + channelz.Warningf(logger, s.channelz, "grpc: Server.processRPC failed to write status: %v", err) + } + return err } func (s *Server) handleMalformedMethodName(stream *transport.ServerStream, ti *traceInfo) { @@ -1854,18 +1591,14 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Ser srv, knownService := s.services[service] if knownService { - if md, ok := srv.methods[method]; ok { - s.processUnaryRPC(ctx, stream, srv, md, ti) - return - } if sd, ok := srv.streams[method]; ok { - s.processStreamingRPC(ctx, stream, srv, sd, ti) + s.processRPC(ctx, stream, srv, sd, ti) return } } // Unknown service, or known server unknown method. if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil { - s.processStreamingRPC(ctx, stream, nil, unknownDesc, ti) + s.processRPC(ctx, stream, nil, unknownDesc, ti) return } var errDesc string @@ -2069,9 +1802,6 @@ func (s *Server) isRegisteredMethod(serviceMethod string) bool { method := serviceMethod[pos+1:] srv, knownService := s.services[service] if knownService { - if _, ok := srv.methods[method]; ok { - return true - } if _, ok := srv.streams[method]; ok { return true } diff --git a/vendor/google.golang.org/grpc/stats/opentelemetry/client_metrics.go b/vendor/google.golang.org/grpc/stats/opentelemetry/client_metrics.go index fb07704ffd..3ec48e0e3b 100644 --- a/vendor/google.golang.org/grpc/stats/opentelemetry/client_metrics.go +++ b/vendor/google.golang.org/grpc/stats/opentelemetry/client_metrics.go @@ -160,28 +160,14 @@ func (h *clientMetricsHandler) HandleConn(context.Context, stats.ConnStats) {} // TagRPC implements per RPC attempt context management for metrics. func (h *clientMetricsHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { - ctx, ri := getOrCreateClientRPCInfo(ctx) - ai := ri.ai - if ai.xdsLabels == nil { - ai.xdsLabels = map[string]string{ - // The defaults for all the per call labels from a plugin that - // executes on the callpath that this OpenTelemetry component - // currently supports. - "grpc.lb.locality": "", - "grpc.lb.backend_service": "", - } - } - + ctx, ri := getOrCreateClientRPCInfo(ctx, info) // Numerous stats handlers can be used for the same channel. This callback // ensures that all label updates are propagated to the rpc attempt info across // derived contexts. ctx = istats.RegisterTelemetryLabelCallback(ctx, func(labels map[string]string) { - maps.Copy(ai.xdsLabels, labels) + maps.Copy(ri.ai.xdsLabels, labels) }) - ai.startTime = time.Now() - ai.method = removeLeadingSlash(info.FullMethodName) - return ctx } diff --git a/vendor/google.golang.org/grpc/stats/opentelemetry/client_tracing.go b/vendor/google.golang.org/grpc/stats/opentelemetry/client_tracing.go index cffdb96976..64cda94411 100644 --- a/vendor/google.golang.org/grpc/stats/opentelemetry/client_tracing.go +++ b/vendor/google.golang.org/grpc/stats/opentelemetry/client_tracing.go @@ -124,7 +124,7 @@ func (h *clientTracingHandler) HandleConn(context.Context, stats.ConnStats) {} // TagRPC implements per RPC attempt context management for traces. func (h *clientTracingHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { - ctx, ri := getOrCreateClientRPCInfo(ctx) + ctx, ri := getOrCreateClientRPCInfo(ctx, info) ci := getCallInfo(ctx) if ci == nil { logger.Error("context passed into client side stats handler (TagRPC) has no call info") diff --git a/vendor/google.golang.org/grpc/stats/opentelemetry/opentelemetry.go b/vendor/google.golang.org/grpc/stats/opentelemetry/opentelemetry.go index b9b0c7af57..878e4eb9ec 100644 --- a/vendor/google.golang.org/grpc/stats/opentelemetry/opentelemetry.go +++ b/vendor/google.golang.org/grpc/stats/opentelemetry/opentelemetry.go @@ -216,21 +216,55 @@ func serverRPCInfo(ctx context.Context) *rpcInfo { return ri } -func getOrCreateClientRPCInfo(ctx context.Context) (context.Context, *rpcInfo) { +func getOrCreateClientRPCInfo(ctx context.Context, info *stats.RPCTagInfo) (context.Context, *rpcInfo) { ri := clientRPCInfo(ctx) if ri != nil { return ctx, ri } - ri = &rpcInfo{ai: &attemptInfo{}} + ri = &rpcInfo{ + ai: &attemptInfo{ + startTime: time.Now(), + method: removeLeadingSlash(info.FullMethodName), + xdsLabels: map[string]string{ + // The defaults for all the per call labels from a plugin that + // executes on the callpath that this OpenTelemetry component + // currently supports. + "grpc.lb.locality": "", + "grpc.lb.backend_service": "", + }, + }, + } return context.WithValue(ctx, clientRPCInfoKey{}, ri), ri } -func getOrCreateServerRPCInfo(ctx context.Context) (context.Context, *rpcInfo) { +func getOrCreateServerRPCInfo(ctx context.Context, info *stats.RPCTagInfo, options MetricsOptions) (context.Context, *rpcInfo) { ri := serverRPCInfo(ctx) if ri != nil { return ctx, ri } - ri = &rpcInfo{ai: &attemptInfo{}} + method := info.FullMethodName + if options.MethodAttributeFilter != nil { + if !options.MethodAttributeFilter(method) { + method = "other" + } + } + server := internal.ServerFromContext.(func(context.Context) *grpc.Server)(ctx) + if server == nil { // Shouldn't happen, defensive programming. + logger.Error("ctx passed into server side stats handler has no grpc server ref") + method = "other" + } else { + isRegisteredMethod := internal.IsRegisteredMethod.(func(*grpc.Server, string) bool) + if !isRegisteredMethod(server, method) { + method = "other" + } + } + + ri = &rpcInfo{ + ai: &attemptInfo{ + startTime: time.Now(), + method: removeLeadingSlash(method), + }, + } return context.WithValue(ctx, serverRPCInfoKey{}, ri), ri } diff --git a/vendor/google.golang.org/grpc/stats/opentelemetry/server_metrics.go b/vendor/google.golang.org/grpc/stats/opentelemetry/server_metrics.go index 4db7978034..7ec0e4b2d1 100644 --- a/vendor/google.golang.org/grpc/stats/opentelemetry/server_metrics.go +++ b/vendor/google.golang.org/grpc/stats/opentelemetry/server_metrics.go @@ -26,7 +26,6 @@ import ( "google.golang.org/grpc" estats "google.golang.org/grpc/experimental/stats" - "google.golang.org/grpc/internal" "google.golang.org/grpc/metadata" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" @@ -180,27 +179,7 @@ func (h *serverMetricsHandler) HandleConn(context.Context, stats.ConnStats) {} // TagRPC implements per RPC context management for metrics. func (h *serverMetricsHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { - method := info.FullMethodName - if h.options.MetricsOptions.MethodAttributeFilter != nil { - if !h.options.MetricsOptions.MethodAttributeFilter(method) { - method = "other" - } - } - server := internal.ServerFromContext.(func(context.Context) *grpc.Server)(ctx) - if server == nil { // Shouldn't happen, defensive programming. - logger.Error("ctx passed into server side stats handler has no grpc server ref") - method = "other" - } else { - isRegisteredMethod := internal.IsRegisteredMethod.(func(*grpc.Server, string) bool) - if !isRegisteredMethod(server, method) { - method = "other" - } - } - ctx, ri := getOrCreateServerRPCInfo(ctx) - ai := ri.ai - ai.startTime = time.Now() - ai.method = removeLeadingSlash(method) - + ctx, _ = getOrCreateServerRPCInfo(ctx, info, h.options.MetricsOptions) return ctx } diff --git a/vendor/google.golang.org/grpc/stats/opentelemetry/server_tracing.go b/vendor/google.golang.org/grpc/stats/opentelemetry/server_tracing.go index c267ba1ed0..952e787b20 100644 --- a/vendor/google.golang.org/grpc/stats/opentelemetry/server_tracing.go +++ b/vendor/google.golang.org/grpc/stats/opentelemetry/server_tracing.go @@ -39,8 +39,8 @@ func (h *serverTracingHandler) initializeTraces() { } // TagRPC implements per RPC attempt context management for traces. -func (h *serverTracingHandler) TagRPC(ctx context.Context, _ *stats.RPCTagInfo) context.Context { - ctx, ri := getOrCreateServerRPCInfo(ctx) +func (h *serverTracingHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { + ctx, ri := getOrCreateServerRPCInfo(ctx, info, h.options.MetricsOptions) ctx, _ = h.traceTagRPC(ctx, ri.ai) return ctx } diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index 51aff85dfb..52e59f2c5e 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -28,6 +28,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "google.golang.org/grpc/balancer" @@ -148,6 +149,94 @@ type ClientStream interface { RecvMsg(m any) error } +// clientStreamWrapper wraps a ClientStream and handles SendMsg, CloseSend, and +// RecvMsg parities based on the nature of stream. +type clientStreamWrapper struct { + ClientStream + desc *StreamDesc + closeSendCalled atomic.Bool +} + +// CloseSend closes the send direction of the stream. The implementation ensures +// that CloseSend is only called once on the underlying ClientStream, even if +// CloseSend is called multiple times on the wrapper. +func (w *clientStreamWrapper) CloseSend() error { + if w.closeSendCalled.Swap(true) { + return nil + } + return w.ClientStream.CloseSend() +} + +// SendMsg sends message m across the stream. For RPCs where client can call +// SendMsg only once, i.e. only server-streaming RPCs, it converts io.EOF to nil +// and immediately calls CloseSend to trigger any interceptor hooks. +func (w *clientStreamWrapper) SendMsg(m any) error { + err := w.ClientStream.SendMsg(m) + // If the RPC is a client-streaming RPC, the client can send multiple + // messages. In this case, the client should handle any type of + // error,including io.EOF and call CloseSend once it is done sending messages. + if w.desc.ClientStreams { + return err + } + + if err == io.EOF { + // For non-client-streaming RPCs, we return nil instead of EOF on error + // because the generated code requires it. finish is not called; RecvMsg() + // will call it with the stream's status independently. + return nil + } + if err != nil { + return err + } + // In some scenarios (e.g., xDS), the same interceptors process both unary and + // streaming RPCs, relying on CloseSend to signal that no more messages are on + // the way. Although protobuf-generated stubs already invoke CloseSend for + // server-streaming RPCs, it is explicitly called here to ensure downstream + // interceptors are also notified when callers interact with the ClientStream + // API directly. + if err := w.CloseSend(); err != nil && err != io.EOF { + return err + } + return nil + +} + +// RecvMsg receives message m from the stream. For RPCs that call RecvMsg only +// once i.e. only client streaming RPCs, it calls the underlying RecvMsg a +// second time after receiving the first message to get the trailers. +func (w *clientStreamWrapper) RecvMsg(m any) error { + err := w.ClientStream.RecvMsg(m) + if err != nil { + return err + } + if w.desc.ServerStreams { + return nil + } + // Call RecvMsg again for non-server streaming RPCs to get the trailers and + // ensure RPC has completed successfully. + err = w.ClientStream.RecvMsg(m) + if err == io.EOF { + return nil + } + if err == nil { + return status.Error(codes.Internal, "cardinality violation: expected for non server-streaming RPCs, but received another message") + } + return err +} + +// defaultStreamInterceptor is a StreamClientInterceptor which wraps the +// ClientStream and is always invoked as the first interceptor. It consolidates +// behavior for different RPC types at the level closest to the application, +// which simplifies the underlying stream implementation and other interceptors +// by avoiding duplicate or scattered handling. +func defaultStreamInterceptor(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) { + cs, err := streamer(ctx, desc, cc, method, opts...) + if err != nil { + return nil, err + } + return &clientStreamWrapper{ClientStream: cs, desc: desc}, nil +} + // NewStream creates a new Stream for the client side. This is typically // called by generated code. ctx is used for the lifetime of the stream. // @@ -253,14 +342,11 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth mc := &emptyMethodConfig var onCommit func() - newStream := func(ctx context.Context, filterOpts ...CallOption) (ClientStream, error) { - if filterOpts != nil { - opts = combine(opts, filterOpts) - } + newStream := func(ctx context.Context, opts ...CallOption) (ClientStream, error) { return newClientStreamWithParams(ctx, desc, cc, method, mc, onCommit, nameResolutionDelayed, opts...) } - rpcInfo := iresolver.RPCInfo{Context: ctx, Method: method} + rpcInfo := iresolver.RPCInfo{Context: ctx, Method: method, Authority: cc.authority} rpcConfig, err := cc.safeConfigSelector.SelectConfig(rpcInfo) if err != nil { if st, ok := status.FromError(err); ok { @@ -278,13 +364,23 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth ctx = rpcConfig.Context } mc = &rpcConfig.MethodConfig - onCommit = rpcConfig.OnCommitted + + if rpcConfig.OnCommitted != nil { + onCommit = rpcConfig.OnCommitted + // Register an OnFinish CallOption with the OnCommitted callback to + // ensure it is invoked on stream termination, even if the stream + // fails early before committing. Implementations of OnCommitted are + // expected to be idempotent (e.g., guarded by sync.Once), since both + // onCommit and OnFinish may run for a single RPC. + opts = append(opts, OnFinish(func(error) { rpcConfig.OnCommitted() })) + } + if rpcConfig.Interceptor != nil { rpcInfo.Context = nil ns := newStream if interceptor, ok := rpcConfig.Interceptor.(clientInterceptor); ok { - newStream = func(ctx context.Context, filterOpts ...CallOption) (ClientStream, error) { - cs, err := interceptor.NewStream(ctx, rpcInfo, ns, filterOpts...) + newStream = func(ctx context.Context, opts ...CallOption) (ClientStream, error) { + cs, err := interceptor.NewStream(ctx, rpcInfo, ns, opts...) if err != nil { return nil, toRPCErr(err) } @@ -296,7 +392,7 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth } } - return newStream(ctx) + return newStream(ctx, opts...) } func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, mc *serviceconfig.MethodConfig, onCommit func(), nameResolutionDelayed bool, opts ...CallOption) (_ ClientStream, err error) { @@ -543,6 +639,9 @@ func (a *csAttempt) newStream() error { // maintained in it are local to the attempt. When the attempt has to be // retried, a new instance of csAttempt will be created. if a.pickResult.Metadata != nil { + if err := imetadata.Validate(a.pickResult.Metadata); err != nil { + return status.Error(codes.Internal, err.Error()) + } // We currently do not have a function it the metadata package which // merges given metadata with existing metadata in a context. Existing // function `AppendToOutgoingContext()` takes a variadic argument of key @@ -1044,8 +1143,8 @@ func (cs *clientStream) RecvMsg(m any) error { binlog.Log(cs.ctx, sm) } } - if err != nil || !cs.desc.ServerStreams { - // err != nil or non-server-streaming indicates end of stream. + if err != nil { + // err != nil indicates end of stream. cs.finish(err) } return err @@ -1093,7 +1192,8 @@ func (cs *clientStream) finish(err error) { } cs.finished = true cs.commitAttemptLocked() - if cs.attempt != nil { + attemptCreated := cs.attempt != nil + if attemptCreated { cs.attempt.finish(err) // after functions all rely upon having a stream. if cs.attempt.transportStream != nil { @@ -1131,7 +1231,13 @@ func (cs *clientStream) finish(err error) { if err == nil { cs.retryThrottler.successfulRPC() } - endOfClientStream(cs.cc, err, cs.opts...) + // If no attempt was ever created, stream creation has failed, and the + // cleanup is left to newClientStream, whose deferred cleanup invokes + // endOfClientStream if the call fails. Invoking it here as well would + // run the cleanup twice for the same call. + if attemptCreated { + endOfClientStream(cs.cc, err, cs.opts...) + } cs.cancel() } @@ -1145,12 +1251,6 @@ func (a *csAttempt) sendMsg(m any, hdr []byte, payld mem.BufferSlice, dataLength a.mu.Unlock() } if err := a.transportStream.Write(hdr, payld, &transport.WriteOptions{Last: !cs.desc.ClientStreams}); err != nil { - if !cs.desc.ClientStreams { - // For non-client-streaming RPCs, we return nil instead of EOF on error - // because the generated code requires it. finish is not called; RecvMsg() - // will call it with the stream's status independently. - return nil - } return io.EOF } if a.statsHandler != nil { @@ -1218,18 +1318,7 @@ func (a *csAttempt) recvMsg(m any, payInfo *payloadInfo) (err error) { Length: payInfo.uncompressedBytes.Len(), }) } - if cs.desc.ServerStreams { - // Subsequent messages should be received by subsequent RecvMsg calls. - return nil - } - // Special handling for non-server-stream rpcs. - // This recv expects EOF or errors, so we don't collect inPayload. - if err := recv(&a.parser, cs.codec, a.transportStream, a.decompressorV0, m, *cs.callInfo.maxReceiveMessageSize, nil, a.decompressorV1, false); err == io.EOF { - return a.transportStream.Status().Err() // non-server streaming Recv returns nil on success - } else if err != nil { - return toRPCErr(err) - } - return status.Error(codes.Internal, "cardinality violation: expected for non server-streaming RPCs, but received another message") + return nil } func (a *csAttempt) finish(err error) { @@ -1399,7 +1488,7 @@ func newNonRetryClientStream(ctx context.Context, desc *StreamDesc, method strin } }() } - return as, nil + return &clientStreamWrapper{ClientStream: as, desc: desc}, nil } type addrConnStream struct { @@ -1497,12 +1586,6 @@ func (as *addrConnStream) SendMsg(m any) (err error) { } if err := as.transportStream.Write(hdr, payload, &transport.WriteOptions{Last: !as.desc.ClientStreams}); err != nil { - if !as.desc.ClientStreams { - // For non-client-streaming RPCs, we return nil instead of EOF on error - // because the generated code requires it. finish is not called; RecvMsg() - // will call it with the stream's status independently. - return nil - } return io.EOF } @@ -1511,8 +1594,8 @@ func (as *addrConnStream) SendMsg(m any) (err error) { func (as *addrConnStream) RecvMsg(m any) (err error) { defer func() { - if err != nil || !as.desc.ServerStreams { - // err != nil or non-server-streaming indicates end of stream. + if err != nil { + // err != nil indicates end of stream. as.finish(err) } }() @@ -1551,20 +1634,7 @@ func (as *addrConnStream) RecvMsg(m any) (err error) { return toRPCErr(err) } as.receivedFirstMsg = true - - if as.desc.ServerStreams { - // Subsequent messages should be received by subsequent RecvMsg calls. - return nil - } - - // Special handling for non-server-stream rpcs. - // This recv expects EOF or errors, so we don't collect inPayload. - if err := recv(&as.parser, as.codec, as.transportStream, as.decompressorV0, m, *as.callInfo.maxReceiveMessageSize, nil, as.decompressorV1, false); err == io.EOF { - return as.transportStream.Status().Err() // non-server streaming Recv returns nil on success - } else if err != nil { - return toRPCErr(err) - } - return status.Error(codes.Internal, "cardinality violation: expected for non server-streaming RPCs, but received another message") + return nil } func (as *addrConnStream) finish(err error) { @@ -1675,6 +1745,8 @@ type serverStream struct { // synchronized. serverHeaderBinlogged bool + statusWritten atomic.Bool // True if status has been written to the transport. + mu sync.Mutex // protects trInfo.tr after the service handler runs. } @@ -1723,6 +1795,16 @@ func (ss *serverStream) SetTrailer(md metadata.MD) { ss.s.SetTrailer(md) } +// writeStatus sends the status of a stream to the client. It uses an atomic +// CAS to guarantee that the status is written to the transport exactly once, +// even if called concurrently. +func (ss *serverStream) writeStatus(st *status.Status) error { + if !ss.statusWritten.CompareAndSwap(false, true) { + return nil + } + return ss.s.WriteStatus(st) +} + func (ss *serverStream) SendMsg(m any) (err error) { defer func() { if ss.trInfo != nil { @@ -1739,7 +1821,7 @@ func (ss *serverStream) SendMsg(m any) (err error) { } if err != nil && err != io.EOF { st, _ := status.FromError(toRPCErr(err)) - ss.s.WriteStatus(st) + ss.writeStatus(st) // Non-user specified status was sent out. This should be an error // case (as a server side Cancel maybe). // @@ -1822,7 +1904,7 @@ func (ss *serverStream) RecvMsg(m any) (err error) { } if err != nil && err != io.EOF { st, _ := status.FromError(toRPCErr(err)) - ss.s.WriteStatus(st) + ss.writeStatus(st) // Non-user specified status was sent out. This should be an error // case (as a server side Cancel maybe). // diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go index 835dc07fdc..75f8ef50d4 100644 --- a/vendor/google.golang.org/grpc/version.go +++ b/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.83.2" +const Version = "1.84.0" diff --git a/vendor/google.golang.org/grpc/xds/server.go b/vendor/google.golang.org/grpc/xds/server.go index e48f809d02..f820062f61 100644 --- a/vendor/google.golang.org/grpc/xds/server.go +++ b/vendor/google.golang.org/grpc/xds/server.go @@ -19,7 +19,6 @@ package xds import ( - "context" "errors" "fmt" "net" @@ -73,11 +72,16 @@ type GRPCServer struct { // The underlying gRPC server has no service registered and has not started to // accept requests yet. func NewGRPCServer(opts ...grpc.ServerOption) (*GRPCServer, error) { - newOpts := []grpc.ServerOption{ - grpc.ChainUnaryInterceptor(xdsUnaryInterceptor), - grpc.ChainStreamInterceptor(xdsStreamInterceptor), - } - newOpts = append(newOpts, opts...) + // xdsFilterWrapper is a callback passed to the underlying gRPC server. + // It adapts the generic stream parameter and delegates to RouteAndProcess + // to execute xDS HTTP filter interceptors for each incoming RPC. + xDSFilterWrapper := func(ss grpc.ServerStream) (grpc.ServerStream, error) { + return server.RouteAndProcess(ss) + } + // Construct a grpc.ServerOption that registers xDSFilterWrapper on + // the server. + xDSFilterWrapperOption := internal.XDSFilterWrapperOption.(func(func(grpc.ServerStream) (grpc.ServerStream, error)) grpc.ServerOption) + newOpts := append([]grpc.ServerOption{xDSFilterWrapperOption(xDSFilterWrapper)}, opts...) s := &GRPCServer{ gs: newGRPCServer(newOpts...), quit: grpcsync.NewEvent(), @@ -229,21 +233,3 @@ func (s *GRPCServer) GracefulStop() { s.xdsClientClose() } } - -// xdsUnaryInterceptor is the unary interceptor added to the gRPC server to -// perform any xDS specific functionality on unary RPCs. -func xdsUnaryInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { - if err := server.RouteAndProcess(ctx); err != nil { - return nil, err - } - return handler(ctx, req) -} - -// xdsStreamInterceptor is the stream interceptor added to the gRPC server to -// perform any xDS specific functionality on streaming RPCs. -func xdsStreamInterceptor(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - if err := server.RouteAndProcess(ss.Context()); err != nil { - return err - } - return handler(srv, ss) -} diff --git a/vendor/google.golang.org/grpc/xds/xds.go b/vendor/google.golang.org/grpc/xds/xds.go index c6a1f25f7a..182c32dfed 100644 --- a/vendor/google.golang.org/grpc/xds/xds.go +++ b/vendor/google.golang.org/grpc/xds/xds.go @@ -40,6 +40,7 @@ import ( _ "google.golang.org/grpc/credentials/tls/certprovider/pemfile" // Register the file watcher certificate provider plugin. _ "google.golang.org/grpc/internal/xds/balancer" // Register the balancers. _ "google.golang.org/grpc/internal/xds/clusterspecifier/rls" // Register the RLS cluster specifier plugin. Note that this does not register the RLS LB policy. + _ "google.golang.org/grpc/internal/xds/httpfilter/extproc" // Register the extproc filter. _ "google.golang.org/grpc/internal/xds/httpfilter/fault" // Register the fault injection filter. _ "google.golang.org/grpc/internal/xds/httpfilter/rbac" // Register the RBAC filter. _ "google.golang.org/grpc/internal/xds/httpfilter/router" // Register the router filter. diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types.go index b3a8ce7ef4..c0e968886a 100644 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types.go +++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types.go @@ -402,7 +402,7 @@ const CustomResourceCleanupFinalizer = "customresourcecleanup.apiextensions.k8s. // CustomResourceDefinition represents a resource that should be exposed on the API server. Its name MUST be in the format // <.spec.name>.<.spec.group>. type CustomResourceDefinition struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -420,7 +420,7 @@ type CustomResourceDefinition struct { // CustomResourceDefinitionList is a list of CustomResourceDefinition objects. type CustomResourceDefinitionList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -489,7 +489,7 @@ type CustomResourceSubresourceScale struct { // ConversionReview describes a conversion request/response. type ConversionReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // request describes the attributes for the conversion request. // +optional Request *ConversionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"` diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/zz_generated.conversion.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/zz_generated.conversion.go index 4d02c8df03..29639388da 100644 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/zz_generated.conversion.go +++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/zz_generated.conversion.go @@ -276,12 +276,7 @@ func RegisterConversions(s *runtime.Scheme) error { } func autoConvert_v1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceColumnDefinition(in *CustomResourceColumnDefinition, out *apiextensions.CustomResourceColumnDefinition, s conversion.Scope) error { - out.Name = in.Name - out.Type = in.Type - out.Format = in.Format - out.Description = in.Description - out.Priority = in.Priority - out.JSONPath = in.JSONPath + *out = *(*apiextensions.CustomResourceColumnDefinition)(unsafe.Pointer(in)) return nil } @@ -291,12 +286,7 @@ func Convert_v1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceCo } func autoConvert_apiextensions_CustomResourceColumnDefinition_To_v1_CustomResourceColumnDefinition(in *apiextensions.CustomResourceColumnDefinition, out *CustomResourceColumnDefinition, s conversion.Scope) error { - out.Name = in.Name - out.Type = in.Type - out.Format = in.Format - out.Description = in.Description - out.Priority = in.Priority - out.JSONPath = in.JSONPath + *out = *(*CustomResourceColumnDefinition)(unsafe.Pointer(in)) return nil } @@ -351,12 +341,7 @@ func Convert_apiextensions_CustomResourceDefinition_To_v1_CustomResourceDefiniti } func autoConvert_v1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourceDefinitionCondition(in *CustomResourceDefinitionCondition, out *apiextensions.CustomResourceDefinitionCondition, s conversion.Scope) error { - out.Type = apiextensions.CustomResourceDefinitionConditionType(in.Type) - out.Status = apiextensions.ConditionStatus(in.Status) - out.LastTransitionTime = in.LastTransitionTime - out.Reason = in.Reason - out.Message = in.Message - out.ObservedGeneration = in.ObservedGeneration + *out = *(*apiextensions.CustomResourceDefinitionCondition)(unsafe.Pointer(in)) return nil } @@ -366,12 +351,7 @@ func Convert_v1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourc } func autoConvert_apiextensions_CustomResourceDefinitionCondition_To_v1_CustomResourceDefinitionCondition(in *apiextensions.CustomResourceDefinitionCondition, out *CustomResourceDefinitionCondition, s conversion.Scope) error { - out.Type = CustomResourceDefinitionConditionType(in.Type) - out.Status = ConditionStatus(in.Status) - out.LastTransitionTime = in.LastTransitionTime - out.Reason = in.Reason - out.Message = in.Message - out.ObservedGeneration = in.ObservedGeneration + *out = *(*CustomResourceDefinitionCondition)(unsafe.Pointer(in)) return nil } @@ -423,12 +403,7 @@ func Convert_apiextensions_CustomResourceDefinitionList_To_v1_CustomResourceDefi } func autoConvert_v1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(in *CustomResourceDefinitionNames, out *apiextensions.CustomResourceDefinitionNames, s conversion.Scope) error { - out.Plural = in.Plural - out.Singular = in.Singular - out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames)) - out.Kind = in.Kind - out.ListKind = in.ListKind - out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories)) + *out = *(*apiextensions.CustomResourceDefinitionNames)(unsafe.Pointer(in)) return nil } @@ -438,12 +413,7 @@ func Convert_v1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDef } func autoConvert_apiextensions_CustomResourceDefinitionNames_To_v1_CustomResourceDefinitionNames(in *apiextensions.CustomResourceDefinitionNames, out *CustomResourceDefinitionNames, s conversion.Scope) error { - out.Plural = in.Plural - out.Singular = in.Singular - out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames)) - out.Kind = in.Kind - out.ListKind = in.ListKind - out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories)) + *out = *(*CustomResourceDefinitionNames)(unsafe.Pointer(in)) return nil } @@ -522,12 +492,7 @@ func autoConvert_apiextensions_CustomResourceDefinitionSpec_To_v1_CustomResource } func autoConvert_v1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus(in *CustomResourceDefinitionStatus, out *apiextensions.CustomResourceDefinitionStatus, s conversion.Scope) error { - out.Conditions = *(*[]apiextensions.CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions)) - if err := Convert_v1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil { - return err - } - out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions)) - out.ObservedGeneration = in.ObservedGeneration + *out = *(*apiextensions.CustomResourceDefinitionStatus)(unsafe.Pointer(in)) return nil } @@ -537,12 +502,7 @@ func Convert_v1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDe } func autoConvert_apiextensions_CustomResourceDefinitionStatus_To_v1_CustomResourceDefinitionStatus(in *apiextensions.CustomResourceDefinitionStatus, out *CustomResourceDefinitionStatus, s conversion.Scope) error { - out.Conditions = *(*[]CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions)) - if err := Convert_apiextensions_CustomResourceDefinitionNames_To_v1_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil { - return err - } - out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions)) - out.ObservedGeneration = in.ObservedGeneration + *out = *(*CustomResourceDefinitionStatus)(unsafe.Pointer(in)) return nil } @@ -604,9 +564,7 @@ func Convert_apiextensions_CustomResourceDefinitionVersion_To_v1_CustomResourceD } func autoConvert_v1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale(in *CustomResourceSubresourceScale, out *apiextensions.CustomResourceSubresourceScale, s conversion.Scope) error { - out.SpecReplicasPath = in.SpecReplicasPath - out.StatusReplicasPath = in.StatusReplicasPath - out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath)) + *out = *(*apiextensions.CustomResourceSubresourceScale)(unsafe.Pointer(in)) return nil } @@ -616,9 +574,7 @@ func Convert_v1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSu } func autoConvert_apiextensions_CustomResourceSubresourceScale_To_v1_CustomResourceSubresourceScale(in *apiextensions.CustomResourceSubresourceScale, out *CustomResourceSubresourceScale, s conversion.Scope) error { - out.SpecReplicasPath = in.SpecReplicasPath - out.StatusReplicasPath = in.StatusReplicasPath - out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath)) + *out = *(*CustomResourceSubresourceScale)(unsafe.Pointer(in)) return nil } @@ -628,6 +584,7 @@ func Convert_apiextensions_CustomResourceSubresourceScale_To_v1_CustomResourceSu } func autoConvert_v1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus(in *CustomResourceSubresourceStatus, out *apiextensions.CustomResourceSubresourceStatus, s conversion.Scope) error { + *out = *(*apiextensions.CustomResourceSubresourceStatus)(unsafe.Pointer(in)) return nil } @@ -637,6 +594,7 @@ func Convert_v1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceS } func autoConvert_apiextensions_CustomResourceSubresourceStatus_To_v1_CustomResourceSubresourceStatus(in *apiextensions.CustomResourceSubresourceStatus, out *CustomResourceSubresourceStatus, s conversion.Scope) error { + *out = *(*CustomResourceSubresourceStatus)(unsafe.Pointer(in)) return nil } @@ -646,8 +604,7 @@ func Convert_apiextensions_CustomResourceSubresourceStatus_To_v1_CustomResourceS } func autoConvert_v1_CustomResourceSubresources_To_apiextensions_CustomResourceSubresources(in *CustomResourceSubresources, out *apiextensions.CustomResourceSubresources, s conversion.Scope) error { - out.Status = (*apiextensions.CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status)) - out.Scale = (*apiextensions.CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale)) + *out = *(*apiextensions.CustomResourceSubresources)(unsafe.Pointer(in)) return nil } @@ -657,8 +614,7 @@ func Convert_v1_CustomResourceSubresources_To_apiextensions_CustomResourceSubres } func autoConvert_apiextensions_CustomResourceSubresources_To_v1_CustomResourceSubresources(in *apiextensions.CustomResourceSubresources, out *CustomResourceSubresources, s conversion.Scope) error { - out.Status = (*CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status)) - out.Scale = (*CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale)) + *out = *(*CustomResourceSubresources)(unsafe.Pointer(in)) return nil } @@ -704,8 +660,7 @@ func Convert_apiextensions_CustomResourceValidation_To_v1_CustomResourceValidati } func autoConvert_v1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(in *ExternalDocumentation, out *apiextensions.ExternalDocumentation, s conversion.Scope) error { - out.Description = in.Description - out.URL = in.URL + *out = *(*apiextensions.ExternalDocumentation)(unsafe.Pointer(in)) return nil } @@ -715,8 +670,7 @@ func Convert_v1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(in } func autoConvert_apiextensions_ExternalDocumentation_To_v1_ExternalDocumentation(in *apiextensions.ExternalDocumentation, out *ExternalDocumentation, s conversion.Scope) error { - out.Description = in.Description - out.URL = in.URL + *out = *(*ExternalDocumentation)(unsafe.Pointer(in)) return nil } @@ -1243,7 +1197,7 @@ func Convert_apiextensions_JSONSchemaPropsOrStringArray_To_v1_JSONSchemaPropsOrS } func autoConvert_v1_SelectableField_To_apiextensions_SelectableField(in *SelectableField, out *apiextensions.SelectableField, s conversion.Scope) error { - out.JSONPath = in.JSONPath + *out = *(*apiextensions.SelectableField)(unsafe.Pointer(in)) return nil } @@ -1253,7 +1207,7 @@ func Convert_v1_SelectableField_To_apiextensions_SelectableField(in *SelectableF } func autoConvert_apiextensions_SelectableField_To_v1_SelectableField(in *apiextensions.SelectableField, out *SelectableField, s conversion.Scope) error { - out.JSONPath = in.JSONPath + *out = *(*SelectableField)(unsafe.Pointer(in)) return nil } @@ -1293,12 +1247,7 @@ func Convert_apiextensions_ServiceReference_To_v1_ServiceReference(in *apiextens } func autoConvert_v1_ValidationRule_To_apiextensions_ValidationRule(in *ValidationRule, out *apiextensions.ValidationRule, s conversion.Scope) error { - out.Rule = in.Rule - out.Message = in.Message - out.MessageExpression = in.MessageExpression - out.Reason = (*apiextensions.FieldValueErrorReason)(unsafe.Pointer(in.Reason)) - out.FieldPath = in.FieldPath - out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf)) + *out = *(*apiextensions.ValidationRule)(unsafe.Pointer(in)) return nil } @@ -1308,12 +1257,7 @@ func Convert_v1_ValidationRule_To_apiextensions_ValidationRule(in *ValidationRul } func autoConvert_apiextensions_ValidationRule_To_v1_ValidationRule(in *apiextensions.ValidationRule, out *ValidationRule, s conversion.Scope) error { - out.Rule = in.Rule - out.Message = in.Message - out.MessageExpression = in.MessageExpression - out.Reason = (*FieldValueErrorReason)(unsafe.Pointer(in.Reason)) - out.FieldPath = in.FieldPath - out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf)) + *out = *(*ValidationRule)(unsafe.Pointer(in)) return nil } diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go index fb844903ed..e92c715a7a 100644 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go +++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go @@ -442,7 +442,7 @@ const CustomResourceCleanupFinalizer = "customresourcecleanup.apiextensions.k8s. // <.spec.name>.<.spec.group>. // Deprecated in v1.16, planned for removal in v1.22. Use apiextensions.k8s.io/v1 CustomResourceDefinition instead. type CustomResourceDefinition struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -463,7 +463,7 @@ type CustomResourceDefinition struct { // CustomResourceDefinitionList is a list of CustomResourceDefinition objects. type CustomResourceDefinitionList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -536,7 +536,7 @@ type CustomResourceSubresourceScale struct { // ConversionReview describes a conversion request/response. type ConversionReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // request describes the attributes for the conversion request. // +optional Request *ConversionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"` diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go index 5e388dc69b..85e1836c16 100644 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go +++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go @@ -271,12 +271,7 @@ func RegisterConversions(s *runtime.Scheme) error { } func autoConvert_v1beta1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceColumnDefinition(in *CustomResourceColumnDefinition, out *apiextensions.CustomResourceColumnDefinition, s conversion.Scope) error { - out.Name = in.Name - out.Type = in.Type - out.Format = in.Format - out.Description = in.Description - out.Priority = in.Priority - out.JSONPath = in.JSONPath + *out = *(*apiextensions.CustomResourceColumnDefinition)(unsafe.Pointer(in)) return nil } @@ -286,12 +281,7 @@ func Convert_v1beta1_CustomResourceColumnDefinition_To_apiextensions_CustomResou } func autoConvert_apiextensions_CustomResourceColumnDefinition_To_v1beta1_CustomResourceColumnDefinition(in *apiextensions.CustomResourceColumnDefinition, out *CustomResourceColumnDefinition, s conversion.Scope) error { - out.Name = in.Name - out.Type = in.Type - out.Format = in.Format - out.Description = in.Description - out.Priority = in.Priority - out.JSONPath = in.JSONPath + *out = *(*CustomResourceColumnDefinition)(unsafe.Pointer(in)) return nil } @@ -373,12 +363,7 @@ func Convert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDef } func autoConvert_v1beta1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourceDefinitionCondition(in *CustomResourceDefinitionCondition, out *apiextensions.CustomResourceDefinitionCondition, s conversion.Scope) error { - out.Type = apiextensions.CustomResourceDefinitionConditionType(in.Type) - out.Status = apiextensions.ConditionStatus(in.Status) - out.LastTransitionTime = in.LastTransitionTime - out.Reason = in.Reason - out.Message = in.Message - out.ObservedGeneration = in.ObservedGeneration + *out = *(*apiextensions.CustomResourceDefinitionCondition)(unsafe.Pointer(in)) return nil } @@ -388,12 +373,7 @@ func Convert_v1beta1_CustomResourceDefinitionCondition_To_apiextensions_CustomRe } func autoConvert_apiextensions_CustomResourceDefinitionCondition_To_v1beta1_CustomResourceDefinitionCondition(in *apiextensions.CustomResourceDefinitionCondition, out *CustomResourceDefinitionCondition, s conversion.Scope) error { - out.Type = CustomResourceDefinitionConditionType(in.Type) - out.Status = ConditionStatus(in.Status) - out.LastTransitionTime = in.LastTransitionTime - out.Reason = in.Reason - out.Message = in.Message - out.ObservedGeneration = in.ObservedGeneration + *out = *(*CustomResourceDefinitionCondition)(unsafe.Pointer(in)) return nil } @@ -445,12 +425,7 @@ func Convert_apiextensions_CustomResourceDefinitionList_To_v1beta1_CustomResourc } func autoConvert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(in *CustomResourceDefinitionNames, out *apiextensions.CustomResourceDefinitionNames, s conversion.Scope) error { - out.Plural = in.Plural - out.Singular = in.Singular - out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames)) - out.Kind = in.Kind - out.ListKind = in.ListKind - out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories)) + *out = *(*apiextensions.CustomResourceDefinitionNames)(unsafe.Pointer(in)) return nil } @@ -460,12 +435,7 @@ func Convert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResour } func autoConvert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(in *apiextensions.CustomResourceDefinitionNames, out *CustomResourceDefinitionNames, s conversion.Scope) error { - out.Plural = in.Plural - out.Singular = in.Singular - out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames)) - out.Kind = in.Kind - out.ListKind = in.ListKind - out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories)) + *out = *(*CustomResourceDefinitionNames)(unsafe.Pointer(in)) return nil } @@ -571,12 +541,7 @@ func Convert_apiextensions_CustomResourceDefinitionSpec_To_v1beta1_CustomResourc } func autoConvert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus(in *CustomResourceDefinitionStatus, out *apiextensions.CustomResourceDefinitionStatus, s conversion.Scope) error { - out.Conditions = *(*[]apiextensions.CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions)) - if err := Convert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil { - return err - } - out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions)) - out.ObservedGeneration = in.ObservedGeneration + *out = *(*apiextensions.CustomResourceDefinitionStatus)(unsafe.Pointer(in)) return nil } @@ -586,12 +551,7 @@ func Convert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResou } func autoConvert_apiextensions_CustomResourceDefinitionStatus_To_v1beta1_CustomResourceDefinitionStatus(in *apiextensions.CustomResourceDefinitionStatus, out *CustomResourceDefinitionStatus, s conversion.Scope) error { - out.Conditions = *(*[]CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions)) - if err := Convert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil { - return err - } - out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions)) - out.ObservedGeneration = in.ObservedGeneration + *out = *(*CustomResourceDefinitionStatus)(unsafe.Pointer(in)) return nil } @@ -653,9 +613,7 @@ func Convert_apiextensions_CustomResourceDefinitionVersion_To_v1beta1_CustomReso } func autoConvert_v1beta1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale(in *CustomResourceSubresourceScale, out *apiextensions.CustomResourceSubresourceScale, s conversion.Scope) error { - out.SpecReplicasPath = in.SpecReplicasPath - out.StatusReplicasPath = in.StatusReplicasPath - out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath)) + *out = *(*apiextensions.CustomResourceSubresourceScale)(unsafe.Pointer(in)) return nil } @@ -665,9 +623,7 @@ func Convert_v1beta1_CustomResourceSubresourceScale_To_apiextensions_CustomResou } func autoConvert_apiextensions_CustomResourceSubresourceScale_To_v1beta1_CustomResourceSubresourceScale(in *apiextensions.CustomResourceSubresourceScale, out *CustomResourceSubresourceScale, s conversion.Scope) error { - out.SpecReplicasPath = in.SpecReplicasPath - out.StatusReplicasPath = in.StatusReplicasPath - out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath)) + *out = *(*CustomResourceSubresourceScale)(unsafe.Pointer(in)) return nil } @@ -677,6 +633,7 @@ func Convert_apiextensions_CustomResourceSubresourceScale_To_v1beta1_CustomResou } func autoConvert_v1beta1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus(in *CustomResourceSubresourceStatus, out *apiextensions.CustomResourceSubresourceStatus, s conversion.Scope) error { + *out = *(*apiextensions.CustomResourceSubresourceStatus)(unsafe.Pointer(in)) return nil } @@ -686,6 +643,7 @@ func Convert_v1beta1_CustomResourceSubresourceStatus_To_apiextensions_CustomReso } func autoConvert_apiextensions_CustomResourceSubresourceStatus_To_v1beta1_CustomResourceSubresourceStatus(in *apiextensions.CustomResourceSubresourceStatus, out *CustomResourceSubresourceStatus, s conversion.Scope) error { + *out = *(*CustomResourceSubresourceStatus)(unsafe.Pointer(in)) return nil } @@ -695,8 +653,7 @@ func Convert_apiextensions_CustomResourceSubresourceStatus_To_v1beta1_CustomReso } func autoConvert_v1beta1_CustomResourceSubresources_To_apiextensions_CustomResourceSubresources(in *CustomResourceSubresources, out *apiextensions.CustomResourceSubresources, s conversion.Scope) error { - out.Status = (*apiextensions.CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status)) - out.Scale = (*apiextensions.CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale)) + *out = *(*apiextensions.CustomResourceSubresources)(unsafe.Pointer(in)) return nil } @@ -706,8 +663,7 @@ func Convert_v1beta1_CustomResourceSubresources_To_apiextensions_CustomResourceS } func autoConvert_apiextensions_CustomResourceSubresources_To_v1beta1_CustomResourceSubresources(in *apiextensions.CustomResourceSubresources, out *CustomResourceSubresources, s conversion.Scope) error { - out.Status = (*CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status)) - out.Scale = (*CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale)) + *out = *(*CustomResourceSubresources)(unsafe.Pointer(in)) return nil } @@ -753,8 +709,7 @@ func Convert_apiextensions_CustomResourceValidation_To_v1beta1_CustomResourceVal } func autoConvert_v1beta1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(in *ExternalDocumentation, out *apiextensions.ExternalDocumentation, s conversion.Scope) error { - out.Description = in.Description - out.URL = in.URL + *out = *(*apiextensions.ExternalDocumentation)(unsafe.Pointer(in)) return nil } @@ -764,8 +719,7 @@ func Convert_v1beta1_ExternalDocumentation_To_apiextensions_ExternalDocumentatio } func autoConvert_apiextensions_ExternalDocumentation_To_v1beta1_ExternalDocumentation(in *apiextensions.ExternalDocumentation, out *ExternalDocumentation, s conversion.Scope) error { - out.Description = in.Description - out.URL = in.URL + *out = *(*ExternalDocumentation)(unsafe.Pointer(in)) return nil } @@ -1292,7 +1246,7 @@ func Convert_apiextensions_JSONSchemaPropsOrStringArray_To_v1beta1_JSONSchemaPro } func autoConvert_v1beta1_SelectableField_To_apiextensions_SelectableField(in *SelectableField, out *apiextensions.SelectableField, s conversion.Scope) error { - out.JSONPath = in.JSONPath + *out = *(*apiextensions.SelectableField)(unsafe.Pointer(in)) return nil } @@ -1302,7 +1256,7 @@ func Convert_v1beta1_SelectableField_To_apiextensions_SelectableField(in *Select } func autoConvert_apiextensions_SelectableField_To_v1beta1_SelectableField(in *apiextensions.SelectableField, out *SelectableField, s conversion.Scope) error { - out.JSONPath = in.JSONPath + *out = *(*SelectableField)(unsafe.Pointer(in)) return nil } @@ -1342,12 +1296,7 @@ func Convert_apiextensions_ServiceReference_To_v1beta1_ServiceReference(in *apie } func autoConvert_v1beta1_ValidationRule_To_apiextensions_ValidationRule(in *ValidationRule, out *apiextensions.ValidationRule, s conversion.Scope) error { - out.Rule = in.Rule - out.Message = in.Message - out.MessageExpression = in.MessageExpression - out.Reason = (*apiextensions.FieldValueErrorReason)(unsafe.Pointer(in.Reason)) - out.FieldPath = in.FieldPath - out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf)) + *out = *(*apiextensions.ValidationRule)(unsafe.Pointer(in)) return nil } @@ -1357,12 +1306,7 @@ func Convert_v1beta1_ValidationRule_To_apiextensions_ValidationRule(in *Validati } func autoConvert_apiextensions_ValidationRule_To_v1beta1_ValidationRule(in *apiextensions.ValidationRule, out *ValidationRule, s conversion.Scope) error { - out.Rule = in.Rule - out.Message = in.Message - out.MessageExpression = in.MessageExpression - out.Reason = (*FieldValueErrorReason)(unsafe.Pointer(in.Reason)) - out.FieldPath = in.FieldPath - out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf)) + *out = *(*ValidationRule)(unsafe.Pointer(in)) return nil } diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1/customresourcedefinition.go b/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1/customresourcedefinition.go index 4884c25237..0fd3d5369d 100644 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1/customresourcedefinition.go +++ b/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1/customresourcedefinition.go @@ -19,8 +19,11 @@ limitations under the License. package v1 import ( + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + internal "k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal" apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" metav1 "k8s.io/client-go/applyconfigurations/meta/v1" ) @@ -30,7 +33,7 @@ import ( // CustomResourceDefinition represents a resource that should be exposed on the API server. Its name MUST be in the format // <.spec.name>.<.spec.group>. type CustomResourceDefinitionApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` @@ -50,6 +53,46 @@ func CustomResourceDefinition(name string) *CustomResourceDefinitionApplyConfigu return b } +// ExtractCustomResourceDefinitionFrom extracts the applied configuration owned by fieldManager from +// customResourceDefinition for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// customResourceDefinition must be a unmodified CustomResourceDefinition API object that was retrieved from the Kubernetes API. +// ExtractCustomResourceDefinitionFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCustomResourceDefinitionFrom(customResourceDefinition *apiextensionsv1.CustomResourceDefinition, fieldManager string, subresource string) (*CustomResourceDefinitionApplyConfiguration, error) { + b := &CustomResourceDefinitionApplyConfiguration{} + err := managedfields.ExtractInto(customResourceDefinition, internal.Parser().Type("io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinition"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(customResourceDefinition.Name) + + b.WithKind("CustomResourceDefinition") + b.WithAPIVersion("apiextensions.k8s.io/v1") + return b, nil +} + +// ExtractCustomResourceDefinition extracts the applied configuration owned by fieldManager from +// customResourceDefinition. If no managedFields are found in customResourceDefinition for fieldManager, a +// CustomResourceDefinitionApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// customResourceDefinition must be a unmodified CustomResourceDefinition API object that was retrieved from the Kubernetes API. +// ExtractCustomResourceDefinition provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCustomResourceDefinition(customResourceDefinition *apiextensionsv1.CustomResourceDefinition, fieldManager string) (*CustomResourceDefinitionApplyConfiguration, error) { + return ExtractCustomResourceDefinitionFrom(customResourceDefinition, fieldManager, "") +} + +// ExtractCustomResourceDefinitionStatus extracts the applied configuration owned by fieldManager from +// customResourceDefinition for the status subresource. +func ExtractCustomResourceDefinitionStatus(customResourceDefinition *apiextensionsv1.CustomResourceDefinition, fieldManager string) (*CustomResourceDefinitionApplyConfiguration, error) { + return ExtractCustomResourceDefinitionFrom(customResourceDefinition, fieldManager, "status") +} + func (b CustomResourceDefinitionApplyConfiguration) IsApplyConfiguration() {} // WithKind sets the Kind field in the declarative configuration to the given value diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1/customresourcedefinition.go b/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1/customresourcedefinition.go index 4838dafcb6..19a7711af1 100644 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1/customresourcedefinition.go +++ b/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1/customresourcedefinition.go @@ -19,8 +19,11 @@ limitations under the License. package v1beta1 import ( + apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + internal "k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" v1 "k8s.io/client-go/applyconfigurations/meta/v1" ) @@ -31,7 +34,7 @@ import ( // <.spec.name>.<.spec.group>. // Deprecated in v1.16, planned for removal in v1.22. Use apiextensions.k8s.io/v1 CustomResourceDefinition instead. type CustomResourceDefinitionApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` @@ -51,6 +54,46 @@ func CustomResourceDefinition(name string) *CustomResourceDefinitionApplyConfigu return b } +// ExtractCustomResourceDefinitionFrom extracts the applied configuration owned by fieldManager from +// customResourceDefinition for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// customResourceDefinition must be a unmodified CustomResourceDefinition API object that was retrieved from the Kubernetes API. +// ExtractCustomResourceDefinitionFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCustomResourceDefinitionFrom(customResourceDefinition *apiextensionsv1beta1.CustomResourceDefinition, fieldManager string, subresource string) (*CustomResourceDefinitionApplyConfiguration, error) { + b := &CustomResourceDefinitionApplyConfiguration{} + err := managedfields.ExtractInto(customResourceDefinition, internal.Parser().Type("io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinition"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(customResourceDefinition.Name) + + b.WithKind("CustomResourceDefinition") + b.WithAPIVersion("apiextensions.k8s.io/v1beta1") + return b, nil +} + +// ExtractCustomResourceDefinition extracts the applied configuration owned by fieldManager from +// customResourceDefinition. If no managedFields are found in customResourceDefinition for fieldManager, a +// CustomResourceDefinitionApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// customResourceDefinition must be a unmodified CustomResourceDefinition API object that was retrieved from the Kubernetes API. +// ExtractCustomResourceDefinition provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCustomResourceDefinition(customResourceDefinition *apiextensionsv1beta1.CustomResourceDefinition, fieldManager string) (*CustomResourceDefinitionApplyConfiguration, error) { + return ExtractCustomResourceDefinitionFrom(customResourceDefinition, fieldManager, "") +} + +// ExtractCustomResourceDefinitionStatus extracts the applied configuration owned by fieldManager from +// customResourceDefinition for the status subresource. +func ExtractCustomResourceDefinitionStatus(customResourceDefinition *apiextensionsv1beta1.CustomResourceDefinition, fieldManager string) (*CustomResourceDefinitionApplyConfiguration, error) { + return ExtractCustomResourceDefinitionFrom(customResourceDefinition, fieldManager, "status") +} + func (b CustomResourceDefinitionApplyConfiguration) IsApplyConfiguration() {} // WithKind sets the Kind field in the declarative configuration to the given value diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal/internal.go b/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal/internal.go new file mode 100644 index 0000000000..04927b8351 --- /dev/null +++ b/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal/internal.go @@ -0,0 +1,1250 @@ +/* +Copyright The Kubernetes 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. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package internal + +import ( + fmt "fmt" + sync "sync" + + typed "sigs.k8s.io/structured-merge-diff/v6/typed" +) + +func Parser() *typed.Parser { + parserOnce.Do(func() { + var err error + parser, err = typed.NewParser(schemaYAML) + if err != nil { + panic(fmt.Sprintf("Failed to parse schema: %v", err)) + } + }) + return parser +} + +var parserOnce sync.Once +var parser *typed.Parser +var schemaYAML = typed.YAMLObject(`types: +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceColumnDefinition + map: + fields: + - name: description + type: + scalar: string + - name: format + type: + scalar: string + - name: jsonPath + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" + - name: priority + type: + scalar: numeric + - name: type + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceConversion + map: + fields: + - name: strategy + type: + scalar: string + default: "" + - name: webhook + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookConversion +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinition + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionSpec + default: {} + - name: status + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionStatus + default: {} +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionCondition + map: + fields: + - name: lastTransitionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: message + type: + scalar: string + - name: observedGeneration + type: + scalar: numeric + - name: reason + type: + scalar: string + - name: status + type: + scalar: string + default: "" + - name: type + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionNames + map: + fields: + - name: categories + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: kind + type: + scalar: string + default: "" + - name: listKind + type: + scalar: string + - name: plural + type: + scalar: string + default: "" + - name: shortNames + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: singular + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionSpec + map: + fields: + - name: conversion + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceConversion + - name: group + type: + scalar: string + default: "" + - name: names + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionNames + default: {} + - name: preserveUnknownFields + type: + scalar: boolean + - name: scope + type: + scalar: string + default: "" + - name: versions + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionVersion + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionStatus + map: + fields: + - name: acceptedNames + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionNames + default: {} + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionCondition + elementRelationship: associative + keys: + - type + - name: observedGeneration + type: + scalar: numeric + - name: storedVersions + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionVersion + map: + fields: + - name: additionalPrinterColumns + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceColumnDefinition + elementRelationship: atomic + - name: deprecated + type: + scalar: boolean + - name: deprecationWarning + type: + scalar: string + - name: name + type: + scalar: string + default: "" + - name: schema + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceValidation + - name: selectableFields + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.SelectableField + elementRelationship: atomic + - name: served + type: + scalar: boolean + default: false + - name: storage + type: + scalar: boolean + default: false + - name: subresources + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresources +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresourceScale + map: + fields: + - name: labelSelectorPath + type: + scalar: string + - name: specReplicasPath + type: + scalar: string + default: "" + - name: statusReplicasPath + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresourceStatus + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresources + map: + fields: + - name: scale + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresourceScale + - name: status + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresourceStatus +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceValidation + map: + fields: + - name: openAPIV3Schema + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ExternalDocumentation + map: + fields: + - name: description + type: + scalar: string + - name: url + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSON + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + map: + fields: + - name: $ref + type: + scalar: string + - name: $schema + type: + scalar: string + - name: additionalItems + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrBool + - name: additionalProperties + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrBool + - name: allOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + elementRelationship: atomic + - name: anyOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + elementRelationship: atomic + - name: default + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSON + - name: definitions + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + - name: dependencies + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrStringArray + - name: description + type: + scalar: string + - name: enum + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSON + elementRelationship: atomic + - name: example + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSON + - name: exclusiveMaximum + type: + scalar: boolean + - name: exclusiveMinimum + type: + scalar: boolean + - name: externalDocs + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ExternalDocumentation + - name: format + type: + scalar: string + - name: id + type: + scalar: string + - name: items + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrArray + - name: maxItems + type: + scalar: numeric + - name: maxLength + type: + scalar: numeric + - name: maxProperties + type: + scalar: numeric + - name: maximum + type: + scalar: numeric + - name: minItems + type: + scalar: numeric + - name: minLength + type: + scalar: numeric + - name: minProperties + type: + scalar: numeric + - name: minimum + type: + scalar: numeric + - name: multipleOf + type: + scalar: numeric + - name: not + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + - name: nullable + type: + scalar: boolean + - name: oneOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + elementRelationship: atomic + - name: pattern + type: + scalar: string + - name: patternProperties + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + - name: properties + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + - name: required + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: title + type: + scalar: string + - name: type + type: + scalar: string + - name: uniqueItems + type: + scalar: boolean + - name: x-kubernetes-embedded-resource + type: + scalar: boolean + - name: x-kubernetes-int-or-string + type: + scalar: boolean + - name: x-kubernetes-list-map-keys + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: x-kubernetes-list-type + type: + scalar: string + - name: x-kubernetes-map-type + type: + scalar: string + - name: x-kubernetes-preserve-unknown-fields + type: + scalar: boolean + - name: x-kubernetes-validations + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ValidationRule + elementRelationship: associative + keys: + - rule +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrArray + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrBool + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrStringArray + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.SelectableField + map: + fields: + - name: jsonPath + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ServiceReference + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: namespace + type: + scalar: string + default: "" + - name: path + type: + scalar: string + - name: port + type: + scalar: numeric +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ValidationRule + map: + fields: + - name: fieldPath + type: + scalar: string + - name: message + type: + scalar: string + - name: messageExpression + type: + scalar: string + - name: optionalOldSelf + type: + scalar: boolean + - name: reason + type: + scalar: string + - name: rule + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookClientConfig + map: + fields: + - name: caBundle + type: + scalar: string + - name: service + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ServiceReference + - name: url + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookConversion + map: + fields: + - name: clientConfig + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookClientConfig + - name: conversionReviewVersions + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceColumnDefinition + map: + fields: + - name: JSONPath + type: + scalar: string + default: "" + - name: description + type: + scalar: string + - name: format + type: + scalar: string + - name: name + type: + scalar: string + default: "" + - name: priority + type: + scalar: numeric + - name: type + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceConversion + map: + fields: + - name: conversionReviewVersions + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: strategy + type: + scalar: string + default: "" + - name: webhookClientConfig + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.WebhookClientConfig +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinition + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionSpec + default: {} + - name: status + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionStatus + default: {} +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionCondition + map: + fields: + - name: lastTransitionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: message + type: + scalar: string + - name: observedGeneration + type: + scalar: numeric + - name: reason + type: + scalar: string + - name: status + type: + scalar: string + default: "" + - name: type + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionNames + map: + fields: + - name: categories + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: kind + type: + scalar: string + default: "" + - name: listKind + type: + scalar: string + - name: plural + type: + scalar: string + default: "" + - name: shortNames + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: singular + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionSpec + map: + fields: + - name: additionalPrinterColumns + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceColumnDefinition + elementRelationship: atomic + - name: conversion + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceConversion + - name: group + type: + scalar: string + default: "" + - name: names + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionNames + default: {} + - name: preserveUnknownFields + type: + scalar: boolean + - name: scope + type: + scalar: string + default: "" + - name: selectableFields + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.SelectableField + elementRelationship: atomic + - name: subresources + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresources + - name: validation + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceValidation + - name: version + type: + scalar: string + - name: versions + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionVersion + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionStatus + map: + fields: + - name: acceptedNames + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionNames + default: {} + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionCondition + elementRelationship: associative + keys: + - type + - name: observedGeneration + type: + scalar: numeric + - name: storedVersions + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionVersion + map: + fields: + - name: additionalPrinterColumns + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceColumnDefinition + elementRelationship: atomic + - name: deprecated + type: + scalar: boolean + - name: deprecationWarning + type: + scalar: string + - name: name + type: + scalar: string + default: "" + - name: schema + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceValidation + - name: selectableFields + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.SelectableField + elementRelationship: atomic + - name: served + type: + scalar: boolean + default: false + - name: storage + type: + scalar: boolean + default: false + - name: subresources + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresources +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceScale + map: + fields: + - name: labelSelectorPath + type: + scalar: string + - name: specReplicasPath + type: + scalar: string + default: "" + - name: statusReplicasPath + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceStatus + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresources + map: + fields: + - name: scale + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceScale + - name: status + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceStatus +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceValidation + map: + fields: + - name: openAPIV3Schema + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ExternalDocumentation + map: + fields: + - name: description + type: + scalar: string + - name: url + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSON + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + map: + fields: + - name: $ref + type: + scalar: string + - name: $schema + type: + scalar: string + - name: additionalItems + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrBool + - name: additionalProperties + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrBool + - name: allOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + elementRelationship: atomic + - name: anyOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + elementRelationship: atomic + - name: default + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSON + - name: definitions + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + - name: dependencies + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrStringArray + - name: description + type: + scalar: string + - name: enum + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSON + elementRelationship: atomic + - name: example + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSON + - name: exclusiveMaximum + type: + scalar: boolean + - name: exclusiveMinimum + type: + scalar: boolean + - name: externalDocs + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ExternalDocumentation + - name: format + type: + scalar: string + - name: id + type: + scalar: string + - name: items + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrArray + - name: maxItems + type: + scalar: numeric + - name: maxLength + type: + scalar: numeric + - name: maxProperties + type: + scalar: numeric + - name: maximum + type: + scalar: numeric + - name: minItems + type: + scalar: numeric + - name: minLength + type: + scalar: numeric + - name: minProperties + type: + scalar: numeric + - name: minimum + type: + scalar: numeric + - name: multipleOf + type: + scalar: numeric + - name: not + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + - name: nullable + type: + scalar: boolean + - name: oneOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + elementRelationship: atomic + - name: pattern + type: + scalar: string + - name: patternProperties + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + - name: properties + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + - name: required + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: title + type: + scalar: string + - name: type + type: + scalar: string + - name: uniqueItems + type: + scalar: boolean + - name: x-kubernetes-embedded-resource + type: + scalar: boolean + - name: x-kubernetes-int-or-string + type: + scalar: boolean + - name: x-kubernetes-list-map-keys + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: x-kubernetes-list-type + type: + scalar: string + - name: x-kubernetes-map-type + type: + scalar: string + - name: x-kubernetes-preserve-unknown-fields + type: + scalar: boolean + - name: x-kubernetes-validations + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ValidationRule + elementRelationship: associative + keys: + - rule +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrArray + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrBool + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrStringArray + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.SelectableField + map: + fields: + - name: jsonPath + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ServiceReference + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: namespace + type: + scalar: string + default: "" + - name: path + type: + scalar: string + - name: port + type: + scalar: numeric +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ValidationRule + map: + fields: + - name: fieldPath + type: + scalar: string + - name: message + type: + scalar: string + - name: messageExpression + type: + scalar: string + - name: optionalOldSelf + type: + scalar: boolean + - name: reason + type: + scalar: string + - name: rule + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.WebhookClientConfig + map: + fields: + - name: caBundle + type: + scalar: string + - name: service + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ServiceReference + - name: url + type: + scalar: string +- name: io.k8s.apimachinery.pkg.apis.meta.v1.FieldsV1 + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apimachinery.pkg.apis.meta.v1.ManagedFieldsEntry + map: + fields: + - name: apiVersion + type: + scalar: string + - name: fieldsType + type: + scalar: string + - name: fieldsV1 + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.FieldsV1 + - name: manager + type: + scalar: string + - name: operation + type: + scalar: string + - name: subresource + type: + scalar: string + - name: time + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time +- name: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + map: + fields: + - name: annotations + type: + map: + elementType: + scalar: string + - name: creationTimestamp + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: deletionGracePeriodSeconds + type: + scalar: numeric + - name: deletionTimestamp + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: finalizers + type: + list: + elementType: + scalar: string + elementRelationship: associative + - name: generateName + type: + scalar: string + - name: generation + type: + scalar: numeric + - name: labels + type: + map: + elementType: + scalar: string + - name: managedFields + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ManagedFieldsEntry + elementRelationship: atomic + - name: name + type: + scalar: string + - name: namespace + type: + scalar: string + - name: ownerReferences + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.OwnerReference + elementRelationship: associative + keys: + - uid + - name: resourceVersion + type: + scalar: string + - name: selfLink + type: + scalar: string + - name: uid + type: + scalar: string +- name: io.k8s.apimachinery.pkg.apis.meta.v1.OwnerReference + map: + fields: + - name: apiVersion + type: + scalar: string + default: "" + - name: blockOwnerDeletion + type: + scalar: boolean + - name: controller + type: + scalar: boolean + - name: kind + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" + - name: uid + type: + scalar: string + default: "" + elementRelationship: atomic +- name: io.k8s.apimachinery.pkg.apis.meta.v1.Time + scalar: untyped +- name: __untyped_atomic_ + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic +- name: __untyped_deduced_ + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +`) diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go b/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go index 93dd79d63f..8e13f11bb7 100644 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go +++ b/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go @@ -30,7 +30,7 @@ import ( ) type Interface interface { - Discovery() discovery.DiscoveryInterface + Discovery() discovery.DiscoveryInterfaces ApiextensionsV1() apiextensionsv1.ApiextensionsV1Interface ApiextensionsV1beta1() apiextensionsv1beta1.ApiextensionsV1beta1Interface } @@ -53,7 +53,7 @@ func (c *Clientset) ApiextensionsV1beta1() apiextensionsv1beta1.ApiextensionsV1b } // Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { +func (c *Clientset) Discovery() discovery.DiscoveryInterfaces { if c == nil { return nil } diff --git a/vendor/modules.txt b/vendor/modules.txt index 1c6bba7903..4f9ea07985 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,3 +1,28 @@ +# cel.dev/cel-go v0.33.2 +## explicit; go 1.23.0 +cel.dev/cel-go/cel +cel.dev/cel-go/cel/async +cel.dev/cel-go/checker +cel.dev/cel-go/checker/decls +cel.dev/cel-go/common +cel.dev/cel-go/common/ast +cel.dev/cel-go/common/containers +cel.dev/cel-go/common/cost +cel.dev/cel-go/common/debug +cel.dev/cel-go/common/decls +cel.dev/cel-go/common/env +cel.dev/cel-go/common/functions +cel.dev/cel-go/common/operators +cel.dev/cel-go/common/overloads +cel.dev/cel-go/common/runes +cel.dev/cel-go/common/stdlib +cel.dev/cel-go/common/types +cel.dev/cel-go/common/types/pb +cel.dev/cel-go/common/types/ref +cel.dev/cel-go/common/types/traits +cel.dev/cel-go/interpreter +cel.dev/cel-go/parser +cel.dev/cel-go/parser/gen # cel.dev/expr v0.25.2 ## explicit; go 1.23.0 cel.dev/expr @@ -8,7 +33,7 @@ cloud.google.com/go/internal cloud.google.com/go/internal/optional cloud.google.com/go/internal/trace cloud.google.com/go/internal/version -# cloud.google.com/go/auth v0.19.0 +# cloud.google.com/go/auth v0.20.0 ## explicit; go 1.25.0 cloud.google.com/go/auth cloud.google.com/go/auth/credentials @@ -78,11 +103,11 @@ cloud.google.com/go/storage/internal/apiv2/storagepb # dario.cat/mergo v1.0.2 ## explicit; go 1.13 dario.cat/mergo -# github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c -## explicit; go 1.16 +# github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 +## explicit; go 1.17 github.com/Azure/go-ansiterm github.com/Azure/go-ansiterm/winterm -# github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 +# github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0 ## explicit; go 1.25.0 github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp # github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 @@ -97,8 +122,8 @@ github.com/IBM/pgxpoolprometheus # github.com/Masterminds/squirrel v1.5.4 ## explicit; go 1.14 github.com/Masterminds/squirrel -# github.com/Microsoft/go-winio v0.6.2 -## explicit; go 1.21 +# github.com/Microsoft/go-winio v0.6.3 +## explicit; go 1.26.0 github.com/Microsoft/go-winio github.com/Microsoft/go-winio/internal/fs github.com/Microsoft/go-winio/internal/socket @@ -318,7 +343,7 @@ github.com/docker/cli/cli/config/types ## explicit; go 1.21 github.com/docker/docker-credential-helpers/client github.com/docker/docker-credential-helpers/credentials -# github.com/docker/go-connections v0.7.0 +# github.com/docker/go-connections v0.8.2 ## explicit; go 1.23 github.com/docker/go-connections/sockets github.com/docker/go-connections/tlsconfig @@ -463,81 +488,57 @@ github.com/go-logr/stdr ## explicit; go 1.12 github.com/go-ole/go-ole github.com/go-ole/go-ole/oleutil -# github.com/go-openapi/jsonpointer v1.0.0 -## explicit; go 1.25.0 +# github.com/go-openapi/jsonpointer v1.0.2 +## explicit; go 1.26.0 github.com/go-openapi/jsonpointer github.com/go-openapi/jsonpointer/jsonname -# github.com/go-openapi/jsonreference v1.0.0 -## explicit; go 1.25.0 +# github.com/go-openapi/jsonreference v1.0.3 +## explicit; go 1.26.0 github.com/go-openapi/jsonreference github.com/go-openapi/jsonreference/internal -# github.com/go-openapi/swag v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag -# github.com/go-openapi/swag/cmdutils v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/cmdutils v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/cmdutils -# github.com/go-openapi/swag/conv v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/conv v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/conv -# github.com/go-openapi/swag/fileutils v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/fileutils v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/fileutils -# github.com/go-openapi/swag/jsonutils v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/jsonutils v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/jsonutils github.com/go-openapi/swag/jsonutils/adapters github.com/go-openapi/swag/jsonutils/adapters/ifaces github.com/go-openapi/swag/jsonutils/adapters/stdlib/json -# github.com/go-openapi/swag/loading v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/loading v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/loading -# github.com/go-openapi/swag/mangling v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/mangling v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/mangling -# github.com/go-openapi/swag/netutils v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/netutils v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/netutils -# github.com/go-openapi/swag/pools v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/pools v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/pools -# github.com/go-openapi/swag/stringutils v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/stringutils v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/stringutils -# github.com/go-openapi/swag/typeutils v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/typeutils v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/typeutils -# github.com/go-openapi/swag/yamlutils v0.28.0 -## explicit; go 1.25.0 +# github.com/go-openapi/swag/yamlutils v0.29.2 +## explicit; go 1.26.0 github.com/go-openapi/swag/yamlutils # github.com/go-viper/mapstructure/v2 v2.5.0 ## explicit; go 1.18 github.com/go-viper/mapstructure/v2 github.com/go-viper/mapstructure/v2/internal/errors -# github.com/google/cel-go v0.31.0 -## explicit; go 1.23.0 -github.com/google/cel-go/cel -github.com/google/cel-go/cel/async -github.com/google/cel-go/checker -github.com/google/cel-go/checker/decls -github.com/google/cel-go/common -github.com/google/cel-go/common/ast -github.com/google/cel-go/common/containers -github.com/google/cel-go/common/debug -github.com/google/cel-go/common/decls -github.com/google/cel-go/common/env -github.com/google/cel-go/common/functions -github.com/google/cel-go/common/operators -github.com/google/cel-go/common/overloads -github.com/google/cel-go/common/runes -github.com/google/cel-go/common/stdlib -github.com/google/cel-go/common/types -github.com/google/cel-go/common/types/pb -github.com/google/cel-go/common/types/ref -github.com/google/cel-go/common/types/traits -github.com/google/cel-go/interpreter -github.com/google/cel-go/parser -github.com/google/cel-go/parser/gen # github.com/google/gnostic-models v0.7.0 ## explicit; go 1.22 github.com/google/gnostic-models/compiler @@ -619,11 +620,11 @@ github.com/google/s2a-go/stream # github.com/google/uuid v1.6.0 ## explicit github.com/google/uuid -# github.com/googleapis/enterprise-certificate-proxy v0.3.14 +# github.com/googleapis/enterprise-certificate-proxy v0.3.15 ## explicit; go 1.24.11 github.com/googleapis/enterprise-certificate-proxy/client github.com/googleapis/enterprise-certificate-proxy/client/util -# github.com/googleapis/gax-go/v2 v2.21.0 +# github.com/googleapis/gax-go/v2 v2.22.0 ## explicit; go 1.25.0 github.com/googleapis/gax-go/v2 github.com/googleapis/gax-go/v2/apierror @@ -642,12 +643,12 @@ github.com/gorilla/websocket github.com/grpc-ecosystem/go-grpc-middleware github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap github.com/grpc-ecosystem/go-grpc-middleware/tags -# github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 -## explicit; go 1.23.0 +# github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.4 +## explicit; go 1.24.0 github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/validator -# github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 -## explicit; go 1.25.0 +# github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 +## explicit; go 1.26.0 github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options github.com/grpc-ecosystem/grpc-gateway/v2/runtime @@ -661,10 +662,11 @@ github.com/jackc/pgpassfile # github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 ## explicit; go 1.14 github.com/jackc/pgservicefile -# github.com/jackc/pgx/v5 v5.10.0 +# github.com/jackc/pgx/v5 v5.11.0 ## explicit; go 1.25.0 github.com/jackc/pgx/v5 github.com/jackc/pgx/v5/internal/iobufpool +github.com/jackc/pgx/v5/internal/pgdatetime github.com/jackc/pgx/v5/internal/pgio github.com/jackc/pgx/v5/internal/sanitize github.com/jackc/pgx/v5/internal/stmtcache @@ -675,15 +677,15 @@ github.com/jackc/pgx/v5/pgproto3 github.com/jackc/pgx/v5/pgtype github.com/jackc/pgx/v5/pgxpool github.com/jackc/pgx/v5/stdlib -# github.com/jackc/puddle/v2 v2.2.2 +# github.com/jackc/puddle/v2 v2.2.3 ## explicit; go 1.19 github.com/jackc/puddle/v2 github.com/jackc/puddle/v2/internal/genstack # github.com/json-iterator/go v1.1.12 ## explicit; go 1.12 github.com/json-iterator/go -# github.com/klauspost/compress v1.19.1 -## explicit; go 1.24 +# github.com/klauspost/compress v1.20.1 +## explicit; go 1.25 github.com/klauspost/compress github.com/klauspost/compress/flate github.com/klauspost/compress/fse @@ -691,6 +693,7 @@ github.com/klauspost/compress/gzip github.com/klauspost/compress/huff0 github.com/klauspost/compress/internal/cpuinfo github.com/klauspost/compress/internal/le +github.com/klauspost/compress/internal/regmask github.com/klauspost/compress/internal/snapref github.com/klauspost/compress/zstd github.com/klauspost/compress/zstd/internal/xxhash @@ -737,7 +740,7 @@ github.com/moby/docker-image-spec/specs-go/v1 github.com/moby/go-archive github.com/moby/go-archive/compression github.com/moby/go-archive/tarheader -# github.com/moby/moby/api v1.55.0 +# github.com/moby/moby/api v1.56.1 ## explicit; go 1.24 github.com/moby/moby/api/pkg/authconfig github.com/moby/moby/api/pkg/stdcopy @@ -758,7 +761,7 @@ github.com/moby/moby/api/types/storage github.com/moby/moby/api/types/swarm github.com/moby/moby/api/types/system github.com/moby/moby/api/types/volume -# github.com/moby/moby/client v0.5.1 +# github.com/moby/moby/client v0.6.2 ## explicit; go 1.24 github.com/moby/moby/client github.com/moby/moby/client/internal @@ -846,15 +849,15 @@ github.com/opencontainers/runtime-spec/specs-go ## explicit; go 1.23.0 github.com/openfga/api/proto/authzen/v1 github.com/openfga/api/proto/openfga/v1 -# github.com/openfga/language/pkg/go v0.3.2-0.20260730144454-83fedf8a4e70 +# github.com/openfga/language/pkg/go v0.3.2 ## explicit; go 1.25.0 github.com/openfga/language/pkg/go/errors github.com/openfga/language/pkg/go/gen github.com/openfga/language/pkg/go/graph github.com/openfga/language/pkg/go/transformer github.com/openfga/language/pkg/go/utils -# github.com/openfga/openfga v1.20.0 -## explicit; go 1.25.7 +# github.com/openfga/openfga v1.23.0 +## explicit; go 1.26.0 github.com/openfga/openfga/assets github.com/openfga/openfga/internal/authz github.com/openfga/openfga/internal/build @@ -904,6 +907,9 @@ github.com/openfga/openfga/pkg/server/commands/v2breaking github.com/openfga/openfga/pkg/server/config github.com/openfga/openfga/pkg/server/errors github.com/openfga/openfga/pkg/storage +github.com/openfga/openfga/pkg/storage/adapter +github.com/openfga/openfga/pkg/storage/adapter/ast +github.com/openfga/openfga/pkg/storage/adapter/query github.com/openfga/openfga/pkg/storage/cache/keys github.com/openfga/openfga/pkg/storage/postgres github.com/openfga/openfga/pkg/storage/sqlcommon @@ -932,8 +938,8 @@ github.com/pmezard/go-difflib/difflib # github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 ## explicit; go 1.14 github.com/power-devops/perfstat -# github.com/pressly/goose/v3 v3.27.3 -## explicit; go 1.25.7 +# github.com/pressly/goose/v3 v3.29.0 +## explicit; go 1.26.0 github.com/pressly/goose/v3 github.com/pressly/goose/v3/database github.com/pressly/goose/v3/database/dialect @@ -945,8 +951,8 @@ github.com/pressly/goose/v3/internal/sqlparser github.com/pressly/goose/v3/lock github.com/pressly/goose/v3/lock/internal/store github.com/pressly/goose/v3/lock/internal/table -# github.com/prometheus/client_golang v1.24.1 -## explicit; go 1.25.0 +# github.com/prometheus/client_golang v1.25.0 +## explicit; go 1.26.0 github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header github.com/prometheus/client_golang/prometheus @@ -956,28 +962,28 @@ github.com/prometheus/client_golang/prometheus/promauto github.com/prometheus/client_golang/prometheus/promhttp github.com/prometheus/client_golang/prometheus/promhttp/internal github.com/prometheus/client_golang/prometheus/push -# github.com/prometheus/client_model v0.6.2 -## explicit; go 1.22.0 +# github.com/prometheus/client_model v0.6.3 +## explicit; go 1.23 github.com/prometheus/client_model/go -# github.com/prometheus/common v0.70.1 -## explicit; go 1.25.0 +# github.com/prometheus/common v0.72.0 +## explicit; go 1.26.0 github.com/prometheus/common/expfmt github.com/prometheus/common/model # github.com/prometheus/otlptranslator v1.0.0 ## explicit; go 1.23.0 github.com/prometheus/otlptranslator -# github.com/prometheus/procfs v0.21.1 +# github.com/prometheus/procfs v0.22.0 ## explicit; go 1.25.0 github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs -github.com/prometheus/procfs/internal/util +github.com/prometheus/procfs/internal/parsers # github.com/rivo/uniseg v0.2.0 ## explicit; go 1.12 github.com/rivo/uniseg # github.com/sagikazarmark/locafero v0.9.0 ## explicit; go 1.23.0 github.com/sagikazarmark/locafero -# github.com/sethvargo/go-retry v0.4.0 +# github.com/sethvargo/go-retry v0.5.0 ## explicit; go 1.25 github.com/sethvargo/go-retry # github.com/shirou/gopsutil v3.21.11+incompatible @@ -995,8 +1001,8 @@ github.com/shirou/gopsutil/v4/internal/common github.com/shirou/gopsutil/v4/mem github.com/shirou/gopsutil/v4/net github.com/shirou/gopsutil/v4/process -# github.com/sirupsen/logrus v1.9.4 -## explicit; go 1.17 +# github.com/sirupsen/logrus v1.10.2 +## explicit; go 1.23 github.com/sirupsen/logrus # github.com/sourcegraph/conc v0.3.0 ## explicit; go 1.19 @@ -1028,7 +1034,7 @@ github.com/spf13/viper/internal/encoding/json github.com/spf13/viper/internal/encoding/toml github.com/spf13/viper/internal/encoding/yaml github.com/spf13/viper/internal/features -# github.com/spiffe/go-spiffe/v2 v2.7.0 +# github.com/spiffe/go-spiffe/v2 v2.8.1 ## explicit; go 1.24.0 github.com/spiffe/go-spiffe/v2/bundle/jwtbundle github.com/spiffe/go-spiffe/v2/bundle/spiffebundle @@ -1105,17 +1111,17 @@ go.opentelemetry.io/contrib/bridges/prometheus # go.opentelemetry.io/contrib/detectors/gcp v1.44.0 ## explicit; go 1.25.0 go.opentelemetry.io/contrib/detectors/gcp -# go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 +## explicit; go 1.26.0 go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal -# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 +## explicit; go 1.26.0 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv -# go.opentelemetry.io/otel v1.45.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel go.opentelemetry.io/otel/attribute go.opentelemetry.io/otel/attribute/internal @@ -1126,6 +1132,7 @@ go.opentelemetry.io/otel/internal/baggage go.opentelemetry.io/otel/internal/errorhandler go.opentelemetry.io/otel/internal/global go.opentelemetry.io/otel/propagation +go.opentelemetry.io/otel/propagation/internal/hextable go.opentelemetry.io/otel/semconv/internal/metricpool go.opentelemetry.io/otel/semconv/v1.21.0 go.opentelemetry.io/otel/semconv/v1.37.0 @@ -1153,12 +1160,12 @@ go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/envco go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/oconf go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/retry go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/transform -# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform -# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/counter @@ -1174,20 +1181,19 @@ go.opentelemetry.io/otel/exporters/prometheus/internal go.opentelemetry.io/otel/exporters/prometheus/internal/counter go.opentelemetry.io/otel/exporters/prometheus/internal/observ go.opentelemetry.io/otel/exporters/prometheus/internal/x -# go.opentelemetry.io/otel/log v0.21.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/log v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/log go.opentelemetry.io/otel/log/embedded go.opentelemetry.io/otel/log/global -go.opentelemetry.io/otel/log/internal/global go.opentelemetry.io/otel/log/noop -# go.opentelemetry.io/otel/metric v1.45.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/metric v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/metric go.opentelemetry.io/otel/metric/embedded go.opentelemetry.io/otel/metric/noop -# go.opentelemetry.io/otel/sdk v1.45.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/sdk v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/sdk go.opentelemetry.io/otel/sdk/instrumentation go.opentelemetry.io/otel/sdk/internal/attrnorm @@ -1204,25 +1210,25 @@ go.opentelemetry.io/otel/sdk/log/internal/attrnorm go.opentelemetry.io/otel/sdk/log/internal/counter go.opentelemetry.io/otel/sdk/log/internal/observ go.opentelemetry.io/otel/sdk/log/internal/x -# go.opentelemetry.io/otel/sdk/metric v1.45.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/sdk/metric v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/sdk/metric go.opentelemetry.io/otel/sdk/metric/exemplar go.opentelemetry.io/otel/sdk/metric/internal go.opentelemetry.io/otel/sdk/metric/internal/aggregate go.opentelemetry.io/otel/sdk/metric/internal/attrnorm +go.opentelemetry.io/otel/sdk/metric/internal/finish go.opentelemetry.io/otel/sdk/metric/internal/observ go.opentelemetry.io/otel/sdk/metric/internal/reservoir -go.opentelemetry.io/otel/sdk/metric/internal/x go.opentelemetry.io/otel/sdk/metric/metricdata -# go.opentelemetry.io/otel/trace v1.45.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/trace v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded go.opentelemetry.io/otel/trace/internal/telemetry go.opentelemetry.io/otel/trace/noop -# go.opentelemetry.io/proto/otlp v1.11.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/proto/otlp v1.11.1 +## explicit; go 1.26.0 go.opentelemetry.io/proto/otlp/collector/logs/v1 go.opentelemetry.io/proto/otlp/collector/metrics/v1 go.opentelemetry.io/proto/otlp/collector/trace/v1 @@ -1254,7 +1260,7 @@ go.yaml.in/yaml/v2 # go.yaml.in/yaml/v3 v3.0.5 ## explicit; go 1.16 go.yaml.in/yaml/v3 -# golang.org/x/crypto v0.57.0 +# golang.org/x/crypto v0.58.0 ## explicit; go 1.26.0 golang.org/x/crypto/blowfish golang.org/x/crypto/chacha20 @@ -1267,10 +1273,10 @@ golang.org/x/crypto/internal/alias golang.org/x/crypto/internal/poly1305 golang.org/x/crypto/ssh golang.org/x/crypto/ssh/internal/bcrypt_pbkdf -# golang.org/x/exp v0.0.0-20260718201538-764159d718ef -## explicit; go 1.25.0 +# golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e +## explicit; go 1.26.0 golang.org/x/exp/slices -# golang.org/x/net v0.60.0 +# golang.org/x/net v0.62.0 ## explicit; go 1.26.0 golang.org/x/net/bpf golang.org/x/net/dns/dnsmessage @@ -1285,8 +1291,8 @@ golang.org/x/net/internal/timeseries golang.org/x/net/proxy golang.org/x/net/trace golang.org/x/net/websocket -# golang.org/x/oauth2 v0.36.0 -## explicit; go 1.25.0 +# golang.org/x/oauth2 v0.37.0 +## explicit; go 1.26.0 golang.org/x/oauth2 golang.org/x/oauth2/authhandler golang.org/x/oauth2/google @@ -1298,22 +1304,22 @@ golang.org/x/oauth2/google/internal/stsexchange golang.org/x/oauth2/internal golang.org/x/oauth2/jws golang.org/x/oauth2/jwt -# golang.org/x/sync v0.23.0 +# golang.org/x/sync v0.24.0 ## explicit; go 1.26.0 golang.org/x/sync/errgroup golang.org/x/sync/semaphore golang.org/x/sync/singleflight -# golang.org/x/sys v0.48.0 +# golang.org/x/sys v0.49.0 ## explicit; go 1.26.0 golang.org/x/sys/cpu golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows golang.org/x/sys/windows/registry -# golang.org/x/term v0.46.0 +# golang.org/x/term v0.47.0 ## explicit; go 1.26.0 golang.org/x/term -# golang.org/x/text v0.42.0 +# golang.org/x/text v0.43.0 ## explicit; go 1.26.0 golang.org/x/text/cases golang.org/x/text/encoding @@ -1383,7 +1389,7 @@ gonum.org/v1/gonum/optimize/convex/lp gonum.org/v1/gonum/stat gonum.org/v1/gonum/stat/combin gonum.org/v1/gonum/stat/distuv -# google.golang.org/api v0.274.0 +# google.golang.org/api v0.278.0 ## explicit; go 1.25.0 google.golang.org/api/googleapi google.golang.org/api/googleapi/transport @@ -1411,8 +1417,8 @@ google.golang.org/genproto/googleapis/type/date google.golang.org/genproto/googleapis/type/expr google.golang.org/genproto/googleapis/type/interval google.golang.org/genproto/googleapis/type/timeofday -# google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d -## explicit; go 1.25.0 +# google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e +## explicit; go 1.26.0 google.golang.org/genproto/googleapis/api google.golang.org/genproto/googleapis/api/annotations google.golang.org/genproto/googleapis/api/distribution @@ -1423,12 +1429,12 @@ google.golang.org/genproto/googleapis/api/metric google.golang.org/genproto/googleapis/api/monitoredres google.golang.org/genproto/googleapis/api/serviceconfig google.golang.org/genproto/googleapis/api/visibility -# google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d -## explicit; go 1.25.0 +# google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b +## explicit; go 1.26.0 google.golang.org/genproto/googleapis/rpc/code google.golang.org/genproto/googleapis/rpc/errdetails google.golang.org/genproto/googleapis/rpc/status -# google.golang.org/grpc v1.83.2 +# google.golang.org/grpc v1.84.0 ## explicit; go 1.25.0 google.golang.org/grpc google.golang.org/grpc/attributes @@ -1508,6 +1514,7 @@ google.golang.org/grpc/internal/hierarchy google.golang.org/grpc/internal/idle google.golang.org/grpc/internal/mem google.golang.org/grpc/internal/metadata +google.golang.org/grpc/internal/optional google.golang.org/grpc/internal/pretty google.golang.org/grpc/internal/proto/grpc_lookup_v1 google.golang.org/grpc/internal/proxyattributes @@ -1556,6 +1563,8 @@ google.golang.org/grpc/internal/xds/clients/xdsclient/metrics google.golang.org/grpc/internal/xds/clusterspecifier google.golang.org/grpc/internal/xds/clusterspecifier/rls google.golang.org/grpc/internal/xds/httpfilter +google.golang.org/grpc/internal/xds/httpfilter/extproc +google.golang.org/grpc/internal/xds/httpfilter/extproc/internal google.golang.org/grpc/internal/xds/httpfilter/fault google.golang.org/grpc/internal/xds/httpfilter/rbac google.golang.org/grpc/internal/xds/httpfilter/router @@ -1718,13 +1727,14 @@ k8s.io/api/storage/v1alpha1 k8s.io/api/storage/v1beta1 k8s.io/api/storagemigration/v1 k8s.io/api/storagemigration/v1beta1 -# k8s.io/apiextensions-apiserver v0.36.1 +# k8s.io/apiextensions-apiserver v0.37.0 ## explicit; go 1.26.0 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1 k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1 k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1 +k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1 @@ -2208,11 +2218,12 @@ k8s.io/utils/net k8s.io/utils/ptr k8s.io/utils/third_party/forked/golang/btree k8s.io/utils/trace -# sigs.k8s.io/controller-runtime v0.24.1 +# sigs.k8s.io/controller-runtime v0.25.2 ## explicit; go 1.26.0 sigs.k8s.io/controller-runtime sigs.k8s.io/controller-runtime/pkg/builder sigs.k8s.io/controller-runtime/pkg/cache +sigs.k8s.io/controller-runtime/pkg/cache/cacheapi sigs.k8s.io/controller-runtime/pkg/cache/internal sigs.k8s.io/controller-runtime/pkg/certwatcher sigs.k8s.io/controller-runtime/pkg/certwatcher/metrics @@ -2221,6 +2232,8 @@ sigs.k8s.io/controller-runtime/pkg/client/apiutil sigs.k8s.io/controller-runtime/pkg/client/config sigs.k8s.io/controller-runtime/pkg/client/fake sigs.k8s.io/controller-runtime/pkg/client/interceptor +sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler +sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier sigs.k8s.io/controller-runtime/pkg/cluster sigs.k8s.io/controller-runtime/pkg/config sigs.k8s.io/controller-runtime/pkg/controller diff --git a/vendor/sigs.k8s.io/controller-runtime/.golangci.yml b/vendor/sigs.k8s.io/controller-runtime/.golangci.yml index 334333a5f2..669ff5aca7 100644 --- a/vendor/sigs.k8s.io/controller-runtime/.golangci.yml +++ b/vendor/sigs.k8s.io/controller-runtime/.golangci.yml @@ -56,6 +56,9 @@ linters: msg: Use ginkgos SpecContext or go testings t.Context instead - pattern: context.TODO msg: Use ginkgos SpecContext or go testings t.Context instead + goconst: + ignore-tests: true + min-occurrences: 5 govet: disable: - fieldalignment @@ -77,10 +80,11 @@ linters: - pkg: sigs.k8s.io/controller-runtime alias: ctrl no-unaliased: true + misspell: + mode: default modernize: disable: - omitzero - - fmtappendf revive: rules: # The following rules are recommended https://github.com/mgechev/revive#recommended-configuration diff --git a/vendor/sigs.k8s.io/controller-runtime/FAQ.md b/vendor/sigs.k8s.io/controller-runtime/FAQ.md index 9c36c8112e..c182755349 100644 --- a/vendor/sigs.k8s.io/controller-runtime/FAQ.md +++ b/vendor/sigs.k8s.io/controller-runtime/FAQ.md @@ -14,7 +14,7 @@ attempt to reconcile *all* state for that given root objects. should always reconcile state by reading all the state it needs, then writing updates. This allows your reconciler to correctly respond to generic events, adjust to skipped or coalesced events, and easily deal -with application startup. The controller will enqueue reconcile requests +with application startup. The controller will enqueue reconcile requests for both old and new objects if a mapping changes, but it's your responsibility to make sure you have enough information to be able clean up state that's no longer referenced. @@ -40,10 +40,7 @@ on your situation. In general, write your controller with the assumption that information will eventually be correct, but may be slightly out of date. Make sure that your reconcile function enforces the entire state of the world each -time it runs. If none of this works for you, you can always construct -a client that reads directly from the API server, but this is generally -considered to be a last resort, and the two approaches above should -generally cover most circumstances. +time it runs. ### Q: Where's the fake client? How do I use it? diff --git a/vendor/sigs.k8s.io/controller-runtime/Makefile b/vendor/sigs.k8s.io/controller-runtime/Makefile index 40e7db6e70..f64d647e2a 100644 --- a/vendor/sigs.k8s.io/controller-runtime/Makefile +++ b/vendor/sigs.k8s.io/controller-runtime/Makefile @@ -1,18 +1,16 @@ -#!/usr/bin/env bash - -# Copyright 2020 The Kubernetes Authors. +# Copyright 2020 The Kubernetes 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 +# 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 +# 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. +# 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. # If you update this file, please follow # https://suva.sh/posts/well-documented-makefiles @@ -198,6 +196,10 @@ verify-modules: modules $(GO_MOD_CHECK) ## Verify go modules are up to date fi $(GO_MOD_CHECK) $(GO_MOD_CHECK_IGNORE) +.PHONY: verify-boilerplate +verify-boilerplate: + ./hack/verify-boilerplate.sh + APIDIFF_OLD_COMMIT ?= $(shell git rev-parse origin/main) .PHONY: apidiff diff --git a/vendor/sigs.k8s.io/controller-runtime/README.md b/vendor/sigs.k8s.io/controller-runtime/README.md index 8549f4e880..35eddc4574 100644 --- a/vendor/sigs.k8s.io/controller-runtime/README.md +++ b/vendor/sigs.k8s.io/controller-runtime/README.md @@ -53,6 +53,8 @@ Compatible k8s.io/*, client-go and minimum Go versions can be looked up in our [ | | k8s.io/*, client-go | minimum Go version | |----------|:-------------------:|:------------------:| +| CR v0.24 | v0.36 | 1.26 | +| CR v0.23 | v0.35 | 1.25 | | CR v0.22 | v0.34 | 1.24 | | CR v0.21 | v0.33 | 1.24 | | CR v0.20 | v0.32 | 1.23 | diff --git a/vendor/sigs.k8s.io/controller-runtime/alias.go b/vendor/sigs.k8s.io/controller-runtime/alias.go index a2848693a2..3077a9f4dc 100644 --- a/vendor/sigs.k8s.io/controller-runtime/alias.go +++ b/vendor/sigs.k8s.io/controller-runtime/alias.go @@ -107,7 +107,7 @@ var ( // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running // in cluster and use the cluster provided kubeconfig. // - // The returned `*rest.Config` has client-side ratelimting disabled as we can rely on API priority and + // The returned `*rest.Config` has client-side rate limiting disabled as we can rely on API priority and // fairness. Set its QPS to a value equal or bigger than 0 to re-enable it. // // Will log an error and exit if there is an error creating the rest.Config. @@ -117,7 +117,7 @@ var ( // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running // in cluster and use the cluster provided kubeconfig. // - // The returned `*rest.Config` has client-side ratelimting disabled as we can rely on API priority and + // The returned `*rest.Config` has client-side rate limiting disabled as we can rely on API priority and // fairness. Set its QPS to a value equal or bigger than 0 to re-enable it. // // Config precedence diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go index 2a6a6c6be0..73026259b7 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go @@ -17,7 +17,6 @@ limitations under the License. package cache import ( - "context" "fmt" "maps" "net/http" @@ -36,6 +35,7 @@ import ( toolscache "k8s.io/client-go/tools/cache" "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" "sigs.k8s.io/controller-runtime/pkg/cache/internal" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" @@ -46,17 +46,15 @@ var ( ) // InformerGetOptions defines the behavior of how informers are retrieved. -type InformerGetOptions internal.GetOptions +type InformerGetOptions = cacheapi.InformerGetOptions // InformerGetOption defines an option that alters the behavior of how informers are retrieved. -type InformerGetOption func(*InformerGetOptions) +type InformerGetOption = cacheapi.InformerGetOption // BlockUntilSynced determines whether a get request for an informer should block // until the informer's cache has synced. func BlockUntilSynced(shouldBlock bool) InformerGetOption { - return func(opts *InformerGetOptions) { - opts.BlockUntilSynced = &shouldBlock - } + return cacheapi.BlockUntilSynced(shouldBlock) } // Cache knows how to load Kubernetes objects, fetch informers to request @@ -73,67 +71,10 @@ type Cache interface { // Informers knows how to create or fetch informers for different // group-version-kinds, and add indices to those informers. It's safe to call // GetInformer from multiple threads. -type Informers interface { - // GetInformer fetches or constructs an informer for the given object that corresponds to a single - // API kind and resource. - GetInformer(ctx context.Context, obj client.Object, opts ...InformerGetOption) (Informer, error) - - // GetInformerForKind is similar to GetInformer, except that it takes a group-version-kind, instead - // of the underlying object. - GetInformerForKind(ctx context.Context, gvk schema.GroupVersionKind, opts ...InformerGetOption) (Informer, error) - - // RemoveInformer removes an informer entry and stops it if it was running. - RemoveInformer(ctx context.Context, obj client.Object) error - - // Start runs all the informers known to this cache until the context is closed. - // It blocks. - Start(ctx context.Context) error - - // WaitForCacheSync waits for all the caches to sync. Returns false if it could not sync a cache. - WaitForCacheSync(ctx context.Context) bool - - // FieldIndexer adds indices to the managed informers. - client.FieldIndexer -} +type Informers = cacheapi.Informers // Informer allows you to interact with the underlying informer. -type Informer interface { - // AddEventHandler adds an event handler to the shared informer using the shared informer's resync - // period. Events to a single handler are delivered sequentially, but there is no coordination - // between different handlers. - // It returns a registration handle for the handler that can be used to remove - // the handler again and an error if the handler cannot be added. - AddEventHandler(handler toolscache.ResourceEventHandler) (toolscache.ResourceEventHandlerRegistration, error) - - // AddEventHandlerWithResyncPeriod adds an event handler to the shared informer using the - // specified resync period. Events to a single handler are delivered sequentially, but there is - // no coordination between different handlers. - // It returns a registration handle for the handler that can be used to remove - // the handler again and an error if the handler cannot be added. - AddEventHandlerWithResyncPeriod(handler toolscache.ResourceEventHandler, resyncPeriod time.Duration) (toolscache.ResourceEventHandlerRegistration, error) - - // AddEventHandlerWithOptions is a variant of AddEventHandlerWithResyncPeriod where - // all optional parameters are passed in as a struct. - AddEventHandlerWithOptions(handler toolscache.ResourceEventHandler, options toolscache.HandlerOptions) (toolscache.ResourceEventHandlerRegistration, error) - - // RemoveEventHandler removes a previously added event handler given by - // its registration handle. - // This function is guaranteed to be idempotent and thread-safe. - RemoveEventHandler(handle toolscache.ResourceEventHandlerRegistration) error - - // AddIndexers adds indexers to this store. It is valid to add indexers - // after an informer was started. - AddIndexers(indexers toolscache.Indexers) error - - // HasSynced return true if the informers underlying store has synced. - HasSynced() bool - - // HasSyncedChecker completes if the informers underlying store has synced. - HasSyncedChecker() toolscache.DoneChecker - - // IsStopped returns true if the informer has been stopped. - IsStopped() bool -} +type Informer = cacheapi.Informer // AllNamespaces should be used as the map key to deliminate namespace settings // that apply to all namespaces that themselves do not have explicit settings. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cacheapi/cacheapi.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cacheapi/cacheapi.go new file mode 100644 index 0000000000..9f3aa62eeb --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cacheapi/cacheapi.go @@ -0,0 +1,153 @@ +/* +Copyright 2026 The Kubernetes 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 cacheapi + +import ( + "context" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + toolscache "k8s.io/client-go/tools/cache" +) + +// InformerGetOptions defines the behavior of how informers are retrieved. +type InformerGetOptions struct { + // BlockUntilSynced controls if the informer retrieval will block until the informer is synced. Defaults to `true`. + BlockUntilSynced *bool +} + +// InformerGetOption defines an option that alters the behavior of how informers are retrieved. +type InformerGetOption func(*InformerGetOptions) + +// BlockUntilSynced determines whether a get request for an informer should block +// until the informer's cache has synced. +func BlockUntilSynced(shouldBlock bool) InformerGetOption { + return func(opts *InformerGetOptions) { + opts.BlockUntilSynced = &shouldBlock + } +} + +// Object is a Kubernetes object, allows functions to work indistinctly with +// any resource that implements both Object interfaces. +// +// Semantically, these are objects which are both serializable (runtime.Object) +// and identifiable (metav1.Object) -- think any object which you could write +// as YAML or JSON, and then `kubectl create`. +// +// Code-wise, this means that any object which embeds both ObjectMeta (which +// provides metav1.Object) and TypeMeta (which provides half of runtime.Object) +// and has a `DeepCopyObject` implementation (the other half of runtime.Object) +// will implement this by default. +// +// For example, nearly all the built-in types are Objects, as well as all +// KubeBuilder-generated CRDs (unless you do something real funky to them). +// +// By and large, most things that implement runtime.Object also implement +// Object -- it's very rare to have *just* a runtime.Object implementation (the +// cases tend to be funky built-in types like Webhook payloads that don't have +// a `metadata` field). +// +// Notice that XYZList types are distinct: they implement ObjectList instead. +type Object interface { + metav1.Object + runtime.Object +} + +// IndexerFunc knows how to take an object and turn it into a series +// of non-namespaced keys. Namespaced objects are automatically given +// namespaced and non-spaced variants, so keys do not need to include namespace. +type IndexerFunc func(Object) []string + +// FieldIndexer knows how to index over a particular "field" such that it +// can later be used by a field selector. +type FieldIndexer interface { + // IndexField adds an index with the given field name on the given object type + // by using the given function to extract the value for that field. If you want + // compatibility with the Kubernetes API server, only return one key, and only use + // fields that the API server supports. Otherwise, you can return multiple keys, + // and "equality" in the field selector means that at least one key matches the value. + // The FieldIndexer will automatically take care of indexing over namespace + // and supporting efficient all-namespace queries. + IndexField(ctx context.Context, obj Object, field string, extractValue IndexerFunc) error +} + +// Informers knows how to create or fetch informers for different +// group-version-kinds, and add indices to those informers. It's safe to call +// GetInformer from multiple threads. +type Informers interface { + // GetInformer fetches or constructs an informer for the given object that corresponds to a single + // API kind and resource. + GetInformer(ctx context.Context, obj Object, opts ...InformerGetOption) (Informer, error) + + // GetInformerForKind is similar to GetInformer, except that it takes a group-version-kind, instead + // of the underlying object. + GetInformerForKind(ctx context.Context, gvk schema.GroupVersionKind, opts ...InformerGetOption) (Informer, error) + + // RemoveInformer removes an informer entry and stops it if it was running. + RemoveInformer(ctx context.Context, obj Object) error + + // Start runs all the informers known to this cache until the context is closed. + // It blocks. + Start(ctx context.Context) error + + // WaitForCacheSync waits for all the caches to sync. Returns false if it could not sync a cache. + WaitForCacheSync(ctx context.Context) bool + + // FieldIndexer adds indices to the managed informers. + FieldIndexer +} + +// Informer allows you to interact with the underlying informer. +type Informer interface { + // AddEventHandler adds an event handler to the shared informer using the shared informer's resync + // period. Events to a single handler are delivered sequentially, but there is no coordination + // between different handlers. + // It returns a registration handle for the handler that can be used to remove + // the handler again and an error if the handler cannot be added. + AddEventHandler(handler toolscache.ResourceEventHandler) (toolscache.ResourceEventHandlerRegistration, error) + + // AddEventHandlerWithResyncPeriod adds an event handler to the shared informer using the + // specified resync period. Events to a single handler are delivered sequentially, but there is + // no coordination between different handlers. + // It returns a registration handle for the handler that can be used to remove + // the handler again and an error if the handler cannot be added. + AddEventHandlerWithResyncPeriod(handler toolscache.ResourceEventHandler, resyncPeriod time.Duration) (toolscache.ResourceEventHandlerRegistration, error) + + // AddEventHandlerWithOptions is a variant of AddEventHandlerWithResyncPeriod where + // all optional parameters are passed in as a struct. + AddEventHandlerWithOptions(handler toolscache.ResourceEventHandler, options toolscache.HandlerOptions) (toolscache.ResourceEventHandlerRegistration, error) + + // RemoveEventHandler removes a previously added event handler given by + // its registration handle. + // This function is guaranteed to be idempotent and thread-safe. + RemoveEventHandler(handle toolscache.ResourceEventHandlerRegistration) error + + // AddIndexers adds indexers to this store. It is valid to add indexers + // after an informer was started. + AddIndexers(indexers toolscache.Indexers) error + + // HasSynced return true if the informers underlying store has synced. + HasSynced() bool + + // HasSyncedChecker completes if the informers underlying store has synced. + HasSyncedChecker() toolscache.DoneChecker + + // IsStopped returns true if the informer has been stopped. + IsStopped() bool +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/delegating_by_gvk_cache.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/delegating_by_gvk_cache.go index adc5d957a4..faeb55454b 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/delegating_by_gvk_cache.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/delegating_by_gvk_cache.go @@ -21,8 +21,8 @@ import ( "maps" "slices" "strings" - "sync" + "golang.org/x/sync/errgroup" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/client" @@ -77,24 +77,15 @@ func (dbt *delegatingByGVKCache) Start(ctx context.Context) error { allCaches := slices.Collect(maps.Values(dbt.caches)) allCaches = append(allCaches, dbt.defaultCache) - wg := &sync.WaitGroup{} - errs := make(chan error) + group, childCtx := errgroup.WithContext(ctx) for idx := range allCaches { cache := allCaches[idx] - wg.Go(func() { - if err := cache.Start(ctx); err != nil { - errs <- err - } + group.Go(func() error { + return cache.Start(childCtx) }) } - select { - case err := <-errs: - return err - case <-ctx.Done(): - wg.Wait() - return nil - } + return ignoreContextCanceled(group.Wait()) } func (dbt *delegatingByGVKCache) WaitForCacheSync(ctx context.Context) bool { diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/informer_cache.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/informer_cache.go index f8a1faa7b9..13ac80e75c 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/informer_cache.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/informer_cache.go @@ -76,6 +76,7 @@ func (ic *informerCache) Get(ctx context.Context, key client.ObjectKey, out clie if !started { return &ErrCacheNotStarted{} } + return cache.Reader.Get(ctx, key, out, opts...) } @@ -137,7 +138,7 @@ func applyGetOptions(opts ...InformerGetOption) *internal.GetOptions { for _, opt := range opts { opt(cfg) } - return (*internal.GetOptions)(cfg) + return cfg } // GetInformerForKind returns the informer for the GroupVersionKind. If no informer exists, one will be started. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/cache_reader.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/cache_reader.go index 624869f590..3c4ea50c97 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/cache_reader.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/cache_reader.go @@ -34,9 +34,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/internal/field/selector" ) -// CacheReader is a client.Reader. -var _ client.Reader = &CacheReader{} - // CacheReader wraps a cache.Index to implement the client.Reader interface for a single type. type CacheReader struct { // indexer is the underlying indexer wrapped by this cache. @@ -55,7 +52,7 @@ type CacheReader struct { } // Get checks the indexer for the object and writes a copy of it if found. -func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Object, opts ...client.GetOption) error { +func (c *CacheReader) Get(ctx context.Context, key client.ObjectKey, out client.Object, opts ...client.GetOption) error { getOpts := client.GetOptions{} getOpts.ApplyOptions(opts) @@ -109,7 +106,7 @@ func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Ob } // List lists items out of the indexer and writes them to out. -func (c *CacheReader) List(_ context.Context, out client.ObjectList, opts ...client.ListOption) error { +func (c *CacheReader) List(ctx context.Context, out client.ObjectList, opts ...client.ListOption) error { var objs []any var err error diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/informers.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/informers.go index 619e36abd3..4724e26e9b 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/informers.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/informers.go @@ -38,6 +38,7 @@ import ( "k8s.io/client-go/metadata" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" logf "sigs.k8s.io/controller-runtime/pkg/internal/log" "sigs.k8s.io/controller-runtime/pkg/internal/syncs" @@ -136,10 +137,7 @@ type tracker struct { // GetOptions provides configuration to customize the behavior when // getting an informer. -type GetOptions struct { - // BlockUntilSynced controls if the informer retrieval will block until the informer is synced. Defaults to `true`. - BlockUntilSynced *bool -} +type GetOptions = cacheapi.InformerGetOptions // Informers create and caches Informers for (runtime.Object, schema.GroupVersionKind) pairs. // It uses a standard parameter codec constructed based on the given generated Scheme. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/multi_namespace_cache.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/multi_namespace_cache.go index 592519c35d..05fdcb8655 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/multi_namespace_cache.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/multi_namespace_cache.go @@ -18,10 +18,12 @@ package cache import ( "context" + "errors" "fmt" "strings" "time" + "golang.org/x/sync/errgroup" corev1 "k8s.io/api/core/v1" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -160,31 +162,34 @@ func (c *multiNamespaceCache) GetInformerForKind(ctx context.Context, gvk schema } func (c *multiNamespaceCache) Start(ctx context.Context) error { - errs := make(chan error) - // start global cache + group, childCtx := errgroup.WithContext(ctx) + if c.clusterCache != nil { - go func() { - err := c.clusterCache.Start(ctx) - if err != nil { - errs <- fmt.Errorf("failed to start cluster-scoped cache: %w", err) - } - }() + clusterCache := c.clusterCache + group.Go(func() error { + return clusterCache.Start(childCtx) + }) } - // start namespaced caches for ns, cache := range c.namespaceToCache { - go func(ns string, cache Cache) { - if err := cache.Start(ctx); err != nil { - errs <- fmt.Errorf("failed to start cache for namespace %s: %w", ns, err) + group.Go(func() error { + if err := cache.Start(childCtx); err != nil { + return fmt.Errorf("failed to start cache for namespace %s: %w", ns, err) } - }(ns, cache) + return nil + }) } - select { - case <-ctx.Done(): + + return ignoreContextCanceled(group.Wait()) +} + +// ignoreContextCanceled returns nil if the error is a context.Canceled error, +// otherwise returns the error unchanged. +func ignoreContextCanceled(err error) error { + if errors.Is(err, context.Canceled) { return nil - case err := <-errs: - return err } + return err } func (c *multiNamespaceCache) WaitForCacheSync(ctx context.Context) bool { diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go index ad946daeaa..4fd3e92f16 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go @@ -23,16 +23,21 @@ import ( "net/http" "strings" + "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/metadata" "k8s.io/client-go/rest" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" + "sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier" "sigs.k8s.io/controller-runtime/pkg/log" ) @@ -71,6 +76,9 @@ type Options struct { // - FieldValidationStrict // For more details, see: https://kubernetes.io/docs/reference/using-api/api-concepts/#field-validation FieldValidation string + + // Log will be used by the client if it encounters any errors. + Log logr.Logger } // CacheOptions are options for creating a cache-backed client. @@ -85,6 +93,26 @@ type CacheOptions struct { // read unstructured objects or lists from the cache. // If false, unstructured objects will always result in a live lookup. Unstructured bool + + // EnableReadYourWritesConsistency controls if read requests against the cache will + // block until the cache observed all write requests that started before the read + // request. Lists will wait for all pending write requests to the gvk the List is for. + // + // The `DisableReadYourWritesConsistency` option can be used to disable this functionality + // for individual requests, both on reads to keep them from waiting and on writes to + // prevent them from blocking subsequent reads. + // + // The blocking is always scoped to the representation (typed, unstructured or + // PartialObjectMetadata), meaning a write only blocks reads of the same representation. + // + // This is an experimental feature, a form of this will be kept but both the details of + // how exactly it works and how exactly it is configured may change. + // + // This feature does not work correctly when a resource has more than one Namespace + // configured. + // + // Defaults to false. + EnableReadYourWritesConsistency *bool } // NewClientFunc allows a user to define how to create a client. @@ -113,9 +141,17 @@ type NewClientFunc func(config *rest.Config, options Options) (Client, error) // corresponding group, version, and kind for the given type. In the // case of unstructured types, the group, version, and kind will be extracted // from the corresponding fields on the object. -func New(config *rest.Config, options Options) (c Client, err error) { - c, err = newClient(config, options) - if err == nil && options.DryRun != nil && *options.DryRun { +func New(config *rest.Config, options Options) (Client, error) { + _, c, err := newClient(config, options) + if err != nil { + return nil, err + } + + return wrapClient(c, options), nil +} + +func wrapClient(c Client, options Options) Client { + if options.DryRun != nil && *options.DryRun { c = NewDryRunClient(c) } if fo := options.FieldOwner; fo != "" { @@ -125,12 +161,12 @@ func New(config *rest.Config, options Options) (c Client, err error) { c = WithFieldValidation(c, FieldValidation(fv)) } - return c, err + return c } -func newClient(config *rest.Config, options Options) (*client, error) { +func newClient(config *rest.Config, options Options) (*client, Client, error) { if config == nil { - return nil, fmt.Errorf("must provide non-nil rest.Config to client.New") + return nil, nil, fmt.Errorf("must provide non-nil rest.Config to client.New") } config = rest.CopyConfig(config) @@ -152,7 +188,7 @@ func newClient(config *rest.Config, options Options) (*client, error) { var err error options.HTTPClient, err = rest.HTTPClientFor(config) if err != nil { - return nil, err + return nil, nil, err } } @@ -166,10 +202,14 @@ func newClient(config *rest.Config, options Options) (*client, error) { var err error options.Mapper, err = apiutil.NewDynamicRESTMapper(config, options.HTTPClient) if err != nil { - return nil, err + return nil, nil, err } } + if options.Log.IsZero() { + options.Log = log.Log.WithName("client") + } + resources := &clientRestResources{ httpClient: options.HTTPClient, config: config, @@ -182,7 +222,7 @@ func newClient(config *rest.Config, options Options) (*client, error) { rawMetaClient, err := metadata.NewForConfigAndClient(metadata.ConfigFor(config), options.HTTPClient) if err != nil { - return nil, fmt.Errorf("unable to construct metadata-only client for use as part of client: %w", err) + return nil, nil, fmt.Errorf("unable to construct metadata-only client for use as part of client: %w", err) } c := &client{ @@ -202,7 +242,7 @@ func newClient(config *rest.Config, options Options) (*client, error) { mapper: options.Mapper, } if options.Cache == nil || options.Cache.Reader == nil { - return c, nil + return c, c, nil } // We want a cache if we're here. @@ -215,11 +255,26 @@ func newClient(config *rest.Config, options Options) (*client, error) { for _, obj := range options.Cache.DisableFor { gvk, err := c.GroupVersionKindFor(obj) if err != nil { - return nil, err + return nil, nil, err } c.uncachedGVKs[gvk] = struct{}{} } - return c, nil + + if !ptr.Deref(options.Cache.EnableReadYourWritesConsistency, false) { + return c, c, nil + } + + informerCache, isCache := options.Cache.Reader.(cacheapi.Informers) + if !isCache { + return nil, nil, fmt.Errorf("cache reader does not implement %T, can not provide ReadYourWritesConsistency", cacheapi.Informers(nil)) + } + + return c, newConsistentClient( + c, + informerCache, + writebarrier.NewWriteBarrier, + options.Log, + ), nil } var _ Client = &client{} @@ -319,11 +374,18 @@ func (c *client) Update(ctx context.Context, obj Object, opts ...UpdateOption) e // Delete implements client.Client. func (c *client) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { + _, err := c.delete(ctx, obj, opts...) + return err +} + +// delete issues a delete call and returns the response or an error. The response +// gets deserialized into an unstructured and is either a metav1.Status if the object +// is gone from storage or the object if it remains, for example because of finalizers. +func (c *client) delete(ctx context.Context, obj Object, opts ...DeleteOption) (*unstructured.Unstructured, error) { switch obj.(type) { case runtime.Unstructured: return c.unstructuredClient.Delete(ctx, obj, opts...) - case *metav1.PartialObjectMetadata: - return c.metadataClient.Delete(ctx, obj, opts...) + // The typed client can also delete PartialObjectMeta default: return c.typedClient.Delete(ctx, obj, opts...) } @@ -542,7 +604,7 @@ func (co *SubResourceCreateOptions) ApplyOptions(opts []SubResourceCreateOption) // ApplyToSubResourceCreate applies the the configuration on the given create options. func (co *SubResourceCreateOptions) ApplyToSubResourceCreate(o *SubResourceCreateOptions) { - co.CreateOptions.ApplyToCreate(&co.CreateOptions) + co.CreateOptions.ApplyToCreate(&o.CreateOptions) } // SubResourcePatchOptions holds all possible configurations for a subresource patch diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/config/config.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/config/config.go index 1c39f4d854..9c7187046f 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/config/config.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/config/config.go @@ -61,7 +61,7 @@ func RegisterFlags(fs *flag.FlagSet) { // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running // in cluster and use the cluster provided kubeconfig. // -// The returned `*rest.Config` has client-side ratelimting disabled as we can rely on API priority and +// The returned `*rest.Config` has client-side rate limiting disabled as we can rely on API priority and // fairness. Set its QPS to a value equal or bigger than 0 to re-enable it. // // Config precedence: @@ -81,7 +81,7 @@ func GetConfig() (*rest.Config, error) { // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running // in cluster and use the cluster provided kubeconfig. // -// The returned `*rest.Config` has client-side ratelimting disabled as we can rely on API priority and +// The returned `*rest.Config` has client-side rate limiting disabled as we can rely on API priority and // fairness. Set its QPS to a value equal or bigger than 0 to re-enable it. // // Config precedence: @@ -169,7 +169,7 @@ func loadConfigWithContext(apiServerURL string, loader clientcmd.ClientConfigLoa // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running // in cluster and use the cluster provided kubeconfig. // -// The returned `*rest.Config` has client-side ratelimting disabled as we can rely on API priority and +// The returned `*rest.Config` has client-side rate limiting disabled as we can rely on API priority and // fairness. Set its QPS to a value equal or bigger than 0 to re-enable it. // // Will log an error and exit if there is an error creating the rest.Config. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/consistency.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/consistency.go new file mode 100644 index 0000000000..70d28a7f5a --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/consistency.go @@ -0,0 +1,565 @@ +/* +Copyright The Kubernetes 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 client + +import ( + "context" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "sync" + "time" + + "github.com/go-logr/logr" + "github.com/prometheus/client_golang/prometheus" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" + "sigs.k8s.io/controller-runtime/pkg/client/apiutil" + "sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler" + "sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier" + crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" +) + +var ( + consistencyClientWaitDuration = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "controller_runtime_client_consistency_wait_duration_seconds", + Help: "Length of time waiting for the cache to observe writes before serving reads.", + Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10}, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, + }, + []string{"operation", "result"}, + ) +) + +func init() { + crmetrics.Registry.MustRegister( + consistencyClientWaitDuration, + ) +} + +type consistentClientUpstream interface { + Client + + delete(ctx context.Context, obj Object, opts ...DeleteOption) (*unstructured.Unstructured, error) +} + +var _ Client = (*consistentClient)(nil) + +func newConsistentClient( + upstream consistentClientUpstream, + informers cacheapi.Informers, + newWriteBarrier func() writebarrier.WriteBarrier, + log logr.Logger, +) *consistentClient { + return &consistentClient{ + upstream: upstream, + informers: informers, + writeBarriers: newThreadSafeMap[gvkAndRepresentation](func() writebarrier.WriteBarriers { + return writebarrier.NewWriteBarriers(newWriteBarrier) + }), + consistencyHandlers: newThreadSafeMap[gvkAndRepresentation](func() *consistencyhandler.ConsistencyHandler { + return consistencyhandler.NewHandler(log) + }), + } +} + +type consistentClient struct { + upstream consistentClientUpstream + informers cacheapi.Informers + + writeBarriers *threadSafeMap[gvkAndRepresentation, writebarrier.WriteBarriers] + + consistencyHandlers *threadSafeMap[gvkAndRepresentation, *consistencyhandler.ConsistencyHandler] +} + +type gvkAndRepresentation struct { + gvk schema.GroupVersionKind + representation representationID +} + +func representationIDForObj(obj any) representationID { + switch obj.(type) { + case *unstructured.Unstructured, *unstructured.UnstructuredList: + return representationIDUnstructured + case *metav1.PartialObjectMetadata, *metav1.PartialObjectMetadataList: + return representationIDPartialObjectMetadata + default: + return representationIDTyped + } +} + +type representationID int8 + +const ( + representationIDUnstructured representationID = iota + representationIDPartialObjectMetadata + representationIDTyped +) + +func (c *consistentClient) getConsistencyHandler( + ctx context.Context, + gvkAndRepresentation gvkAndRepresentation, + obj Object, +) (*consistencyhandler.ConsistencyHandler, error) { + h := c.consistencyHandlers.getOrCreate(gvkAndRepresentation) + if h.Registered() { + return h, nil + } + + informer, err := c.informers.GetInformer(ctx, obj, cacheapi.BlockUntilSynced(true)) + if err != nil { + return nil, fmt.Errorf("failed to get informer for GVK %s: %w", gvkAndRepresentation.gvk, err) + } + + if err := h.Register(ctx, informer); err != nil { + return nil, fmt.Errorf("failed to register consistency handler on informer for GVK %s: %w", gvkAndRepresentation.gvk, err) + } + return h, nil +} + +const consistencyClientWaitDurationResultSuccess = "success" + +func consistencyClientWaitDurationResult(err error) string { + switch { + case errors.Is(err, context.DeadlineExceeded): + return "timeout" + case err != nil: + return "error" + default: + return consistencyClientWaitDurationResultSuccess + } +} + +func (c *consistentClient) Get(ctx context.Context, key ObjectKey, obj Object, opts ...GetOption) (err error) { + if (&GetOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency { + return c.upstream.Get(ctx, key, obj, opts...) + } + + start := time.Now() + var waitDuration time.Duration + var result string + defer func() { + if waitDuration == 0 { + waitDuration = time.Since(start) + } + if result == "" { + result = consistencyClientWaitDurationResult(err) + } + consistencyClientWaitDuration. + WithLabelValues("get", result). + Observe(waitDuration.Seconds()) + }() + + gvk, err := apiutil.GVKForObject(obj, c.upstream.Scheme()) + if err != nil { + return fmt.Errorf("failed to get GVK for object %T: %w", obj, err) + } + gvkAndRepresentation := gvkAndRepresentation{gvk: gvk, representation: representationIDForObj(obj)} + + select { + case <-c.writeBarriers.getOrCreate(gvkAndRepresentation).Seal(key): + case <-ctx.Done(): + return ctx.Err() + } + + h, err := c.getConsistencyHandler(ctx, gvkAndRepresentation, obj) + if err != nil { + return err + } + if err := h.WaitForGet(ctx, key); err != nil { + return fmt.Errorf("failed to wait for cache to catch up: %w", err) + } + + waitDuration = time.Since(start) + result = consistencyClientWaitDurationResultSuccess + return c.upstream.Get(ctx, key, obj, opts...) +} + +func (c *consistentClient) List(ctx context.Context, list ObjectList, opts ...ListOption) (err error) { + if (&ListOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency { + return c.upstream.List(ctx, list, opts...) + } + + start := time.Now() + var waitDuration time.Duration + var result string + defer func() { + if waitDuration == 0 { + waitDuration = time.Since(start) + } + if result == "" { + result = consistencyClientWaitDurationResult(err) + } + consistencyClientWaitDuration. + WithLabelValues("list", result). + Observe(waitDuration.Seconds()) + }() + + gvk, err := apiutil.GVKForObject(list, c.upstream.Scheme()) + if err != nil { + return fmt.Errorf("failed to get GVK for list %T: %w", list, err) + } + gvk.Kind = strings.TrimSuffix(gvk.Kind, "List") + gvkAndRepresentation := gvkAndRepresentation{gvk: gvk, representation: representationIDForObj(list)} + + for _, s := range c.writeBarriers.getOrCreate(gvkAndRepresentation).SealAll() { + select { + case <-s: + case <-ctx.Done(): + return ctx.Err() + } + } + + var obj Object + switch gvkAndRepresentation.representation { + case representationIDUnstructured: + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(gvk) + obj = u + case representationIDPartialObjectMetadata: + m := &metav1.PartialObjectMetadata{} + m.SetGroupVersionKind(gvk) + obj = m + case representationIDTyped: + raw, err := c.upstream.Scheme().New(gvk) + if err != nil { + return fmt.Errorf("failed to create object for GVK %s: %w", gvk, err) + } + asserted, ok := raw.(Object) + if !ok { + return fmt.Errorf("object of type %T for GVK %s does not implement Object", raw, gvk) + } + obj = asserted + } + + h, err := c.getConsistencyHandler(ctx, gvkAndRepresentation, obj) + if err != nil { + return err + } + if err := h.WaitForList(ctx); err != nil { + return fmt.Errorf("failed to wait for cache to catch up: %w", err) + } + + waitDuration = time.Since(start) + result = consistencyClientWaitDurationResultSuccess + return c.upstream.List(ctx, list, opts...) +} + +func (c *consistentClient) Create(ctx context.Context, obj Object, opts ...CreateOption) error { + return c.writeAndRecordRV(ctx, obj, (&CreateOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Create(ctx, obj, opts...) + }) +} + +func (c *consistentClient) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { + return c.writeAndRecordRV(ctx, obj, (&UpdateOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Update(ctx, obj, opts...) + }) +} + +func (c *consistentClient) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { + return c.writeAndRecordRV(ctx, obj, (&PatchOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Patch(ctx, obj, patch, opts...) + }) +} + +func (c *consistentClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error { + return c.writeAndRecordRV(ctx, obj, (&ApplyOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Apply(ctx, obj, opts...) + }) +} + +func writeTargetFor(obj any, scheme *runtime.Scheme) (gvkAndRepresentation, types.NamespacedName, Object, func() (string, error), error) { + switch t := obj.(type) { + case *unstructuredApplyConfiguration: + return gvkAndRepresentation{gvk: t.Unstructured.GroupVersionKind(), representation: representationIDUnstructured}, + ObjectKeyFromObject(t), + t.Unstructured, + func() (string, error) { return t.Unstructured.GetResourceVersion(), nil }, + nil + case applyConfiguration: + gvk, err := gvkFromApplyConfiguration(t) + if err != nil { + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("failed to get GVK for apply configuration %T: %w", obj, err) + } + cacheObj, err := scheme.New(gvk) + if err != nil { + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("failed to create object for GVK %s: %w", gvk, err) + } + clientObj, ok := cacheObj.(Object) + if !ok { + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("object of type %T for GVK %s does not implement client.Object", cacheObj, gvk) + } + clientObj.SetName(ptr.Deref(t.GetName(), "")) + clientObj.SetNamespace(ptr.Deref(t.GetNamespace(), "")) + return gvkAndRepresentation{gvk: gvk, representation: representationIDTyped}, + ObjectKeyFromObject(clientObj), + clientObj, + func() (string, error) { return resourceVersionFromApplyConfiguration(t) }, + nil + case *metav1.PartialObjectMetadata: + return gvkAndRepresentation{gvk: t.GroupVersionKind(), representation: representationIDPartialObjectMetadata}, + ObjectKeyFromObject(t), + t, + func() (string, error) { return t.GetResourceVersion(), nil }, + nil + case Object: + gvk, err := apiutil.GVKForObject(t, scheme) + if err != nil { + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("failed to get GVK for object %T: %w", obj, err) + } + return gvkAndRepresentation{gvk: gvk, representation: representationIDTyped}, + ObjectKeyFromObject(t), + t, + func() (string, error) { return t.GetResourceVersion(), nil }, + nil + default: + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("unsupported type %T, must be either %T, %T or %T", obj, Object(nil), &unstructuredApplyConfiguration{}, applyConfiguration(nil)) + } +} + +func (c *consistentClient) writeAndRecordRV(ctx context.Context, obj any, disableConsistency bool, write func() error) error { + if disableConsistency { + return write() + } + + gvkAndRepresentation, namespacedName, cacheObj, getResourceVersion, err := writeTargetFor(obj, c.upstream.Scheme()) + if err != nil { + return err + } + + // We don't technically need an informer since the RV is monotonically increasing, but we want to fail + // ASAP if the cache can not be setup. + h, err := c.getConsistencyHandler(ctx, gvkAndRepresentation, cacheObj) + if err != nil { + return err + } + + release := c.writeBarriers.getOrCreate(gvkAndRepresentation).Begin(namespacedName) + defer release() + + if err := write(); err != nil { + return err + } + + rvRaw, err := getResourceVersion() + if err != nil { + return fmt.Errorf("failed to get resource version from %T: %w", obj, err) + } + rv, err := strconv.ParseInt(rvRaw, 10, 64) + if err != nil { + return fmt.Errorf("failed to parse resource version %s: %w", rvRaw, err) + } + + h.SetMinimumRV(ObjectKeyFromObject(cacheObj), rv) + + return nil +} + +func resourceVersionFromApplyConfiguration(obj applyConfiguration) (string, error) { + v := reflect.ValueOf(obj) + for v.Kind() == reflect.Pointer { + v = v.Elem() + } + if v.Kind() != reflect.Struct { + return "", fmt.Errorf("expected struct, got %s", v.Kind()) + } + rv := v.FieldByName("ResourceVersion") + if !rv.IsValid() { + return "", fmt.Errorf("type %T has no ResourceVersion field", obj) + } + if rv.Kind() != reflect.Pointer || rv.Type().Elem().Kind() != reflect.String { + return "", fmt.Errorf("ResourceVersion field in %T is not *string", obj) + } + if rv.IsNil() { + return "", fmt.Errorf("ResourceVersion field in %T is nil", obj) + } + return rv.Elem().String(), nil +} + +func (c *consistentClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { + if (&DeleteOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency { + return c.upstream.Delete(ctx, obj, opts...) + } + + gvk, err := apiutil.GVKForObject(obj, c.upstream.Scheme()) + if err != nil { + return fmt.Errorf("failed to get GVK for object %v: %w", obj, err) + } + + gvkAndRepresentation := gvkAndRepresentation{gvk: gvk, representation: representationIDForObj(obj)} + h, err := c.getConsistencyHandler(ctx, gvkAndRepresentation, obj) + if err != nil { + return err + } + + namespacedName := ObjectKeyFromObject(obj) + uid, err := c.uidForDelete(ctx, gvk, namespacedName, obj, opts...) + if err != nil { + return err + } + + release := c.writeBarriers.getOrCreate(gvkAndRepresentation).Begin(namespacedName) + defer release() + + // Register the delete before we execute it, otherwise it may be in the cache + // before we register it, causing a deadlock. + h.AddPendingDelete(namespacedName, uid) + + response, err := c.upstream.delete(ctx, obj, opts...) + if err != nil { + h.RemovePendingDelete(namespacedName, uid) + return err + } + + // Prefer waiting for the RV rather than an actual event since that is likely to be more resilient. + // This can only work if the response contains the RV which in turn only happens if the request did + // not delete the object from storage, for example because it had a finalizer. + if rvRaw := response.GetResourceVersion(); rvRaw != "" { + rv, err := strconv.ParseInt(rvRaw, 10, 64) + if err != nil { + return fmt.Errorf("failed to parse resource version %s: %w", rvRaw, err) + } + h.RemovePendingDelete(namespacedName, uid) + h.SetMinimumRV(namespacedName, rv) + } + + return nil +} + +func (c *consistentClient) uidForDelete(ctx context.Context, gvk schema.GroupVersionKind, key ObjectKey, obj Object, opts ...DeleteOption) (types.UID, error) { + deleteOptions := (&DeleteOptions{}).ApplyOptions(opts) + if p := deleteOptions.Preconditions; p != nil && ptr.Deref(p.UID, "") != "" { + return *p.UID, nil + } + + if uid := obj.GetUID(); uid != "" { + return uid, nil + } + + existing, ok := obj.DeepCopyObject().(Object) + if !ok { + return "", fmt.Errorf("deepcopy of %T does not implement client.Object", obj) + } + if err := c.upstream.Get(ctx, key, existing); err != nil { + return "", fmt.Errorf("failed to get %s %s to determine its uid: %w", gvk.Kind, key, err) + } + + return existing.GetUID(), nil +} + +func (c *consistentClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { + return errors.New("DeleteAllOf is not supported by consistentClient, please use List and Delete instead") +} + +func (c *consistentClient) Status() SubResourceWriter { + return c.SubResource("status") +} + +func (c *consistentClient) Scheme() *runtime.Scheme { + return c.upstream.Scheme() +} + +func (c *consistentClient) RESTMapper() meta.RESTMapper { + return c.upstream.RESTMapper() +} + +func (c *consistentClient) GroupVersionKindFor(obj runtime.Object) (schema.GroupVersionKind, error) { + return c.upstream.GroupVersionKindFor(obj) +} + +func (c *consistentClient) IsObjectNamespaced(obj runtime.Object) (bool, error) { + return c.upstream.IsObjectNamespaced(obj) +} + +func (c *consistentClient) SubResource(subResource string) SubResourceClient { + return &consistentSubResourceClient{ + writeAndRecordRV: c.writeAndRecordRV, + upstream: c.upstream.SubResource(subResource), + } +} + +type consistentSubResourceClient struct { + writeAndRecordRV func(ctx context.Context, obj any, disableConsistency bool, write func() error) error + upstream SubResourceClient +} + +func (c *consistentSubResourceClient) Get(ctx context.Context, obj, subResource Object, opts ...SubResourceGetOption) error { + return c.upstream.Get(ctx, obj, subResource, opts...) +} + +// Create is excluded from read-your-writes consistency, because it either returns a +// status with no RV (pod/eviction, pod/binding) or a virtual resource that is not +// persisted (serviceaccount/token). +func (c *consistentSubResourceClient) Create(ctx context.Context, obj, subResource Object, opts ...SubResourceCreateOption) error { + return c.upstream.Create(ctx, obj, subResource, opts...) +} + +func (c *consistentSubResourceClient) Update(ctx context.Context, obj Object, opts ...SubResourceUpdateOption) error { + return c.writeAndRecordRV(ctx, obj, (&SubResourceUpdateOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Update(ctx, obj, opts...) + }) +} + +func (c *consistentSubResourceClient) Patch(ctx context.Context, obj Object, patch Patch, opts ...SubResourcePatchOption) error { + return c.writeAndRecordRV(ctx, obj, (&SubResourcePatchOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Patch(ctx, obj, patch, opts...) + }) +} + +func (c *consistentSubResourceClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...SubResourceApplyOption) error { + return c.writeAndRecordRV(ctx, obj, (&SubResourceApplyOptions{}).ApplyOpts(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Apply(ctx, obj, opts...) + }) +} + +func newThreadSafeMap[k comparable, v any](newValue func() v) *threadSafeMap[k, v] { + return &threadSafeMap[k, v]{ + data: map[k]v{}, + newValue: newValue, + } +} + +type threadSafeMap[k comparable, v any] struct { + lock sync.Mutex + data map[k]v + newValue func() v +} + +func (t *threadSafeMap[k, v]) getOrCreate(key k) v { + t.lock.Lock() + defer t.lock.Unlock() + + val, exists := t.data[key] + if !exists { + val = t.newValue() + t.data[key] = val + } + + return val +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/client.go index accf917cab..995d94780f 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/client.go @@ -24,6 +24,7 @@ import ( "slices" "strings" "sync" + "sync/atomic" "time" /* @@ -130,6 +131,7 @@ type ClientBuilder struct { interceptorFuncs *interceptor.Funcs typeConverters []managedfields.TypeConverter returnManagedFields bool + globalRVCounter bool isBuilt bool // indexes maps each GroupVersionKind (GVK) to the indexes registered for that GVK. @@ -179,6 +181,15 @@ func (f *ClientBuilder) WithObjectTracker(ot testing.ObjectTracker) *ClientBuild return f } +// WithGlobalResourceVersionCounter makes the client use a global counter for resourceVersions +// rather than tracking them per object, mimicking what the apiserver does. +// +// Disabled by default. +func (f *ClientBuilder) WithGlobalResourceVersionCounter() *ClientBuilder { + f.globalRVCounter = true + return f +} + // WithIndex can be optionally used to register an index with name `field` and indexer `extractValue` // for API objects of the same GroupVersionKind (GVK) as `obj` in the fake client. // It can be invoked multiple times, both with objects of the same GVK or different ones. @@ -307,6 +318,9 @@ func (f *ClientBuilder) Build() client.WithWatch { withStatusSubresource: withStatusSubResource, usesFieldManagedObjectTracker: usesFieldManagedObjectTracker, } + if f.globalRVCounter { + tracker.resourceVersionCounter = &atomic.Uint64{} + } for _, obj := range f.initObject { if err := tracker.Add(obj); err != nil { @@ -343,14 +357,15 @@ func (f *ClientBuilder) Build() client.WithWatch { const trackerAddResourceVersion = "999" -// convertFromUnstructuredIfNecessary will convert runtime.Unstructured for a GVK that is recognized -// by the schema into the whatever the schema produces with New() for said GVK. +// convertFromUnstructuredOrPartialObjectMetaIfNecessary will convert runtime.Unstructured or metav1.PartialObjectMetadata +// for a GVK that is recognized by the schema into the whatever the schema produces with New() for said GVK. // This is required because the tracker unconditionally saves on manipulations, but its List() implementation // tries to assign whatever it finds into a ListType it gets from schema.New() - Thus we have to ensure // we save as the very same type, otherwise subsequent List requests will fail. -func convertFromUnstructuredIfNecessary(s *runtime.Scheme, o runtime.Object) (runtime.Object, error) { - u, isUnstructured := o.(runtime.Unstructured) - if !isUnstructured { +func convertFromUnstructuredOrPartialObjectMetaIfNecessary(s *runtime.Scheme, o runtime.Object) (runtime.Object, error) { + _, isUnstructured := o.(runtime.Unstructured) + _, isPartial := o.(*metav1.PartialObjectMetadata) + if !isUnstructured && !isPartial { return o, nil } gvk := o.GetObjectKind().GroupVersionKind() @@ -362,16 +377,17 @@ func convertFromUnstructuredIfNecessary(s *runtime.Scheme, o runtime.Object) (ru if err != nil { return nil, fmt.Errorf("scheme recognizes %s but failed to produce an object for it: %w", gvk, err) } - if _, isTypedUnstructured := typed.(runtime.Unstructured); isTypedUnstructured { + switch typed.(type) { + case runtime.Unstructured, *metav1.PartialObjectMetadata: return o, nil } - unstructuredSerialized, err := json.Marshal(u) + serialized, err := json.Marshal(o) if err != nil { - return nil, fmt.Errorf("failed to serialize %T: %w", unstructuredSerialized, err) + return nil, fmt.Errorf("failed to serialize %T: %w", o, err) } - if err := json.Unmarshal(unstructuredSerialized, typed); err != nil { - return nil, fmt.Errorf("failed to unmarshal the content of %T into %T: %w", u, typed, err) + if err := json.Unmarshal(serialized, typed); err != nil { + return nil, fmt.Errorf("failed to unmarshal the content of %T into %T: %w", o, typed, err) } return typed, nil @@ -812,12 +828,19 @@ func (c *fakeClient) update(obj client.Object, isStatus bool, opts ...client.Upd c.trackerWriteLock.Lock() defer c.trackerWriteLock.Unlock() - // Retain managed fields + // Retain the current managed fields when the incoming object leaves them + // unset (nil), mirroring apimachinery fieldmanager: a non-nil empty + // slice is treated as an explicit clear. Always retain on status + // updates, as managed fields can only be modified through the main + // resource: this is for example used by the csaupgrade package in + // client-go to migrate objects from client-side to server-side apply. // We can ignore all errors here since update will fail if we encounter an error. - obj.SetManagedFields(nil) - current, _ := c.tracker.Get(gvr, accessor.GetNamespace(), accessor.GetName()) - if currentMetaObj, ok := current.(metav1.Object); ok { - obj.SetManagedFields(currentMetaObj.GetManagedFields()) + if isStatus || obj.GetManagedFields() == nil { + obj.SetManagedFields(nil) + current, _ := c.tracker.Get(gvr, accessor.GetNamespace(), accessor.GetName()) + if currentMetaObj, ok := current.(metav1.Object); ok { + obj.SetManagedFields(currentMetaObj.GetManagedFields()) + } } if err := c.tracker.update(gvr, obj, accessor.GetNamespace(), isStatus, false, *updateOptions.AsUpdateOptions()); err != nil { @@ -858,7 +881,11 @@ func (c *fakeClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, return err } - acJSON, err := json.Marshal(u) + return copyIntoApplyConfiguration(u, obj) +} + +func copyIntoApplyConfiguration(from any, obj runtime.ApplyConfiguration) error { + acJSON, err := json.Marshal(from) if err != nil { return fmt.Errorf("failed to marshal patched object: %w", err) } @@ -942,7 +969,11 @@ func (c *fakeClient) patch(obj client.Object, patch client.Patch, opts ...client if isApplyCreate { // Overwrite it unconditionally, this matches the apiserver behavior // which allows to set it on create, but will then ignore it. - obj.SetResourceVersion("1") + if c.tracker.resourceVersionCounter != nil { + obj.SetResourceVersion(c.tracker.nextResourceVersion()) + } else { + obj.SetResourceVersion("1") + } } else { // SSA deletionTimestamp updates are silently ignored obj.SetDeletionTimestamp(oldAccessor.GetDeletionTimestamp()) @@ -1331,10 +1362,6 @@ func (sw *fakeSubResourceClient) statusPatch(body client.Object, patch client.Pa } func (sw *fakeSubResourceClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...client.SubResourceApplyOption) error { - if sw.subResource != "status" { - return errors.New("fakeSubResourceClient currently only supports Apply for status subresource") - } - applyOpts := &client.SubResourceApplyOptions{} applyOpts.ApplyOpts(opts) @@ -1348,27 +1375,80 @@ func (sw *fakeSubResourceClient) Apply(ctx context.Context, obj runtime.ApplyCon return fmt.Errorf("failed to unmarshal apply configuration: %w", err) } - patchOpts := &client.SubResourcePatchOptions{} - patchOpts.Raw = applyOpts.AsPatchOptions() - - if applyOpts.SubResourceBody != nil { + switch sw.subResource { + case subResourceScale: + if applyOpts.SubResourceBody == nil { + return apierrors.NewBadRequest("missing SubResourceBody") + } subResourceBodySerialized, err := json.Marshal(applyOpts.SubResourceBody) if err != nil { return fmt.Errorf("failed to serialize subresource body: %w", err) } - subResourceBody := &unstructured.Unstructured{} - if err := json.Unmarshal(subResourceBodySerialized, subResourceBody); err != nil { + scale := &autoscalingv1.Scale{} + if err := json.Unmarshal(subResourceBodySerialized, scale); err != nil { return fmt.Errorf("failed to unmarshal subresource body: %w", err) } - patchOpts.SubResourceBody = subResourceBody - } - return sw.Patch(ctx, u, &fakeApplyPatch{}, patchOpts) + sw.client.schemeLock.RLock() + target, err := sw.client.scheme.New(u.GroupVersionKind()) + sw.client.schemeLock.RUnlock() + if err != nil { + return err + } + targetObj, isObject := target.(client.Object) + if !isObject { + return fmt.Errorf("%T is not a client.Object", target) + } + + if err := sw.client.Get(ctx, client.ObjectKeyFromObject(u), targetObj); err != nil { + return err + } + if err := applyScale(targetObj, scale); err != nil { + return err + } + if err := sw.client.update(targetObj, false, &client.UpdateOptions{FieldManager: applyOpts.FieldManager}); err != nil { + return err + } + + content, err := runtime.DefaultUnstructuredConverter.ToUnstructured(targetObj) + if err != nil { + return fmt.Errorf("failed to convert %T to unstructured: %w", targetObj, err) + } + result := &unstructured.Unstructured{Object: content} + result.SetGroupVersionKind(u.GroupVersionKind()) + + return copyIntoApplyConfiguration(result, obj) + case "status": + patchOpts := &client.SubResourcePatchOptions{} + patchOpts.Raw = applyOpts.AsPatchOptions() + + result := u + if applyOpts.SubResourceBody != nil { + subResourceBodySerialized, err := json.Marshal(applyOpts.SubResourceBody) + if err != nil { + return fmt.Errorf("failed to serialize subresource body: %w", err) + } + subResourceBody := &unstructured.Unstructured{} + if err := json.Unmarshal(subResourceBodySerialized, subResourceBody); err != nil { + return fmt.Errorf("failed to unmarshal subresource body: %w", err) + } + patchOpts.SubResourceBody = subResourceBody + result = subResourceBody + } + + if err := sw.Patch(ctx, u, &fakeApplyPatch{}, patchOpts); err != nil { + return err + } + + return copyIntoApplyConfiguration(result, obj) + default: + return errors.New("fakeSubResourceClient currently only supports Apply for status and scale subresource") + } } func allowsUnconditionalUpdate(gvk schema.GroupVersionKind) bool { switch gvk.Group { - case "apps": + case "apps": //nolint:goconst switch gvk.Kind { case "ControllerRevision", "DaemonSet", "Deployment", "ReplicaSet", "StatefulSet": return true @@ -1526,6 +1606,24 @@ func getSingleOrZeroOptions[T any](opts []T) (opt T, err error) { func extractScale(obj client.Object) (*autoscalingv1.Scale, error) { switch obj := obj.(type) { + case *unstructured.Unstructured: + var typed client.Object + switch obj.GroupVersionKind() { + case appsv1.SchemeGroupVersion.WithKind("Deployment"): + typed = &appsv1.Deployment{} + case appsv1.SchemeGroupVersion.WithKind("ReplicaSet"): + typed = &appsv1.ReplicaSet{} + case appsv1.SchemeGroupVersion.WithKind("StatefulSet"): + typed = &appsv1.StatefulSet{} + case corev1.SchemeGroupVersion.WithKind("ReplicationController"): + typed = &corev1.ReplicationController{} + default: + return nil, fmt.Errorf("scale subresource for resource %T is not implemented", obj) + } + if err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, typed); err != nil { + return nil, err + } + return extractScale(typed) case *appsv1.Deployment: var replicas int32 = 1 if obj.Spec.Replicas != nil { @@ -1630,6 +1728,16 @@ func extractScale(obj client.Object) (*autoscalingv1.Scale, error) { func applyScale(obj client.Object, scale *autoscalingv1.Scale) error { switch obj := obj.(type) { + case *unstructured.Unstructured: + switch obj.GroupVersionKind() { + case appsv1.SchemeGroupVersion.WithKind("Deployment"), + appsv1.SchemeGroupVersion.WithKind("ReplicaSet"), + appsv1.SchemeGroupVersion.WithKind("StatefulSet"), + corev1.SchemeGroupVersion.WithKind("ReplicationController"): + return unstructured.SetNestedField(obj.Object, int64(scale.Spec.Replicas), "spec", "replicas") + default: + return fmt.Errorf("scale subresource for resource %T is not implemented", obj) + } case *appsv1.Deployment: obj.Spec.Replicas = new(scale.Spec.Replicas) case *appsv1.ReplicaSet: @@ -1645,12 +1753,13 @@ func applyScale(obj client.Object, scale *autoscalingv1.Scale) error { return nil } -// AddIndex adds an index to a fake client. It will panic if used with a client that is not a fake client. +// AddIndex adds an index to a fake client. It will panic if used with a client that is not a fake client, +// or a wrapper around one, such as the client returned by ClientBuilder.WithInterceptorFuncs. // It will error if there is already an index for given object with the same name as field. // // It can be used to test code that adds indexes to the cache at runtime. func AddIndex(c client.Client, obj runtime.Object, field string, extractValue client.IndexerFunc) error { - fakeClient, isFakeClient := c.(*fakeClient) + fakeClient, isFakeClient := unwrapFakeClient(c) if !isFakeClient { panic("AddIndex can only be used with a fake client") } @@ -1679,6 +1788,21 @@ func AddIndex(c client.Client, obj runtime.Object, field string, extractValue cl return nil } +// unwrapFakeClient returns the *fakeClient backing c, unwrapping any clients that wrap it, such as the +// interceptor client returned by ClientBuilder.WithInterceptorFuncs. +func unwrapFakeClient(c client.Client) (*fakeClient, bool) { + for { + if fc, ok := c.(*fakeClient); ok { + return fc, true + } + unwrapper, ok := c.(interface{ Unwrap() client.WithWatch }) + if !ok { + return nil, false + } + c = unwrapper.Unwrap() + } +} + func (c *fakeClient) addToSchemeIfUnknownAndUnstructuredOrPartial(obj runtime.Object) error { c.schemeLock.Lock() defer c.schemeLock.Unlock() diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/versioned_tracker.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/versioned_tracker.go index 62ccac2bec..ef615cf23e 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/versioned_tracker.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/versioned_tracker.go @@ -22,6 +22,7 @@ import ( "fmt" "runtime/debug" "strconv" + "sync/atomic" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" @@ -44,6 +45,12 @@ type versionedTracker struct { scheme *runtime.Scheme withStatusSubresource sets.Set[schema.GroupVersionKind] usesFieldManagedObjectTracker bool + + resourceVersionCounter *atomic.Uint64 +} + +func (t versionedTracker) nextResourceVersion() string { + return strconv.FormatUint(t.resourceVersionCounter.Add(1), 10) } func (t versionedTracker) Add(obj runtime.Object) error { @@ -66,14 +73,18 @@ func (t versionedTracker) Add(obj runtime.Object) error { return fmt.Errorf("refusing to create obj %s with metadata.deletionTimestamp but no finalizers", accessor.GetName()) } if accessor.GetResourceVersion() == "" { - // We use a "magic" value of 999 here because this field - // is parsed as uint and and 0 is already used in Update. - // As we can't go lower, go very high instead so this can - // be recognized - accessor.SetResourceVersion(trackerAddResourceVersion) + if t.resourceVersionCounter != nil { + accessor.SetResourceVersion(t.nextResourceVersion()) + } else { + // We use a "magic" value of 999 here because this field + // is parsed as uint and and 0 is already used in Update. + // As we can't go lower, go very high instead so this can + // be recognized + accessor.SetResourceVersion(trackerAddResourceVersion) + } } - obj, err = convertFromUnstructuredIfNecessary(t.scheme, obj) + obj, err = convertFromUnstructuredOrPartialObjectMetaIfNecessary(t.scheme, obj) if err != nil { return err } @@ -87,6 +98,18 @@ func (t versionedTracker) Add(obj runtime.Object) error { return fmt.Errorf("invalid managedFields on %T: %w", obj, err) } } + // The trackers add panics when using PartialObjectMetadata without registering it to + // the scheme. + if _, isPartial := obj.(*metav1.PartialObjectMetadata); isPartial { + gvk, err := apiutil.GVKForObject(obj, t.scheme) + if err != nil { + return fmt.Errorf("failed to get gvk for %T: %w", obj, err) + } + if !t.scheme.Recognizes(gvk) { + t.scheme.AddKnownTypeWithName(gvk, obj) + } + } + if err := t.upstream.Add(obj); err != nil { return err } @@ -110,8 +133,12 @@ func (t versionedTracker) Create(gvr schema.GroupVersionResource, obj runtime.Ob if accessor.GetResourceVersion() != "" { return apierrors.NewBadRequest("resourceVersion can not be set for Create requests") } - accessor.SetResourceVersion("1") - obj, err = convertFromUnstructuredIfNecessary(t.scheme, obj) + if t.resourceVersionCounter != nil { + accessor.SetResourceVersion(t.nextResourceVersion()) + } else { + accessor.SetResourceVersion("1") + } + obj, err = convertFromUnstructuredOrPartialObjectMetaIfNecessary(t.scheme, obj) if err != nil { return err } @@ -286,12 +313,16 @@ func (t versionedTracker) updateObject( if oldAccessor.GetResourceVersion() == "" { oldAccessor.SetResourceVersion("0") } - intResourceVersion, err := strconv.ParseUint(oldAccessor.GetResourceVersion(), 10, 64) - if err != nil { - return nil, false, fmt.Errorf("can not convert resourceVersion %q to int: %w", oldAccessor.GetResourceVersion(), err) + if t.resourceVersionCounter != nil { + accessor.SetResourceVersion(t.nextResourceVersion()) + } else { + intResourceVersion, err := strconv.ParseUint(oldAccessor.GetResourceVersion(), 10, 64) + if err != nil { + return nil, false, fmt.Errorf("can not convert resourceVersion %q to int: %w", oldAccessor.GetResourceVersion(), err) + } + intResourceVersion++ + accessor.SetResourceVersion(strconv.FormatUint(intResourceVersion, 10)) } - intResourceVersion++ - accessor.SetResourceVersion(strconv.FormatUint(intResourceVersion, 10)) if !deleting && !deletionTimestampEqual(accessor, oldAccessor) { return nil, false, fmt.Errorf("error: Unable to edit %s: metadata.deletionTimestamp field is immutable", accessor.GetName()) @@ -301,7 +332,7 @@ func (t versionedTracker) updateObject( return nil, false, t.Delete(gvr, accessor.GetNamespace(), accessor.GetName(), metav1.DeleteOptions{DryRun: dryRun}) } - obj, err = convertFromUnstructuredIfNecessary(t.scheme, obj) + obj, err = convertFromUnstructuredOrPartialObjectMetaIfNecessary(t.scheme, obj) return obj, false, err } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/interceptor/intercept.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/interceptor/intercept.go index b98af1a693..5b9751edc0 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/interceptor/intercept.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/interceptor/intercept.go @@ -1,3 +1,19 @@ +/* +Copyright The Kubernetes 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 interceptor import ( @@ -44,6 +60,13 @@ type interceptor struct { var _ client.WithWatch = &interceptor{} +// Unwrap returns the client that is wrapped by this interceptor. This is used by consumers that need to +// access functionality of the wrapped client that is not part of the client.WithWatch interface, such as +// sigs.k8s.io/controller-runtime/pkg/client/fake.AddIndex. +func (c interceptor) Unwrap() client.WithWatch { + return c.client +} + func (c interceptor) GroupVersionKindFor(obj runtime.Object) (schema.GroupVersionKind, error) { return c.client.GroupVersionKindFor(obj) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go index 1af1f3a368..87c6d17ae9 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go @@ -26,6 +26,8 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/watch" + + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" ) // ObjectKey identifies a Kubernetes Object. @@ -194,20 +196,11 @@ type WithWatch interface { // IndexerFunc knows how to take an object and turn it into a series // of non-namespaced keys. Namespaced objects are automatically given // namespaced and non-spaced variants, so keys do not need to include namespace. -type IndexerFunc func(Object) []string +type IndexerFunc = cacheapi.IndexerFunc // FieldIndexer knows how to index over a particular "field" such that it // can later be used by a field selector. -type FieldIndexer interface { - // IndexField adds an index with the given field name on the given object type - // by using the given function to extract the value for that field. If you want - // compatibility with the Kubernetes API server, only return one key, and only use - // fields that the API server supports. Otherwise, you can return multiple keys, - // and "equality" in the field selector means that at least one key matches the value. - // The FieldIndexer will automatically take care of indexing over namespace - // and supporting efficient all-namespace queries. - IndexField(ctx context.Context, obj Object, field string, extractValue IndexerFunc) error -} +type FieldIndexer = cacheapi.FieldIndexer // IgnoreNotFound returns nil on NotFound errors. // All other values that are not NotFound errors or nil are returned unmodified. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler/consistencyhandler.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler/consistencyhandler.go new file mode 100644 index 0000000000..9c247c2df5 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler/consistencyhandler.go @@ -0,0 +1,345 @@ +/* +Copyright The Kubernetes 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 consistencyhandler + +import ( + "context" + "fmt" + "maps" + "strconv" + "sync" + "sync/atomic" + + "github.com/go-logr/logr" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/client-go/tools/cache" + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" +) + +func NewHandler(log logr.Logger) *ConsistencyHandler { + return &ConsistencyHandler{ + rvBroadCaster: &broadcaster{}, + pendingDeletesBroadcaster: &broadcaster{}, + pendingDeletes: make(map[types.NamespacedName]sets.Set[types.UID]), + minimumRVs: make(map[types.NamespacedName]int64), + log: log, + triggerCleanup: make(chan struct{}, 1), + } +} + +type ConsistencyHandler struct { + rvBroadCaster *broadcaster + observedRV atomic.Int64 + + pendingDeletesBroadcaster *broadcaster + pendingDeletesLock sync.RWMutex + // pendingDeletes holds pending deletes. Must only be accessed when holding pendingDeletesLock + pendingDeletes map[types.NamespacedName]sets.Set[types.UID] + + minimumRVsLock sync.RWMutex + // minimumRVs stores the minimum RVs we must have seen before returning reads. Must only be + // accessed when holding minimumRVsLock. + minimumRVs map[types.NamespacedName]int64 + + registerLock sync.RWMutex + registered bool + registration *cache.ResourceEventHandlerRegistration + + log logr.Logger + + // triggerCleanup triggers the cleanup of pendingRVs that are smaller + // than observedRV. It holds a one element buffered channel, because + // having more than one queued cleanup doesn't make sense. + triggerCleanup chan struct{} +} + +func (h *ConsistencyHandler) Registered() bool { + h.registerLock.RLock() + defer h.registerLock.RUnlock() + return h.registered +} + +func (h *ConsistencyHandler) Register(ctx context.Context, informer cacheapi.Informer) error { + h.registerLock.Lock() + defer h.registerLock.Unlock() + + // Check again in case it got registered while we waited for the lock + if h.registered { + return nil + } + + if h.registration != nil { + return h.waitForHandlerSyncLocked(ctx, *h.registration) + } + + registration, err := informer.AddEventHandler(h) + if err != nil { + return fmt.Errorf("failed to add consistency handler to informer: %w", err) + } + h.registration = ®istration + + return h.waitForHandlerSyncLocked(ctx, registration) +} + +func (h *ConsistencyHandler) waitForHandlerSyncLocked(ctx context.Context, registration cache.ResourceEventHandlerRegistration) error { + select { + case <-registration.HasSyncedChecker().Done(): + h.registered = true + return nil + case <-ctx.Done(): + return fmt.Errorf("failed waiting for consistency handler to sync: %w", ctx.Err()) + } +} + +func (h *ConsistencyHandler) SetMinimumRV(key types.NamespacedName, rv int64) { + h.minimumRVsLock.Lock() + defer h.minimumRVsLock.Unlock() + if rv > h.minimumRVs[key] && rv > h.observedRV.Load() { + h.minimumRVs[key] = rv + } +} + +func (h *ConsistencyHandler) getMinimumRVForKey(key types.NamespacedName) int64 { + h.minimumRVsLock.RLock() + defer h.minimumRVsLock.RUnlock() + return h.minimumRVs[key] +} + +func (h *ConsistencyHandler) getMinimumRVForGVK() int64 { + h.minimumRVsLock.RLock() + defer h.minimumRVsLock.RUnlock() + var maxRV int64 + for _, rv := range h.minimumRVs { + if rv > maxRV { + maxRV = rv + } + } + return maxRV +} + +func (h *ConsistencyHandler) cleanupMinimumRVs() { + h.minimumRVsLock.Lock() + defer h.minimumRVsLock.Unlock() + for key, rv := range h.minimumRVs { + if rv <= h.observedRV.Load() { + delete(h.minimumRVs, key) + } + } +} + +func (h *ConsistencyHandler) AddPendingDelete(key types.NamespacedName, uid types.UID) { + h.pendingDeletesLock.Lock() + defer h.pendingDeletesLock.Unlock() + + if h.pendingDeletes[key] == nil { + h.pendingDeletes[key] = sets.New(uid) + return + } + h.pendingDeletes[key].Insert(uid) +} + +func (h *ConsistencyHandler) RemovePendingDelete(key types.NamespacedName, uid types.UID) { + h.pendingDeletesLock.Lock() + defer h.pendingDeletesLock.Unlock() + + if h.pendingDeletes[key] != nil { + h.pendingDeletes[key].Delete(uid) + if len(h.pendingDeletes[key]) == 0 { + delete(h.pendingDeletes, key) + } + h.pendingDeletesBroadcaster.broadcast() + } +} + +func (h *ConsistencyHandler) WaitForList(ctx context.Context) error { + // snapshot deletes before waiting for the RV so we don't end up including + // deletes that came in while we waited. + h.pendingDeletesLock.RLock() + pendingDeletes := sets.Set[types.UID]{} + for _, uids := range h.pendingDeletes { + maps.Copy(pendingDeletes, uids) + } + h.pendingDeletesLock.RUnlock() + + if err := h.waitForRV(ctx, h.getMinimumRVForGVK()); err != nil { + return err + } + + return h.waitDeletes(ctx, pendingDeletes) +} + +func (h *ConsistencyHandler) WaitForGet(ctx context.Context, key types.NamespacedName) error { + // snapshot deletes before waiting for the RV so we don't end up including + // deletes that came in while we waited. + h.pendingDeletesLock.RLock() + pendingDeletes := maps.Clone(h.pendingDeletes[key]) + h.pendingDeletesLock.RUnlock() + + if err := h.waitForRV(ctx, h.getMinimumRVForKey(key)); err != nil { + return err + } + + return h.waitDeletes(ctx, pendingDeletes) +} + +func (h *ConsistencyHandler) waitDeletes(ctx context.Context, uids sets.Set[types.UID]) error { + if len(uids) == 0 { + return nil + } + + for { + // must store the chan before checking the deletes to guarantee that even if the deletes + // get updated after our check and before the select, we still get an event. + updatedChan := h.pendingDeletesBroadcaster.getWaitChan() + done := h.allDeleted(uids) + if done { + return nil + } + + select { + case <-updatedChan: + continue + case <-ctx.Done(): + return fmt.Errorf("failed waiting to observe deletes for uids %v: %w", sets.List(uids), ctx.Err()) + } + } +} + +func (h *ConsistencyHandler) allDeleted(uids sets.Set[types.UID]) bool { + h.pendingDeletesLock.RLock() + defer h.pendingDeletesLock.RUnlock() + + for wantDeleted := range uids { + for _, notDeletedUIDs := range h.pendingDeletes { + if notDeletedUIDs.Has(wantDeleted) { + return false + } + } + } + + return true +} + +func (h *ConsistencyHandler) observeDeletion(obj cacheapi.Object) { + h.RemovePendingDelete(types.NamespacedName{Namespace: obj.GetNamespace(), Name: obj.GetName()}, obj.GetUID()) +} + +func (h *ConsistencyHandler) waitForRV(ctx context.Context, rv int64) error { + for { + // must store the chan before checking the RV to guarantee that even if the RV + // gets updated after our check and before the select, we still get an event. + updatedChan := h.rvBroadCaster.getWaitChan() + if h.observedRV.Load() >= rv { + return nil + } + select { + case <-updatedChan: + continue + case <-ctx.Done(): + return fmt.Errorf("failed waiting to observe resource version %d: %w", rv, ctx.Err()) + } + } +} + +func (h *ConsistencyHandler) observeResourceVersion(rv string) { + parsed, err := strconv.ParseInt(rv, 10, 64) + if err != nil { + h.log.Error(err, "Failed to parse resource version as int64", "resourceVersion", rv) + return + } + + for { + current := h.observedRV.Load() + if parsed <= current { + return + } + + if h.observedRV.CompareAndSwap(current, parsed) { + break + } + } + + h.rvBroadCaster.broadcast() + + select { + case h.triggerCleanup <- struct{}{}: + h.cleanupMinimumRVs() + <-h.triggerCleanup + default: + } +} + +func (h *ConsistencyHandler) OnAdd(raw any, _ bool) { + obj, ok := raw.(cacheapi.Object) + if !ok { + h.log.Error(nil, "OnAdd received object that is not a cacheapi.Object", "object", raw) + return + } + go func() { h.observeResourceVersion(obj.GetResourceVersion()) }() +} + +func (h *ConsistencyHandler) OnUpdate(_, newObj any) { + obj, ok := newObj.(cacheapi.Object) + if !ok { + h.log.Error(nil, "OnUpdate received object that is not a cacheapi.Object", "object", newObj) + return + } + go func() { h.observeResourceVersion(obj.GetResourceVersion()) }() +} + +func (h *ConsistencyHandler) OnDelete(raw any) { + var obj cacheapi.Object + switch t := raw.(type) { + case cacheapi.Object: + obj = t + case cache.DeletedFinalStateUnknown: + obj = t.Obj.(cacheapi.Object) + default: + h.log.Error(nil, "OnDelete received object that is not a cacheapi.Object or toolscache.DeletedFinalStateUnknown", "object", raw) + return + } + go func() { h.observeResourceVersion(obj.GetResourceVersion()) }() + go func() { h.observeDeletion(obj) }() +} + +// broadcaster wakes arbitrarily many waiters on broadcast(). +type broadcaster struct { + lock sync.Mutex + ch chan struct{} +} + +func (b *broadcaster) broadcast() { + b.lock.Lock() + defer b.lock.Unlock() + // Lazily create the channel in getWaitChan to avoid creating a channel per event. + if b.ch != nil { + close(b.ch) + b.ch = nil + } +} + +func (b *broadcaster) getWaitChan() <-chan struct{} { + b.lock.Lock() + defer b.lock.Unlock() + + if b.ch == nil { + b.ch = make(chan struct{}) + } + + return b.ch +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier/writebarrier.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier/writebarrier.go new file mode 100644 index 0000000000..77b5f3cbe3 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier/writebarrier.go @@ -0,0 +1,195 @@ +/* +Copyright The Kubernetes 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 writebarrier + +import ( + "sync" + + "k8s.io/apimachinery/pkg/types" +) + +// WriteBarriers adds garbage collection for unused keys to WriteBarrier. +type WriteBarriers interface { + // Begin keeps the passed key locked until the returned release func was called. + Begin(key types.NamespacedName) (release func()) + + // Seal seals the currently-active set of locks to key and returns a channel that + // closes when they are done. + Seal(key types.NamespacedName) <-chan struct{} + + // SealAll is Seal for all keys. + SealAll() []<-chan struct{} +} + +// NewWriteBarriers construct WriteBarriers. newBarrier is configurable for testing purposes only. +func NewWriteBarriers(newBarrier func() WriteBarrier) WriteBarriers { + return &writeBarriers{ + data: map[types.NamespacedName]*writeBarrierWithRefCounter{}, + newBarrier: newBarrier, + } +} + +type writeBarrierWithRefCounter struct { + WriteBarrier + inFlightWrites int +} + +// writeBarriers holds one writeBarrier per key that has an in-flight write. +type writeBarriers struct { + lock sync.Mutex + data map[types.NamespacedName]*writeBarrierWithRefCounter + newBarrier func() WriteBarrier +} + +func (w *writeBarriers) Begin(key types.NamespacedName) func() { + w.lock.Lock() + defer w.lock.Unlock() + + barrier, exists := w.data[key] + if !exists { + barrier = &writeBarrierWithRefCounter{WriteBarrier: w.newBarrier()} + w.data[key] = barrier + } + barrier.inFlightWrites++ + release := barrier.Begin() + + return func() { + release() + + w.lock.Lock() + defer w.lock.Unlock() + barrier.inFlightWrites-- + if barrier.inFlightWrites == 0 { + delete(w.data, key) + } + } +} + +func (w *writeBarriers) Seal(key types.NamespacedName) <-chan struct{} { + w.lock.Lock() + defer w.lock.Unlock() + + barrier, exists := w.data[key] + if !exists { + return closedChannel + } + + return barrier.Seal() +} + +func (w *writeBarriers) SealAll() []<-chan struct{} { + w.lock.Lock() + defer w.lock.Unlock() + + result := make([]<-chan struct{}, 0, len(w.data)) + for _, barrier := range w.data { + result = append(result, barrier.Seal()) + } + + return result +} + +var closedChannel chan struct{} + +func init() { + closedChannel = make(chan struct{}) + close(closedChannel) +} + +type WriteBarrier interface { + Begin() (release func()) + Seal() <-chan struct{} +} + +// NewWriteBarrier creates a new WriteBarrier +func NewWriteBarrier() WriteBarrier { + return &keyWriteBarrier{previous: closedChannel} +} + +// keyWriteBarrier allows to wait for a set of in-flight writes to finish. +type keyWriteBarrier struct { + // lock must be held to access current or previous. + lock sync.Mutex + + // current is the current write batch. It has a reference to the key write + // barrier that it uses to delete itself once done. + current *writeBatch + + // previous is closed once all previous write batches are done. + previous <-chan struct{} +} + +// Begin adds a write to the current batch, starting one if needed. +func (b *keyWriteBarrier) Begin() func() { + b.lock.Lock() + defer b.lock.Unlock() + + if b.current == nil { + b.current = &writeBatch{barrier: b, done: make(chan struct{})} + } + b.current.inFlight++ + + return b.current.release +} + +func (b *keyWriteBarrier) Seal() <-chan struct{} { + b.lock.Lock() + defer b.lock.Unlock() + + if b.current == nil { + return b.previous + } + + // Create a new chan that blocks until both previous + // and current are done. + done := make(chan struct{}) + previous := b.previous + b.previous = done + + current := b.current.done + b.current = nil + + go func() { + for _, c := range []<-chan struct{}{previous, current} { + <-c + } + close(done) + }() + + return done +} + +type writeBatch struct { + barrier *keyWriteBarrier + inFlight int + done chan struct{} +} + +func (w *writeBatch) release() { + w.barrier.lock.Lock() + defer w.barrier.lock.Unlock() + + w.inFlight-- + if w.inFlight > 0 { + return + } + + close(w.done) + if w.barrier.current == w { + w.barrier.current = nil + } +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/metadata_client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/metadata_client.go index d0c6b8e13a..6c0a2078d0 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/metadata_client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/metadata_client.go @@ -49,24 +49,6 @@ func (mc *metadataClient) getResourceInterface(gvk schema.GroupVersionKind, ns s return mc.client.Resource(mapping.Resource).Namespace(ns), nil } -// Delete implements client.Client. -func (mc *metadataClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { - metadata, ok := obj.(*metav1.PartialObjectMetadata) - if !ok { - return fmt.Errorf("metadata client did not understand object: %T", obj) - } - - resInt, err := mc.getResourceInterface(metadata.GroupVersionKind(), metadata.Namespace) - if err != nil { - return err - } - - deleteOpts := DeleteOptions{} - deleteOpts.ApplyOptions(opts) - - return resInt.Delete(ctx, metadata.Name, *deleteOpts.AsDeleteOptions()) -} - // DeleteAllOf implements client.Client. func (mc *metadataClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { metadata, ok := obj.(*metav1.PartialObjectMetadata) diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/object.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/object.go index 31e334d6c2..e5f820438d 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/object.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/object.go @@ -19,6 +19,8 @@ package client import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" ) // Object is a Kubernetes object, allows functions to work indistinctly with @@ -42,10 +44,7 @@ import ( // a `metadata` field). // // Notice that XYZList types are distinct: they implement ObjectList instead. -type Object interface { - metav1.Object - runtime.Object -} +type Object = cacheapi.Object // ObjectList is a Kubernetes object list, allows functions to work // indistinctly with any resource that implements both runtime.Object and diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go index c5bd9f0b8c..aae55edfcb 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go @@ -200,6 +200,72 @@ func (f FieldOwner) ApplyToSubResourceApply(opts *SubResourceApplyOptions) { opts.FieldManager = string(f) } +// DisableReadYourWritesConsistency disables read-your-own-write consistency for the +// request it is passed to. It has no effect if the client was not configured with +// CacheOptions.EnableReadYourWritesConsistency. +// +// On a read request, the request will not wait for the cache to have observed +// previous writes. On a write request, subsequent read requests will not wait +// for the cache to have observed this write. +const DisableReadYourWritesConsistency = disableReadYourWritesConsistency(true) + +type disableReadYourWritesConsistency bool + +// ApplyToGet applies this configuration to the given get options. +func (disableReadYourWritesConsistency) ApplyToGet(opts *GetOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToList applies this configuration to the given list options. +func (disableReadYourWritesConsistency) ApplyToList(opts *ListOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToCreate applies this configuration to the given create options. +func (disableReadYourWritesConsistency) ApplyToCreate(opts *CreateOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToUpdate applies this configuration to the given update options. +func (disableReadYourWritesConsistency) ApplyToUpdate(opts *UpdateOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToPatch applies this configuration to the given patch options. +func (disableReadYourWritesConsistency) ApplyToPatch(opts *PatchOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToApply applies this configuration to the given apply options. +func (disableReadYourWritesConsistency) ApplyToApply(opts *ApplyOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToDelete applies this configuration to the given delete options. +func (disableReadYourWritesConsistency) ApplyToDelete(opts *DeleteOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToSubResourceCreate applies this configuration to the given create options. +func (d disableReadYourWritesConsistency) ApplyToSubResourceCreate(opts *SubResourceCreateOptions) { + d.ApplyToCreate(&opts.CreateOptions) +} + +// ApplyToSubResourceUpdate applies this configuration to the given update options. +func (d disableReadYourWritesConsistency) ApplyToSubResourceUpdate(opts *SubResourceUpdateOptions) { + d.ApplyToUpdate(&opts.UpdateOptions) +} + +// ApplyToSubResourcePatch applies this configuration to the given patch options. +func (d disableReadYourWritesConsistency) ApplyToSubResourcePatch(opts *SubResourcePatchOptions) { + d.ApplyToPatch(&opts.PatchOptions) +} + +// ApplyToSubResourceApply applies this configuration to the given apply options. +func (d disableReadYourWritesConsistency) ApplyToSubResourceApply(opts *SubResourceApplyOptions) { + d.ApplyToApply(&opts.ApplyOptions) +} + // FieldValidation configures field validation for the given requests. type FieldValidation string @@ -269,6 +335,11 @@ type CreateOptions struct { // will contain all unknown and duplicate fields encountered. FieldValidation string + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this write. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw CreateOptions, as passed to the API server. Raw *metav1.CreateOptions } @@ -309,6 +380,9 @@ func (o *CreateOptions) ApplyToCreate(co *CreateOptions) { if o.FieldValidation != "" { co.FieldValidation = o.FieldValidation } + if o.DisableReadYourWritesConsistency { + co.DisableReadYourWritesConsistency = true + } if o.Raw != nil { co.Raw = o.Raw } @@ -343,6 +417,11 @@ type DeleteOptions struct { // foreground. PropagationPolicy *metav1.DeletionPropagation + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this delete. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw DeleteOptions, as passed to the API server. Raw *metav1.DeleteOptions @@ -393,6 +472,9 @@ func (o *DeleteOptions) ApplyToDelete(do *DeleteOptions) { if o.PropagationPolicy != nil { do.PropagationPolicy = o.PropagationPolicy } + if o.DisableReadYourWritesConsistency { + do.DisableReadYourWritesConsistency = true + } if o.Raw != nil { do.Raw = o.Raw } @@ -468,6 +550,11 @@ type GetOptions struct { // otherwise you will mutate the object in the cache. // +optional UnsafeDisableDeepCopy *bool + + // DisableReadYourWritesConsistency indicates that the request will not wait for the + // cache to have observed previous writes. It has no effect if the client was not + // configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool } var _ GetOption = &GetOptions{} @@ -480,6 +567,9 @@ func (o *GetOptions) ApplyToGet(lo *GetOptions) { if o.UnsafeDisableDeepCopy != nil { lo.UnsafeDisableDeepCopy = o.UnsafeDisableDeepCopy } + if o.DisableReadYourWritesConsistency { + lo.DisableReadYourWritesConsistency = true + } } // AsGetOptions returns these options as a flattened metav1.GetOptions. @@ -538,6 +628,11 @@ type ListOptions struct { // +optional UnsafeDisableDeepCopy *bool + // DisableReadYourWritesConsistency indicates that the request will not wait for the + // cache to have observed previous writes. It has no effect if the client was not + // configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw ListOptions, as passed to the API server. Note // that these may not be respected by all implementations of interface, // and the LabelSelector, FieldSelector, Limit and Continue fields are ignored. @@ -569,6 +664,10 @@ func (o *ListOptions) ApplyToList(lo *ListOptions) { if o.UnsafeDisableDeepCopy != nil { lo.UnsafeDisableDeepCopy = o.UnsafeDisableDeepCopy } + + if o.DisableReadYourWritesConsistency { + lo.DisableReadYourWritesConsistency = true + } } // AsListOptions returns these options as a flattened metav1.ListOptions. @@ -797,6 +896,11 @@ type UpdateOptions struct { // will contain all unknown and duplicate fields encountered. FieldValidation string + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this write. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw UpdateOptions, as passed to the API server. Raw *metav1.UpdateOptions } @@ -839,6 +943,9 @@ func (o *UpdateOptions) ApplyToUpdate(uo *UpdateOptions) { if o.FieldValidation != "" { uo.FieldValidation = o.FieldValidation } + if o.DisableReadYourWritesConsistency { + uo.DisableReadYourWritesConsistency = true + } if o.Raw != nil { uo.Raw = o.Raw } @@ -885,6 +992,11 @@ type PatchOptions struct { // will contain all unknown and duplicate fields encountered. FieldValidation string + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this write. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw PatchOptions, as passed to the API server. Raw *metav1.PatchOptions } @@ -939,6 +1051,9 @@ func (o *PatchOptions) ApplyToPatch(po *PatchOptions) { if o.FieldValidation != "" { po.FieldValidation = o.FieldValidation } + if o.DisableReadYourWritesConsistency { + po.DisableReadYourWritesConsistency = true + } if o.Raw != nil { po.Raw = o.Raw } @@ -1020,6 +1135,11 @@ type ApplyOptions struct { // // +required FieldManager string + + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this write. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool } // ApplyOptions applies the given opts onto the ApplyOptions @@ -1042,6 +1162,10 @@ func (o *ApplyOptions) ApplyToApply(opts *ApplyOptions) { if o.FieldManager != "" { opts.FieldManager = o.FieldManager } + + if o.DisableReadYourWritesConsistency { + opts.DisableReadYourWritesConsistency = true + } } // AsPatchOptions constructs patch options from the given ApplyOptions diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go index 5a85941725..396bc6ea63 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go @@ -18,15 +18,15 @@ package client import ( "context" + "encoding/json" "fmt" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/json" "k8s.io/client-go/util/apply" ) var _ Reader = &typedClient{} -var _ Writer = &typedClient{} type typedClient struct { resources *clientRestResources @@ -73,22 +73,35 @@ func (c *typedClient) Update(ctx context.Context, obj Object, opts ...UpdateOpti } // Delete implements client.Client. -func (c *typedClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { +func (c *typedClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) (*unstructured.Unstructured, error) { o, err := c.resources.getObjMeta(obj) if err != nil { - return err + return nil, err } deleteOpts := DeleteOptions{} deleteOpts.ApplyOptions(opts) - return o.Delete(). + // directly deserializing into unstructured fails in the decoder + runtimeObj, err := o.Delete(). NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). Name(o.name). Body(deleteOpts.AsDeleteOptions()). Do(ctx). - Error() + Get() + if err != nil { + return nil, err + } + data, err := json.Marshal(runtimeObj) + if err != nil { + return nil, fmt.Errorf("failed to marshal delete response: %w", err) + } + response := &unstructured.Unstructured{} + if err := json.Unmarshal(data, &response.Object); err != nil { + return nil, fmt.Errorf("failed to unmarshal delete response: %w", err) + } + return response, nil } // DeleteAllOf implements client.Client. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go index d2ea6d7a32..31e935e557 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go @@ -21,12 +21,12 @@ import ( "fmt" "strings" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/util/apply" ) var _ Reader = &unstructuredClient{} -var _ Writer = &unstructuredClient{} type unstructuredClient struct { resources *clientRestResources @@ -93,26 +93,23 @@ func (uc *unstructuredClient) Update(ctx context.Context, obj Object, opts ...Up } // Delete implements client.Client. -func (uc *unstructuredClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { - if _, ok := obj.(runtime.Unstructured); !ok { - return fmt.Errorf("unstructured client did not understand object: %T", obj) - } - +func (uc *unstructuredClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) (*unstructured.Unstructured, error) { o, err := uc.resources.getObjMeta(obj) if err != nil { - return err + return nil, err } deleteOpts := DeleteOptions{} deleteOpts.ApplyOptions(opts) - return o.Delete(). + response := &unstructured.Unstructured{} + return response, o.Delete(). NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). Name(o.name). Body(deleteOpts.AsDeleteOptions()). Do(ctx). - Error() + Into(response) } // DeleteAllOf implements client.Client. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/watch.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/watch.go index 181b22a673..6f1d81471d 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/watch.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/watch.go @@ -28,15 +28,16 @@ import ( // NewWithWatch returns a new WithWatch. func NewWithWatch(config *rest.Config, options Options) (WithWatch, error) { - client, err := newClient(config, options) + base, c, err := newClient(config, options) if err != nil { return nil, err } - return &watchingClient{client: client}, nil + return &watchingClient{Client: wrapClient(c, options), base: base}, nil } type watchingClient struct { - *client + Client + base *client } func (w *watchingClient) Watch(ctx context.Context, list ObjectList, opts ...ListOption) (watch.Interface, error) { @@ -67,7 +68,7 @@ func (w *watchingClient) metadataWatch(ctx context.Context, obj *metav1.PartialO listOpts := w.listOpts(opts...) - resInt, err := w.client.metadataClient.getResourceInterface(gvk, listOpts.Namespace) + resInt, err := w.base.metadataClient.getResourceInterface(gvk, listOpts.Namespace) if err != nil { return nil, err } @@ -76,7 +77,7 @@ func (w *watchingClient) metadataWatch(ctx context.Context, obj *metav1.PartialO } func (w *watchingClient) unstructuredWatch(ctx context.Context, obj runtime.Unstructured, opts ...ListOption) (watch.Interface, error) { - r, err := w.client.unstructuredClient.resources.getResource(obj) + r, err := w.base.unstructuredClient.resources.getResource(obj) if err != nil { return nil, err } @@ -86,12 +87,12 @@ func (w *watchingClient) unstructuredWatch(ctx context.Context, obj runtime.Unst return r.Get(). NamespaceIfScoped(listOpts.Namespace, r.isNamespaced()). Resource(r.resource()). - VersionedParams(listOpts.AsListOptions(), w.client.unstructuredClient.paramCodec). + VersionedParams(listOpts.AsListOptions(), w.base.unstructuredClient.paramCodec). Watch(ctx) } func (w *watchingClient) typedWatch(ctx context.Context, obj ObjectList, opts ...ListOption) (watch.Interface, error) { - r, err := w.client.typedClient.resources.getResource(obj) + r, err := w.base.typedClient.resources.getResource(obj) if err != nil { return nil, err } @@ -101,6 +102,6 @@ func (w *watchingClient) typedWatch(ctx context.Context, obj ObjectList, opts .. return r.Get(). NamespaceIfScoped(listOpts.Namespace, r.isNamespaced()). Resource(r.resource()). - VersionedParams(listOpts.AsListOptions(), w.client.typedClient.paramCodec). + VersionedParams(listOpts.AsListOptions(), w.base.typedClient.paramCodec). Watch(ctx) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cluster/internal.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cluster/internal.go index 755f83b546..e01f072694 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cluster/internal.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cluster/internal.go @@ -24,12 +24,12 @@ import ( "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/rest" - "k8s.io/client-go/tools/events" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" intrec "sigs.k8s.io/controller-runtime/pkg/internal/recorder" + "sigs.k8s.io/controller-runtime/pkg/recorder" ) type cluster struct { @@ -88,7 +88,7 @@ func (c *cluster) GetEventRecorderFor(name string) record.EventRecorder { return c.recorderProvider.GetEventRecorderFor(name) } -func (c *cluster) GetEventRecorder(name string) events.EventRecorder { +func (c *cluster) GetEventRecorder(name string) recorder.EventRecorder { return c.recorderProvider.GetEventRecorder(name) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/config/controller.go b/vendor/sigs.k8s.io/controller-runtime/pkg/config/controller.go index 5eea2965f6..2877383f97 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/config/controller.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/config/controller.go @@ -44,7 +44,14 @@ type Controller struct { // e.g. ReplicaSet in apps group (regardless of version) would be `ReplicaSet.apps`. GroupKindConcurrency map[string]int - // MaxConcurrentReconciles is the maximum number of concurrent Reconciles which can be run. Defaults to 1. + // MaxConcurrentReconciles is the maximum number of concurrent reconciliations which can be run. + // Defaults to 1. + // + // This value is used as a default for controllers that do not specify their own value. + // Per-controller options take precedence over this setting. + // + // For more details on how concurrency works, see the MaxConcurrentReconciles + // field in pkg/controller.TypedOptions. MaxConcurrentReconciles int // CacheSyncTimeout refers to the time limit set to wait for syncing caches. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/controller.go b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/controller.go index 853788d52f..1a5485f7b7 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/controller.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/controller.go @@ -45,7 +45,26 @@ type TypedOptions[request comparable] struct { // Defaults to false if Controller.SkipNameValidation setting from the Manager is also unset. SkipNameValidation *bool - // MaxConcurrentReconciles is the maximum number of concurrent Reconciles which can be run. Defaults to 1. + // MaxConcurrentReconciles is the maximum number of concurrent reconciliations + // that can be run. Defaults to 1. + // + // This value controls the number of worker goroutines that process items from + // the controller's workqueue. Increasing it allows different queue items to be + // reconciled in parallel, which can improve throughput when a controller manages + // many objects or when reconciliation involves slow operations such as external + // API calls. + // + // The workqueue ensures that the same item is not processed by multiple + // workers at the same time. If the same item is added again while it is being + // processed, it is processed again only after the current reconciliation + // finishes. For the default reconcile.Request type, the item key is the object's + // namespace/name. + // + // This option can also be configured at the manager level via + // config.Controller.MaxConcurrentReconciles or per GroupKind via + // config.Controller.GroupKindConcurrency (applied when using the builder + // utilities and no per-controller value is set). Per-controller values + // take precedence. MaxConcurrentReconciles int // CacheSyncTimeout refers to the time limit set to wait for syncing caches. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/metrics.go b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/metrics.go index 967a252dfb..14ab602de3 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/metrics.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/metrics.go @@ -1,3 +1,19 @@ +/* +Copyright The Kubernetes 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 priorityqueue import ( diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/priorityqueue.go b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/priorityqueue.go index 69ac25083b..aa9ab44e22 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/priorityqueue.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/priorityqueue.go @@ -1,3 +1,19 @@ +/* +Copyright The Kubernetes 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 priorityqueue import ( @@ -397,7 +413,16 @@ func (w *priorityqueue[T]) handleReadyItems() { w.waiters-- delete(w.items, item.Key) toDelete = append(toDelete, item) - w.get <- *item + // w.get is unbuffered, so this send blocks until a GetWithPriority + // consumer receives. A consumer that is parked in GetWithPriority can + // instead return via <-w.done once ShutDown closes it, leaving no one + // to receive here. Also watch w.done so the send does not block forever + // and deadlock the queue (the whole queue stalls because w.lock is held). + select { + case w.get <- *item: + case <-w.done: + return false + } return w.waiters > 0 }) @@ -512,22 +537,28 @@ func (w *priorityqueue[T]) logState() { if !w.log.V(5).Enabled() { continue } - w.lock.Lock() - items := make([]*item[T], 0, len(w.items)) - w.waiting.Ascend(func(item *item[T]) bool { - items = append(items, item) - return true - }) - w.ready.Ascend(func(item *item[T]) bool { - items = append(items, item) - return true - }) - w.lock.Unlock() - w.log.V(5).Info("workqueue_items", "items", items) + w.log.V(5).Info("workqueue_items", "items", w.cloneItems()) } } +// cloneItems returns a deep copy of all queued items, taken under the lock, so that callers +// like logState can use them after it is released without racing with writers of ReadyAt. +func (w *priorityqueue[T]) cloneItems() []item[T] { + w.lock.Lock() + defer w.lock.Unlock() + + items := make([]item[T], 0, len(w.items)) + appendItem := func(it *item[T]) bool { + items = append(items, it.clone()) + return true + } + w.waiting.Ascend(appendItem) + w.ready.Ascend(appendItem) + + return items +} + func lessWaiting[T comparable](a, b *item[T]) bool { if !a.ReadyAt.Equal(*b.ReadyAt) { return a.ReadyAt.Before(*b.ReadyAt) @@ -549,6 +580,15 @@ type item[T comparable] struct { ReadyAt *time.Time `json:"readyAt,omitempty"` } +// clone returns a copy of the item that shares no memory with it. +func (i *item[T]) clone() item[T] { + clone := *i + if i.ReadyAt != nil { + clone.ReadyAt = new(*i.ReadyAt) + } + return clone +} + func (w *priorityqueue[T]) updateUnfinishedWorkLoop() { t := time.Tick(500 * time.Millisecond) // borrowed from workqueue: https://github.com/kubernetes/kubernetes/blob/67a807bf142c7a2a5ecfdb2a5d24b4cdea4cc79c/staging/src/k8s.io/client-go/util/workqueue/queue.go#L182 for { diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/webhook.go b/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/webhook.go index a6961bf7c6..7e176304c1 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/webhook.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/webhook.go @@ -1,9 +1,12 @@ /* Copyright 2019 The Kubernetes 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. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/handler/enqueue.go b/vendor/sigs.k8s.io/controller-runtime/pkg/handler/enqueue.go index 64cbe8a4d1..be6ba1faaa 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/handler/enqueue.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/handler/enqueue.go @@ -108,7 +108,7 @@ func (e *TypedEnqueueRequestForObject[T]) Generic(ctx context.Context, evt event } func isNil(arg any) bool { - if v := reflect.ValueOf(arg); !v.IsValid() || ((v.Kind() == reflect.Ptr || + if v := reflect.ValueOf(arg); !v.IsValid() || ((v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface || v.Kind() == reflect.Slice || v.Kind() == reflect.Map || diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/controller.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/controller.go index bf81da39b6..3e7bd6ea31 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/controller.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/controller.go @@ -58,6 +58,7 @@ type Options[request comparable] struct { NewQueue func(controllerName string, rateLimiter workqueue.TypedRateLimiter[request]) workqueue.TypedRateLimitingInterface[request] // MaxConcurrentReconciles is the maximum number of concurrent Reconciles which can be run. Defaults to 1. + // See controller.TypedOptions.MaxConcurrentReconciles for full documentation. MaxConcurrentReconciles int // CacheSyncTimeout refers to the time limit set on waiting for cache to sync @@ -96,7 +97,8 @@ type Controller[request comparable] struct { // Name is used to uniquely identify a Controller in tracing, logging and monitoring. Name is required. Name string - // MaxConcurrentReconciles is the maximum number of concurrent Reconciles which can be run. Defaults to 1. + // MaxConcurrentReconciles is the number of worker goroutines spawned to process work queue items. + // See controller.TypedOptions.MaxConcurrentReconciles for full documentation. MaxConcurrentReconciles int // Reconciler is a function that can be called at any time with the Name / Namespace of an object and @@ -277,6 +279,7 @@ func (c *Controller[request]) Start(ctx context.Context) error { // but lock outside to get proper handling of the queue shutdown c.mu.Lock() if c.Started { + c.mu.Unlock() return errors.New("controller was started more than once. This is likely to be caused by being added to a manager multiple times") } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/metrics/metrics.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/metrics/metrics.go index 39b435c453..1ece25c97f 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/metrics/metrics.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/metrics/metrics.go @@ -32,7 +32,7 @@ var ( ReconcileTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "controller_runtime_reconcile_total", Help: "Total number of reconciliations per controller", - }, []string{"controller", "result"}) + }, []string{"controller", "result"}) //nolint:goconst // ReconcileErrors is a prometheus counter metrics which holds the total // number of errors from the Reconciler. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/field/selector/utils.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/field/selector/utils.go index 8f6dc71ede..ffa3beba33 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/field/selector/utils.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/field/selector/utils.go @@ -5,7 +5,7 @@ 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 + 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, diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/httpserver/server.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/httpserver/server.go index 02fbe03cd9..d343fe27e7 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/httpserver/server.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/httpserver/server.go @@ -1,3 +1,19 @@ +/* +Copyright The Kubernetes 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 httpserver import ( diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/metrics/workqueue.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/metrics/workqueue.go index 94a98f96ed..35da4c1f2f 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/metrics/workqueue.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/metrics/workqueue.go @@ -48,7 +48,7 @@ var ( Subsystem: WorkQueueSubsystem, Name: DepthKey, Help: "Current depth of workqueue by workqueue and priority", - }, []string{"name", "controller", "priority"}) + }, []string{"name", "controller", "priority"}) //nolint:goconst adds = prometheus.NewCounterVec(prometheus.CounterOpts{ Subsystem: WorkQueueSubsystem, diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/recorder/recorder.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/recorder/recorder.go index 4a1ccd7c0c..1f2738e5ed 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/recorder/recorder.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/recorder/recorder.go @@ -30,6 +30,7 @@ import ( "k8s.io/client-go/tools/events" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/recorder" ) // EventBroadcasterProducer makes an event broadcaster, returning @@ -161,8 +162,11 @@ func (p *Provider) GetEventRecorderFor(name string) record.EventRecorder { } // GetEventRecorder returns an event recorder that broadcasts to this provider's -// broadcaster. All events will be associated with a component of the given name. -func (p *Provider) GetEventRecorder(name string) events.EventRecorder { +// broadcaster. All events will be associated with the given reportingController +// name. client-go appends "-" and the hostname to derive reportingInstance, +// which must fit within the events.k8s.io/v1 128-character limit. +// The returned recorder supports both Eventf and AnnotatedEventf. +func (p *Provider) GetEventRecorder(name string) recorder.EventRecorder { return &lazyRecorder{ prov: p, name: name, @@ -171,19 +175,24 @@ func (p *Provider) GetEventRecorder(name string) events.EventRecorder { // lazyRecorder is a recorder that doesn't actually instantiate any underlying // recorder until the first event is emitted. +var _ recorder.EventRecorder = (*lazyRecorder)(nil) + type lazyRecorder struct { prov *Provider name string - recOnce sync.Once - rec events.EventRecorder + recOnce sync.Once + eventRecorder events.EventRecorder + annotatedEventRecorder events.AnnotatedEventRecorder } // ensureRecording ensures that a concrete recorder is populated for this recorder. func (l *lazyRecorder) ensureRecording() { l.recOnce.Do(func() { _, broadcaster := l.prov.getBroadcaster() - l.rec = broadcaster.NewRecorder(l.prov.scheme, l.name) + rec := broadcaster.NewRecorder(l.prov.scheme, l.name) + l.eventRecorder = rec + l.annotatedEventRecorder = rec.(events.AnnotatedEventRecorder) }) } @@ -192,7 +201,17 @@ func (l *lazyRecorder) Eventf(regarding runtime.Object, related runtime.Object, l.prov.lock.RLock() if !l.prov.stopped { - l.rec.Eventf(regarding, related, eventtype, reason, action, note, args...) + l.eventRecorder.Eventf(regarding, related, eventtype, reason, action, note, args...) + } + l.prov.lock.RUnlock() +} + +func (l *lazyRecorder) AnnotatedEventf(regarding runtime.Object, related runtime.Object, annotations map[string]string, eventtype, reason, action, note string, args ...any) { + l.ensureRecording() + + l.prov.lock.RLock() + if !l.prov.stopped { + l.annotatedEventRecorder.AnnotatedEventf(regarding, related, annotations, eventtype, reason, action, note, args...) } l.prov.lock.RUnlock() } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/source/event_handler.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/source/event_handler.go index 9d614f34a5..57a5cf98a1 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/source/event_handler.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/source/event_handler.go @@ -35,7 +35,7 @@ var log = logf.RuntimeLog.WithName("source").WithName("EventHandler") var _ cache.ResourceEventHandler = &EventHandler[client.Object, any]{} // NewEventHandler creates a new EventHandler. -func NewEventHandler[object client.Object, request comparable]( +func NewEventHandler[object any, request comparable]( ctx context.Context, queue workqueue.TypedRateLimitingInterface[request], handler handler.TypedEventHandler[object, request], @@ -49,7 +49,7 @@ func NewEventHandler[object client.Object, request comparable]( } // EventHandler adapts a handler.EventHandler interface to a cache.ResourceEventHandler interface. -type EventHandler[object client.Object, request comparable] struct { +type EventHandler[object any, request comparable] struct { // ctx stores the context that created the event handler // that is used to propagate cancellation signals to each handler function. ctx context.Context diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/source/kind.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/source/kind.go index 4eb82f9825..286d8094b7 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/source/kind.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/source/kind.go @@ -1,3 +1,19 @@ +/* +Copyright The Kubernetes 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 internal import ( @@ -148,7 +164,7 @@ func (ks *Kind[object, request]) WaitForSync(ctx context.Context) error { } func isNil(arg any) bool { - if v := reflect.ValueOf(arg); !v.IsValid() || ((v.Kind() == reflect.Ptr || + if v := reflect.ValueOf(arg); !v.IsValid() || ((v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface || v.Kind() == reflect.Slice || v.Kind() == reflect.Map || diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/syncs/syncs.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/syncs/syncs.go index c78a30377a..5e70f5ea01 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/syncs/syncs.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/syncs/syncs.go @@ -1,3 +1,19 @@ +/* +Copyright The Kubernetes 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 syncs import ( diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/process.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/process.go index f1bfda425f..9436c91786 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/process.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/process.go @@ -18,6 +18,7 @@ package process import ( "crypto/tls" + "errors" "fmt" "io" "net" @@ -128,6 +129,8 @@ func (ps *State) Init(name string) error { type stopChannel chan struct{} +var signalProcess = signalProcessImpl + // CheckFlag checks the help output of this command for the presence of the given flag, specified // without the leading `--` (e.g. `CheckFlag("insecure-port")` checks for `--insecure-port`), // returning true if the flag is present. @@ -266,10 +269,11 @@ func (ps *State) Stop() error { case <-ps.waitDone: break case <-timedOut: + timeoutErr := fmt.Errorf("timeout waiting for process %s to stop", path.Base(ps.Path)) if err := signalProcess(ps.Cmd.Process, syscall.SIGKILL); err != nil { - return fmt.Errorf("unable to kill process %s: %w", ps.Path, err) + return errors.Join(timeoutErr, fmt.Errorf("unable to kill process %s: %w", ps.Path, err)) } - return fmt.Errorf("timeout waiting for process %s to stop", path.Base(ps.Path)) + return timeoutErr } ps.ready = false return nil diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_other.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_other.go index 5cbce8f416..6a41ca77bd 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_other.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_other.go @@ -1,4 +1,4 @@ -//go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !zos +//go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !windows && !zos /* Copyright 2026 The Kubernetes Authors. @@ -23,6 +23,6 @@ import ( "syscall" ) -func signalProcess(process *os.Process, sig syscall.Signal) error { +func signalProcessImpl(process *os.Process, sig syscall.Signal) error { return process.Signal(sig) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_unix.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_unix.go index d86fc97213..1993962abb 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_unix.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_unix.go @@ -23,6 +23,6 @@ import ( "syscall" ) -func signalProcess(process *os.Process, sig syscall.Signal) error { +func signalProcessImpl(process *os.Process, sig syscall.Signal) error { return syscall.Kill(-process.Pid, sig) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_windows.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_windows.go new file mode 100644 index 0000000000..678d5924ce --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_windows.go @@ -0,0 +1,28 @@ +//go:build windows + +/* +Copyright 2026 The Kubernetes 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 process + +import ( + "os" + "syscall" +) + +func signalProcess(process *os.Process, _ syscall.Signal) error { + return process.Kill() +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go index ceb1450d1b..c029e7b48e 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go @@ -32,7 +32,6 @@ import ( "k8s.io/apimachinery/pkg/runtime" kerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/client-go/rest" - "k8s.io/client-go/tools/events" "k8s.io/client-go/tools/leaderelection" "k8s.io/client-go/tools/leaderelection/resourcelock" "k8s.io/client-go/tools/record" @@ -46,6 +45,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/internal/httpserver" intrec "sigs.k8s.io/controller-runtime/pkg/internal/recorder" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + "sigs.k8s.io/controller-runtime/pkg/recorder" "sigs.k8s.io/controller-runtime/pkg/webhook" ) @@ -264,7 +264,7 @@ func (cm *controllerManager) GetEventRecorderFor(name string) record.EventRecord return cm.cluster.GetEventRecorderFor(name) //nolint:staticcheck } -func (cm *controllerManager) GetEventRecorder(name string) events.EventRecorder { +func (cm *controllerManager) GetEventRecorder(name string) recorder.EventRecorder { return cm.cluster.GetEventRecorder(name) } @@ -462,6 +462,10 @@ func (cm *controllerManager) Start(ctx context.Context) (err error) { // Create a context that inherits all keys from the parent context // but can be cancelled independently for leader election management baseCtx := context.WithoutCancel(ctx) + + // Inject the logger into the context for client-go contextual logging + baseCtx = logr.NewContext(baseCtx, cm.logger.WithName("leaderelection")) + leaderCtx, cancel := context.WithCancel(baseCtx) cm.leaderElectionCancel = cancel if leaderElector != nil { diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go index 53e29fc56f..da8889df4f 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go @@ -1,3 +1,19 @@ +/* +Copyright The Kubernetes 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 manager import ( diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/server.go b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/server.go index 1983165da8..cdf989a0e8 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/server.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/server.go @@ -5,7 +5,7 @@ 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 + 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, diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/client_go_adapter.go b/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/client_go_adapter.go index ff28998c44..7d3d319704 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/client_go_adapter.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/client_go_adapter.go @@ -18,6 +18,10 @@ package metrics import ( "context" + "net/url" + "sync" + "sync/atomic" + "time" "github.com/prometheus/client_golang/prometheus" clientmetrics "k8s.io/client-go/tools/metrics" @@ -27,16 +31,134 @@ import ( // that client-go registers metrics. We copy the names and formats // from Kubernetes so that we match the core controllers. -var ( - // client metrics. +const ( + hostLabel = "host" + verbLabel = "verb" +) + +// defaultRESTClientDurationBuckets matches Kubernetes core controller REST client metrics. +// They start at 5ms; override via RESTClientMetricsOptions.DurationBuckets if a scrape +// pipeline still consumes classic buckets and needs sub-5ms resolution. +var defaultRESTClientDurationBuckets = []float64{0.005, 0.025, 0.1, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 15.0, 30.0, 60.0} + +func restClientDurationHistogram(name, help string, labels []string, buckets []float64) *prometheus.HistogramVec { + if len(buckets) == 0 { + buckets = defaultRESTClientDurationBuckets + } + return prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Name: name, + Help: help, + Buckets: buckets, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, + }, labels) +} +func newRequestLatency(buckets []float64) *prometheus.HistogramVec { + return restClientDurationHistogram( + "rest_client_request_duration_seconds", + "Request latency in seconds. Broken down by verb and host.", + []string{verbLabel, hostLabel}, + buckets, + ) +} + +func newResolverLatency(buckets []float64) *prometheus.HistogramVec { + return restClientDurationHistogram( + "rest_client_dns_resolution_duration_seconds", + "DNS resolver latency in seconds. Broken down by host.", + []string{hostLabel}, + buckets, + ) +} + +func newRateLimiterLatency(buckets []float64) *prometheus.HistogramVec { + return restClientDurationHistogram( + "rest_client_rate_limiter_duration_seconds", + "Client side rate limiter latency in seconds. Broken down by verb, and host.", + []string{verbLabel, hostLabel}, + buckets, + ) +} + +func newRequestSize() *prometheus.HistogramVec { + return prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "rest_client_request_size_bytes", + Help: "Request size in bytes. Broken down by verb and host.", + // 64 bytes to 16MB + Buckets: []float64{64, 256, 512, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216}, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, + }, + []string{verbLabel, hostLabel}, + ) +} + +func newResponseSize() *prometheus.HistogramVec { + return prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "rest_client_response_size_bytes", + Help: "Response size in bytes. Broken down by verb and host.", + // 64 bytes to 16MB + Buckets: []float64{64, 256, 512, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216}, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, + }, + []string{verbLabel, hostLabel}, + ) +} + +func newRequestRetry() *prometheus.CounterVec { + return prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "rest_client_request_retries_total", + Help: "Number of request retries, partitioned by status code, verb, and host.", + }, + []string{"code", verbLabel, hostLabel}, + ) +} + +var ( + // requestResult is registered by default. The other client metrics are + // opt-in: adapters start with a nil collector and RegisterRESTClientMetrics* + // stores the HistogramVec / CounterVec. requestResult = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "rest_client_requests_total", Help: "Number of HTTP requests, partitioned by status code, method, and host.", }, - []string{"code", "method", "host"}, + []string{"code", "method", hostLabel}, ) + + requestLatency = &latencyAdapter{} + resolverLatency = &resolverLatencyAdapter{} + requestSize = &sizeAdapter{} + responseSize = &sizeAdapter{} + rateLimiterLatency = &latencyAdapter{} + requestRetry = &retryAdapter{} +) + +// RESTClientMetric identifies an opt-in client-go REST client metric. +// Pass values to RegisterRESTClientMetrics to enable a subset. +type RESTClientMetric int + +const ( + // MetricRequestLatency enables the rest_client_request_duration_seconds metric. + MetricRequestLatency = iota + 1 + // MetricDNSResolutionLatency enables the rest_client_dns_resolution_duration_seconds metric. + MetricDNSResolutionLatency + // MetricRequestSize enables the rest_client_request_size_bytes metric. + MetricRequestSize + // MetricResponseSize enables the rest_client_response_size_bytes metric. + MetricResponseSize + // MetricRateLimiterLatency enables the rest_client_rate_limiter_duration_seconds metric. + MetricRateLimiterLatency + // MetricRequestRetry enables the rest_client_request_retries_total metric. + MetricRequestRetry ) func init() { @@ -50,10 +172,66 @@ func registerClientMetrics() { // register the metrics with client-go clientmetrics.Register(clientmetrics.RegisterOpts{ - RequestResult: &resultAdapter{metric: requestResult}, + RequestResult: &resultAdapter{metric: requestResult}, + RequestLatency: requestLatency, + ResolverLatency: resolverLatency, + RequestSize: requestSize, + ResponseSize: responseSize, + RateLimiterLatency: rateLimiterLatency, + RequestRetry: requestRetry, }) } +// RESTClientMetricsOptions configures RegisterRESTClientMetricsWithOptions. +type RESTClientMetricsOptions struct { + // DurationBuckets overrides the classic Prometheus histogram buckets used by + // rest_client_request_duration_seconds, rest_client_dns_resolution_duration_seconds, + // and rest_client_rate_limiter_duration_seconds. + // + // If nil or empty, the Kubernetes-default buckets are kept (starting at 5ms). + // Native histogram settings are not changed. + // + // DurationBuckets is read when each duration metric is first registered. + // Later calls for the same metric are ignored so already-registered collectors + // are not replaced. + DurationBuckets []float64 +} + +// RegisterRESTClientMetrics enables the given client metrics using default buckets +// that match Kubernetes core controllers. +func RegisterRESTClientMetrics(metrics ...RESTClientMetric) { + RegisterRESTClientMetricsWithOptions(RESTClientMetricsOptions{}, metrics...) +} + +// RegisterRESTClientMetricsWithOptions enables the given client metrics. +// See RESTClientMetricsOptions for knobs such as custom duration buckets. +func RegisterRESTClientMetricsWithOptions(opts RESTClientMetricsOptions, metrics ...RESTClientMetric) { + for _, m := range metrics { + switch m { + case MetricRequestLatency: + requestLatency.enable(func() *prometheus.HistogramVec { + return newRequestLatency(opts.DurationBuckets) + }) + case MetricDNSResolutionLatency: + resolverLatency.enable(func() *prometheus.HistogramVec { + return newResolverLatency(opts.DurationBuckets) + }) + case MetricRequestSize: + requestSize.enable(newRequestSize) + case MetricResponseSize: + responseSize.enable(newResponseSize) + case MetricRateLimiterLatency: + rateLimiterLatency.enable(func() *prometheus.HistogramVec { + return newRateLimiterLatency(opts.DurationBuckets) + }) + case MetricRequestRetry: + requestRetry.enable(newRequestRetry) + default: + // unknown metric, ignore + } + } +} + // this section contains adapters, implementations, and other sundry organic, artisanally // hand-crafted syntax trees required to convince client-go that it actually wants to let // someone use its metrics. @@ -69,3 +247,87 @@ type resultAdapter struct { func (r *resultAdapter) Increment(_ context.Context, code, method, host string) { r.metric.WithLabelValues(code, method, host).Inc() } + +type latencyAdapter struct { + once sync.Once + metric atomic.Pointer[prometheus.HistogramVec] +} + +func (l *latencyAdapter) enable(newMetric func() *prometheus.HistogramVec) { + l.once.Do(func() { + h := newMetric() + l.metric.Store(h) + Registry.MustRegister(h) + }) +} + +func (l *latencyAdapter) Observe(_ context.Context, verb string, u url.URL, duration time.Duration) { + h := l.metric.Load() + if h == nil { + return + } + h.WithLabelValues(verb, u.Host).Observe(duration.Seconds()) +} + +type resolverLatencyAdapter struct { + once sync.Once + metric atomic.Pointer[prometheus.HistogramVec] +} + +func (r *resolverLatencyAdapter) enable(newMetric func() *prometheus.HistogramVec) { + r.once.Do(func() { + h := newMetric() + r.metric.Store(h) + Registry.MustRegister(h) + }) +} + +func (r *resolverLatencyAdapter) Observe(_ context.Context, host string, duration time.Duration) { + h := r.metric.Load() + if h == nil { + return + } + h.WithLabelValues(host).Observe(duration.Seconds()) +} + +type sizeAdapter struct { + once sync.Once + metric atomic.Pointer[prometheus.HistogramVec] +} + +func (r *sizeAdapter) enable(newMetric func() *prometheus.HistogramVec) { + r.once.Do(func() { + h := newMetric() + r.metric.Store(h) + Registry.MustRegister(h) + }) +} + +func (r *sizeAdapter) Observe(_ context.Context, verb string, host string, size float64) { + h := r.metric.Load() + if h == nil { + return + } + h.WithLabelValues(verb, host).Observe(size) +} + +type retryAdapter struct { + once sync.Once + metric atomic.Pointer[prometheus.CounterVec] +} + +func (r *retryAdapter) enable(newMetric func() *prometheus.CounterVec) { + r.once.Do(func() { + c := newMetric() + r.metric.Store(c) + Registry.MustRegister(c) + }) +} + +func (r *retryAdapter) IncrementRetry(_ context.Context, code, verb, host string) { + c := r.metric.Load() + if c == nil { + return + } + c.WithLabelValues(code, verb, host).Inc() +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/leaderelection.go b/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/leaderelection.go index 61e1009d32..2253827b83 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/leaderelection.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/leaderelection.go @@ -1,3 +1,19 @@ +/* +Copyright The Kubernetes 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 metrics import ( diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/server/server.go b/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/server/server.go index 146757b1f9..f3f6cbb1b6 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/server/server.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/server/server.go @@ -105,6 +105,10 @@ type Options struct { // This also allows providing a certificate via GetCertificate. TLSOpts []func(*tls.Config) + // HandlerOpts is used to allow configuring the promhttp handler used to serve metrics. + // These options are applied after the default handler options are set and can override them. + HandlerOpts []func(*promhttp.HandlerOpts) + // ListenConfig contains options for listening to an address on the metric server. ListenConfig net.ListenConfig } @@ -218,9 +222,7 @@ func (s *defaultServer) Start(ctx context.Context) error { mux := http.NewServeMux() - handler := promhttp.HandlerFor(metrics.Registry, promhttp.HandlerOpts{ - ErrorHandling: promhttp.HTTPErrorOnError, - }) + handler := promhttp.HandlerFor(metrics.Registry, s.handlerOpts()) if s.metricsFilter != nil { log := log.WithValues("path", defaultMetricsEndpoint) var err error @@ -270,6 +272,16 @@ func (s *defaultServer) Start(ctx context.Context) error { return nil } +func (s *defaultServer) handlerOpts() promhttp.HandlerOpts { + handlerOpts := promhttp.HandlerOpts{ + ErrorHandling: promhttp.HTTPErrorOnError, + } + for _, op := range s.options.HandlerOpts { + op(&handlerOpts) + } + return handlerOpts +} + func (s *defaultServer) createListener(ctx context.Context, log logr.Logger) (net.Listener, error) { if !s.options.SecureServing { return s.options.ListenConfig.Listen(ctx, "tcp", s.options.BindAddress) diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/predicate/predicate.go b/vendor/sigs.k8s.io/controller-runtime/pkg/predicate/predicate.go index 9f24cb178c..d5086af3c3 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/predicate/predicate.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/predicate/predicate.go @@ -30,6 +30,9 @@ import ( var log = logf.RuntimeLog.WithName("predicate").WithName("eventFilters") // Predicate filters events before enqueuing the keys. +// +// NOTE: This does not affect what the cache stores. That is configured via +// cache.Options, which are global to all users of the cache. type Predicate = TypedPredicate[client.Object] // TypedPredicate filters events before enqueuing the keys. @@ -417,7 +420,7 @@ func LabelSelectorPredicate(s metav1.LabelSelector) (Predicate, error) { } func isNil(arg any) bool { - if v := reflect.ValueOf(arg); !v.IsValid() || ((v.Kind() == reflect.Ptr || + if v := reflect.ValueOf(arg); !v.IsValid() || ((v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface || v.Kind() == reflect.Slice || v.Kind() == reflect.Map || diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/recorder/recorder.go b/vendor/sigs.k8s.io/controller-runtime/pkg/recorder/recorder.go index b34fecb525..945202f81c 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/recorder/recorder.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/recorder/recorder.go @@ -25,12 +25,27 @@ import ( "k8s.io/client-go/tools/record" ) +// EventRecorder combines both events.EventRecorder and events.AnnotatedEventRecorder +// so that callers only need a single recorder to emit both regular and annotated events. +type EventRecorder interface { + events.EventRecorder + events.AnnotatedEventRecorder +} + // Provider knows how to generate new event recorders with given name. type Provider interface { // GetEventRecorderFor returns an EventRecorder for the old events API. // // Deprecated: this uses the old events API and will be removed in a future release. Please use GetEventRecorder instead. GetEventRecorderFor(name string) record.EventRecorder - // GetEventRecorder returns a EventRecorder with given name. - GetEventRecorder(name string) events.EventRecorder + // GetEventRecorder returns an EventRecorder with given name. + // + // The name is used as the reportingController of events.k8s.io/v1 Events + // and must be a valid Kubernetes qualified name. client-go derives the + // reportingInstance by appending "-" and the current hostname to + // reportingController. reportingInstance must be no more than 128 + // characters, so callers should ensure that len(name) + 1 + len(hostname) + // is at most 128. + // The returned recorder supports both Eventf and AnnotatedEventf. + GetEventRecorder(name string) EventRecorder } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/source/source.go b/vendor/sigs.k8s.io/controller-runtime/pkg/source/source.go index e4f63ee5b5..8e17ad7577 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/source/source.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/source/source.go @@ -264,19 +264,23 @@ func (cs *channel[object, request]) syncLoop(ctx context.Context) { } } -// Informer is used to provide a source of events originating inside the cluster from Watches (e.g. Pod Create). -type Informer struct { +// TypedInformer is used to provide a source of events originating inside the cluster from Watches using generic +// event handlers and predicates. +type TypedInformer[object any, request comparable] struct { // Informer is the controller-runtime Informer Informer cache.Informer - Handler handler.EventHandler - Predicates []predicate.Predicate + Handler handler.TypedEventHandler[object, request] + Predicates []predicate.TypedPredicate[object] } +// Informer is used to provide a source of events originating inside the cluster from Watches (e.g. Pod Create). +type Informer = TypedInformer[client.Object, reconcile.Request] + var _ Source = &Informer{} // Start is internal and should be called only by the Controller to register an EventHandler with the Informer // to enqueue reconcile.Requests. -func (is *Informer) Start(ctx context.Context, queue workqueue.TypedRateLimitingInterface[reconcile.Request]) error { +func (is *TypedInformer[object, request]) Start(ctx context.Context, queue workqueue.TypedRateLimitingInterface[request]) error { // Informer should have been specified by the user. if is.Informer == nil { return fmt.Errorf("must specify Informer.Informer") @@ -294,7 +298,7 @@ func (is *Informer) Start(ctx context.Context, queue workqueue.TypedRateLimiting return nil } -func (is *Informer) String() string { +func (is *TypedInformer[object, request]) String() string { return fmt.Sprintf("informer source: %p", is.Informer) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/decode.go b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/decode.go index 576262cf70..535db0ab3f 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/decode.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/decode.go @@ -5,7 +5,7 @@ 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 + 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, diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/defaulter_custom.go b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/defaulter_custom.go index 9fec8003f2..da3bba50cd 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/defaulter_custom.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/defaulter_custom.go @@ -70,7 +70,7 @@ func WithDefaulter[T runtime.Object](scheme *runtime.Scheme, defaulter Defaulter new: func() T { var zero T typ := reflect.TypeOf(zero) - if typ.Kind() == reflect.Ptr { + if typ.Kind() == reflect.Pointer { return reflect.New(typ.Elem()).Interface().(T) } return zero diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/multi.go b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/multi.go index ef9c456248..9156da2c24 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/multi.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/multi.go @@ -5,7 +5,7 @@ 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 + 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, diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/response.go b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/response.go index ec1c88c989..4f05c0f463 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/response.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/response.go @@ -5,7 +5,7 @@ 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 + 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, diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/validator_custom.go b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/validator_custom.go index f8401571d0..07a68c6a04 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/validator_custom.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/validator_custom.go @@ -64,7 +64,7 @@ func WithValidator[T runtime.Object](scheme *runtime.Scheme, validator Validator new: func() T { var zero T typ := reflect.TypeOf(zero) - if typ.Kind() == reflect.Ptr { + if typ.Kind() == reflect.Pointer { return reflect.New(typ.Elem()).Interface().(T) } return zero diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/webhook.go b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/webhook.go index cba6da2cb0..4ac8e4a9c6 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/webhook.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/webhook.go @@ -5,7 +5,7 @@ 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 + 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, diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/server.go b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/server.go index 079f0a55ff..67dafb3456 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/server.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/server.go @@ -75,10 +75,18 @@ type Options struct { // Port is the port number that the server will serve. // It will be defaulted to 9443 if unspecified. + // + // To disable the webhook server set Port to -1. Port int - // CertDir is the directory that contains the server key and certificate. Defaults to - // /k8s-webhook-server/serving-certs. + // CertDir is the directory that contains the server key and certificate. + // The server expects the files to be named CertName and KeyName (see + // below). If unset, CertDir defaults to + // /k8s-webhook-server/serving-certs, where comes + // from os.TempDir() (usually /tmp on Linux, but TMPDIR-dependent). + // Most operators should configure this explicitly (for example, to the + // cert directory mounted in by a Kubernetes Secret) rather than relying + // on the default. CertDir string // CertName is the server certificate name. Defaults to tls.crt. @@ -136,7 +144,7 @@ func (o *Options) setDefaults() { o.WebhookMux = http.NewServeMux() } - if o.Port <= 0 { + if o.Port == 0 { o.Port = DefaultPort } @@ -180,7 +188,11 @@ func (s *DefaultServer) Register(path string, hook http.Handler) { s.webhookMux.Handle(path, metrics.InstrumentedHook(path, hook)) regLog := log.WithValues("path", path) - regLog.Info("Registering webhook") + if s.Options.Port < 0 { + regLog.Info("Webhook is disabled") + } else { + regLog.Info("Registering webhook") + } } // Start runs the server. @@ -188,6 +200,11 @@ func (s *DefaultServer) Register(path string, hook http.Handler) { func (s *DefaultServer) Start(ctx context.Context) error { s.defaultingOnce.Do(s.setDefaults) + if s.Options.Port < 0 { + log.Info("Webhook server is disabled") + return nil + } + log.Info("Starting webhook server") cfg := &tls.Config{ @@ -278,6 +295,9 @@ func (s *DefaultServer) StartedChecker() healthz.Checker { s.mu.Lock() defer s.mu.Unlock() + if s.Options.Port < 0 { + return nil + } if !s.started { return fmt.Errorf("webhook server has not been started yet") }