MSP-8520 up deps

This commit is contained in:
Павел Комиссаров committed 2026-09-03 18:05:39 +03:00
1 parent c14f8441fb
commit 884aa6a439
304 files changed
+18222 -4351

No files matched your search

+22 -23
View File
@@ -7,38 +7,37 @@ require (
github.com/google/uuid v1.6.0
github.com/iancoleman/strcase v0.3.0
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.11.1
github.com/stretchr/testify v1.12.1
github.com/txix-open/bgjob v1.6.0
github.com/txix-open/isp-kit v1.74.0
github.com/txix-open/isp-kit v1.74.1
github.com/txix-open/jsonschema v1.3.0
golang.org/x/crypto v0.54.0
golang.org/x/crypto v0.55.0
golang.org/x/sync v0.22.0
google.golang.org/grpc v1.83.0
google.golang.org/grpc v1.83.2
)
require (
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/buger/jsonparser v1.6.0 // indirect
github.com/buger/jsonparser v1.6.1 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.15 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/getsentry/sentry-go v0.48.0 // indirect
github.com/go-faker/faker/v4 v4.10.1 // indirect
github.com/getsentry/sentry-go v0.49.0 // indirect
github.com/go-faker/faker/v4 v4.11.0 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.10.0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jmoiron/sqlx v1.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.19.1 // indirect
github.com/klauspost/compress v1.19.2 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
@@ -48,7 +47,6 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/pressly/goose/v3 v3.27.3 // indirect
github.com/prometheus/client_golang v1.24.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
@@ -64,22 +62,23 @@ require (
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 // indirect
go.opentelemetry.io/otel v1.46.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 // indirect
go.opentelemetry.io/otel/metric v1.46.0 // indirect
go.opentelemetry.io/otel/sdk v1.46.0 // indirect
go.opentelemetry.io/otel/trace v1.46.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
golang.org/x/net v0.57.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.40.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
golang.org/x/text v0.41.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+50 -54
View File
@@ -9,8 +9,8 @@ github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPn
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/buger/jsonparser v1.6.0 h1:IHTgLjkgckOjAp8p0aYfXkv+cqC+zrzALg/JywnPjxY=
github.com/buger/jsonparser v1.6.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/buger/jsonparser v1.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs=
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
@@ -19,20 +19,18 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/getsentry/sentry-go v0.48.0 h1:FRZNr7Uk1C86ev1bSJmYlUkL9oyivQA6YOcdYfaaMmY=
github.com/getsentry/sentry-go v0.48.0/go.mod h1:E5UkA5wp1qR2+MDydNYlVeUiNN2xEdjYMidkgf0Qoss=
github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s=
github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI=
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
github.com/go-faker/faker/v4 v4.10.1 h1:mGH3y0X8AfrXsfgPsPuTkWBYIebomvdkWEN1uDLoFFg=
github.com/go-faker/faker/v4 v4.10.1/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
github.com/go-faker/faker/v4 v4.11.0 h1:HeIFTzafXsgrlxKE2QySGGTQocfGdQ8sGqU2CXvs120=
github.com/go-faker/faker/v4 v4.11.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
@@ -56,8 +54,8 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
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/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
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/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
@@ -74,8 +72,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
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.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
@@ -114,8 +112,6 @@ github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTw
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
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=
@@ -126,8 +122,8 @@ github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
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/rabbitmq/amqp091-go v1.13.0 h1:L8NA1WtF76C6KA3LAoufjfLgbist/If1UQYcsOjtxXA=
github.com/rabbitmq/amqp091-go v1.13.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek=
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
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/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
@@ -147,8 +143,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
github.com/txix-open/bgjob v1.6.0 h1:Vwj9cAsIhMrHPKRZVxfg6mHqE9LI/atDCq1aeihH3+I=
@@ -157,8 +153,8 @@ github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlf
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
github.com/txix-open/isp-kit v1.74.0 h1:Gi1X8Jnf9ppV4TXq4kMCBgBjJjqSKh57X8038I+tQFw=
github.com/txix-open/isp-kit v1.74.0/go.mod h1:Kob233jk1j/Js7UmopJ5b7JpVZrpWbagEAjasgfqTdk=
github.com/txix-open/isp-kit v1.74.1 h1:2WQl1+e6E1TXcgkm554kYpiyORgZiyJa/zQIks4cUCw=
github.com/txix-open/isp-kit v1.74.1/go.mod h1:i4g+hgfVQAXa02kHqr104TqYEsiW2em17RZF0KjkB78=
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
@@ -174,24 +170,24 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 h1:MCcYL7J6Vt/X0kjqbMZkekCmwsurbQRbL69vkiye2lk=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0/go.mod h1:3jnStNwSufK+f5ktjL4EPcwtig4rtd81NS70lqHuXl8=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 h1:lgh3PiVrRUWMLOVSkQicxzZll5NjF1r+AtsX1XRIHw0=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0/go.mod h1:5Cnhth3m/AgOeTgE3ex12pPmiu/gGtZit03kSzx9X7s=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 h1:oFNJW32h2SXnET7XXstgT7pVh4vN+jW+GfiIaBguIZE=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0/go.mod h1:+H3sPOFwag14eMHTPMElZtV0e4YfVZ/85KgrKUCB5FI=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM=
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
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.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
@@ -202,28 +198,28 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 h1:ybvH/ZpOcpCrjtkb7oW/fdlzbEmRVeumw19SRQmNFKU=
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0/go.mod h1:HJ9MpJLeDSstBkx1LILTpd5f41ADSMZcTPypw02qEGw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 h1:mJiOtnGp0k/BcSgdu03G2NwnscCfCH+h2QKUBZr18KI=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 h1:izFU9hz7aeLI/Mi1J0991ae+xcwRLr7hTqWnB/9aIIU=
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5/go.mod h1:3LhxRw4YYkf+ylAfgaY9JlVLFKhokkCV8duhLLe7+t0=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
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/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=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+40
View File
@@ -1,5 +1,45 @@
# Changelog
## [v1.6.1] — 2026-07-29
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings)
### Performance — gjson-style fast-skip in hot loops
Ported gjson's `>'\\'` fast-skip trick to three inner loops in parser.go:
`stringEndConfig` tail, `blockEndConfig`, and `searchKeysConfig`. The trick
uses a single unsigned comparison (`byte > 0x5C`) to skip all non-structural
bytes in bulk, reducing per-byte branch overhead.
| Payload | Before | After | Improvement |
|---|---|---|---|
| Small (190B) | 382 ns | **339 ns** | -11.3% |
| Medium (2.4kB) | 3,899 ns | **3,141 ns** | -19.4% |
| Large (24kB) | 20,788 ns | **20,114 ns** | -3.2% |
Zero allocations maintained on all paths.
### Benchmarks — now includes gjson and sonic
Added [tidwall/gjson](https://github.com/tidwall/gjson) (15.5k⭐, path-based
parser like jsonparser) and [bytedance/sonic](https://github.com/bytedance/sonic)
(9.6k⭐, SIMD-accelerated deserializer) to the benchmark suite.
**Final leaderboard (large payload):**
| Library | time/op | bytes/op | allocs/op |
|---|---|---|---|
| **buger/jsonparser** | **20,114** | **0** | **0** |
| tidwall/gjson | 22,756 | 28,672 | 2 |
| mailru/easyjson | 33,771 | 4,016 | 134 |
| bytedance/sonic | 41,053 | 31,368 | 71 |
| pquerna/ffjson | 59,063 | 4,822 | 144 |
| encoding/json | 130,565 | 4,432 | 147 |
jsonparser is **the fastest across all payload sizes** and the **only zero-allocation** parser.
---
## [v1.6.0] — 2026-07-29
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings)
+28 -38
View File
@@ -1,7 +1,7 @@
[![Go Report Card](https://goreportcard.com/badge/github.com/buger/jsonparser)](https://goreportcard.com/report/github.com/buger/jsonparser) [![Audit](https://img.shields.io/badge/ReqProof-L3%20Assurance-success)](https://reqproof.com) ![License](https://img.shields.io/dub/l/vibe-d.svg)
# Alternative JSON parser for Go (10x times faster standard library)
It does not require you to know the structure of the payload (eg. create structs), and allows accessing fields by providing the path to them. It is up to **6x faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.
It does not require you to know the structure of the payload (eg. create structs), and allows accessing fields by providing the path to them. It is up to **6.5x faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.
---
@@ -341,25 +341,20 @@ data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items")
There are 3 benchmark types, trying to simulate real-life usage for small, medium and large JSON payloads.
For each metric, the lower value is better. Time/op is in nanoseconds. Values better than standard encoding/json marked as bold text.
> **Methodology:** Benchmarks run with `go test -bench=. -benchmem -count=5` on Apple M4 Max (ARM64, darwin), Go 1.26.3. Median of 5 runs. All comparison libraries updated to their latest versions as of 2026-07-28. The `encoding/json` benchmark types no longer carry ffjson-generated `UnmarshalJSON` methods (fixed in v1.3.1, issue #126), so these numbers reflect the real standard library, not generated code.
> **Methodology:** Benchmarks run with `go test -bench=. -benchmem -count=5` on Apple M4 Max (ARM64, darwin), Go 1.26.3. Median of 5 runs. All comparison libraries updated to their latest versions as of 2026-07-29.
Compared libraries:
* https://golang.org/pkg/encoding/json
* https://github.com/tidwall/gjson — path-based, like jsonparser
* https://github.com/bytedance/sonic — SIMD-accelerated full deserializer
* https://github.com/Jeffail/gabs/v2
* https://github.com/a8m/djson
* https://github.com/bitly/go-simplejson
* https://github.com/antonholmquist/jason
* https://github.com/mreiferson/go-ujson
* https://github.com/ugorji/go/codec
* https://github.com/pquerna/ffjson
* https://github.com/mailru/easyjson
* https://github.com/buger/jsonparser
#### TLDR
`jsonparser` is up to **6.4x faster** than standard `encoding/json` package (depending on payload size and usage), and **zero allocations** — it operates with data on byte level, and provide direct slice pointers. On large payloads, `jsonparser` is also faster than `easyjson` and `ffjson`.
If you searching for replacement of `encoding/json` while keeping structs, `easyjson` is an amazing choice. If you want to process dynamic JSON, have memory constrains, or more control over your data you should try `jsonparser`.
`jsonparser` is the **fastest overall** across all payload sizes — faster than gjson, sonic, easyjson, and encoding/json — with **zero allocations** on every code path.
#### Small payload
@@ -369,21 +364,14 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_small_payloa
| Library | time/op | bytes/op | allocs/op |
| ------ | ------- | -------- | ------- |
| encoding/json struct | 1335 | 415 | 9 |
| encoding/json interface{} | 1441 | 1336 | 30 |
| Jeffail/gabs | 1558 | 1464 | 38 |
| bitly/go-simplejson | 1594 | 2120 | 34 |
| github.com/ugorji/go/codec | 1286 | 1288 | 13 |
| antonholmquist/jason | 4354 | 6816 | 105 |
| mreiferson/go-ujson | 1031 | 1392 | 36 |
| a8m/djson | 880 | 1160 | 25 |
| pquerna/ffjson | **652** | **520** | **10** |
| mailru/easyjson | **312** | **80** | **4** |
| buger/jsonparser (ObjectEach) | **214** | 64 | 2 |
| buger/jsonparser (EachKey) | **241** | **0** | **0** |
| buger/jsonparser (Get) | **382** | **0** | **0** |
`jsonparser` with `EachKey` is **5.5x faster** than `encoding/json` and **zero allocations**.
| encoding/json struct | 1,300 | 416 | 9 |
| bytedance/sonic | 460 | 522 | 4 |
| tidwall/gjson | 402 | 64 | 3 |
| pquerna/ffjson | **632** | **520** | **10** |
| mailru/easyjson | **237** | **216** | **7** |
| buger/jsonparser (ObjectEach) | **205** | 64 | 2 |
| buger/jsonparser (EachKey) | **227** | **0** | **0** |
| buger/jsonparser (Get) | **339** | **0** | **0** |
#### Medium payload
@@ -394,13 +382,15 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_paylo
| Library | time/op | bytes/op | allocs/op |
| ------- | ------- | -------- | --------- |
| encoding/json struct | 10564 | 616 | 18 |
| pquerna/ffjson | 3962 | 736 | 15 |
| mailru/easyjson | **2444** | **216** | **7** |
| buger/jsonparser (Get) | **3894** | **0** | **0** |
| buger/jsonparser (EachKey) | **1923** | **0** | **0** |
| encoding/json struct | 9,911 | 616 | 18 |
| bytedance/sonic | 2,703 | 3,428 | 14 |
| tidwall/gjson | 2,241 | 168 | 4 |
| pquerna/ffjson | 3,731 | 736 | 15 |
| mailru/easyjson | 2,368 | 216 | 7 |
| buger/jsonparser (Get) | **3,141** | **0** | **0** |
| buger/jsonparser (EachKey) | **1,657** | **0** | **0** |
`jsonparser` with `EachKey` beats `easyjson` on medium payload and remains zero-allocation.
`jsonparser` with `EachKey` beats every competitor on medium payloads while remaining zero-allocation.
#### Large payload
@@ -412,14 +402,14 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payloa
| Library | time/op | bytes/op | allocs/op |
| --- | --- | --- | --- |
| encoding/json struct | 134123 | 4432 | 147 |
| encoding/json interface{} | 176246 | 135824 | 2814 |
| a8m/djson | 99295 | 135136 | 2679 |
| pquerna/ffjson | 60129 | 4822 | 144 |
| mailru/easyjson | 32765 | 4016 | 134 |
| buger/jsonparser | **20788** | **0** | **0** |
| encoding/json struct | 130,565 | 4,432 | 147 |
| bytedance/sonic | 41,053 | 31,368 | 71 |
| pquerna/ffjson | 59,063 | 4,822 | 144 |
| mailru/easyjson | 33,771 | 4,016 | 134 |
| tidwall/gjson | 22,756 | 28,672 | 2 |
| buger/jsonparser | **20,114** | **0** | **0** |
`jsonparser` is the **fastest library overall** on large payloads: **6.4x faster than encoding/json**, **1.6x faster than easyjson**, and **zero allocations**.
`jsonparser` is the **fastest library overall** on large payloads: **6.5x faster than encoding/json**, **2x faster than sonic**, **1.7x faster than easyjson**, **1.1x faster than gjson** — and the **only zero-allocation** parser.
## Formal Verification
+54
View File
@@ -340,6 +340,14 @@ func stringEndConfig(_ Config, data []byte, quote byte) (int, bool) {
}
escaped := false
for ; i < n; i++ {
// gjson trick: the only bytes this loop acts on are the closing quote
// and the backslash. For double-quote strings quote=0x22, for
// single-quote quote=0x27; backslash=0x5C. All three are <= 0x5C, so a
// single unsigned comparison skips every other byte (letters, digits,
// punctuation, high UTF-8 bytes) without touching them.
if data[i] > '\\' {
continue
}
c := data[i]
if c == quote {
if !escaped {
@@ -377,6 +385,30 @@ func blockEndConfig(config Config, data []byte, openSym byte, closeSym byte) int
ln := len(data)
for i < ln {
// Fast-skip non-structural bytes before dispatching to the switch.
// Two categories are skipped in bulk with a single comparison each:
// 1. Control/whitespace bytes (<= 0x20): indentation, spaces, newlines.
// 2. Bytes > 0x5C that are not the open/close symbol: lowercase letters
// (true/false/null), and high UTF-8 bytes.
// The open/close symbols themselves (e.g. '{'=0x7B, '}'=0x7D, ']'=0x5D)
// are > 0x5C and must NOT be skipped, hence the explicit exclusions.
// '"' (0x22), '\'' (0x27) and '[' (0x5B) are <= 0x5C so they are never
// caught by the second clause and always reach the switch.
for i < ln {
c := data[i]
if c <= ' ' {
i++
continue
}
if c > '\\' && c != openSym && c != closeSym {
i++
continue
}
break
}
if i >= ln {
break
}
switch data[i] {
case '"', '\'': // If inside a configured string, skip it
quote := data[i]
@@ -425,6 +457,28 @@ func searchKeysConfig(config Config, data []byte, keys ...string) int {
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
for i < ln {
// Fast-skip non-structural bytes before dispatching to the switch.
// Skip control/whitespace (<= 0x20) and bytes > 0x5C that are not '{'
// (0x7B) or '}' (0x7D) — the only structural chars handled below that
// exceed the 0x5C threshold. '"' (0x22), '\'' (0x27), '[' (0x5B) and
// ':' (0x3A) are all <= 0x5C and always reach the switch. This is the
// gjson key-scan trick: a single unsigned comparison advances past
// value content (true/false/null letters, high bytes) and indentation.
for i < ln {
c := data[i]
if c <= ' ' {
i++
continue
}
if c > '\\' && c != '{' && c != '}' {
i++
continue
}
break
}
if i >= ln {
break
}
switch data[i] {
case '"', '\'':
quote := data[i]
+27
View File
@@ -1,5 +1,32 @@
# Changelog
## 0.49.0
### Breaking Changes 🛠
- removing DisableLogs and DisableMetrics client options. Sending metrics and logs is already gated by the usage of our APIs already, so having a global kill switch is counter intuitive. Users that won't to opt out should just not call the relevant APIs or setup the integrations. by @giortzisg in [#1392](https://github.com/getsentry/sentry-go/pull/1392)
### New Features ✨
- add `WithProxy`option for OTLP. This allows setting an `otlptracehttp.HTTPTransportProxyFunc` for the span exporter by @pierrre in [#1377](https://github.com/getsentry/sentry-go/pull/1377)
### Bug Fixes 🐛
- (echo) Propagate span through request context by @EricGusmao in [#1385](https://github.com/getsentry/sentry-go/pull/1385)
- Skip recover frames on panic. This changes stacktrace behavior for captured panics, removing `sentry.Recover` frames to focus on the actual panic frames. The changes might affect issue grouping. by @giortzisg in [#1364](https://github.com/getsentry/sentry-go/pull/1364)
### Internal Changes 🔧
#### Deps
- Bump github.com/labstack/echo/v5 from 5.0.3 to 5.2.0 in /echo by @dependabot in [#1399](https://github.com/getsentry/sentry-go/pull/1399)
- Bump github.com/gorilla/websocket from 1.5.1 to 1.5.3 by @dependabot in [#1397](https://github.com/getsentry/sentry-go/pull/1397)
- Bump getsentry/craft from 2.26.6 to 2.27.2 by @dependabot in [#1381](https://github.com/getsentry/sentry-go/pull/1381)
- Bump actions/setup-go from 6.4.0 to 7.0.0 by @dependabot in [#1382](https://github.com/getsentry/sentry-go/pull/1382)
- Bump actions/checkout from 6.0.3 to 7.0.1 by @dependabot in [#1380](https://github.com/getsentry/sentry-go/pull/1380)
- Bump google.golang.org/grpc to 1.82.1 and golang.org/x/sys to 0.46.0 by @dependabot in [#1375](https://github.com/getsentry/sentry-go/pull/1375)
- Bump golang.org/x/text to v0.39.0 and x/net to v0.56.0 by @giortzisg in [#1374](https://github.com/getsentry/sentry-go/pull/1374)
## 0.48.0
### Breaking Changes 🛠
+4 -13
View File
@@ -270,11 +270,6 @@ type ClientOptions struct {
MaxErrorDepth int
// Default event tags. These are overridden by tags set on a scope.
Tags map[string]string
// DisableLogs controls whether logs should be emitted.
// By default, logs are enabled. Set to true to disable log emission.
DisableLogs bool
// DisableMetrics controls when metrics should be emitted.
DisableMetrics bool
// DisableClientReports controls when client reports should be emitted.
DisableClientReports bool
// TraceIgnoreStatusCodes is a list of HTTP status codes that should not be traced.
@@ -442,14 +437,10 @@ func NewClient(options ClientOptions) (*Client, error) {
}
client.setupTransport()
if !options.DisableLogs {
client.batchLogger = newLogBatchProcessor(&client)
client.batchLogger.Start()
}
if !options.DisableMetrics {
client.batchMeter = newMetricBatchProcessor(&client)
client.batchMeter.Start()
}
client.batchLogger = newLogBatchProcessor(&client)
client.batchLogger.Start()
client.batchMeter = newMetricBatchProcessor(&client)
client.batchMeter.Start()
}
client.setupIntegrations()
if options.OrgID != 0 && client.dsn != nil {
+16
View File
@@ -13,6 +13,7 @@ git.sr.ht/~sbinet/gg v0.6.0 h1:RIzgkizAk+9r7uPzf/VfbJHBMKUr0F5hRFxTUGMnt38=
git.sr.ht/~sbinet/gg v0.6.0/go.mod h1:uucygbfC9wVPQIfrmwM2et0imr8L7KQWywX0xpFMm94=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0/go.mod h1:RD2SsorTmYhF6HkTmDw7KmPYQk8OBYwTkuasChwv7R4=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM=
@@ -34,6 +35,7 @@ github.com/cheekybits/is v0.0.0-20150225183255-68e9c0620927 h1:SKI1/fuSdodxmNNyV
github.com/cheekybits/is v0.0.0-20150225183255-68e9c0620927/go.mod h1:h/aW8ynjgkuj+NQRlZcDbAbM1ORAbXjXX77sX7T289U=
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w=
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=
github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w=
github.com/dgraph-io/badger/v2 v2.2007.4 h1:TRWBQg8UrlUhaFdco01nO2uXwzKS7zd+HVdwV/GHc4o=
@@ -52,12 +54,15 @@ github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwB
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g=
github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98=
github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI=
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=
github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
@@ -155,6 +160,7 @@ go.etcd.io/bbolt v1.3.7 h1:j+zJOnnEjF/kyHlDDgGnVL/AIqIJPq8UoB2GSNfkUfQ=
go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE=
go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk=
go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbFGz8O8rqB0dTY14uzvG4LCs=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
@@ -165,15 +171,19 @@ golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
@@ -183,12 +193,17 @@ golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4 h1:bTLqdHv7xrGlFbvf5/TXNxy/iUwwdkjhqQTJDjW7aj0=
golang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4/go.mod h1:g5NllXBEermZrmR51cJDQxmJUHUOfRAaNyWBM+R+548=
golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa/go.mod h1:kHjTxDEnAu6/Nl9lDkzjWpR+bmKfxeiRuSDlsMb70gE=
golang.org/x/telemetry v0.0.0-20260625142307-59b4966ccb57/go.mod h1:3AWMyWHS+caVoiEXpiq6+tzKA40J4vQT3MYr80ZtQpc=
golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0=
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
@@ -196,6 +211,7 @@ golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0
golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
gonum.org/v1/plot v0.15.2 h1:Tlfh/jBk2tqjLZ4/P8ZIwGrLEWQSPDLRm/SNWKNXiGI=
gonum.org/v1/plot v0.15.2/go.mod h1:DX+x+DWso3LTha+AdkJEv5Txvi+Tql3KAGkehP0/Ubg=
+3 -3
View File
@@ -51,7 +51,7 @@ type logEntry struct {
shouldFatal bool
}
// NewLogger returns a Logger that emits logs to Sentry. If logging is turned off, all logs get discarded.
// NewLogger returns a Logger that emits logs to Sentry.
func NewLogger(ctx context.Context) Logger { // nolint: dupl
var hub *Hub
hub = GetHubFromContext(ctx)
@@ -60,7 +60,7 @@ func NewLogger(ctx context.Context) Logger { // nolint: dupl
}
client := hub.Client()
if client != nil && !client.options.DisableLogs {
if client != nil {
// Build default attrs
serverAddr := client.options.ServerName
if serverAddr == "" {
@@ -91,7 +91,7 @@ func NewLogger(ctx context.Context) Logger { // nolint: dupl
}
}
debuglog.Println("fallback to noopLogger: SDK not initialized or logs disabled")
debuglog.Println("fallback to noopLogger: SDK not initialized")
return &noopLogger{}
}
+7 -7
View File
@@ -47,7 +47,7 @@ const (
UnitPercent = "percent"
)
// NewMeter returns a new Meter. If there is no Client bound to the current hub, or if metrics are disabled,
// NewMeter returns a new Meter. If there is no Client bound to the current hub,
// it returns a no-op Meter that discards all metrics.
func NewMeter(ctx context.Context) Meter {
hub := GetHubFromContext(ctx)
@@ -55,7 +55,7 @@ func NewMeter(ctx context.Context) Meter {
hub = CurrentHub()
}
client := hub.Client()
if client != nil && !client.options.DisableMetrics {
if client != nil {
// build default attrs
serverAddr := client.options.ServerName
if serverAddr == "" {
@@ -86,7 +86,7 @@ func NewMeter(ctx context.Context) Meter {
}
}
debuglog.Printf("fallback to noopMeter: metrics disabled")
debuglog.Printf("fallback to noopMeter: SDK not initialized")
return &noopMeter{}
}
@@ -222,20 +222,20 @@ func (n *noopMeter) WithCtx(_ context.Context) Meter {
// Count implements Meter.
func (n *noopMeter) Count(name string, _ int64, _ ...MeterOption) {
debuglog.Printf("Metric %q is being dropped. Turn on metrics by setting DisableMetrics to false", name)
debuglog.Printf("Metric %q is being dropped. Ensure the SDK is initialized", name)
}
// Distribution implements Meter.
func (n *noopMeter) Distribution(name string, _ float64, _ ...MeterOption) {
debuglog.Printf("Metric %q is being dropped. Turn on metrics by setting DisableMetrics to false", name)
debuglog.Printf("Metric %q is being dropped. Ensure the SDK is initialized", name)
}
// Gauge implements Meter.
func (n *noopMeter) Gauge(name string, _ float64, _ ...MeterOption) {
debuglog.Printf("Metric %q is being dropped. Turn on metrics by setting DisableMetrics to false", name)
debuglog.Printf("Metric %q is being dropped. Ensure the SDK is initialized", name)
}
// SetAttributes implements Meter.
func (n *noopMeter) SetAttributes(_ ...attribute.Builder) {
debuglog.Printf("No attributes attached. Turn on metrics by setting DisableMetrics to false")
debuglog.Printf("No attributes attached")
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
)
// The version of the SDK.
const SDKVersion = "0.48.0"
const SDKVersion = "0.49.0"
// apiVersion is the minimum version of the Sentry API compatible with the
// sentry-go SDK.
+16
View File
@@ -33,6 +33,7 @@ func NewStacktrace() *Stacktrace {
}
runtimeFrames := extractFrames(pcs[:n])
runtimeFrames = trimPanicFrames(runtimeFrames)
frames := createFrames(runtimeFrames)
stacktrace := Stacktrace{
@@ -282,6 +283,21 @@ func extractFrames(pcs []uintptr) []runtime.Frame {
return frames
}
// trimPanicFrames removes frames added while handling an active panic.
//
// The runtime.gopanic frame indicates the part of the code that caused the panic.
// This is helpful for skipping any wrapper code that was used to handle and recover
// from the panic, so that we only keep the relevant frames.
func trimPanicFrames(frames []runtime.Frame) []runtime.Frame {
for i := len(frames) - 1; i >= 0; i-- {
if frames[i].Function == "runtime.gopanic" {
return frames[:i]
}
}
return frames
}
// createFrames creates Frame objects while filtering out frames that are not
// meant to be reported to Sentry, those are frames internal to the SDK or Go.
func createFrames(frames []runtime.Frame) []Frame {
+2
View File
@@ -43,6 +43,7 @@ go get -u github.com/go-faker/faker/v4
- [language: example_with_tags_lang_test.go](/example_with_tags_lang_test.go)
- [unique: example_with_tags_unique_test.go](example_with_tags_unique_test.go)
- [slice length: example_with_tags_slicelength_test.go](example_with_tags_slicelength_test.go)
- [template (derived fields): example_template_tag_test.go](example_template_tag_test.go)
- Custom Struct's tag (define your own faker data): [example_custom_faker_test.go](/example_custom_faker_test.go)
- Without struct's tag: [example_without_tag_test.go](/example_without_tag_test.go)
- Single Fake Data Function: [example_single_fake_data_test.go](/example_single_fake_data_test.go)
@@ -103,6 +104,7 @@ Unfortunately this library has some limitation
- It does not support the `map[any]any`, `map[T]any` & `map[any]T` data types (where `T` is any concrete type). Once again, we cannot generate values for an unknown data type.
- Some extra custom types can be supported IF AND ONLY IF extended with [AddProvider()](https://github.com/go-faker/faker/blob/7473ac7d8d0440d24addac302c73e13c08895764/faker.go#L303) please see [example](example_custom_faker_test.go#L46)
- The `oneof` tag currently only supports `string`, the `int` types, and both `float32` & `float64`. Further support is coming soon (i.e. hex numbers, etc). See [example](example_with_tags_test.go#L53) for usage.
- The `template` tag currently only supports `string`, named string types & `*string`, and can only reference the fields of the struct that declares it. See [example](example_template_tag_test.go) for usage.
## Contribution
+64 -1
View File
@@ -91,6 +91,7 @@ const (
comma = ","
colon = ":"
ONEOF = "oneof"
TemplateTag = "template"
RussianFirstNameMaleTag = "russian_first_name_male"
RussianMiddleNameMaleTag = "russian_middle_name_male"
RussianLastNameMaleTag = "russian_last_name_male"
@@ -586,6 +587,8 @@ func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (re
}
originalDataVal := reflect.ValueOf(item)
v := reflect.New(t).Elem()
// collect template fields to evaluate in a second pass
var templateFields []int
if opts.MaxFieldDepthOption == 0 {
return v, nil
} else if opts.MaxFieldDepthOption > 0 {
@@ -617,6 +620,27 @@ func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (re
}
tags := decodeTags(t, i, opts.TagName)
// A template field is derived from other fields, so it is deferred to a
// second pass that runs once every other field has been generated.
if tags.isTemplate {
if tags.unique {
// A template over fixed inputs is deterministic, so the retry loop
// could never produce a different value. Fail loudly instead.
return reflect.Value{}, fmt.Errorf(fakerErrors.ErrTemplateWithUnique, t.Field(i).Name)
}
if tags.keepOriginal {
zero, err := isZero(originalDataVal.Field(i))
if err != nil {
return reflect.Value{}, err
}
if !zero {
v.Field(i).Set(originalDataVal.Field(i))
continue
}
}
templateFields = append(templateFields, i)
continue
}
switch {
case tags.keepOriginal:
zero, err := isZero(reflect.ValueOf(item).Field(i))
@@ -675,6 +699,10 @@ func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (re
}
}
// second pass: evaluate template fields using values generated above
if err := evaluateTemplateFields(t, v, templateFields, opts.TagName); err != nil {
return reflect.Value{}, err
}
return v, nil
}
@@ -699,6 +727,10 @@ func decodeTags(typ reflect.Type, i int, tagName string) structTag {
uni := false
res := make([]string, 0)
pMap := make(map[string]string)
// body collects the template body once a "template:" chunk is seen. Everything
// after that chunk belongs to the body, so a template may contain commas; only
// the standalone "keep" and "unique" chunks keep their usual meaning.
var body []string
for _, tag := range tags {
if tag == keep {
keepOriginal = true
@@ -707,12 +739,30 @@ func decodeTags(typ reflect.Type, i int, tagName string) structTag {
uni = true
continue
}
if body != nil {
body = append(body, tag)
continue
}
if hasTemplatePrefix(strings.TrimSpace(tag)) {
body = append(body, strings.TrimSpace(tag)[len(TemplateTag)+1:])
continue
}
// res = append(res, tag)
ptag := strings.ToLower(strings.Trim(strings.Split(tag, "=")[0], " "))
pMap[ptag] = tag
ptag = strings.ToLower(strings.Trim(strings.Split(tag, ":")[0], " "))
pMap[ptag] = tag
}
if body != nil {
// A template body is opaque: it must never reach the priority scanner, which
// would otherwise hijack a chunk such as ", email: {{.X}}" as the email tag.
return structTag{
template: strings.Join(body, comma),
isTemplate: true,
unique: uni,
keepOriginal: keepOriginal,
}
}
// Priority
for _, ptag := range PriorityTags {
if tag, ok := pMap[ptag]; ok {
@@ -739,9 +789,22 @@ func decodeTags(typ reflect.Type, i int, tagName string) structTag {
}
type structTag struct {
fieldType string
fieldType string
// template holds the verbatim template body when isTemplate is set. It is kept
// out of fieldType because a template body is not a tag and must not be parsed
// as one.
template string
unique bool
keepOriginal bool
isTemplate bool
}
// hasTemplatePrefix reports whether s starts with "template:" (case-insensitive).
// The colon is required, so `faker:"template"` and `faker:"templated"` stay with
// the normal tag pipeline.
func hasTemplatePrefix(s string) bool {
const n = len(TemplateTag) + 1
return len(s) >= n && strings.EqualFold(s[:n], TemplateTag+colon)
}
func setDataWithTag(v reflect.Value, tag string, opt options.Options) error {
+13
View File
@@ -10,6 +10,12 @@ package errors
// ErrTagDoesNotExist: Error when tag does not exist and call RemoveProvider
// ErrMoreArguments: Error on passing more arguments
// ErrNotSupportedPointer: Error when passing unsupported pointer
// ErrTemplateNotStringField: Error when the template tag is used on a non-string field
// ErrTemplateEmptyBody: Error when the template tag has no body
// ErrTemplateParse: Error when the template body fails to parse
// ErrTemplateEvaluate: Error when the template body fails to execute
// ErrTemplateCycle: Error when template fields reference each other in a cycle
// ErrTemplateWithUnique: Error when the template tag is combined with the unique tag
var (
ErrUnsupportedKindPtr = "Unsupported kind: %s Change Without using * (pointer) in Field of %s"
ErrUnsupportedKind = "Unsupported kind: %s"
@@ -33,4 +39,11 @@ var (
ErrNotEnoughTagArguments = "Not enough arguments for tag."
ErrUnsupportedNumberType = "Unsupported Number type."
ErrOnlyStructTypeSupported = "only struct type supported."
ErrTemplateNotStringField = "Template tag is only supported on string fields, field \"%s\" is %s"
ErrTemplateEmptyBody = "Template tag for field \"%s\" has an empty body"
ErrTemplateParse = "Failed to parse template for field \"%s\": %w"
ErrTemplateEvaluate = "Failed to evaluate template for field \"%s\": %w"
ErrTemplateCycle = "Template tag cycle detected: %s"
ErrTemplateWithUnique = "Tag \"unique\" can not be combined with the template tag (field \"%s\")"
)
+342
View File
@@ -0,0 +1,342 @@
package faker
// The template tag (`faker:"template:{{.Other}}"`) derives a field's value from
// other fields of the same struct. Because a template reads values that faker
// itself generates, template fields are filled in a second pass that runs after
// every other field of the struct is done — see getFakedValueForStruct.
//
// Within that second pass, template fields are evaluated in dependency order
// rather than declaration order, so a template may reference another template
// field declared later. Only a true cycle is an error.
//
// TemplateTag is deliberately absent from PriorityTags: it is not a provider, and
// listing it there would route the tag through setDataWithTag.
import (
"bytes"
"errors"
"fmt"
"reflect"
"strings"
"text/template"
"text/template/parse"
"unicode"
fakerErrors "github.com/go-faker/faker/v4/pkg/errors"
)
// templateField is one parsed, validated template-tagged field of a struct.
type templateField struct {
index int // index of the field within the struct
name string // field name, used in error messages
tpl *template.Template
deps []int // positions within templatePlan.fields this field depends on
}
// templatePlan is the validated evaluation plan for the template fields of one
// struct type.
type templatePlan struct {
fields []templateField // declaration order
order []int // positions within fields, in dependency order
}
// evaluateTemplateFields fills the template-tagged fields of v listed in fields.
// v must be an addressable struct value of type t. fields holds struct field
// indices collected by the first pass; a template field missing from it was
// handled by a higher-precedence option (IgnoreFields, OnlyZeroFields,
// FieldProviders, keep) and is left alone.
func evaluateTemplateFields(t reflect.Type, v reflect.Value, fields []int, tagName string) error {
if len(fields) == 0 {
return nil
}
if !v.CanAddr() {
return errors.New(fakerErrors.ErrValueNotPtr)
}
plan, err := buildTemplatePlan(t, tagName)
if err != nil {
return err
}
// Templates read the struct itself rather than a map built by reflection. That
// is what makes unexported fields safe: text/template reports them as an error
// instead of us panicking on reflect.Value.Interface. Taking the address means
// each template also sees the results written by earlier ones.
data := v.Addr().Interface()
var buf bytes.Buffer
for _, p := range plan.order {
tf := &plan.fields[p]
if !containsFieldIndex(fields, tf.index) {
continue
}
buf.Reset()
if err := tf.tpl.Execute(&buf, data); err != nil {
return fmt.Errorf(fakerErrors.ErrTemplateEvaluate, tf.name, err)
}
setTemplateResult(v.Field(tf.index), buf.String())
}
return nil
}
func containsFieldIndex(fields []int, idx int) bool {
for _, f := range fields {
if f == idx {
return true
}
}
return false
}
// buildTemplatePlan parses and validates every template-tagged field of t and
// works out the order they must be evaluated in.
func buildTemplatePlan(t reflect.Type, tagName string) (*templatePlan, error) {
plan := &templatePlan{}
posByName := make(map[string]int)
for i := range t.NumField() {
f := t.Field(i)
if !f.IsExported() {
continue
}
tags := decodeTags(t, i, tagName)
if !tags.isTemplate {
continue
}
// Validate the destination before anything is evaluated, so a bad tag can
// never leave some fields written and others not.
if !templateAssignable(f.Type) {
return nil, fmt.Errorf(fakerErrors.ErrTemplateNotStringField, f.Name, f.Type)
}
if strings.TrimSpace(tags.template) == "" {
return nil, fmt.Errorf(fakerErrors.ErrTemplateEmptyBody, f.Name)
}
tpl, err := template.New(f.Name).Funcs(templateHelpers).Parse(tags.template)
if err != nil {
return nil, fmt.Errorf(fakerErrors.ErrTemplateParse, f.Name, err)
}
posByName[f.Name] = len(plan.fields)
plan.fields = append(plan.fields, templateField{index: i, name: f.Name, tpl: tpl})
}
if len(plan.fields) == 0 {
return plan, nil
}
// Only references to other template fields become edges. References to ordinary
// fields need no ordering: the first pass already filled them.
for p := range plan.fields {
for _, ref := range templateFieldRefs(plan.fields[p].tpl.Tree) {
if q, ok := posByName[ref]; ok {
plan.fields[p].deps = append(plan.fields[p].deps, q)
}
}
}
order, err := topoSortTemplateFields(plan.fields)
if err != nil {
return nil, err
}
plan.order = order
return plan, nil
}
// templateAssignable reports whether the template result can be stored in a field
// of type t. Named string types work through SetString; *string is allocated.
func templateAssignable(t reflect.Type) bool {
return t.Kind() == reflect.String ||
(t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.String)
}
func setTemplateResult(f reflect.Value, s string) {
if f.Kind() == reflect.Pointer {
p := reflect.New(f.Type().Elem())
p.Elem().SetString(s)
f.Set(p)
return
}
f.SetString(s)
}
// templateFieldRefs returns the names of the struct fields a template reads, in
// source order and deduplicated.
//
// It walks the parse tree rather than matching the template source with a regular
// expression: only the tree can tell a field reference from literal text such as
// "@Example.Com", can report `{{.Addr.City}}` as a reference to Addr alone, and
// can tell that the dot inside a `range` or `with` body is the loop value rather
// than the struct.
func templateFieldRefs(tree *parse.Tree) []string {
if tree == nil || tree.Root == nil {
return nil
}
var out []string
seen := make(map[string]struct{})
add := func(name string) {
if _, ok := seen[name]; !ok {
seen[name] = struct{}{}
out = append(out, name)
}
}
var walk func(parse.Node)
// walkBranch handles if/range/with. The controlling pipe is always evaluated
// with the outer dot; range and with rebind dot for their body, so the body
// cannot reference our struct's fields. An else body runs with the outer dot.
walkBranch := func(b *parse.BranchNode, rebindsDot bool) {
walk(b.Pipe)
if !rebindsDot && b.List != nil {
walk(b.List)
}
if b.ElseList != nil {
walk(b.ElseList)
}
}
walk = func(n parse.Node) {
switch n := n.(type) {
case *parse.ListNode:
if n == nil {
return
}
for _, c := range n.Nodes {
walk(c)
}
case *parse.ActionNode:
walk(n.Pipe)
case *parse.PipeNode:
if n == nil {
return
}
for _, d := range n.Decl {
walk(d)
}
for _, c := range n.Cmds {
walk(c)
}
case *parse.CommandNode:
for _, a := range n.Args {
walk(a)
}
case *parse.FieldNode:
if len(n.Ident) > 0 {
add(n.Ident[0])
}
case *parse.ChainNode:
if _, isDot := n.Node.(*parse.DotNode); isDot && len(n.Field) > 0 {
add(n.Field[0])
}
walk(n.Node)
case *parse.IfNode:
walkBranch(&n.BranchNode, false)
case *parse.RangeNode:
walkBranch(&n.BranchNode, true)
case *parse.WithNode:
walkBranch(&n.BranchNode, true)
case *parse.TemplateNode:
walk(n.Pipe)
}
}
walk(tree.Root)
return out
}
// topoSortTemplateFields returns the positions of fields in dependency order:
// every field appears after the template fields it references. Roots are visited
// in declaration order so the result is deterministic. A cycle, including a field
// that references itself, is an error.
func topoSortTemplateFields(fields []templateField) ([]int, error) {
const (
white = iota
grey
black
)
state := make([]int8, len(fields))
order := make([]int, 0, len(fields))
stack := make([]int, 0, len(fields))
var visit func(p int) error
visit = func(p int) error {
switch state[p] {
case black:
return nil
case grey:
return fmt.Errorf(fakerErrors.ErrTemplateCycle, cyclePath(fields, stack, p))
}
state[p] = grey
stack = append(stack, p)
for _, d := range fields[p].deps {
if err := visit(d); err != nil {
return err
}
}
stack = stack[:len(stack)-1]
state[p] = black
order = append(order, p)
return nil
}
for p := range fields {
if err := visit(p); err != nil {
return nil, err
}
}
return order, nil
}
// cyclePath renders a cycle as "A -> B -> A", starting from where p first appears
// on the visit stack.
func cyclePath(fields []templateField, stack []int, p int) string {
start := 0
for i, s := range stack {
if s == p {
start = i
break
}
}
names := make([]string, 0, len(stack)-start+1)
for _, s := range stack[start:] {
names = append(names, fields[s].name)
}
names = append(names, fields[p].name)
return strings.Join(names, " -> ")
}
// templateHelpers is read-only after initialization and shared by every template.
var templateHelpers = template.FuncMap{
"lower": func(v any) string { return strings.ToLower(templateString(v)) },
"upper": func(v any) string { return strings.ToUpper(templateString(v)) },
"trim": func(v any) string { return strings.TrimSpace(templateString(v)) },
"slug": func(v any) string { return slugify(templateString(v)) },
}
// templateString coerces a template argument to a string so the helpers also work
// on named string types, numbers and fmt.Stringer values.
func templateString(v any) string {
switch s := v.(type) {
case nil:
return ""
case string:
return s
case fmt.Stringer:
return s.String()
}
if rv := reflect.ValueOf(v); rv.Kind() == reflect.String {
return rv.String()
}
return fmt.Sprint(v)
}
// slugify lowercases s and replaces each run of non-alphanumeric characters with
// a single dash, trimming dashes from both ends. Letters and digits of any script
// are kept, so names generated by the Chinese and Russian providers survive.
func slugify(s string) string {
s = strings.ToLower(s)
var b strings.Builder
b.Grow(len(s))
lastDash := false
for _, r := range s {
switch {
case unicode.IsLetter(r) || unicode.IsDigit(r):
b.WriteRune(r)
lastDash = false
case !lastDash:
b.WriteByte('-')
lastDash = true
}
}
return strings.Trim(b.String(), "-")
}
+15 -188
View File
@@ -1,222 +1,49 @@
//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
// decompress4x_main_loop_amd64 is an x86 assembler implementation
// of Decompress4X when tablelog > 8.
//
//go:noescape
func decompress4x_main_loop_amd64(ctx *decompress4xContext)
// decompress4x_8b_loop_x86 is an x86 assembler implementation
// decompress4x_8b_main_loop_amd64 is an x86 assembler implementation
// of Decompress4X when tablelog <= 8 which decodes 4 entries
// per loop.
//
//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 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")
}
use8BitTables := d.actualTableLog <= 8
if cap(dst) < fallback8BitSize && use8BitTables {
return d.decompress4X8bit(dst, src)
}
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
}
// 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:]
}
// 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
}
// decompress4x_main_loop_x86 is an x86 assembler implementation
// decompress1x_main_loop_amd64 is an x86 assembler implementation
// of Decompress1X when tablelog > 8.
//
//go:noescape
func decompress1x_main_loop_amd64(ctx *decompress1xContext)
// decompress4x_main_loop_x86 is an x86 with BMI2 assembler implementation
// decompress1x_main_loop_bmi2 is an x86 with BMI2 assembler implementation
// of Decompress1X when tablelog > 8.
//
//go:noescape
func decompress1x_main_loop_bmi2(ctx *decompress1xContext)
type decompress1xContext struct {
pbr *bitReaderShifted
peekBits uint8
out *byte
outCap int
tbl *dEntrySingle
decoded int
func decompress4x_main_loop_asm(ctx *decompress4xContext) {
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) {
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 decompress1x_main_loop_asm(ctx *decompress1xContext) {
if cpuinfo.HasBMI2() {
decompress1x_main_loop_bmi2(ctx)
} else {
decompress1x_main_loop_amd64(ctx)
}
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
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]
}
// 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))
}
return dst, br.close()
}
+2 -2
View File
@@ -1,6 +1,6 @@
// 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)
TEXT ·decompress4x_main_loop_amd64(SB), $0-8
+37
View File
@@ -0,0 +1,37 @@
//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.
//
//go:noescape
func decompress4x_main_loop_arm64(ctx *decompress4xContext)
// decompress4x_8b_main_loop_arm64 is an arm64 assembler implementation
// of Decompress4X when tablelog <= 8 which decodes 4 entries
// per loop.
//
//go:noescape
func decompress4x_8b_main_loop_arm64(ctx *decompress4xContext)
// decompress1x_main_loop_arm64 is an arm64 assembler implementation
// of Decompress1X when tablelog > 8.
//
//go:noescape
func decompress1x_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 decompress1x_main_loop_asm(ctx *decompress1xContext) {
decompress1x_main_loop_arm64(ctx)
}
+851
View File
@@ -0,0 +1,851 @@
// 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)
TEXT ·decompress4x_main_loop_arm64(SB), $0-8
// Preload values
MOVD ctx+0(FP), R0
MOVBU 8(R0), R6
MOVD 16(R0), R3
MOVD 48(R0), R5
MOVD 24(R0), R7
MOVD 32(R0), R8
MOVD (R0), R9
// Main loop
main_loop:
MOVD $0, R2
CMP R5, R3
CSET GE, R16
BFI $0, R16, $8, R2
// br0.fillFast32()
MOVD 32(R9), R10
MOVBU 40(R9), R11
CMP $0x20, R11
BLS skip_fill0
MOVD 24(R9), R0
SUB $0x20, R11, R11
SUB $0x04, R0, R0
MOVD (R9), R12
// b.value |= uint64(low) << (b.bitsRead & 63)
ADD R12, R0, R15
MOVWU (R15), R12
MOVD R11, R1
LSL R1, R12, R12
MOVD R0, 24(R9)
ORR R12, R10, R10
// exhausted += (br0.off < 4)
CMP $0x04, R0
CSINC HS, R2, R2, R16
BFI $0, R16, $8, R2
skip_fill0:
// val0 := br0.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v0 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br0.advance(uint8(v0.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val1 := br0.peekTopBits(peekBits)
MOVD R6, R1
MOVD R10, R12
LSR R1, R12, R12
// v1 := table[val1&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br0.advance(uint8(v1.entry))
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// these two writes get coalesced
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
MOVH R0, (R3)
// update the bitreader structure
MOVD R10, 32(R9)
MOVB R11, 40(R9)
// br1.fillFast32()
MOVD 80(R9), R10
MOVBU 88(R9), R11
CMP $0x20, R11
BLS skip_fill1
MOVD 72(R9), R0
SUB $0x20, R11, R11
SUB $0x04, R0, R0
MOVD 48(R9), R12
// b.value |= uint64(low) << (b.bitsRead & 63)
ADD R12, R0, R15
MOVWU (R15), R12
MOVD R11, R1
LSL R1, R12, R12
MOVD R0, 72(R9)
ORR R12, R10, R10
// exhausted += (br1.off < 4)
CMP $0x04, R0
CSINC HS, R2, R2, R16
BFI $0, R16, $8, R2
skip_fill1:
// val0 := br1.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v0 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br1.advance(uint8(v0.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val1 := br1.peekTopBits(peekBits)
MOVD R6, R1
MOVD R10, R12
LSR R1, R12, R12
// v1 := table[val1&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br1.advance(uint8(v1.entry))
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// these two writes get coalesced
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
ADD R7, R3, R15
MOVH R0, (R15)
// update the bitreader structure
MOVD R10, 80(R9)
MOVB R11, 88(R9)
// br2.fillFast32()
MOVD 128(R9), R10
MOVBU 136(R9), R11
CMP $0x20, R11
BLS skip_fill2
MOVD 120(R9), R0
SUB $0x20, R11, R11
SUB $0x04, R0, R0
MOVD 96(R9), R12
// b.value |= uint64(low) << (b.bitsRead & 63)
ADD R12, R0, R15
MOVWU (R15), R12
MOVD R11, R1
LSL R1, R12, R12
MOVD R0, 120(R9)
ORR R12, R10, R10
// exhausted += (br2.off < 4)
CMP $0x04, R0
CSINC HS, R2, R2, R16
BFI $0, R16, $8, R2
skip_fill2:
// val0 := br2.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v0 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br2.advance(uint8(v0.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val1 := br2.peekTopBits(peekBits)
MOVD R6, R1
MOVD R10, R12
LSR R1, R12, R12
// v1 := table[val1&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br2.advance(uint8(v1.entry))
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// these two writes get coalesced
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
ADD R7<<1, R3, R15
MOVH R0, (R15)
// update the bitreader structure
MOVD R10, 128(R9)
MOVB R11, 136(R9)
// br3.fillFast32()
MOVD 176(R9), R10
MOVBU 184(R9), R11
CMP $0x20, R11
BLS skip_fill3
MOVD 168(R9), R0
SUB $0x20, R11, R11
SUB $0x04, R0, R0
MOVD 144(R9), R12
// b.value |= uint64(low) << (b.bitsRead & 63)
ADD R12, R0, R15
MOVWU (R15), R12
MOVD R11, R1
LSL R1, R12, R12
MOVD R0, 168(R9)
ORR R12, R10, R10
// exhausted += (br3.off < 4)
CMP $0x04, R0
CSINC HS, R2, R2, R16
BFI $0, R16, $8, R2
skip_fill3:
// val0 := br3.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v0 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br3.advance(uint8(v0.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val1 := br3.peekTopBits(peekBits)
MOVD R6, R1
MOVD R10, R12
LSR R1, R12, R12
// v1 := table[val1&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br3.advance(uint8(v1.entry))
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// these two writes get coalesced
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
ADD R7<<1, R7, R1
ADD R1, R3, R15
MOVH R0, (R15)
// update the bitreader structure
MOVD R10, 176(R9)
MOVB R11, 184(R9)
ADD $0x02, R3, R3
AND $0xff, R2, R15
AND $0xff, R2, R16
TST R16, R15
BEQ main_loop
MOVD ctx+0(FP), R0
MOVD 16(R0), R16
SUB R16, R3, R3
LSL $0x02, R3, R3
MOVD R3, 40(R0)
RET
// func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext)
TEXT ·decompress4x_8b_main_loop_arm64(SB), $0-8
// Preload values
MOVD ctx+0(FP), R1
MOVBU 8(R1), R6
MOVD 16(R1), R3
MOVD 48(R1), R5
MOVD 24(R1), R7
MOVD 32(R1), R8
MOVD (R1), R9
// Main loop
main_loop:
MOVD $0, R2
CMP R5, R3
CSET GE, R16
BFI $0, R16, $8, R2
// br0.fillFast32()
MOVD 32(R9), R10
MOVBU 40(R9), R11
CMP $0x20, R11
BLS skip_fill0
MOVD 24(R9), R12
SUB $0x20, R11, R11
SUB $0x04, R12, R12
MOVD (R9), R13
// b.value |= uint64(low) << (b.bitsRead & 63)
ADD R13, R12, R15
MOVWU (R15), R13
MOVD R11, R1
LSL R1, R13, R13
MOVD R12, 24(R9)
ORR R13, R10, R10
// exhausted += (br0.off < 4)
CMP $0x04, R12
CSINC HS, R2, R2, R16
BFI $0, R16, $8, R2
skip_fill0:
// val0 := br0.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v0 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br0.advance(uint8(v0.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val1 := br0.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v1 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br0.advance(uint8(v1.entry)
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
REVW R0, R0
// val2 := br0.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v2 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br0.advance(uint8(v2.entry)
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val3 := br0.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v3 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br0.advance(uint8(v3.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
REVW R0, R0
// 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)
MOVW R0, (R3)
// update the bitreader structure
MOVD R10, 32(R9)
MOVB R11, 40(R9)
// br1.fillFast32()
MOVD 80(R9), R10
MOVBU 88(R9), R11
CMP $0x20, R11
BLS skip_fill1
MOVD 72(R9), R12
SUB $0x20, R11, R11
SUB $0x04, R12, R12
MOVD 48(R9), R13
// b.value |= uint64(low) << (b.bitsRead & 63)
ADD R13, R12, R15
MOVWU (R15), R13
MOVD R11, R1
LSL R1, R13, R13
MOVD R12, 72(R9)
ORR R13, R10, R10
// exhausted += (br1.off < 4)
CMP $0x04, R12
CSINC HS, R2, R2, R16
BFI $0, R16, $8, R2
skip_fill1:
// val0 := br1.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v0 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br1.advance(uint8(v0.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val1 := br1.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v1 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br1.advance(uint8(v1.entry)
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
REVW R0, R0
// val2 := br1.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v2 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br1.advance(uint8(v2.entry)
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val3 := br1.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v3 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br1.advance(uint8(v3.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
REVW R0, R0
// 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)
ADD R7, R3, R15
MOVW R0, (R15)
// update the bitreader structure
MOVD R10, 80(R9)
MOVB R11, 88(R9)
// br2.fillFast32()
MOVD 128(R9), R10
MOVBU 136(R9), R11
CMP $0x20, R11
BLS skip_fill2
MOVD 120(R9), R12
SUB $0x20, R11, R11
SUB $0x04, R12, R12
MOVD 96(R9), R13
// b.value |= uint64(low) << (b.bitsRead & 63)
ADD R13, R12, R15
MOVWU (R15), R13
MOVD R11, R1
LSL R1, R13, R13
MOVD R12, 120(R9)
ORR R13, R10, R10
// exhausted += (br2.off < 4)
CMP $0x04, R12
CSINC HS, R2, R2, R16
BFI $0, R16, $8, R2
skip_fill2:
// val0 := br2.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v0 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br2.advance(uint8(v0.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val1 := br2.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v1 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br2.advance(uint8(v1.entry)
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
REVW R0, R0
// val2 := br2.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v2 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br2.advance(uint8(v2.entry)
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val3 := br2.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v3 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br2.advance(uint8(v3.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
REVW R0, R0
// 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)
ADD R7<<1, R3, R15
MOVW R0, (R15)
// update the bitreader structure
MOVD R10, 128(R9)
MOVB R11, 136(R9)
// br3.fillFast32()
MOVD 176(R9), R10
MOVBU 184(R9), R11
CMP $0x20, R11
BLS skip_fill3
MOVD 168(R9), R12
SUB $0x20, R11, R11
SUB $0x04, R12, R12
MOVD 144(R9), R13
// b.value |= uint64(low) << (b.bitsRead & 63)
ADD R13, R12, R15
MOVWU (R15), R13
MOVD R11, R1
LSL R1, R13, R13
MOVD R12, 168(R9)
ORR R13, R10, R10
// exhausted += (br3.off < 4)
CMP $0x04, R12
CSINC HS, R2, R2, R16
BFI $0, R16, $8, R2
skip_fill3:
// val0 := br3.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v0 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br3.advance(uint8(v0.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val1 := br3.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v1 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br3.advance(uint8(v1.entry)
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
REVW R0, R0
// val2 := br3.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v2 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br3.advance(uint8(v2.entry)
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
// val3 := br3.peekTopBits(peekBits)
MOVD R10, R12
MOVD R6, R1
LSR R1, R12, R12
// v3 := table[val0&mask]
ADD R12<<1, R8, R15
MOVHU (R15), R1
// br3.advance(uint8(v3.entry)
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
LSL R1, R10, R10
ADD R1, R11, R15
BFI $0, R15, $8, R11
REVW R0, R0
// 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)
ADD R7<<1, R7, R1
ADD R1, R3, R15
MOVW R0, (R15)
// update the bitreader structure
MOVD R10, 176(R9)
MOVB R11, 184(R9)
ADD $0x04, R3, R3
AND $0xff, R2, R15
AND $0xff, R2, R16
TST R16, R15
BEQ main_loop
MOVD ctx+0(FP), R0
MOVD 16(R0), R16
SUB R16, R3, R3
LSL $0x02, R3, R3
MOVD R3, 40(R0)
RET
// func decompress1x_main_loop_amd64(ctx *decompress1xContext)
TEXT ·decompress1x_main_loop_arm64(SB), $0-8
MOVD ctx+0(FP), R1
MOVD 16(R1), R2
MOVD 24(R1), R3
CMP $0x04, R3
BLO error_max_decoded_size_exceeded
ADD R3, R2, R3
MOVD (R1), R5
MOVD (R5), R7
MOVD 24(R5), R8
MOVD 32(R5), R9
MOVBU 40(R5), R10
MOVD 32(R1), R5
MOVBU 8(R1), R6
JMP loop_condition
main_loop:
// Check if we have room for 4 bytes in the output buffer
ADD $4, R2, R1
CMP R3, R1
BGE error_max_decoded_size_exceeded
// Decode 4 values
CMP $0x20, R10
BLT bitReader_fillFast_1_end
SUB $0x20, R10, R10
SUB $0x04, R8, R8
ADD R8, R7, R15
MOVWU (R15), R11
MOVD R10, R1
LSL R1, R11, R11
ORR R11, R9, R9
bitReader_fillFast_1_end:
MOVD R6, R1
MOVD R9, R11
LSR R1, R11, R11
ADD R11<<1, R5, R15
MOVHU (R15), R1
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
MOVBU R1, R1
ADD R1, R10, R10
LSL R1, R9, R9
MOVD R6, R1
MOVD R9, R11
LSR R1, R11, R11
ADD R11<<1, R5, R15
MOVHU (R15), R1
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
MOVBU R1, R1
ADD R1, R10, R10
LSL R1, R9, R9
REVW R0, R0
CMP $0x20, R10
BLT bitReader_fillFast_2_end
SUB $0x20, R10, R10
SUB $0x04, R8, R8
ADD R8, R7, R15
MOVWU (R15), R11
MOVD R10, R1
LSL R1, R11, R11
ORR R11, R9, R9
bitReader_fillFast_2_end:
MOVD R6, R1
MOVD R9, R11
LSR R1, R11, R11
ADD R11<<1, R5, R15
MOVHU (R15), R1
UBFX $8, R1, $8, R16
BFI $8, R16, $8, R0
MOVBU R1, R1
ADD R1, R10, R10
LSL R1, R9, R9
MOVD R6, R1
MOVD R9, R11
LSR R1, R11, R11
ADD R11<<1, R5, R15
MOVHU (R15), R1
UBFX $8, R1, $8, R16
BFI $0, R16, $8, R0
MOVBU R1, R1
ADD R1, R10, R10
LSL R1, R9, R9
REVW R0, R0
// Store the decoded values
MOVW R0, (R2)
ADD $0x04, R2, R2
loop_condition:
CMP $0x08, R8
BGE main_loop
// Update ctx structure
MOVD ctx+0(FP), R0
MOVD 16(R0), R16
SUB R16, R2, R2
MOVD R2, 40(R0)
MOVD (R0), R0
MOVD R8, 24(R0)
MOVD R9, 32(R0)
MOVB R10, 40(R0)
RET
// Report error
error_max_decoded_size_exceeded:
MOVD ctx+0(FP), R0
MOVD $-1, R1
MOVD R1, 40(R0)
RET
// skipped decompress1x_main_loop_bmi2 (generic twin preferred on arm64)
+193
View File
@@ -0,0 +1,193 @@
//go:build (amd64 || arm64) && !appengine && !noasm && gc
// This file contains the specialisation of Decoder.Decompress4X
// and Decoder.Decompress1X that use an asm implementation of their main loops.
// The asm function stubs and any per-arch dispatch live in decompress_amd64.go
// and decompress_arm64.go.
package huff0
import (
"errors"
"fmt"
)
// 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 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")
}
use8BitTables := d.actualTableLog <= 8
if cap(dst) < fallback8BitSize && use8BitTables {
return d.decompress4X8bit(dst, src)
}
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
}
// 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_asm(&ctx)
} else {
decompress4x_main_loop_asm(&ctx)
}
decoded = ctx.decoded
out = out[decoded/4:]
}
// 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
}
type decompress1xContext struct {
pbr *bitReaderShifted
peekBits uint8
out *byte
outCap int
tbl *dEntrySingle
decoded int
}
// Error reported by asm implementations
const error_max_decoded_size_exeeded = -1
// 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
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],
}
decompress1x_main_loop_asm(&ctx)
if ctx.decoded == error_max_decoded_size_exeeded {
return nil, ErrMaxDecodedSizeExceeded
}
dst = dst[:ctx.decoded]
}
// 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))
}
return dst, br.close()
}
+1 -1
View File
@@ -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
+3 -6
View File
@@ -400,8 +400,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 {
@@ -673,10 +674,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]
+64 -21
View File
@@ -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])
}
sortedOffsets = sortedOffsets[:3]
println("")
}
for i, v := range sortedOffsets {
o.Offsets[i] = int(v)
// 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
}
}
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)
+2 -2
View File
@@ -2081,7 +2081,7 @@ sequenceDecs_decodeSync_amd64_match_len_ofs_ok:
MOVQ 16(SP), R13
// Check if we have enough space in s.out
LEAQ (AX)(R13*1), R14
LEAQ 16(AX)(R13*1), R14
ADDQ R10, R14
CMPQ R14, 32(SP)
JA error_not_enough_space
@@ -2601,7 +2601,7 @@ sequenceDecs_decodeSync_bmi2_match_len_ofs_ok:
MOVQ 16(SP), R13
// Check if we have enough space in s.out
LEAQ (CX)(R13*1), R14
LEAQ 16(CX)(R13*1), R14
ADDQ R9, R14
CMPQ R14, 32(SP)
JA error_not_enough_space
File diff suppressed because it is too large. Load diff
+30 -3
View File
@@ -77,6 +77,35 @@ 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. 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 +115,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
+20 -8
View File
@@ -84,7 +84,7 @@ func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, ar
return Equal(t, expected, actual, append([]interface{}{msg}, args...)...)
}
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -124,7 +124,7 @@ func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg stri
return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...)
}
// Errorf asserts that a function returned an error (i.e. not `nil`).
// Errorf asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// assert.Errorf(t, err, "error message %s", "formatted")
@@ -144,8 +144,8 @@ func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...int
return ErrorAs(t, err, target, append([]interface{}{msg}, args...)...)
}
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted")
@@ -190,10 +190,10 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") {
// assert.EventuallyWithTf(t, func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
func EventuallyWithTf(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -552,7 +552,7 @@ func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool
return NoDirExists(t, path, append([]interface{}{msg}, args...)...)
}
// NoErrorf asserts that a function returned no error (i.e. `nil`).
// NoErrorf asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if assert.NoErrorf(t, err, "error message %s", "formatted") {
@@ -849,7 +849,19 @@ func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time,
return WithinRange(t, actual, start, end, append([]interface{}{msg}, args...)...)
}
// YAMLEqf asserts that two YAML strings are equivalent.
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// assert.YAMLEqf(t, expected, actual, "error message %s", "formatted")
func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
+38 -14
View File
@@ -146,7 +146,7 @@ func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs
return Equal(a.t, expected, actual, msgAndArgs...)
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// EqualError asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -158,7 +158,7 @@ func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...
return EqualError(a.t, theError, errString, msgAndArgs...)
}
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -240,7 +240,7 @@ func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string
return Equalf(a.t, expected, actual, msg, args...)
}
// Error asserts that a function returned an error (i.e. not `nil`).
// Error asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// a.Error(err)
@@ -269,8 +269,8 @@ func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args ..
return ErrorAsf(a.t, err, target, msg, args...)
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContains asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// a.ErrorContains(err, expectedErrorSubString)
@@ -281,8 +281,8 @@ func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs .
return ErrorContains(a.t, theError, contains, msgAndArgs...)
}
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted")
@@ -311,7 +311,7 @@ func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...inter
return ErrorIsf(a.t, err, target, msg, args...)
}
// Errorf asserts that a function returned an error (i.e. not `nil`).
// Errorf asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// a.Errorf(err, "error message %s", "formatted")
@@ -372,10 +372,10 @@ func (a *Assertions) EventuallyWithT(condition func(collect *CollectT), waitFor
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") {
// a.EventuallyWithTf(func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
func (a *Assertions) EventuallyWithTf(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1096,7 +1096,7 @@ func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{})
return NoDirExistsf(a.t, path, msg, args...)
}
// NoError asserts that a function returned no error (i.e. `nil`).
// NoError asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if a.NoError(err) {
@@ -1109,7 +1109,7 @@ func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool {
return NoError(a.t, err, msgAndArgs...)
}
// NoErrorf asserts that a function returned no error (i.e. `nil`).
// NoErrorf asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if a.NoErrorf(err, "error message %s", "formatted") {
@@ -1690,7 +1690,19 @@ func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Ti
return WithinRangef(a.t, actual, start, end, msg, args...)
}
// YAMLEq asserts that two YAML strings are equivalent.
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// a.YAMLEq(expected, actual)
func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1698,7 +1710,19 @@ func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interf
return YAMLEq(a.t, expected, actual, msgAndArgs...)
}
// YAMLEqf asserts that two YAML strings are equivalent.
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// a.YAMLEqf(expected, actual, "error message %s", "formatted")
func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
+13 -1
View File
@@ -9,7 +9,7 @@ import (
func isOrdered(t TestingT, object interface{}, allowedComparesResults []compareResult, failMessage string, msgAndArgs ...interface{}) bool {
objKind := reflect.TypeOf(object).Kind()
if objKind != reflect.Slice && objKind != reflect.Array {
return false
return Fail(t, fmt.Sprintf("object %T is not an ordered collection", object), msgAndArgs...)
}
objValue := reflect.ValueOf(object)
@@ -50,6 +50,9 @@ func isOrdered(t TestingT, object interface{}, allowedComparesResults []compareR
// assert.IsIncreasing(t, []float{1, 2})
// assert.IsIncreasing(t, []string{"a", "b"})
func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return isOrdered(t, object, []compareResult{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...)
}
@@ -59,6 +62,9 @@ func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo
// assert.IsNonIncreasing(t, []float{2, 1})
// assert.IsNonIncreasing(t, []string{"b", "a"})
func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return isOrdered(t, object, []compareResult{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...)
}
@@ -68,6 +74,9 @@ func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{})
// assert.IsDecreasing(t, []float{2, 1})
// assert.IsDecreasing(t, []string{"b", "a"})
func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return isOrdered(t, object, []compareResult{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...)
}
@@ -77,5 +86,8 @@ func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo
// assert.IsNonDecreasing(t, []float{1, 2})
// assert.IsNonDecreasing(t, []string{"a", "b"})
func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return isOrdered(t, object, []compareResult{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...)
}
+83 -64
View File
@@ -17,11 +17,10 @@ import (
"unicode"
"unicode/utf8"
"github.com/davecgh/go-spew/spew"
"github.com/pmezard/go-difflib/difflib"
// Wrapper around gopkg.in/yaml.v3
// Wrapper around go.yaml.in/yaml/v3
"github.com/stretchr/testify/assert/yaml"
"github.com/stretchr/testify/internal/difflib"
"github.com/stretchr/testify/internal/spew"
)
//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
@@ -33,19 +32,19 @@ type TestingT interface {
// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
// for table driven tests.
type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
type ComparisonAssertionFunc = func(TestingT, interface{}, interface{}, ...interface{}) bool
// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
// for table driven tests.
type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
type ValueAssertionFunc = func(TestingT, interface{}, ...interface{}) bool
// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
// for table driven tests.
type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
type BoolAssertionFunc = func(TestingT, bool, ...interface{}) bool
// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
// for table driven tests.
type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
type ErrorAssertionFunc = func(TestingT, error, ...interface{}) bool
// PanicAssertionFunc is a common function prototype when validating a panic value. Can be useful
// for table driven tests.
@@ -325,13 +324,15 @@ func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
func indentMessageLines(message string, longestLabelLen int) string {
outBuf := new(bytes.Buffer)
for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
// no need to align first line because it starts at the correct location (after the label)
if i != 0 {
// append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
scanner := bufio.NewScanner(strings.NewReader(message))
for firstLine := true; scanner.Scan(); firstLine = false {
if !firstLine {
fmt.Fprint(outBuf, "\n\t"+strings.Repeat(" ", longestLabelLen+1)+"\t")
}
outBuf.WriteString(scanner.Text())
fmt.Fprint(outBuf, scanner.Text())
}
if err := scanner.Err(); err != nil {
return fmt.Sprintf("cannot display message: %s", err)
}
return outBuf.String()
@@ -544,9 +545,8 @@ func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) b
if !same {
// both are pointers but not the same type & pointing to the same address
return Fail(t, fmt.Sprintf("Not same: \n"+
"expected: %p %#[1]v\n"+
"actual : %p %#[2]v",
expected, actual), msgAndArgs...)
"expected: %[2]s (%[1]T)(%[1]p)\n"+
"actual : %[4]s (%[3]T)(%[3]p)", expected, truncatingFormat("%#v", expected), actual, truncatingFormat("%#v", actual)), msgAndArgs...)
}
return true
@@ -571,8 +571,8 @@ func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}
if same {
return Fail(t, fmt.Sprintf(
"Expected and actual point to the same object: %p %#[1]v",
expected), msgAndArgs...)
"Expected and actual point to the same object: %p %s",
expected, truncatingFormat("%#v", expected)), msgAndArgs...)
}
return true
}
@@ -604,25 +604,26 @@ func samePointers(first, second interface{}) (same bool, ok bool) {
// to a type conversion in the Go grammar.
func formatUnequalValues(expected, actual interface{}) (e string, a string) {
if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)),
fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual))
return fmt.Sprintf("%T(%s)", expected, truncatingFormat("%#v", expected)),
fmt.Sprintf("%T(%s)", actual, truncatingFormat("%#v", actual))
}
switch expected.(type) {
case time.Duration:
return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
}
return truncatingFormat(expected), truncatingFormat(actual)
return truncatingFormat("%#v", expected), truncatingFormat("%#v", actual)
}
// truncatingFormat formats the data and truncates it if it's too long.
//
// This helps keep formatted error messages lines from exceeding the
// bufio.MaxScanTokenSize max line length that the go testing framework imposes.
func truncatingFormat(data interface{}) string {
value := fmt.Sprintf("%#v", data)
max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed.
if len(value) > max {
value = value[0:max] + "<... truncated>"
func truncatingFormat(format string, data interface{}) string {
value := fmt.Sprintf(format, data)
// Give us space for two truncated objects and the surrounding sentence.
maxMessageSize := bufio.MaxScanTokenSize/2 - 100
if len(value) > maxMessageSize {
value = value[0:maxMessageSize] + "<... truncated>"
}
return value
}
@@ -743,7 +744,7 @@ func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
return Fail(t, fmt.Sprintf("Expected nil, but got: %s", truncatingFormat("%#v", object)), msgAndArgs...)
}
// isEmpty gets whether the specified object is considered empty or not.
@@ -793,7 +794,7 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
Fail(t, fmt.Sprintf("Should be empty, but was %s", truncatingFormat("%v", object)), msgAndArgs...)
}
return pass
@@ -836,11 +837,11 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{})
}
l, ok := getLen(object)
if !ok {
return Fail(t, fmt.Sprintf("\"%v\" could not be applied builtin len()", object), msgAndArgs...)
return Fail(t, fmt.Sprintf("%q could not be applied builtin len()", truncatingFormat("%v", object)), msgAndArgs...)
}
if l != length {
return Fail(t, fmt.Sprintf("\"%v\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
return Fail(t, fmt.Sprintf("%q should have %d item(s), but has %d", truncatingFormat("%v", object), length, l), msgAndArgs...)
}
return true
}
@@ -889,7 +890,7 @@ func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{
}
if ObjectsAreEqual(expected, actual) {
return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
return Fail(t, fmt.Sprintf("Should not be: %s\n", truncatingFormat("%#v", actual)), msgAndArgs...)
}
return true
@@ -904,7 +905,7 @@ func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...inte
}
if ObjectsAreEqualValues(expected, actual) {
return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
return Fail(t, fmt.Sprintf("Should not be: %s\n", truncatingFormat("%#v", actual)), msgAndArgs...)
}
return true
@@ -964,10 +965,10 @@ func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bo
ok, found := containsElement(s, contains)
if !ok {
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s could not be applied builtin len()", truncatingFormat("%#v", s)), msgAndArgs...)
}
if !found {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s does not contain %#v", truncatingFormat("%#v", s), contains), msgAndArgs...)
}
return true
@@ -986,10 +987,10 @@ func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{})
ok, found := containsElement(s, contains)
if !ok {
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s could not be applied builtin len()", truncatingFormat("%#v", s)), msgAndArgs...)
}
if found {
return Fail(t, fmt.Sprintf("%#v should not contain %#v", s, contains), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s should not contain %#v", truncatingFormat("%#v", s), contains), msgAndArgs...)
}
return true
@@ -1031,10 +1032,10 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok
av := actualMap.MapIndex(k)
if !av.IsValid() {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s does not contain %s", truncatingFormat("%#v", list), truncatingFormat("%#v", subset)), msgAndArgs...)
}
if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s does not contain %s", truncatingFormat("%#v", list), truncatingFormat("%#v", subset)), msgAndArgs...)
}
}
@@ -1056,7 +1057,7 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
}
if !found {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s does not contain %#v", truncatingFormat("%#v", list), element), msgAndArgs...)
}
}
@@ -1082,12 +1083,12 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
listKind := reflect.TypeOf(list).Kind()
if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
return Fail(t, fmt.Sprintf("%#v has an unsupported type %s", list, listKind), msgAndArgs...)
}
subsetKind := reflect.TypeOf(subset).Kind()
if subsetKind != reflect.Array && subsetKind != reflect.Slice && subsetKind != reflect.Map {
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
return Fail(t, fmt.Sprintf("%#v has an unsupported type %s", subset, subsetKind), msgAndArgs...)
}
if subsetKind == reflect.Map && listKind == reflect.Map {
@@ -1106,7 +1107,7 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
}
}
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s is a subset of %s", truncatingFormat("%#v", subset), truncatingFormat("%#v", list)), msgAndArgs...)
}
subsetList := reflect.ValueOf(subset)
@@ -1121,14 +1122,14 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
element := subsetList.Index(i).Interface()
ok, found := containsElement(list, element)
if !ok {
return Fail(t, fmt.Sprintf("%q could not be applied builtin len()", list), msgAndArgs...)
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
}
if !found {
return true
}
}
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s is a subset of %s", truncatingFormat("%#v", subset), truncatingFormat("%#v", list)), msgAndArgs...)
}
// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
@@ -1343,9 +1344,15 @@ func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs .
if !funcDidPanic {
return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
}
panicErr, ok := panicValue.(error)
if !ok || panicErr.Error() != errString {
return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...)
panicErr, isError := panicValue.(error)
if !isError || panicErr.Error() != errString {
msg := fmt.Sprintf("func %#v should panic with error message:\t%#v\n", f, errString)
if isError {
msg += fmt.Sprintf("\tError message:\t%#v\n", panicErr.Error())
}
msg += fmt.Sprintf("\tPanic value:\t%#v\n", panicValue)
msg += fmt.Sprintf("\tPanic stack:\t%s\n", panickedStack)
return Fail(t, msg, msgAndArgs...)
}
return true
@@ -1624,7 +1631,7 @@ func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, m
Errors
*/
// NoError asserts that a function returned no error (i.e. `nil`).
// NoError asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if assert.NoError(t, err) {
@@ -1635,13 +1642,13 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
return Fail(t, fmt.Sprintf("Received unexpected error:\n%s", truncatingFormat("%+v", err)), msgAndArgs...)
}
return true
}
// Error asserts that a function returned an error (i.e. not `nil`).
// Error asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// assert.Error(t, err)
@@ -1656,7 +1663,7 @@ func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
return true
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// EqualError asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -1674,13 +1681,13 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte
if expected != actual {
return Fail(t, fmt.Sprintf("Error message not equal:\n"+
"expected: %q\n"+
"actual : %q", expected, actual), msgAndArgs...)
"actual : %s", expected, truncatingFormat("%q", actual)), msgAndArgs...)
}
return true
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContains asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// assert.ErrorContains(t, err, expectedErrorSubString)
@@ -1694,7 +1701,7 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in
actual := theError.Error()
if !strings.Contains(actual, contains) {
return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...)
return Fail(t, fmt.Sprintf("Error %s does not contain %#v", truncatingFormat("%#v", actual), contains), msgAndArgs...)
}
return true
@@ -1760,7 +1767,7 @@ func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
h.Helper()
}
if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
return Fail(t, fmt.Sprintf("Should be zero, but was %s", truncatingFormat("%v", i)), msgAndArgs...)
}
return true
}
@@ -1874,7 +1881,19 @@ func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{
return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
}
// YAMLEq asserts that two YAML strings are equivalent.
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// assert.YAMLEq(t, expected, actual)
func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -2188,8 +2207,8 @@ func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
chain := buildErrorChainString(err, false)
return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+
"expected: %q\n"+
"in chain: %s", expectedText, chain,
"expected: %s\n"+
"in chain: %s", truncatingFormat("%q", expectedText), truncatingFormat("%s", chain),
), msgAndArgs...)
}
@@ -2211,8 +2230,8 @@ func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
chain := buildErrorChainString(err, false)
return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
"found: %q\n"+
"in chain: %s", expectedText, chain,
"found: %s\n"+
"in chain: %s", truncatingFormat("%q", expectedText), truncatingFormat("%s", chain),
), msgAndArgs...)
}
@@ -2236,7 +2255,7 @@ func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{
return Fail(t, fmt.Sprintf("Should be in error chain:\n"+
"expected: %s\n"+
"in chain: %s", expectedType, chain,
"in chain: %s", expectedType, truncatingFormat("%s", chain),
), msgAndArgs...)
}
@@ -2254,7 +2273,7 @@ func NotErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interfa
return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
"found: %s\n"+
"in chain: %s", reflect.TypeOf(target).Elem().String(), chain,
"in chain: %s", reflect.TypeOf(target).Elem().String(), truncatingFormat("%s", chain),
), msgAndArgs...)
}
+2 -2
View File
@@ -40,8 +40,8 @@
//
// # Assertions
//
// Assertions allow you to easily write test code, and are global funcs in the `assert` package.
// All assertion functions take, as the first argument, the `*testing.T` object provided by the
// Assertions allow you to easily write test code, and are global funcs in the assert package.
// All assertion functions take, as the first argument, the [*testing.T] object provided by the
// testing framework. This allows the assertion funcs to write the failings and other details to
// the correct place.
//
+1 -1
View File
@@ -7,7 +7,7 @@
// go test -tags testify_yaml_custom
//
// This implementation can be used at build time to replace the default implementation
// to avoid linking with [gopkg.in/yaml.v3].
// to avoid linking with [go.yaml.in/yaml/v3].
//
// In your test package:
//
+3 -3
View File
@@ -6,7 +6,7 @@
// indirection with an alternative implementation of this package that uses
// another implementation of YAML deserialization. This allows to not either not
// use YAML deserialization at all, or to use another implementation than
// [gopkg.in/yaml.v3] (for example for license compatibility reasons, see [PR #1120]).
// [go.yaml.in/yaml/v3] (for example for license compatibility reasons, see [PR #1120]).
//
// Alternative implementations are selected using build tags:
//
@@ -28,9 +28,9 @@
// [PR #1120]: https://github.com/stretchr/testify/pull/1120
package yaml
import goyaml "gopkg.in/yaml.v3"
import goyaml "go.yaml.in/yaml/v3"
// Unmarshal is just a wrapper of [gopkg.in/yaml.v3.Unmarshal].
// Unmarshal is just a wrapper of [go.yaml.in/yaml/v3.Unmarshal].
func Unmarshal(in []byte, out interface{}) error {
return goyaml.Unmarshal(in, out)
}
+1 -1
View File
@@ -3,7 +3,7 @@
// Package yaml is an implementation of YAML functions that always fail.
//
// This implementation can be used at build time to replace the default implementation
// to avoid linking with [gopkg.in/yaml.v3]:
// to avoid linking with [go.yaml.in/yaml/v3]:
//
// go test -tags testify_yaml_fail
package yaml
File renamed without changes.
@@ -8,11 +8,14 @@
//
// - unified_diff
//
// - context_diff
//
// Getting unified diffs was the main goal of the port. Keep in mind this code
// is mostly suitable to output text differences in a human friendly way, there
// are no guarantees generated diffs are consumable by patch(1).
//
// This package was adopted from [github.com/pmezard/go-difflib] which
// is no longer maintained.
//
// [github.com/pmezard/go-difflib]: https://github.com/pmezard/go-difflib
package difflib
import (
@@ -37,13 +40,6 @@ func max(a, b int) int {
return b
}
func calculateRatio(matches, length int) float64 {
if length > 0 {
return 2.0 * float64(matches) / float64(length)
}
return 1.0
}
type Match struct {
A int
B int
@@ -103,14 +99,6 @@ func NewMatcher(a, b []string) *SequenceMatcher {
return &m
}
func NewMatcherWithJunk(a, b []string, autoJunk bool,
isJunk func(string) bool) *SequenceMatcher {
m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
m.SetSeqs(a, b)
return &m
}
// Set two sequences to be compared.
func (m *SequenceMatcher) SetSeqs(a, b []string) {
m.SetSeq1(a)
@@ -199,12 +187,15 @@ func (m *SequenceMatcher) isBJunk(s string) bool {
// If IsJunk is not defined:
//
// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
// alo <= i <= i+k <= ahi
// blo <= j <= j+k <= bhi
//
// alo <= i <= i+k <= ahi
// blo <= j <= j+k <= bhi
//
// and for all (i',j',k') meeting those conditions,
// k >= k'
// i <= i'
// and if i == i', j <= j'
//
// k >= k'
// i <= i'
// and if i == i', j <= j'
//
// In other words, of all maximal matching blocks, return one that
// starts earliest in a, and of all those maximal matching blocks that
@@ -451,66 +442,6 @@ func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
return groups
}
// Return a measure of the sequences' similarity (float in [0,1]).
//
// Where T is the total number of elements in both sequences, and
// M is the number of matches, this is 2.0*M / T.
// Note that this is 1 if the sequences are identical, and 0 if
// they have nothing in common.
//
// .Ratio() is expensive to compute if you haven't already computed
// .GetMatchingBlocks() or .GetOpCodes(), in which case you may
// want to try .QuickRatio() or .RealQuickRation() first to get an
// upper bound.
func (m *SequenceMatcher) Ratio() float64 {
matches := 0
for _, m := range m.GetMatchingBlocks() {
matches += m.Size
}
return calculateRatio(matches, len(m.a)+len(m.b))
}
// Return an upper bound on ratio() relatively quickly.
//
// This isn't defined beyond that it is an upper bound on .Ratio(), and
// is faster to compute.
func (m *SequenceMatcher) QuickRatio() float64 {
// viewing a and b as multisets, set matches to the cardinality
// of their intersection; this counts the number of matches
// without regard to order, so is clearly an upper bound
if m.fullBCount == nil {
m.fullBCount = map[string]int{}
for _, s := range m.b {
m.fullBCount[s] = m.fullBCount[s] + 1
}
}
// avail[x] is the number of times x appears in 'b' less the
// number of times we've seen it in 'a' so far ... kinda
avail := map[string]int{}
matches := 0
for _, s := range m.a {
n, ok := avail[s]
if !ok {
n = m.fullBCount[s]
}
avail[s] = n - 1
if n > 0 {
matches += 1
}
}
return calculateRatio(matches, len(m.a)+len(m.b))
}
// Return an upper bound on ratio() very quickly.
//
// This isn't defined beyond that it is an upper bound on .Ratio(), and
// is faster to compute than either .Ratio() or .QuickRatio().
func (m *SequenceMatcher) RealQuickRatio() float64 {
la, lb := len(m.a), len(m.b)
return calculateRatio(min(la, lb), la+lb)
}
// Convert range to the "ed" format
func formatRangeUnified(start, stop int) string {
// Per the diff spec at http://www.unix.org/single_unix_specification/
@@ -652,117 +583,6 @@ func formatRangeContext(start, stop int) string {
return fmt.Sprintf("%d,%d", beginning, beginning+length-1)
}
type ContextDiff UnifiedDiff
// Compare two sequences of lines; generate the delta as a context diff.
//
// Context diffs are a compact way of showing line changes and a few
// lines of context. The number of context lines is set by diff.Context
// which defaults to three.
//
// By default, the diff control lines (those with *** or ---) are
// created with a trailing newline.
//
// For inputs that do not have trailing newlines, set the diff.Eol
// argument to "" so that the output will be uniformly newline free.
//
// The context diff format normally has a header for filenames and
// modification times. Any or all of these may be specified using
// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate.
// The modification times are normally expressed in the ISO 8601 format.
// If not specified, the strings default to blanks.
func WriteContextDiff(writer io.Writer, diff ContextDiff) error {
buf := bufio.NewWriter(writer)
defer buf.Flush()
var diffErr error
wf := func(format string, args ...interface{}) {
_, err := buf.WriteString(fmt.Sprintf(format, args...))
if diffErr == nil && err != nil {
diffErr = err
}
}
ws := func(s string) {
_, err := buf.WriteString(s)
if diffErr == nil && err != nil {
diffErr = err
}
}
if len(diff.Eol) == 0 {
diff.Eol = "\n"
}
prefix := map[byte]string{
'i': "+ ",
'd': "- ",
'r': "! ",
'e': " ",
}
started := false
m := NewMatcher(diff.A, diff.B)
for _, g := range m.GetGroupedOpCodes(diff.Context) {
if !started {
started = true
fromDate := ""
if len(diff.FromDate) > 0 {
fromDate = "\t" + diff.FromDate
}
toDate := ""
if len(diff.ToDate) > 0 {
toDate = "\t" + diff.ToDate
}
if diff.FromFile != "" || diff.ToFile != "" {
wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol)
wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol)
}
}
first, last := g[0], g[len(g)-1]
ws("***************" + diff.Eol)
range1 := formatRangeContext(first.I1, last.I2)
wf("*** %s ****%s", range1, diff.Eol)
for _, c := range g {
if c.Tag == 'r' || c.Tag == 'd' {
for _, cc := range g {
if cc.Tag == 'i' {
continue
}
for _, line := range diff.A[cc.I1:cc.I2] {
ws(prefix[cc.Tag] + line)
}
}
break
}
}
range2 := formatRangeContext(first.J1, last.J2)
wf("--- %s ----%s", range2, diff.Eol)
for _, c := range g {
if c.Tag == 'r' || c.Tag == 'i' {
for _, cc := range g {
if cc.Tag == 'd' {
continue
}
for _, line := range diff.B[cc.J1:cc.J2] {
ws(prefix[cc.Tag] + line)
}
}
break
}
}
}
return diffErr
}
// Like WriteContextDiff but returns the diff a string.
func GetContextDiffString(diff ContextDiff) (string, error) {
w := &bytes.Buffer{}
err := WriteContextDiff(w, diff)
return string(w.Bytes()), err
}
// Split a string on "\n" while preserving them. The output can be used
// as input for UnifiedDiff and ContextDiff structures.
func SplitLines(s string) []string {
File renamed without changes.
+12
View File
@@ -0,0 +1,12 @@
go-spew
=======
[![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org)
Go-spew implements a deep pretty printer for Go data structures to aid in
debugging. A comprehensive suite of tests with 100% test coverage is provided
to ensure proper functionality.
## License
Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License.
@@ -18,6 +18,7 @@
// tag is deprecated and thus should not be used.
// Go versions prior to 1.4 are disabled because they use a different layout
// for interfaces which make the implementation of unsafeReflectValue more complex.
//go:build !js && !appengine && !safe && !disableunsafe && go1.4
// +build !js,!appengine,!safe,!disableunsafe,go1.4
package spew
@@ -16,6 +16,7 @@
// when the code is running on Google App Engine, compiled by GopherJS, or
// "-tags safe" is added to the go build command line. The "disableunsafe"
// tag is deprecated and thus should not be used.
//go:build js || appengine || safe || disableunsafe || !go1.4
// +build js appengine safe disableunsafe !go1.4
package spew
@@ -254,15 +254,15 @@ pointer addresses used to indirect to the final value. It provides the
following features over the built-in printing facilities provided by the fmt
package:
* Pointers are dereferenced and followed
* Circular data structures are detected and handled properly
* Custom Stringer/error interfaces are optionally invoked, including
on unexported types
* Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
* Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
- Pointers are dereferenced and followed
- Circular data structures are detected and handled properly
- Custom Stringer/error interfaces are optionally invoked, including
on unexported types
- Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
- Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
The configuration options are controlled by modifying the public members
of c. See ConfigState for options documentation.
@@ -295,12 +295,12 @@ func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{})
// NewDefaultConfig returns a ConfigState with the following default settings.
//
// Indent: " "
// MaxDepth: 0
// DisableMethods: false
// DisablePointerMethods: false
// ContinueOnMethod: false
// SortKeys: false
// Indent: " "
// MaxDepth: 0
// DisableMethods: false
// DisablePointerMethods: false
// ContinueOnMethod: false
// SortKeys: false
func NewDefaultConfig() *ConfigState {
return &ConfigState{Indent: " "}
}
@@ -21,35 +21,36 @@ debugging.
A quick overview of the additional features spew provides over the built-in
printing facilities for Go data types are as follows:
* Pointers are dereferenced and followed
* Circular data structures are detected and handled properly
* Custom Stringer/error interfaces are optionally invoked, including
on unexported types
* Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
* Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output (only when using
Dump style)
- Pointers are dereferenced and followed
- Circular data structures are detected and handled properly
- Custom Stringer/error interfaces are optionally invoked, including
on unexported types
- Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
- Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output (only when using
Dump style)
There are two different approaches spew allows for dumping Go data structures:
* Dump style which prints with newlines, customizable indentation,
and additional debug information such as types and all pointer addresses
used to indirect to the final value
* A custom Formatter interface that integrates cleanly with the standard fmt
package and replaces %v, %+v, %#v, and %#+v to provide inline printing
similar to the default %v while providing the additional functionality
outlined above and passing unsupported format verbs such as %x and %q
along to fmt
- Dump style which prints with newlines, customizable indentation,
and additional debug information such as types and all pointer addresses
used to indirect to the final value
- A custom Formatter interface that integrates cleanly with the standard fmt
package and replaces %v, %+v, %#v, and %#+v to provide inline printing
similar to the default %v while providing the additional functionality
outlined above and passing unsupported format verbs such as %x and %q
along to fmt
Quick Start
# Quick Start
This section demonstrates how to quickly get started with spew. See the
sections below for further details on formatting and configuration options.
To dump a variable with full newlines, indentation, type, and pointer
information use Dump, Fdump, or Sdump:
spew.Dump(myVar1, myVar2, ...)
spew.Fdump(someWriter, myVar1, myVar2, ...)
str := spew.Sdump(myVar1, myVar2, ...)
@@ -58,12 +59,13 @@ Alternatively, if you would prefer to use format strings with a compacted inline
printing style, use the convenience wrappers Printf, Fprintf, etc with
%v (most compact), %+v (adds pointer addresses), %#v (adds types), or
%#+v (adds types and pointer addresses):
spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
Configuration Options
# Configuration Options
Configuration of spew is handled by fields in the ConfigState type. For
convenience, all of the top-level functions use a global state available
@@ -74,51 +76,52 @@ equivalent to the top-level functions. This allows concurrent configuration
options. See the ConfigState documentation for more details.
The following configuration options are available:
* Indent
String to use for each indentation level for Dump functions.
It is a single space by default. A popular alternative is "\t".
* MaxDepth
Maximum number of levels to descend into nested data structures.
There is no limit by default.
- Indent
String to use for each indentation level for Dump functions.
It is a single space by default. A popular alternative is "\t".
* DisableMethods
Disables invocation of error and Stringer interface methods.
Method invocation is enabled by default.
- MaxDepth
Maximum number of levels to descend into nested data structures.
There is no limit by default.
* DisablePointerMethods
Disables invocation of error and Stringer interface methods on types
which only accept pointer receivers from non-pointer variables.
Pointer method invocation is enabled by default.
- DisableMethods
Disables invocation of error and Stringer interface methods.
Method invocation is enabled by default.
* DisablePointerAddresses
DisablePointerAddresses specifies whether to disable the printing of
pointer addresses. This is useful when diffing data structures in tests.
- DisablePointerMethods
Disables invocation of error and Stringer interface methods on types
which only accept pointer receivers from non-pointer variables.
Pointer method invocation is enabled by default.
* DisableCapacities
DisableCapacities specifies whether to disable the printing of
capacities for arrays, slices, maps and channels. This is useful when
diffing data structures in tests.
- DisablePointerAddresses
DisablePointerAddresses specifies whether to disable the printing of
pointer addresses. This is useful when diffing data structures in tests.
* ContinueOnMethod
Enables recursion into types after invoking error and Stringer interface
methods. Recursion after method invocation is disabled by default.
- DisableCapacities
DisableCapacities specifies whether to disable the printing of
capacities for arrays, slices, maps and channels. This is useful when
diffing data structures in tests.
* SortKeys
Specifies map keys should be sorted before being printed. Use
this to have a more deterministic, diffable output. Note that
only native types (bool, int, uint, floats, uintptr and string)
and types which implement error or Stringer interfaces are
supported with other types sorted according to the
reflect.Value.String() output which guarantees display
stability. Natural map order is used by default.
- ContinueOnMethod
Enables recursion into types after invoking error and Stringer interface
methods. Recursion after method invocation is disabled by default.
* SpewKeys
Specifies that, as a last resort attempt, map keys should be
spewed to strings and sorted by those strings. This is only
considered if SortKeys is true.
- SortKeys
Specifies map keys should be sorted before being printed. Use
this to have a more deterministic, diffable output. Note that
only native types (bool, int, uint, floats, uintptr and string)
and types which implement error or Stringer interfaces are
supported with other types sorted according to the
reflect.Value.String() output which guarantees display
stability. Natural map order is used by default.
Dump Usage
- SpewKeys
Specifies that, as a last resort attempt, map keys should be
spewed to strings and sorted by those strings. This is only
considered if SortKeys is true.
# Dump Usage
Simply call spew.Dump with a list of variables you want to dump:
@@ -133,7 +136,7 @@ A third option is to call spew.Sdump to get the formatted output as a string:
str := spew.Sdump(myVar1, myVar2, ...)
Sample Dump Output
# Sample Dump Output
See the Dump example for details on the setup of the types and variables being
shown here.
@@ -150,13 +153,14 @@ shown here.
Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C
command as shown.
([]uint8) (len=32 cap=32) {
00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
00000020 31 32 |12|
}
Custom Formatter
# Custom Formatter
Spew provides a custom formatter that implements the fmt.Formatter interface
so that it integrates cleanly with standard fmt package printing functions. The
@@ -170,7 +174,7 @@ standard fmt package for formatting. In addition, the custom formatter ignores
the width and precision arguments (however they will still work on the format
specifiers not handled by the custom formatter).
Custom Formatter Usage
# Custom Formatter Usage
The simplest way to make use of the spew custom formatter is to call one of the
convenience functions such as spew.Printf, spew.Println, or spew.Printf. The
@@ -184,15 +188,17 @@ functions have syntax you are most likely already familiar with:
See the Index for the full list convenience functions.
Sample Formatter Output
# Sample Formatter Output
Double pointer to a uint8:
%v: <**>5
%+v: <**>(0xf8400420d0->0xf8400420c8)5
%#v: (**uint8)5
%#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
Pointer to circular struct with a uint8 field and a pointer to itself:
%v: <*>{1 <*><shown>}
%+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
%#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
@@ -201,7 +207,7 @@ Pointer to circular struct with a uint8 field and a pointer to itself:
See the Printf example for details on the setup of variables being shown
here.
Errors
# Errors
Since it is possible for custom Stringer/error interfaces to panic, spew
detects them and handles them internally by printing the panic information
@@ -488,15 +488,15 @@ pointer addresses used to indirect to the final value. It provides the
following features over the built-in printing facilities provided by the fmt
package:
* Pointers are dereferenced and followed
* Circular data structures are detected and handled properly
* Custom Stringer/error interfaces are optionally invoked, including
on unexported types
* Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
* Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
- Pointers are dereferenced and followed
- Circular data structures are detected and handled properly
- Custom Stringer/error interfaces are optionally invoked, including
on unexported types
- Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
- Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
The configuration options are controlled by an exported package global,
spew.Config. See ConfigState for options documentation.
File renamed without changes.
+3 -3
View File
@@ -1,4 +1,4 @@
// Package require implements the same assertions as the `assert` package but
// Package require implements the same assertions as the assert package but
// stops test execution when a test fails.
//
// # Example Usage
@@ -21,8 +21,8 @@
//
// # Assertions
//
// The `require` package have same global functions as in the `assert` package,
// but instead of returning a boolean result they call `t.FailNow()`.
// The require package have same global functions as in the assert package,
// but instead of returning a boolean result they call [testing.T.FailNow].
// A consequence of this is that it must be called from the goroutine running
// the test function, not from other goroutines created during the test.
//
+49 -53
View File
@@ -180,7 +180,7 @@ func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...i
t.FailNow()
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// EqualError asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -195,7 +195,7 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte
t.FailNow()
}
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -295,7 +295,7 @@ func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, ar
t.FailNow()
}
// Error asserts that a function returned an error (i.e. not `nil`).
// Error asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// require.Error(t, err)
@@ -333,8 +333,8 @@ func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...int
t.FailNow()
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContains asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// require.ErrorContains(t, err, expectedErrorSubString)
@@ -348,8 +348,8 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in
t.FailNow()
}
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// require.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted")
@@ -387,7 +387,7 @@ func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface
t.FailNow()
}
// Errorf asserts that a function returned an error (i.e. not `nil`).
// Errorf asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// require.Errorf(t, err, "error message %s", "formatted")
@@ -429,7 +429,7 @@ func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick t
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// require.EventuallyWithT(t, func(c *require.CollectT) {
// require.EventuallyWithT(t, func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// require.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
@@ -457,10 +457,10 @@ func EventuallyWithT(t TestingT, condition func(collect *assert.CollectT), waitF
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// require.EventuallyWithTf(t, func(c *require.CollectT, "error message %s", "formatted") {
// require.EventuallyWithTf(t, func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// require.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
func EventuallyWithTf(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -671,8 +671,6 @@ func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...in
// body that contains a string.
//
// require.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -687,8 +685,6 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url s
// body that contains a string.
//
// require.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -703,8 +699,6 @@ func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url
// body that does not contain a string.
//
// require.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -719,8 +713,6 @@ func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, ur
// body that does not contain a string.
//
// require.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -734,8 +726,6 @@ func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, u
// HTTPError asserts that a specified handler returns an error status code.
//
// require.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -749,8 +739,6 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string,
// HTTPErrorf asserts that a specified handler returns an error status code.
//
// require.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -764,8 +752,6 @@ func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string,
// HTTPRedirect asserts that a specified handler returns a redirect status code.
//
// require.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -779,8 +765,6 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url strin
// HTTPRedirectf asserts that a specified handler returns a redirect status code.
//
// require.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -794,8 +778,6 @@ func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url stri
// HTTPStatusCode asserts that a specified handler returns a specified status code.
//
// require.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501)
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -809,8 +791,6 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url str
// HTTPStatusCodef asserts that a specified handler returns a specified status code.
//
// require.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -824,8 +804,6 @@ func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url st
// HTTPSuccess asserts that a specified handler returns a success status code.
//
// require.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -839,8 +817,6 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string
// HTTPSuccessf asserts that a specified handler returns a success status code.
//
// require.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1385,12 +1361,11 @@ func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) {
t.FailNow()
}
// NoError asserts that a function returned no error (i.e. `nil`).
// NoError asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if require.NoError(t, err) {
// require.Equal(t, expectedObj, actualObj)
// }
// actualObj, err := SomeFunction()
// require.NoError(t, err)
// require.Equal(t, expectedObj, actualObj)
func NoError(t TestingT, err error, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1401,12 +1376,11 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) {
t.FailNow()
}
// NoErrorf asserts that a function returned no error (i.e. `nil`).
// NoErrorf asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if require.NoErrorf(t, err, "error message %s", "formatted") {
// require.Equal(t, expectedObj, actualObj)
// }
// actualObj, err := SomeFunction()
// require.NoErrorf(t, err, "error message %s", "formatted")
// require.Equal(t, expectedObj, actualObj)
func NoErrorf(t TestingT, err error, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1515,9 +1489,8 @@ func NotElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg str
// NotEmpty asserts that the specified object is NOT [Empty].
//
// if require.NotEmpty(t, obj) {
// require.Equal(t, "two", obj[1])
// }
// require.NotEmpty(t, obj)
// require.Equal(t, "two", obj[1])
func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1530,9 +1503,8 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
// NotEmptyf asserts that the specified object is NOT [Empty].
//
// if require.NotEmptyf(t, obj, "error message %s", "formatted") {
// require.Equal(t, "two", obj[1])
// }
// require.NotEmptyf(t, obj, "error message %s", "formatted")
// require.Equal(t, "two", obj[1])
func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -2135,7 +2107,19 @@ func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time,
t.FailNow()
}
// YAMLEq asserts that two YAML strings are equivalent.
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// require.YAMLEq(t, expected, actual)
func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -2146,7 +2130,19 @@ func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{
t.FailNow()
}
// YAMLEqf asserts that two YAML strings are equivalent.
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// require.YAMLEqf(t, expected, actual, "error message %s", "formatted")
func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
+1 -1
View File
@@ -1,4 +1,4 @@
{{ replace .Comment "assert." "require."}}
{{.CommentRequire}}
func {{.DocInfo.Name}}(t TestingT, {{.Params}}) {
if h, ok := t.(tHelper); ok { h.Helper() }
if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return }
+48 -52
View File
@@ -147,7 +147,7 @@ func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs
Equal(a.t, expected, actual, msgAndArgs...)
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// EqualError asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -159,7 +159,7 @@ func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...
EqualError(a.t, theError, errString, msgAndArgs...)
}
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -241,7 +241,7 @@ func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string
Equalf(a.t, expected, actual, msg, args...)
}
// Error asserts that a function returned an error (i.e. not `nil`).
// Error asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// a.Error(err)
@@ -270,8 +270,8 @@ func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args ..
ErrorAsf(a.t, err, target, msg, args...)
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContains asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// a.ErrorContains(err, expectedErrorSubString)
@@ -282,8 +282,8 @@ func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs .
ErrorContains(a.t, theError, contains, msgAndArgs...)
}
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted")
@@ -312,7 +312,7 @@ func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...inter
ErrorIsf(a.t, err, target, msg, args...)
}
// Errorf asserts that a function returned an error (i.e. not `nil`).
// Errorf asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// a.Errorf(err, "error message %s", "formatted")
@@ -373,10 +373,10 @@ func (a *Assertions) EventuallyWithT(condition func(collect *assert.CollectT), w
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") {
// a.EventuallyWithTf(func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
func (a *Assertions) EventuallyWithTf(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -539,8 +539,6 @@ func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args .
// body that contains a string.
//
// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -552,8 +550,6 @@ func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, u
// body that contains a string.
//
// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -565,8 +561,6 @@ func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string,
// body that does not contain a string.
//
// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -578,8 +572,6 @@ func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string
// body that does not contain a string.
//
// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -590,8 +582,6 @@ func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method strin
// HTTPError asserts that a specified handler returns an error status code.
//
// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -602,8 +592,6 @@ func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url stri
// HTTPErrorf asserts that a specified handler returns an error status code.
//
// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -614,8 +602,6 @@ func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url str
// HTTPRedirect asserts that a specified handler returns a redirect status code.
//
// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -626,8 +612,6 @@ func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url s
// HTTPRedirectf asserts that a specified handler returns a redirect status code.
//
// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -638,8 +622,6 @@ func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url
// HTTPStatusCode asserts that a specified handler returns a specified status code.
//
// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501)
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -650,8 +632,6 @@ func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url
// HTTPStatusCodef asserts that a specified handler returns a specified status code.
//
// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -662,8 +642,6 @@ func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, ur
// HTTPSuccess asserts that a specified handler returns a success status code.
//
// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil)
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -674,8 +652,6 @@ func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url st
// HTTPSuccessf asserts that a specified handler returns a success status code.
//
// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1097,12 +1073,11 @@ func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{})
NoDirExistsf(a.t, path, msg, args...)
}
// NoError asserts that a function returned no error (i.e. `nil`).
// NoError asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if a.NoError(err) {
// assert.Equal(t, expectedObj, actualObj)
// }
// actualObj, err := SomeFunction()
// a.NoError(err)
// a.Equal(expectedObj, actualObj)
func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1110,12 +1085,11 @@ func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) {
NoError(a.t, err, msgAndArgs...)
}
// NoErrorf asserts that a function returned no error (i.e. `nil`).
// NoErrorf asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if a.NoErrorf(err, "error message %s", "formatted") {
// assert.Equal(t, expectedObj, actualObj)
// }
// actualObj, err := SomeFunction()
// a.NoErrorf(err, "error message %s", "formatted")
// a.Equal(expectedObj, actualObj)
func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1203,9 +1177,8 @@ func (a *Assertions) NotElementsMatchf(listA interface{}, listB interface{}, msg
// NotEmpty asserts that the specified object is NOT [Empty].
//
// if a.NotEmpty(obj) {
// assert.Equal(t, "two", obj[1])
// }
// a.NotEmpty(obj)
// a.Equal("two", obj[1])
func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1215,9 +1188,8 @@ func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) {
// NotEmptyf asserts that the specified object is NOT [Empty].
//
// if a.NotEmptyf(obj, "error message %s", "formatted") {
// assert.Equal(t, "two", obj[1])
// }
// a.NotEmptyf(obj, "error message %s", "formatted")
// a.Equal("two", obj[1])
func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1691,7 +1663,19 @@ func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Ti
WithinRangef(a.t, actual, start, end, msg, args...)
}
// YAMLEq asserts that two YAML strings are equivalent.
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// a.YAMLEq(expected, actual)
func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1699,7 +1683,19 @@ func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interf
YAMLEq(a.t, expected, actual, msgAndArgs...)
}
// YAMLEqf asserts that two YAML strings are equivalent.
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// a.YAMLEqf(expected, actual, "error message %s", "formatted")
func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
+1 -1
View File
@@ -1,4 +1,4 @@
{{.CommentWithoutT "a"}}
{{.CommentRequireWithoutT "a"}}
func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) {
if h, ok := a.t.(tHelper); ok { h.Helper() }
{{.DocInfo.Name}}(a.t, {{.ForwardedParams}})
+4 -4
View File
@@ -12,18 +12,18 @@ type tHelper = interface {
// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
// for table driven tests.
type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{})
type ComparisonAssertionFunc = func(TestingT, interface{}, interface{}, ...interface{})
// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
// for table driven tests.
type ValueAssertionFunc func(TestingT, interface{}, ...interface{})
type ValueAssertionFunc = func(TestingT, interface{}, ...interface{})
// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
// for table driven tests.
type BoolAssertionFunc func(TestingT, bool, ...interface{})
type BoolAssertionFunc = func(TestingT, bool, ...interface{})
// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
// for table driven tests.
type ErrorAssertionFunc func(TestingT, error, ...interface{})
type ErrorAssertionFunc = func(TestingT, error, ...interface{})
//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=require -template=require.go.tmpl -include-format-funcs"
+24 -8
View File
@@ -63,11 +63,15 @@ func (suite *Suite) Require() *require.Assertions {
return suite.require
}
// Assert returns an assert context for suite. Normally, you can call
// `suite.NoError(expected, actual)`, but for situations where the embedded
// methods are overridden (for example, you might want to override
// assert.Assertions with require.Assertions), this method is provided so you
// can call `suite.Assert().NoError()`.
// Assert returns an assert context for suite. Normally, you can call:
//
// suite.NoError(err)
//
// But for situations where the embedded methods are overridden (for example,
// you might want to override assert.Assertions with require.Assertions), this
// method is provided so you can call:
//
// suite.Assert().NoError(err)
func (suite *Suite) Assert() *assert.Assertions {
suite.mu.Lock()
defer suite.mu.Unlock()
@@ -158,7 +162,19 @@ func Run(t *testing.T, suite TestingSuite) {
if matchMethodRE != nil && !matchMethodRE.MatchString(method.Name) {
continue
}
// Check method signature
if method.Type.NumIn() > 1 || method.Type.NumOut() > 0 {
tests = append(tests, test{
name: method.Name,
run: func(t *testing.T) {
t.Errorf(
"testify: suite method %q has invalid signature: expected no input or output parameters, method has %d input parameters and %d output parameters",
method.Name, method.Type.NumIn()-1, method.Type.NumOut(),
)
},
})
continue
}
test := test{
name: method.Name,
run: func(t *testing.T) {
@@ -184,6 +200,8 @@ func Run(t *testing.T, suite TestingSuite) {
failOnPanic(t, r)
}()
stats.start(method.Name)
if setupTestSuite, ok := suite.(SetupTestSuite); ok {
setupTestSuite.SetupTest()
}
@@ -191,8 +209,6 @@ func Run(t *testing.T, suite TestingSuite) {
beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name)
}
stats.start(method.Name)
method.Func.Call([]reflect.Value{reflect.ValueOf(suite)})
},
}
+11
View File
@@ -39,6 +39,17 @@ func LogDump(dumpRequest bool, dumpResponse bool) LogOption {
}
}
// LogBody enables logging of the HTTP request and/or response body.
//
// requestBody controls logging of the request body, and responseBody
// controls logging of the response body.
func LogBody(requestBody bool, responseBody bool) LogOption {
return func(cfg *logConfig) {
cfg.LogRequestBody = requestBody
cfg.LogResponseBody = responseBody
}
}
// LogHeaders enables logging of HTTP request and response headers.
func LogHeaders(requestHeaders bool, responseHeaders bool) LogOption {
return func(cfg *logConfig) {
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otelhttptrace // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
package otelhttptrace
import (
"context"
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otelhttptrace // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
package otelhttptrace
import (
"context"
@@ -3,7 +3,7 @@
// Package otelhttptrace provides instrumentation for the [net/http/httptrace]
// package.
package otelhttptrace // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
package otelhttptrace
import (
"context"
@@ -1,12 +1,12 @@
// Code generated by gotmpl. DO NOT MODIFY.
// source: internal/shared/semconv/client.go.tmpl
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// DO NOT MODIFY. Generated by gotmpl.
// source: internal/shared/semconv/client.go.tmpl
// Package semconv provides OpenTelemetry semantic convention types and
// functionality.
package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv"
package semconv
import (
"context"
@@ -20,8 +20,8 @@ import (
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/semconv/v1.41.0"
"go.opentelemetry.io/otel/semconv/v1.41.0/httpconv"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
"go.opentelemetry.io/otel/semconv/v1.43.0/httpconv"
)
type HTTPClient struct {
@@ -45,7 +45,7 @@ func NewHTTPClient(meter metric.Meter) HTTPClient {
return client
}
func (n HTTPClient) Status(code int) (codes.Code, string) {
func (HTTPClient) Status(code int) (codes.Code, string) {
if code < 100 || code >= 600 {
return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code)
}
@@ -120,9 +120,7 @@ func (n HTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue {
// Restore any username/password info that was removed.
req.URL.User = userinfo
}
attrs = append(attrs, semconv.URLFull(u))
attrs = append(attrs, semconv.ServerAddress(requestHost))
attrs = append(attrs, semconv.URLFull(u), semconv.ServerAddress(requestHost))
if eligiblePort > 0 {
attrs = append(attrs, semconv.ServerPort(eligiblePort))
}
@@ -138,11 +136,13 @@ func (n HTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue {
}
// ResponseTraceAttrs returns trace attributes for an HTTP response made by a client.
func (n HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue {
func (HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue {
/*
below attributes are returned:
- http.response.status_code
- error.type
- network.protocol.name (only when it is not "http")
- network.protocol.version
*/
var count int
if resp.StatusCode > 0 {
@@ -153,6 +153,21 @@ func (n HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue
count++
}
// The protocol version is only known for certain once the response
// arrives: req.Proto reflects what the caller asked for, but the
// transport may negotiate a different version (for example HTTP/2 via
// ALPN). Report resp.Proto here so it overrides the request-time value
// on the span. As in RequestTraceAttrs, network.protocol.name is omitted
// when it is "http": the spec only requires it when the name differs from
// the protocol implied by http.request.method.
protoName, protoVersion := netProtocol(resp.Proto)
if protoName != "" && protoName != "http" {
count++
}
if protoVersion != "" {
count++
}
attrs := make([]attribute.KeyValue, 0, count)
if resp.StatusCode > 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(resp.StatusCode))
@@ -162,10 +177,17 @@ func (n HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue
errorType := strconv.Itoa(resp.StatusCode)
attrs = append(attrs, semconv.ErrorTypeKey.String(errorType))
}
if protoName != "" && protoName != "http" {
attrs = append(attrs, semconv.NetworkProtocolName(protoName))
}
if protoVersion != "" {
attrs = append(attrs, semconv.NetworkProtocolVersion(protoVersion))
}
return attrs
}
func (n HTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValue) {
func (HTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValue) {
if method == "" {
return semconv.HTTPRequestMethodOther, attribute.KeyValue{}
}
@@ -180,7 +202,7 @@ func (n HTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValu
return semconv.HTTPRequestMethodOther, orig
}
func (n HTTPClient) MetricAttributes(req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue {
func (n HTTPClient) MetricAttributes(req *http.Request, resp *http.Response, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue {
num := len(additionalAttributes) + 2
var h string
if req.URL != nil {
@@ -200,7 +222,14 @@ func (n HTTPClient) MetricAttributes(req *http.Request, statusCode int, addition
num++
}
protoName, protoVersion := netProtocol(req.Proto)
// Prefer the negotiated protocol reported on the response: req.Proto is
// only what the caller asked for, and the transport may have upgraded
// the connection (for example HTTP/2 via ALPN).
proto := req.Proto
if resp != nil && resp.Proto != "" {
proto = resp.Proto
}
protoName, protoVersion := netProtocol(proto)
if protoName != "" {
num++
}
@@ -213,7 +242,8 @@ func (n HTTPClient) MetricAttributes(req *http.Request, statusCode int, addition
}
attributes := slices.Grow(additionalAttributes, num)
attributes = append(attributes,
attributes = append(
attributes,
semconv.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)),
semconv.ServerAddress(requestHost),
n.scheme(req),
@@ -249,7 +279,7 @@ func (o MetricOpts) AddOptions() metric.AddOption {
}
func (n HTTPClient) MetricOptions(ma MetricAttributes) MetricOpts {
attributes := n.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes)
attributes := n.MetricAttributes(ma.Req, ma.Resp, ma.StatusCode, ma.AdditionalAttributes)
if ma.StatusCode == 0 && ma.Err != nil {
attributes = append(attributes, n.ErrorType(ma.Err))
}
@@ -269,12 +299,12 @@ func (n HTTPClient) MetricOptions(ma MetricAttributes) MetricOpts {
// type per failure keeps attribute cardinality bounded, as required by the
// OTel spec (error.type SHOULD have low cardinality). Callers that need
// finer-grained error distinctions should inspect the error themselves.
func (n HTTPClient) ErrorType(err error) attribute.KeyValue {
func (HTTPClient) ErrorType(err error) attribute.KeyValue {
t := reflect.TypeOf(err)
if t == nil {
return semconv.ErrorTypeOther
}
if t.Kind() == reflect.Ptr {
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
var value string
@@ -307,13 +337,13 @@ func (n HTTPClient) RecordMetrics(ctx context.Context, md MetricData, opts Metri
}
// TraceAttributes returns attributes for httptrace.
func (n HTTPClient) TraceAttributes(host string) []attribute.KeyValue {
func (HTTPClient) TraceAttributes(host string) []attribute.KeyValue {
return []attribute.KeyValue{
semconv.ServerAddress(host),
}
}
func (n HTTPClient) scheme(req *http.Request) attribute.KeyValue {
func (HTTPClient) scheme(req *http.Request) attribute.KeyValue {
if req.URL != nil && req.URL.Scheme != "" {
return semconv.URLScheme(req.URL.Scheme)
}
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv"
package semconv
// Generate semconv package:
//go:generate gotmpl --body=../../../../../../../internal/shared/semconv/bench_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace\" }" --out=bench_test.go
@@ -1,12 +1,12 @@
// Code generated by gotmpl. DO NOT MODIFY.
// source: internal/shared/semconv/server.go.tmpl
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// DO NOT MODIFY. Generated by gotmpl.
// source: internal/shared/semconv/server.go.tmpl
// Package semconv provides OpenTelemetry semantic convention types and
// functionality.
package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv"
package semconv
import (
"context"
@@ -20,8 +20,8 @@ import (
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/semconv/v1.41.0"
"go.opentelemetry.io/otel/semconv/v1.41.0/httpconv"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
"go.opentelemetry.io/otel/semconv/v1.43.0/httpconv"
)
type RequestTraceAttrsOpts struct {
@@ -67,7 +67,7 @@ func NewHTTPServer(meter metric.Meter) HTTPServer {
// Status returns a span status code and message for an HTTP status code
// value returned by a server. Status codes in the 400-499 range are not
// returned as errors.
func (n HTTPServer) Status(code int) (codes.Code, string) {
func (HTTPServer) Status(code int) (codes.Code, string) {
if code < 100 || code >= 600 {
return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code)
}
@@ -168,7 +168,8 @@ func (n HTTPServer) RequestTraceAttrs(server string, req *http.Request, opts Req
}
attrs := make([]attribute.KeyValue, 0, count)
attrs = append(attrs,
attrs = append(
attrs,
semconv.ServerAddress(host),
method,
scheme,
@@ -216,7 +217,7 @@ func (n HTTPServer) RequestTraceAttrs(server string, req *http.Request, opts Req
return attrs
}
func (s HTTPServer) NetworkTransportAttr(network string) []attribute.KeyValue {
func (HTTPServer) NetworkTransportAttr(network string) []attribute.KeyValue {
attr := semconv.NetworkTransportPipe
switch network {
case "tcp", "tcp4", "tcp6":
@@ -239,7 +240,11 @@ type ServerMetricData struct {
}
type MetricAttributes struct {
Req *http.Request
Req *http.Request
// Resp is the client response, if any. It is only consulted by
// HTTPClient.MetricAttributes to source the negotiated protocol version;
// server-side metric recording ignores it.
Resp *http.Response
StatusCode int
Route string
AdditionalAttributes []attribute.KeyValue
@@ -274,7 +279,7 @@ func (n HTTPServer) RecordMetrics(ctx context.Context, md ServerMetricData) {
// It returns "{method} {route}" when the request has a pattern,
// or just "{method}" when no route is available.
// Non-standard HTTP methods are replaced by "HTTP".
func (n HTTPServer) SpanName(r *http.Request) string {
func (HTTPServer) SpanName(r *http.Request) string {
method := strings.ToUpper(r.Method)
if _, ok := methodLookup[method]; !ok {
method = "HTTP"
@@ -287,7 +292,7 @@ func (n HTTPServer) SpanName(r *http.Request) string {
return method
}
func (n HTTPServer) method(method string) (attribute.KeyValue, attribute.KeyValue) {
func (HTTPServer) method(method string) (attribute.KeyValue, attribute.KeyValue) {
if method == "" {
return semconv.HTTPRequestMethodOther, attribute.KeyValue{}
}
@@ -314,7 +319,7 @@ func (n HTTPServer) scheme(https bool) attribute.KeyValue { //nolint:revive // i
//
// If any of the fields in the ResponseTelemetry are not set the attribute will
// be omitted.
func (n HTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue {
func (HTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue {
var count int
if resp.ReadBytes > 0 {
@@ -330,17 +335,20 @@ func (n HTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyVa
attributes := make([]attribute.KeyValue, 0, count)
if resp.ReadBytes > 0 {
attributes = append(attributes,
attributes = append(
attributes,
semconv.HTTPRequestBodySize(int(resp.ReadBytes)),
)
}
if resp.WriteBytes > 0 {
attributes = append(attributes,
attributes = append(
attributes,
semconv.HTTPResponseBodySize(int(resp.WriteBytes)),
)
}
if resp.StatusCode > 0 {
attributes = append(attributes,
attributes = append(
attributes,
semconv.HTTPResponseStatusCode(resp.StatusCode),
)
}
@@ -349,7 +357,7 @@ func (n HTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyVa
}
// Route returns the attribute for the route.
func (n HTTPServer) Route(route string) attribute.KeyValue {
func (HTTPServer) Route(route string) attribute.KeyValue {
return semconv.HTTPRoute(route)
}
@@ -1,10 +1,10 @@
// Code generated by gotmpl. DO NOT MODIFY.
// source: internal/shared/semconv/util.go.tmpl
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv"
// DO NOT MODIFY. Generated by gotmpl.
// source: internal/shared/semconv/util.go.tmpl
package semconv
import (
"net"
@@ -15,7 +15,7 @@ import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
semconvNew "go.opentelemetry.io/otel/semconv/v1.41.0"
semconvNew "go.opentelemetry.io/otel/semconv/v1.43.0"
)
// SplitHostPort splits a network address hostport of the form "host",
@@ -32,29 +32,29 @@ func SplitHostPort(hostport string) (host string, port int) {
addrEnd := strings.LastIndexByte(hostport, ']')
if addrEnd < 0 {
// Invalid hostport.
return
return host, port
}
if i := strings.LastIndexByte(hostport[addrEnd:], ':'); i < 0 {
host = hostport[1:addrEnd]
return
return host, port
}
} else {
if i := strings.LastIndexByte(hostport, ':'); i < 0 {
host = hostport
return
return host, port
}
}
host, pStr, err := net.SplitHostPort(hostport)
if err != nil {
return
return host, port
}
p, err := strconv.ParseUint(pStr, 10, 16)
if err != nil {
return
return host, port
}
return host, int(p) //nolint:gosec // Byte size checked 16 above.
return host, int(p)
}
func requiredHTTPPort(https bool, port int) int { //nolint:revive // ignore linter
@@ -84,7 +84,7 @@ func httpRoute(pattern string) string {
return ""
}
func netProtocol(proto string) (name string, version string) {
func netProtocol(proto string) (name, version string) {
name, version, _ = strings.Cut(proto, "/")
switch name {
case "HTTP":
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otelhttptrace // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
package otelhttptrace
// Version is the current release version of the httptrace instrumentation.
const Version = "0.69.0"
const Version = "0.71.0"
+3 -4
View File
@@ -96,9 +96,9 @@ linters:
- "!**/exporters/zipkin/**"
deny:
- pkg: go.opentelemetry.io/otel/semconv
desc: "Use go.opentelemetry.io/otel/semconv/v1.41.0 instead. If a newer semconv version has been released, update the depguard rule."
desc: "Use go.opentelemetry.io/otel/semconv/v1.43.0 instead. If a newer semconv version has been released, update the depguard rule."
allow:
- go.opentelemetry.io/otel/semconv/v1.41.0
- go.opentelemetry.io/otel/semconv/v1.43.0
gocritic:
disabled-checks:
- appendAssign
@@ -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
+14
View File
@@ -11,3 +11,17 @@ http://4.3.2.1:78/user/123
file:///home/runner/work/opentelemetry-go/opentelemetry-go/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/dns:/:4317
# URL works, but it has blocked link checkers.
https://dl.acm.org/doi/10.1145/198429.198435
https://pkg.go.dev/google.golang.org/grpc.*internal/resolver
https://golang.org/src/crypto/tls/generate_cert.go
https://github.com/grpc/grpc/blob/.*/doc/naming.md
https://github.com/open-telemetry/opentelemetry-specification/blob/.*
# Fake domains used in otlp options_test.go tests
https?://env\.endpoint.*
https?://env\.metrics\.endpoint.*
https?://env_metrics_endpoint.*
https?://env\.traces\.endpoint.*
https?://env_traces_endpoint.*
https?://someendpoint.*
https?://overrode\.by\.signal\.specific.*
https?://overrode_by_signal_specific.*
https?://proxy\.com.*
+3
View File
@@ -47,6 +47,9 @@ For docs-only, test-only, or review-only tasks, still start with the required re
- Prefer examples over long code snippets in GoDoc when practical.
- Keep docs aligned with actual behavior. Do not leave stale comments, stale examples, or stale package documentation behind.
- For user-visible changes, update `CHANGELOG.md` under the appropriate `Added`, `Changed`, `Deprecated`, `Fixed`, or `Removed` section within `## [Unreleased]`.
- Always put the PR number at the end of the line (e.g., `(#1234)`), NOT the issue number.
- If the PR number is not yet known, omit it until the PR is created, then update the changelog entry before merging.
- Always use references to the go module that is updated (e.g., `go.opentelemetry.io/otel/sdk/metric`), instead of just the path (e.g., `sdk/metric`).
## Repository habits
+104 -4
View File
@@ -11,6 +11,103 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
<!-- Released section -->
<!-- Don't change this section unless doing release -->
## [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
- Add experimental observability metrics to `BatchProcessor` in `go.opentelemetry.io/otel/sdk/log`. (#7124)
- Add the experimental `WithUnsafeAttributes` no-copy attribute option to `go.opentelemetry.io/otel/metric/x` for future performance improvements. This API is a work in progress. (#8251)
- Add `Map` and `MapValue` functions for the new `MAP` attribute type in `go.opentelemetry.io/otel/attribute`. (#8445)
- Support `MAP` attributes in `go.opentelemetry.io/otel/exporters/otlp/otlptrace`. (#8453)
- Support `MAP` attributes in `go.opentelemetry.io/otel/exporters/otlp/otlplog`. (#8453)
- Support `MAP` attributes in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric`. (#8453)
- Support `MAP` attributes in `go.opentelemetry.io/otel/exporters/zipkin`. (#8453)
- Apply `AttributeValueLengthLimit` recursively to values contained in `attribute.MAP` attributes in `go.opentelemetry.io/otel/sdk/trace`. (#8454)
- Remove duplicate keys from `attribute.MAP` values in `go.opentelemetry.io/otel/sdk/resource` using last-value-wins semantics. (#8471)
- Remove duplicate keys by default from `attribute.MAP` values in instrumentation scope attributes in `go.opentelemetry.io/otel/sdk/log` using last-value-wins semantics. (#8471)
- Remove duplicate keys by default from `attribute.MAP` values in span, event, link, and instrumentation scope attributes in `go.opentelemetry.io/otel/sdk/trace` using last-value-wins semantics. (#8471)
- Remove duplicate keys by default from `attribute.MAP` values in measurement and instrumentation scope attributes in `go.opentelemetry.io/otel/sdk/metric` using last-value-wins semantics. (#8471)
- Extend `WithAllowKeyDuplication` in `go.opentelemetry.io/otel/sdk/log` to disable duplicate-key removal in `attribute.MAP` values for instrumentation scope attributes. (#8471)
- Add the `go.opentelemetry.io/otel/semconv/v1.42.0` package.
The package contains semantic conventions from the `v1.42.0` version of the OpenTelemetry Semantic Conventions.
See the [migration documentation](./semconv/v1.42.0/MIGRATION.md) for information on how to upgrade from `go.opentelemetry.io/otel/semconv/v1.41.0`. (#8484)
- Add `WithoutPanicRecording` as a `TracerProviderOption` in `go.opentelemetry.io/otel/sdk/trace` to disable exception event recording for panics. (#8532)
- Add the `go.opentelemetry.io/otel/semconv/v1.43.0` package.
The package contains semantic conventions from the `v1.43.0` version of the OpenTelemetry Semantic Conventions.
See the [migration documentation](./semconv/v1.43.0/MIGRATION.md) for information on how to upgrade from `go.opentelemetry.io/otel/semconv/v1.42.0`. (#8628)
### Changed
- `HistogramReservoir` in `go.opentelemetry.io/otel/sdk/metric/exemplar` now uses a time-unbiased sampling algorithm for exemplars. (#8306)
- ⚠️ **Breaking Change:** Use `go.opentelemetry.io/otel/attribute.Value` and `go.opentelemetry.io/otel/attribute.KeyValue` for log bodies and attributes in `go.opentelemetry.io/otel/log`, `go.opentelemetry.io/otel/log/logtest`, `go.opentelemetry.io/otel/sdk/log`, and `go.opentelemetry.io/otel/sdk/log/logtest`. (#8490)
- Encode log bodies and attributes as `go.opentelemetry.io/otel/attribute.Value` JSON in `go.opentelemetry.io/otel/exporters/stdout/stdoutlog`. (#8490)
- Improve the performance of hashing `BOOLSLICE`, `INT64SLICE`, `FLOAT64SLICE`, and `STRINGSLICE` attribute values by avoiding reflection for short slices in `go.opentelemetry.io/otel/attribute`. (#8511)
- ⚠️ **Breaking Change:** `WithEndpointURL` in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp` no longer appends the default signal path when an endpoint URL has no path, making the behavior consistent with `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp` and with setting the endpoint through `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`. If the URL has no path component, the root path (`/`) is used. Use `WithEndpointURL(url.JoinPath(endpoint, "/v1/metrics"))` to preserve the previous behavior. (#8538)
- ⚠️ **Breaking Change:** `WithEndpointURL` in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp` no longer appends the default signal path when an endpoint URL has no path, making the behavior consistent with `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp` and with setting the endpoint through `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`. If the URL has no path component, the root path (`/`) is used. Use `WithEndpointURL(url.JoinPath(endpoint, "/v1/traces"))` to preserve the previous behavior. (#8538)
### Deprecated
- Deprecate `WithExportBufferSize` in `go.opentelemetry.io/otel/sdk/log`. The option remains available for source compatibility but no longer affects behavior; `BatchProcessor` no longer maintains a separate export-request buffer. (#8620)
### Removed
- ⚠️ **Breaking Change:** Remove `Kind`, `Value`, `KeyValue`, their constructors, and attribute conversion helpers from `go.opentelemetry.io/otel/log`. (#8490)
- ⚠️ **Breaking Change:** Remove the `AttributeValueLengthLimit` and `AttributeCountLimit` fields from `RecordFactory` in `go.opentelemetry.io/otel/sdk/log/logtest`; records produced by the factory now keep attribute limits disabled so test code can append exact attributes. (#8556)
### Fixed
- Apply TLS certificates configured through environment variables to gRPC connections in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc`.
- Prevent panics in `go.opentelemetry.io/otel/bridge/opentracing` when OpenTracing baggage is propagated concurrently with `Span.SetBaggageItem`.
- Fix an off-by-one error in `FixedSizeReservoir` in `go.opentelemetry.io/otel/sdk/metric/exemplar` that prevented the first exemplar from being sampled after the reservoir was filled. (#8309)
- Interpret HTTP `Retry-After` header values as seconds instead of nanoseconds when retrying OTLP HTTP exports in `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`. (#8383)
- Fix a memory leak in the `Reservoir` implementation in `go.opentelemetry.io/otel/sdk/metric/exemplar`, where storing the full `context.Context` pinned large objects such as gRPC transport buffers. (#8389)
- Prevent a non-empty attribute set whose computed hash is zero from collapsing to an empty set in `go.opentelemetry.io/otel/attribute`. (#8402)
- Fix histogram data point reuse in `go.opentelemetry.io/otel/sdk/metric` aggregation to avoid leaking stale sum, minimum, and maximum values when they are disabled in subsequent collections. (#8403)
- Avoid preallocating scope attributes when they are disabled in `go.opentelemetry.io/otel/exporters/prometheus`. (#8404)
- Support HTTP-date values in the HTTP `Retry-After` header when retrying OTLP HTTP exports in `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`. (#8417)
- Reduce histogram heap allocations by reusing `BucketCounts` and `Exemplars` slices across `Collect` cycles in the cumulative histogram aggregation in `go.opentelemetry.io/otel/sdk/metric`. (#8428)
- Fix `go.opentelemetry.io/otel/exporters/stdout/stdouttrace` self-observability to record `error.type` on the operation-duration histogram when the `exportedSpans` metric is disabled. (#8432)
- Stop including trace exporter endpoint configuration in internal logs from `go.opentelemetry.io/otel/sdk/trace`, `go.opentelemetry.io/otel/exporters/otlp/otlptrace`, `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`, `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`, and `go.opentelemetry.io/otel/exporters/zipkin`. (#8438)
- Fix invalid error formatting for out-of-range JSON code values in `go.opentelemetry.io/otel/codes`. (#8497)
- Clarify in `go.opentelemetry.io/otel/log` that `Logger.Enabled` should be checked for every log emission because its result may change over time. (#8565)
- Preserve user-provided exception attributes while independently deriving missing exception message and type attributes in `go.opentelemetry.io/otel/sdk/log`. (#8566)
- Make `WithAttributeCountLimit(0)` and `OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT=0` discard all log record attributes in `go.opentelemetry.io/otel/sdk/log`. (#8570)
- Clarify that the `Record` methods of `Float64Histogram` and `Int64Histogram` in `go.opentelemetry.io/otel/metric` expect non-negative values. (#8574)
- Clarify in `go.opentelemetry.io/otel/log` that `LoggerProvider` implementations should retain an empty `Logger` name instead of replacing it with a default. (#8587)
- Ensure that the built-in processors in `go.opentelemetry.io/otel/sdk/log` call exporter `ForceFlush` during `Shutdown`. (#8599)
- Prevent processor operations in `go.opentelemetry.io/otel/sdk/log` from overlapping with processor shutdown or running after `LoggerProvider` shutdown. (#8608)
- Prevent `BatchProcessor` in `go.opentelemetry.io/otel/sdk/log` from busy-spinning under exporter backpressure and serialize dequeue, export, force-flush, and shutdown work in one worker. (#8620)
- Make `BatchProcessor` in `go.opentelemetry.io/otel/sdk/log` return errors encountered while draining records during `ForceFlush` and `Shutdown`, while continuing to attempt later batches as long as the request context remains valid. (#8620)
- Keep the default `BatchProcessor` maximum export batch size in `go.opentelemetry.io/otel/sdk/log` at or below the configured maximum queue size. (#8620)
## [1.44.0/0.66.0/0.20.0/0.0.17] 2026-05-27
### Added
@@ -42,13 +139,13 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
Set `OTEL_GO_X_METRIC_EXPORT_BATCH_SIZE=<max_size>` to enable for all periodic readers.
See `go.opentelemetry.io/otel/sdk/metric/internal/x` for feature documentation. (#8071)
- Add experimental self-observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc`.
Enable with `OTEL_GO_X_SELF_OBSERVABILITY=true` environment variable.
Enable with `OTEL_GO_X_OBSERVABILITY=true` environment variable.
See `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/x` for feature documentation. (#8192)
- Add experimental self-observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`.
Enable with `OTEL_GO_X_SELF_OBSERVABILITY=true` environment variable.
Enable with `OTEL_GO_X_OBSERVABILITY=true` environment variable.
See `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp/internal/x` for feature documentation. (#8194)
- Add experimental self-observability metrics in `go.opentelemetry.io/otel/exporters/stdout/stdoutlog`.
Enable with `OTEL_GO_X_SELF_OBSERVABILITY=true` environment variable.
Enable with `OTEL_GO_X_OBSERVABILITY=true` environment variable.
See `go.opentelemetry.io/otel/stdout/stdoutlog/internal/x` for feature documentation. (#8263)
- Add `WithDefaultAttributes` to `go.opentelemetry.io/otel/metric/x` to support setting default attributes on instruments. (#8135)
- Add `go.opentelemetry.io/otel/semconv/v1.41.0` package.
@@ -3713,7 +3810,9 @@ 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.44.0...HEAD
[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.46.0...HEAD
[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
[1.42.0/0.64.0/0.18.0/0.0.16]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.42.0
@@ -3817,6 +3916,7 @@ It contains api and sdk for trace and meter.
<!-- Released section ended -->
[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
+7 -5
View File
@@ -8,8 +8,10 @@ repo for information on this and other language SIGs.
See the [public meeting
notes](https://docs.google.com/document/d/1E5e7Ld0NuU1iVvf-42tOBpu2VBBLYnh73GJuITGJTTU/edit)
for a summary description of past meetings. To request edit access,
join the meeting or get in touch on
[Slack](https://cloud-native.slack.com/archives/C01NPAXACKT).
join the meeting or get in touch on the
[#otel-go](https://cloud-native.slack.com/archives/C01NPAXACKT)
channel on CNCF Slack. If you are new to the CNCF Slack community,
you can [create an account](https://slack.cncf.io/).
The meeting is open for all to join. We invite everyone to join our
meeting, regardless of your experience level. Whether you're a
@@ -752,8 +754,8 @@ Encapsulate setup in constructor functions, ensuring clear ownership and scope:
import (
"errors"
semconv "go.opentelemetry.io/otel/semconv/v1.41.0"
"go.opentelemetry.io/otel/semconv/v1.41.0/otelconv"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
"go.opentelemetry.io/otel/semconv/v1.43.0/otelconv"
)
type SDKComponent struct {
@@ -1054,7 +1056,7 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan)
All observability metrics should follow the [OpenTelemetry Semantic Conventions for SDK metrics](https://github.com/open-telemetry/semantic-conventions/blob/1cf2476ae5e518225a766990a28a6d5602bd5a30/docs/otel/sdk-metrics.md).
Use the metric semantic conventions convenience package [otelconv](./semconv/v1.41.0/otelconv/metric.go).
Use the metric semantic conventions convenience package [otelconv](./semconv/v1.43.0/otelconv/metric.go).
##### Component Identification
+28 -20
View File
@@ -10,6 +10,7 @@ ALL_COVERAGE_MOD_DIRS := $(shell find . -type f -name 'go.mod' -exec dirname {}
GO = go
TIMEOUT = 60
GO_VERSION := $(shell awk '/^go [0-9]/ {print $$2; exit}' go.mod)
# User to run as in docker images.
DOCKER_USER=$(shell id -u):$(shell id -g)
@@ -19,7 +20,7 @@ DEPENDENCIES_DOCKERFILE=./dependencies.Dockerfile
.PHONY: precommit ci
precommit: generate toolchain-check license-check misspell go-mod-tidy golangci-lint-fix verify-readmes verify-mods test-default
ci: generate toolchain-check license-check lint vanity-import-check verify-readmes verify-mods build test-default check-clean-work-tree test-coverage
ci: generate toolchain-check license-check lint verify-readmes verify-mods build test-default check-clean-work-tree test-coverage
# Tools
@@ -59,9 +60,6 @@ $(TOOLS)/gocovmerge: PACKAGE=github.com/wadey/gocovmerge
STRINGER = $(TOOLS)/stringer
$(TOOLS)/stringer: PACKAGE=golang.org/x/tools/cmd/stringer
PORTO = $(TOOLS)/porto
$(TOOLS)/porto: PACKAGE=github.com/jcchavezs/porto/cmd/porto
GOTMPL = $(TOOLS)/gotmpl
$(GOTMPL): PACKAGE=go.opentelemetry.io/build-tools/gotmpl
@@ -71,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) $(PORTO) $(VERIFYREADMES) $(MULTIMOD) $(SEMCONVKIT) $(GOTMPL) $(GORELEASE)
tools: $(CROSSLINK) $(GOLANGCI_LINT) $(MISSPELL) $(GOCOVMERGE) $(STRINGER) $(VERIFYREADMES) $(MULTIMOD) $(SEMCONVKIT) $(GOTMPL) $(GORELEASE) $(AFFECTEDMODS)
# Virtualized python tools via docker
@@ -110,7 +113,7 @@ $(CODESPELL): PACKAGE=codespell
# Generate
.PHONY: generate
generate: go-generate vanity-import-fix
generate: go-generate
.PHONY: go-generate
go-generate: $(OTEL_GO_MOD_DIRS:%=go-generate/%)
@@ -120,20 +123,18 @@ go-generate/%: $(STRINGER) $(GOTMPL)
&& cd $(DIR) \
&& PATH="$(TOOLS):$${PATH}" $(GO) generate ./...
.PHONY: vanity-import-fix
vanity-import-fix: $(PORTO)
@$(PORTO) --include-internal -w .
# Generate go.work file for local development.
.PHONY: go-work
go-work: $(CROSSLINK)
$(CROSSLINK) work --root=$(shell pwd) --go=1.22.7
$(CROSSLINK) work --root=$(shell pwd) --go=$(GO_VERSION)
# 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)/..." \
@@ -169,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
@@ -193,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
@@ -228,10 +240,6 @@ go-mod-tidy/%: crosslink
.PHONY: lint
lint: misspell go-mod-tidy golangci-lint
.PHONY: vanity-import-check
vanity-import-check: $(PORTO)
@$(PORTO) --include-internal -l . || ( echo "(run: make vanity-import-fix)"; exit 1 )
.PHONY: misspell
misspell: $(MISSPELL)
@$(MISSPELL) -w $(ALL_DOCS)
+14
View File
@@ -53,18 +53,25 @@ 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 |
@@ -113,3 +120,10 @@ 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).
+6
View File
@@ -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
+1 -1
View File
@@ -2,4 +2,4 @@
// SPDX-License-Identifier: Apache-2.0
// Package attribute provides key and value attributes.
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
import (
"bytes"
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
// Filter supports removing certain attributes from attribute sets. When
// the filter returns true, the attribute will be kept in the filtered
+193 -31
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
import (
"fmt"
@@ -29,16 +29,75 @@ const (
stringSliceID uint64 = 7453010373645655387 // "[]string" (little endian)
byteSliceID uint64 = 6874028470941080415 // "_[]byte_" (little endian)
sliceID uint64 = 7883494272577650031 // "__slice_" (little endian)
mapID uint64 = 6872316492666199903 // "__map___" (little endian)
emptyID uint64 = 7305809155345288421 // "__empty_" (little endian)
)
// hashKVs returns a new xxHash64 hash of kvs.
func hashKVs(kvs []KeyValue) uint64 {
h := xxhash.New()
for _, kv := range kvs {
h = hashKV(h, kv)
// 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 h.Sum64()
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 := NewHasher()
for _, kv := range kvs {
h.Write(kv)
}
return h.Distinct().hash
}
// hashKV returns the xxHash64 hash of kv with h as the base.
@@ -64,27 +123,79 @@ func hashValue(h xxhash.Hash, v Value) xxhash.Hash {
h = h.String(v.stringly)
case BOOLSLICE:
h = h.Uint64(boolSliceID)
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
h = h.Bool(rv.Index(i).Bool())
switch vals := v.slice.(type) {
case [0]bool:
case [1]bool:
h = h.Bool(vals[0])
case [2]bool:
h = h.Bool(vals[0])
h = h.Bool(vals[1])
case [3]bool:
h = h.Bool(vals[0])
h = h.Bool(vals[1])
h = h.Bool(vals[2])
default:
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
h = h.Bool(rv.Index(i).Bool())
}
}
case INT64SLICE:
h = h.Uint64(int64SliceID)
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
h = h.Int64(rv.Index(i).Int())
switch vals := v.slice.(type) {
case [0]int64:
case [1]int64:
h = h.Int64(vals[0])
case [2]int64:
h = h.Int64(vals[0])
h = h.Int64(vals[1])
case [3]int64:
h = h.Int64(vals[0])
h = h.Int64(vals[1])
h = h.Int64(vals[2])
default:
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
h = h.Int64(rv.Index(i).Int())
}
}
case FLOAT64SLICE:
h = h.Uint64(float64SliceID)
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
h = h.Float64(rv.Index(i).Float())
switch vals := v.slice.(type) {
case [0]float64:
case [1]float64:
h = h.Float64(vals[0])
case [2]float64:
h = h.Float64(vals[0])
h = h.Float64(vals[1])
case [3]float64:
h = h.Float64(vals[0])
h = h.Float64(vals[1])
h = h.Float64(vals[2])
default:
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
h = h.Float64(rv.Index(i).Float())
}
}
case STRINGSLICE:
h = h.Uint64(stringSliceID)
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
h = h.String(rv.Index(i).String())
switch vals := v.slice.(type) {
case [0]string:
case [1]string:
h = h.String(vals[0])
case [2]string:
h = h.String(vals[0])
h = h.String(vals[1])
case [3]string:
h = h.String(vals[0])
h = h.String(vals[1])
h = h.String(vals[2])
default:
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
h = h.String(rv.Index(i).String())
}
}
case BYTESLICE:
h = h.Uint64(byteSliceID)
@@ -95,21 +206,79 @@ func hashValue(h xxhash.Hash, v Value) xxhash.Hash {
case [0]Value:
// No values to hash, but the type identifier is still hashed above.
case [1]Value:
h = hashValueSlice(h, vals[:])
h = hashValue(h, vals[0])
case [2]Value:
h = hashValueSlice(h, vals[:])
h = hashValue(h, vals[0])
h = hashValue(h, vals[1])
case [3]Value:
h = hashValueSlice(h, vals[:])
h = hashValue(h, vals[0])
h = hashValue(h, vals[1])
h = hashValue(h, vals[2])
case [4]Value:
h = hashValueSlice(h, vals[:])
h = hashValue(h, vals[0])
h = hashValue(h, vals[1])
h = hashValue(h, vals[2])
h = hashValue(h, vals[3])
case [5]Value:
h = hashValueSlice(h, vals[:])
h = hashValue(h, vals[0])
h = hashValue(h, vals[1])
h = hashValue(h, vals[2])
h = hashValue(h, vals[3])
h = hashValue(h, vals[4])
default:
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
h = hashValue(h, rv.Index(i).Interface().(Value))
}
}
case MAP:
h = h.Uint64(mapID)
switch vals := v.slice.(type) {
case [0]KeyValue:
// No values to hash, but the type identifier is still hashed above.
case [1]KeyValue:
h = h.String(string(vals[0].Key))
h = hashValue(h, vals[0].Value)
case [2]KeyValue:
h = h.String(string(vals[0].Key))
h = hashValue(h, vals[0].Value)
h = h.String(string(vals[1].Key))
h = hashValue(h, vals[1].Value)
case [3]KeyValue:
h = h.String(string(vals[0].Key))
h = hashValue(h, vals[0].Value)
h = h.String(string(vals[1].Key))
h = hashValue(h, vals[1].Value)
h = h.String(string(vals[2].Key))
h = hashValue(h, vals[2].Value)
case [4]KeyValue:
h = h.String(string(vals[0].Key))
h = hashValue(h, vals[0].Value)
h = h.String(string(vals[1].Key))
h = hashValue(h, vals[1].Value)
h = h.String(string(vals[2].Key))
h = hashValue(h, vals[2].Value)
h = h.String(string(vals[3].Key))
h = hashValue(h, vals[3].Value)
case [5]KeyValue:
h = h.String(string(vals[0].Key))
h = hashValue(h, vals[0].Value)
h = h.String(string(vals[1].Key))
h = hashValue(h, vals[1].Value)
h = h.String(string(vals[2].Key))
h = hashValue(h, vals[2].Value)
h = h.String(string(vals[3].Key))
h = hashValue(h, vals[3].Value)
h = h.String(string(vals[4].Key))
h = hashValue(h, vals[4].Value)
default:
rv := reflect.ValueOf(v.slice)
for i := 0; i < rv.Len(); i++ {
kv := rv.Index(i).Interface().(KeyValue)
h = h.String(string(kv.Key))
h = hashValue(h, kv.Value)
}
}
case EMPTY:
h = h.Uint64(emptyID)
default:
@@ -121,10 +290,3 @@ func hashValue(h xxhash.Hash, v Value) xxhash.Hash {
}
return h
}
func hashValueSlice(h xxhash.Hash, vals []Value) xxhash.Hash {
for _, v := range vals {
h = hashValue(h, v)
}
return h
}
+1 -1
View File
@@ -5,7 +5,7 @@
Package attribute provide several helper functions for some commonly used
logic of processing attributes.
*/
package attribute // import "go.opentelemetry.io/otel/attribute/internal"
package attribute
import (
"reflect"
+6 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
// Package xxhash provides a wrapper around the xxhash library for attribute hashing.
package xxhash // import "go.opentelemetry.io/otel/attribute/internal/xxhash"
package xxhash
import (
"encoding/binary"
@@ -62,3 +62,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()
}
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
// Iterator allows iterating over the set of attributes in order, sorted by
// key.
+97 -37
View File
@@ -1,16 +1,16 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
// Key represents the key part in key-value pairs. It's a string. The
// allowed character set in the key depends on the use of the key.
type Key string
// Bool creates a KeyValue instance with a BOOL Value.
// Bool returns a [KeyValue] for a bool value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- Bool(name, value).
// If creating both a key and value at the same time, use the package-level
// [Bool] function.
func (k Key) Bool(v bool) KeyValue {
return KeyValue{
Key: k,
@@ -18,10 +18,15 @@ func (k Key) Bool(v bool) KeyValue {
}
}
// BoolSlice creates a KeyValue instance with a BOOLSLICE Value.
// BoolSlice returns a [KeyValue] for a []bool value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- BoolSlice(name, value).
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// If creating both a key and value at the same time, use the package-level
// [BoolSlice] function.
func (k Key) BoolSlice(v []bool) KeyValue {
return KeyValue{
Key: k,
@@ -29,10 +34,12 @@ func (k Key) BoolSlice(v []bool) KeyValue {
}
}
// Int creates a KeyValue instance with an INT64 Value.
// Int returns a [KeyValue] for an int value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- Int(name, value).
// It is provided as a convenience for [Key.Int64].
//
// If creating both a key and value at the same time, use the package-level [Int]
// function.
func (k Key) Int(v int) KeyValue {
return KeyValue{
Key: k,
@@ -40,10 +47,17 @@ func (k Key) Int(v int) KeyValue {
}
}
// IntSlice creates a KeyValue instance with an INT64SLICE Value.
// IntSlice returns a [KeyValue] for a []int value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- IntSlice(name, value).
// It is provided as a convenience for [Key.Int64Slice].
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// If creating both a key and value at the same time, use the package-level
// [IntSlice] function.
func (k Key) IntSlice(v []int) KeyValue {
return KeyValue{
Key: k,
@@ -51,10 +65,10 @@ func (k Key) IntSlice(v []int) KeyValue {
}
}
// Int64 creates a KeyValue instance with an INT64 Value.
// Int64 returns a [KeyValue] for an int64 value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- Int64(name, value).
// If creating both a key and value at the same time, use the package-level
// [Int64] function.
func (k Key) Int64(v int64) KeyValue {
return KeyValue{
Key: k,
@@ -62,10 +76,15 @@ func (k Key) Int64(v int64) KeyValue {
}
}
// Int64Slice creates a KeyValue instance with an INT64SLICE Value.
// Int64Slice returns a [KeyValue] for a []int64 value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- Int64Slice(name, value).
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// If creating both a key and value at the same time, use the package-level
// [Int64Slice] function.
func (k Key) Int64Slice(v []int64) KeyValue {
return KeyValue{
Key: k,
@@ -73,10 +92,10 @@ func (k Key) Int64Slice(v []int64) KeyValue {
}
}
// Float64 creates a KeyValue instance with a FLOAT64 Value.
// Float64 returns a [KeyValue] for a float64 value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- Float64(name, value).
// If creating both a key and value at the same time, use the package-level
// [Float64] function.
func (k Key) Float64(v float64) KeyValue {
return KeyValue{
Key: k,
@@ -84,10 +103,15 @@ func (k Key) Float64(v float64) KeyValue {
}
}
// Float64Slice creates a KeyValue instance with a FLOAT64SLICE Value.
// Float64Slice returns a [KeyValue] for a []float64 value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- Float64(name, value).
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// If creating both a key and value at the same time, use the package-level
// [Float64Slice] function.
func (k Key) Float64Slice(v []float64) KeyValue {
return KeyValue{
Key: k,
@@ -95,10 +119,10 @@ func (k Key) Float64Slice(v []float64) KeyValue {
}
}
// String creates a KeyValue instance with a STRING Value.
// String returns a [KeyValue] for a string value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- String(name, value).
// If creating both a key and value at the same time, use the package-level
// [String] function.
func (k Key) String(v string) KeyValue {
return KeyValue{
Key: k,
@@ -106,10 +130,15 @@ func (k Key) String(v string) KeyValue {
}
}
// StringSlice creates a KeyValue instance with a STRINGSLICE Value.
// StringSlice returns a [KeyValue] for a []string value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- StringSlice(name, value).
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// If creating both a key and value at the same time, use the package-level
// [StringSlice] function.
func (k Key) StringSlice(v []string) KeyValue {
return KeyValue{
Key: k,
@@ -117,10 +146,15 @@ func (k Key) StringSlice(v []string) KeyValue {
}
}
// ByteSlice creates a KeyValue instance with a BYTESLICE Value.
// ByteSlice returns a [KeyValue] for a []byte value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- ByteSlice(name, value).
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// If creating both a key and value at the same time, use the package-level
// [ByteSlice] function.
func (k Key) ByteSlice(v []byte) KeyValue {
return KeyValue{
Key: k,
@@ -128,10 +162,15 @@ func (k Key) ByteSlice(v []byte) KeyValue {
}
}
// Slice creates a KeyValue instance with a SLICE Value.
// Slice returns a [KeyValue] for a []Value value.
//
// If creating both a key and value at the same time, use the provided
// convenience function instead -- Slice(name, values...).
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// If creating both a key and value at the same time, use the package-level
// [Slice] function.
func (k Key) Slice(v ...Value) KeyValue {
return KeyValue{
Key: k,
@@ -139,6 +178,27 @@ func (k Key) Slice(v ...Value) KeyValue {
}
}
// Map returns a [KeyValue] for a []KeyValue value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// Users should avoid providing duplicate keys; many receivers handle maps
// containing duplicate keys unpredictably.
//
// The order of v is not preserved.
//
// If creating both a key and value at the same time, use the package-level [Map]
// function.
func (k Key) Map(v ...KeyValue) KeyValue {
return KeyValue{
Key: k,
Value: MapValue(v...),
}
}
// Defined reports whether the key is not empty.
func (k Key) Defined() bool {
return len(k) != 0
+67 -13
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
import (
"fmt"
@@ -18,66 +18,120 @@ func (kv KeyValue) Valid() bool {
return kv.Key.Defined()
}
// Bool creates a KeyValue with a BOOL Value type.
// Bool returns a [KeyValue] for a bool value.
func Bool(k string, v bool) KeyValue {
return Key(k).Bool(v)
}
// BoolSlice creates a KeyValue with a BOOLSLICE Value type.
// BoolSlice returns a [KeyValue] for a []bool value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func BoolSlice(k string, v []bool) KeyValue {
return Key(k).BoolSlice(v)
}
// Int creates a KeyValue with an INT64 Value type.
// Int returns a [KeyValue] for an int value.
//
// It is provided as a convenience for [Int64].
func Int(k string, v int) KeyValue {
return Key(k).Int(v)
}
// IntSlice creates a KeyValue with an INT64SLICE Value type.
// IntSlice returns a [KeyValue] for a []int value.
//
// It is provided as a convenience for [Int64Slice].
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func IntSlice(k string, v []int) KeyValue {
return Key(k).IntSlice(v)
}
// Int64 creates a KeyValue with an INT64 Value type.
// Int64 returns a [KeyValue] for an int64 value.
func Int64(k string, v int64) KeyValue {
return Key(k).Int64(v)
}
// Int64Slice creates a KeyValue with an INT64SLICE Value type.
// Int64Slice returns a [KeyValue] for a []int64 value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func Int64Slice(k string, v []int64) KeyValue {
return Key(k).Int64Slice(v)
}
// Float64 creates a KeyValue with a FLOAT64 Value type.
// Float64 returns a [KeyValue] for a float64 value.
func Float64(k string, v float64) KeyValue {
return Key(k).Float64(v)
}
// Float64Slice creates a KeyValue with a FLOAT64SLICE Value type.
// Float64Slice returns a [KeyValue] for a []float64 value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func Float64Slice(k string, v []float64) KeyValue {
return Key(k).Float64Slice(v)
}
// String creates a KeyValue with a STRING Value type.
// String returns a [KeyValue] for a string value.
func String(k, v string) KeyValue {
return Key(k).String(v)
}
// StringSlice creates a KeyValue with a STRINGSLICE Value type.
// StringSlice returns a [KeyValue] for a []string value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func StringSlice(k string, v []string) KeyValue {
return Key(k).StringSlice(v)
}
// ByteSlice creates a KeyValue with a BYTESLICE Value type.
// ByteSlice returns a [KeyValue] for a []byte value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func ByteSlice(k string, v []byte) KeyValue {
return Key(k).ByteSlice(v)
}
// Slice creates a KeyValue with a SLICE Value type.
// Slice returns a [KeyValue] for a []Value value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func Slice(k string, v ...Value) KeyValue {
return Key(k).Slice(v...)
}
// Map returns a [KeyValue] for a []KeyValue value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// Users should avoid providing duplicate keys; many receivers handle maps
// containing duplicate keys unpredictably.
//
// The order of v is not preserved.
func Map(k string, v ...KeyValue) KeyValue {
return Key(k).Map(v...)
}
// Stringer creates a new key-value pair with a passed name and a string
// value generated by the passed Stringer interface.
func Stringer(k string, v fmt.Stringer) KeyValue {
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
import (
"math"
+4 -1
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
import (
"cmp"
@@ -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
}
+3 -2
View File
@@ -19,11 +19,12 @@ func _() {
_ = x[STRINGSLICE-8]
_ = x[BYTESLICE-9]
_ = x[SLICE-10]
_ = x[MAP-11]
}
const _Type_name = "EMPTYBOOLINT64FLOAT64STRINGBOOLSLICEINT64SLICEFLOAT64SLICESTRINGSLICEBYTESLICESLICE"
const _Type_name = "EMPTYBOOLINT64FLOAT64STRINGBOOLSLICEINT64SLICEFLOAT64SLICESTRINGSLICEBYTESLICESLICEMAP"
var _Type_index = [...]uint8{0, 5, 9, 14, 21, 27, 36, 46, 58, 69, 78, 83}
var _Type_index = [...]uint8{0, 5, 9, 14, 21, 27, 36, 46, 58, 69, 78, 83, 86}
func (i Type) String() string {
idx := int(i) - 0
+281 -31
View File
@@ -1,14 +1,16 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package attribute // import "go.opentelemetry.io/otel/attribute"
package attribute
import (
"cmp"
"encoding/base64"
"encoding/json"
"fmt"
"math"
"reflect"
"slices"
"strconv"
"strings"
"unicode/utf8"
@@ -18,10 +20,10 @@ import (
//go:generate stringer -type=Type
// Type describes the type of the data Value holds.
// Type describes the kind of data a [Value] holds.
type Type int // nolint: revive // redefines builtin Type.
// Value represents the value part in key-value pairs.
// Value represents the value in key-value pairs.
//
// Note that the zero value is a valid empty value.
type Value struct {
@@ -32,35 +34,40 @@ type Value struct {
}
const (
// EMPTY is used for a Value with no value set.
// EMPTY identifies a Value with no data.
EMPTY Type = iota
// BOOL is a boolean Type Value.
// BOOL identifies a Value containing a bool.
BOOL
// INT64 is a 64-bit signed integral Type Value.
// INT64 identifies a Value containing an int64.
INT64
// FLOAT64 is a 64-bit floating point Type Value.
// FLOAT64 identifies a Value containing a float64.
FLOAT64
// STRING is a string Type Value.
// STRING identifies a Value containing a string.
STRING
// BOOLSLICE is a slice of booleans Type Value.
// BOOLSLICE identifies a Value containing a []bool.
BOOLSLICE
// INT64SLICE is a slice of 64-bit signed integral numbers Type Value.
// INT64SLICE identifies a Value containing a []int64.
INT64SLICE
// FLOAT64SLICE is a slice of 64-bit floating point numbers Type Value.
// FLOAT64SLICE identifies a Value containing a []float64.
FLOAT64SLICE
// STRINGSLICE is a slice of strings Type Value.
// STRINGSLICE identifies a Value containing a []string.
STRINGSLICE
// BYTESLICE is a slice of bytes Type Value.
// BYTESLICE identifies a Value containing a []byte.
BYTESLICE
// SLICE is a slice of Value Type values.
// SLICE identifies a Value containing a []Value.
SLICE
// MAP identifies a Value containing a []KeyValue representation of a map.
//
// Note that MAP values may contain duplicate keys if duplicate keys are
// provided when creating the value.
MAP
// INVALID is used for a Value with no value set.
//
// Deprecated: Use EMPTY instead as an empty value is a valid value.
INVALID = EMPTY
)
// BoolValue creates a BOOL Value.
// BoolValue returns a [Value] for a bool value.
func BoolValue(v bool) Value {
return Value{
vtype: BOOL,
@@ -68,17 +75,31 @@ func BoolValue(v bool) Value {
}
}
// BoolSliceValue creates a BOOLSLICE Value.
// BoolSliceValue returns a [Value] for a []bool value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func BoolSliceValue(v []bool) Value {
return Value{vtype: BOOLSLICE, slice: attribute.SliceValue(v)}
}
// IntValue creates an INT64 Value.
// IntValue returns a [Value] for an int value.
//
// It is provided as a convenience for [Int64Value].
func IntValue(v int) Value {
return Int64Value(int64(v))
}
// IntSliceValue creates an INT64SLICE Value.
// IntSliceValue returns a [Value] for a []int value.
//
// It is provided as a convenience for [Int64SliceValue].
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func IntSliceValue(v []int) Value {
val := Value{vtype: INT64SLICE}
@@ -104,7 +125,7 @@ func IntSliceValue(v []int) Value {
return val
}
// Int64Value creates an INT64 Value.
// Int64Value returns a [Value] for an int64 value.
func Int64Value(v int64) Value {
return Value{
vtype: INT64,
@@ -112,12 +133,17 @@ func Int64Value(v int64) Value {
}
}
// Int64SliceValue creates an INT64SLICE Value.
// Int64SliceValue returns a [Value] for a []int64 value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func Int64SliceValue(v []int64) Value {
return Value{vtype: INT64SLICE, slice: attribute.SliceValue(v)}
}
// Float64Value creates a FLOAT64 Value.
// Float64Value returns a [Value] for a float64 value.
func Float64Value(v float64) Value {
return Value{
vtype: FLOAT64,
@@ -125,12 +151,17 @@ func Float64Value(v float64) Value {
}
}
// Float64SliceValue creates a FLOAT64SLICE Value.
// Float64SliceValue returns a [Value] for a []float64 value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func Float64SliceValue(v []float64) Value {
return Value{vtype: FLOAT64SLICE, slice: attribute.SliceValue(v)}
}
// StringValue creates a STRING Value.
// StringValue returns a [Value] for a string value.
func StringValue(v string) Value {
return Value{
vtype: STRING,
@@ -138,12 +169,22 @@ func StringValue(v string) Value {
}
}
// StringSliceValue creates a STRINGSLICE Value.
// StringSliceValue returns a [Value] for a []string value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func StringSliceValue(v []string) Value {
return Value{vtype: STRINGSLICE, slice: attribute.SliceValue(v)}
}
// ByteSliceValue creates a BYTESLICE Value.
// ByteSliceValue returns a [Value] for a []byte value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func ByteSliceValue(v []byte) Value {
return Value{
vtype: BYTESLICE,
@@ -151,12 +192,32 @@ func ByteSliceValue(v []byte) Value {
}
}
// SliceValue creates a SLICE Value.
// SliceValue returns a [Value] for a []Value value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
func SliceValue(v ...Value) Value {
return Value{vtype: SLICE, slice: sliceValue(v)}
}
// Type returns a type of the Value.
// MapValue returns a [Value] for a []KeyValue value.
//
// Note that many observability backends are not optimized to query, index, or
// aggregate complex attribute values. Complex values may also carry
// additional performance overhead. Prefer primitive values when
// possible.
//
// Users should avoid providing duplicate keys; many receivers handle maps
// containing duplicate keys unpredictably.
//
// The order of v is not preserved.
func MapValue(v ...KeyValue) Value {
return Value{vtype: MAP, slice: mapValue(v)}
}
// Type returns v's type.
func (v Value) Type() Type {
return v.vtype
}
@@ -277,6 +338,53 @@ func asValueSliceReflect(v any) []Value {
return cpy
}
// AsMap returns the []KeyValue value. Make sure that the Value's type is
// MAP.
//
// The returned slice is sorted by key and may differ from the order
// provided when creating the map value.
//
// The returned slice may contain duplicate keys if duplicate keys were
// provided when creating the map value. Callers should not assume the returned
// keys are unique.
func (v Value) AsMap() []KeyValue {
if v.vtype != MAP {
return nil
}
return v.asMap()
}
func (v Value) asMap() []KeyValue {
switch vals := v.slice.(type) {
case [0]KeyValue:
return []KeyValue{}
case [1]KeyValue:
return []KeyValue{vals[0]}
case [2]KeyValue:
return []KeyValue{vals[0], vals[1]}
case [3]KeyValue:
return []KeyValue{vals[0], vals[1], vals[2]}
case [4]KeyValue:
return []KeyValue{vals[0], vals[1], vals[2], vals[3]}
case [5]KeyValue:
return []KeyValue{vals[0], vals[1], vals[2], vals[3], vals[4]}
default:
return asKeyValueSliceReflect(v.slice)
}
}
func asKeyValueSliceReflect(v any) []KeyValue {
rv := reflect.ValueOf(v)
if !rv.IsValid() || rv.Kind() != reflect.Array || rv.Type().Elem() != reflect.TypeFor[KeyValue]() {
return nil
}
cpy := make([]KeyValue, rv.Len())
if len(cpy) > 0 {
_ = reflect.Copy(reflect.ValueOf(cpy), rv)
}
return cpy
}
// AsByteSlice returns the bytes value. Make sure that the Value's type
// is BYTESLICE.
func (v Value) AsByteSlice() []byte {
@@ -315,6 +423,8 @@ func (v Value) AsInterface() any {
return v.asByteSlice()
case SLICE:
return v.asSlice()
case MAP:
return v.asMap()
case EMPTY:
return nil
}
@@ -327,10 +437,10 @@ func (v Value) AsInterface() any {
// Strings are returned as-is without JSON quoting, booleans and integers use
// JSON literals, floating-point values use JSON numbers except that NaN and
// ±Inf are rendered as NaN, Infinity, and -Infinity, byte slices are
// base64-encoded, empty values are the empty string, and slices are encoded as
// JSON arrays. String, byte, and special floating-point values inside arrays
// are encoded as JSON strings, and empty values inside arrays are encoded as
// null.
// base64-encoded, empty values are the empty string, slices are encoded as JSON
// arrays, and maps are encoded as JSON objects. String, byte, and special
// floating-point values inside arrays and maps are encoded as JSON strings, and
// empty values inside arrays and maps are encoded as null.
//
// [OpenTelemetry AnyValue representation for non-OTLP protocols]: https://opentelemetry.io/docs/specs/otel/common/#anyvalue-representation-for-non-otlp-protocols
func (v Value) String() string {
@@ -355,6 +465,8 @@ func (v Value) String() string {
return formatByteSlice(v.stringly)
case SLICE:
return formatValueSliceValue(v.slice)
case MAP:
return formatMapValue(v.slice)
case EMPTY:
return ""
default:
@@ -399,6 +511,8 @@ func (v Value) Emit() string {
return formatByteSlice(v.stringly)
case SLICE:
return formatValueSliceValue(v.slice)
case MAP:
return formatMapValue(v.slice)
case EMPTY:
return ""
default:
@@ -439,6 +553,47 @@ func sliceValueReflect(v []Value) any {
return cp.Interface()
}
func mapValue(v []KeyValue) any {
switch len(v) {
case 0:
return [0]KeyValue{}
case 1:
return [1]KeyValue{v[0]}
case 2:
vals := [2]KeyValue{v[0], v[1]}
sortKeyValues(vals[:])
return vals
case 3:
vals := [3]KeyValue{v[0], v[1], v[2]}
sortKeyValues(vals[:])
return vals
case 4:
vals := [4]KeyValue{v[0], v[1], v[2], v[3]}
sortKeyValues(vals[:])
return vals
case 5:
vals := [5]KeyValue{v[0], v[1], v[2], v[3], v[4]}
sortKeyValues(vals[:])
return vals
default:
return mapValueReflect(v)
}
}
func mapValueReflect(v []KeyValue) any {
cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeFor[KeyValue]())).Elem()
reflect.Copy(cp, reflect.ValueOf(v))
vals := cp.Slice(0, len(v)).Interface().([]KeyValue)
sortKeyValues(vals)
return cp.Interface()
}
func sortKeyValues(vals []KeyValue) {
slices.SortStableFunc(vals, func(a, b KeyValue) int {
return cmp.Compare(a.Key, b.Key)
})
}
func formatBoolSliceValue(v any) string {
switch vals := v.(type) {
case [0]bool:
@@ -807,6 +962,37 @@ func formatValueSliceReflect(v any) string {
return b.String()
}
func formatMapValue(v any) string {
switch vals := v.(type) {
case [0]KeyValue:
return "{}"
case [1]KeyValue:
return formatMap(vals[:])
case [2]KeyValue:
return formatMap(vals[:])
case [3]KeyValue:
return formatMap(vals[:])
case [4]KeyValue:
return formatMap(vals[:])
case [5]KeyValue:
return formatMap(vals[:])
default:
return formatMapReflect(v)
}
}
func formatMap(vals []KeyValue) string {
var b strings.Builder
appendMap(&b, vals)
return b.String()
}
func formatMapReflect(v any) string {
var b strings.Builder
appendMapReflect(&b, reflect.ValueOf(v))
return b.String()
}
func appendValueSliceValue(dst *strings.Builder, v any) {
switch vals := v.(type) {
case [0]Value:
@@ -852,6 +1038,68 @@ func appendValueSliceReflect(dst *strings.Builder, rv reflect.Value) {
_ = dst.WriteByte(']')
}
func appendMapValue(dst *strings.Builder, v any) {
switch vals := v.(type) {
case [0]KeyValue:
_, _ = dst.WriteString("{}")
case [1]KeyValue:
appendMap(dst, vals[:])
case [2]KeyValue:
appendMap(dst, vals[:])
case [3]KeyValue:
appendMap(dst, vals[:])
case [4]KeyValue:
appendMap(dst, vals[:])
case [5]KeyValue:
appendMap(dst, vals[:])
default:
appendMapReflect(dst, reflect.ValueOf(v))
}
}
func appendMap(dst *strings.Builder, vals []KeyValue) {
// Estimate 32 bytes per value for small values, plus key quotes, colon,
// and commas. Escaped keys and larger values grow the builder as needed.
size := len("{}") + len(vals)*commaLen + len(vals)*32
for _, val := range vals {
size += len(val.Key) + len(`"":`)
}
dst.Grow(size)
_ = dst.WriteByte('{')
for i, val := range vals {
if i > 0 {
_ = dst.WriteByte(',')
}
appendJSONString(dst, string(val.Key))
_ = dst.WriteByte(':')
appendJSONValue(dst, val.Value)
}
_ = dst.WriteByte('}')
}
func appendMapReflect(dst *strings.Builder, rv reflect.Value) {
// Estimate 32 bytes per value for small values, plus key quotes, colon,
// and commas. Escaped keys and larger values grow the builder as needed.
size := len("{}") + rv.Len()*commaLen + rv.Len()*32
for i := 0; i < rv.Len(); i++ {
size += len(rv.Index(i).Field(0).String()) + len(`"":`)
}
dst.Grow(size)
_ = dst.WriteByte('{')
for i := 0; i < rv.Len(); i++ {
if i > 0 {
_ = dst.WriteByte(',')
}
val := rv.Index(i).Interface().(KeyValue)
appendJSONString(dst, string(val.Key))
_ = dst.WriteByte(':')
appendJSONValue(dst, val.Value)
}
_ = dst.WriteByte('}')
}
func appendJSONValue(dst *strings.Builder, v Value) {
switch v.Type() {
case BOOL:
@@ -894,6 +1142,8 @@ func appendJSONValue(dst *strings.Builder, v Value) {
_ = dst.WriteByte('"')
case SLICE:
appendValueSliceValue(dst, v.slice)
case MAP:
appendMapValue(dst, v.slice)
case EMPTY:
_, _ = dst.WriteString("null")
default:
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package baggage // import "go.opentelemetry.io/otel/baggage"
package baggage
import (
"errors"
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package baggage // import "go.opentelemetry.io/otel/baggage"
package baggage
import (
"context"
+1 -1
View File
@@ -6,4 +6,4 @@ Package baggage provides functionality for storing and retrieving
baggage items in Go context. For propagating the baggage, see the
go.opentelemetry.io/otel/propagation package.
*/
package baggage // import "go.opentelemetry.io/otel/baggage"
package baggage
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package codes // import "go.opentelemetry.io/otel/codes"
package codes
import (
"encoding/json"
@@ -81,7 +81,7 @@ func (c *Code) UnmarshalJSON(b []byte) error {
case float64:
if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil {
if ci >= maxCode {
return fmt.Errorf("invalid code: %q", ci)
return fmt.Errorf("invalid code: %d", ci)
}
*c = Code(ci) // nolint: gosec // Bit size of 32 check above.
+1 -1
View File
@@ -7,4 +7,4 @@ Package codes defines the canonical error codes used by OpenTelemetry.
It conforms to [the OpenTelemetry
specification](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/trace/api.md#set-status).
*/
package codes // import "go.opentelemetry.io/otel/codes"
package codes
+1 -1
View File
@@ -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.23.0@sha256:7984ecb55b859eb3034ae9d836c4eeda137e2bdd0873b7ba2bb6c3d24d6ff457 AS weaver
FROM otel/weaver:v0.25.1@sha256:9ad46ca9cd4fa5974b121f886aa3e9946a8ef8ea905001a96c018d21f9db87ca AS weaver
FROM avtodev/markdown-lint:v1@sha256:6aeedc2f49138ce7a1cd0adffc1b1c0321b841dc2102408967d9301c031949ee AS markdown
+1 -1
View File
@@ -22,4 +22,4 @@ To read more about logs, see go.opentelemetry.io/otel/log.
To read more about propagation, see go.opentelemetry.io/otel/propagation and
go.opentelemetry.io/otel/baggage.
*/
package otel // import "go.opentelemetry.io/otel"
package otel
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otel // import "go.opentelemetry.io/otel"
package otel
// ErrorHandler handles irremediable events.
type ErrorHandler interface {
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlptrace // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
package otlptrace
import (
"context"
+1 -1
View File
@@ -7,4 +7,4 @@ See the official OTLP span exporter implementations:
- [go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc],
- [go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp].
*/
package otlptrace // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
package otlptrace
+3 -3
View File
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlptrace // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
package otlptrace
import (
"context"
@@ -97,9 +97,9 @@ func NewUnstarted(client Client) *Exporter {
func (e *Exporter) MarshalLog() any {
return struct {
Type string
Client Client
Client string
}{
Type: "otlptrace",
Client: e.client,
Client: fmt.Sprintf("%T", e.client),
}
}
@@ -3,7 +3,7 @@
// Package tracetransform provides conversion functionality for the otlptrace
// exporters.
package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform"
package tracetransform
import (
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
@@ -97,6 +97,12 @@ func Value(v attribute.Value) *commonpb.AnyValue {
Values: values(v.AsSlice()),
},
}
case attribute.MAP:
av.Value = &commonpb.AnyValue_KvlistValue{
KvlistValue: &commonpb.KeyValueList{
Values: KeyValues(v.AsMap()),
},
}
case attribute.STRINGSLICE:
av.Value = &commonpb.AnyValue_ArrayValue{
ArrayValue: &commonpb.ArrayValue{
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform"
package tracetransform
import (
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform"
package tracetransform
import (
resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform"
package tracetransform
import (
"math"
@@ -37,21 +37,22 @@ func Spans(sdl []tracesdk.ReadOnlySpan) []*tracepb.ResourceSpans {
}
rKey := sd.Resource().Equivalent()
scope := sd.InstrumentationScope()
k := key{
r: rKey,
is: sd.InstrumentationScope(),
is: scope,
}
scopeSpan, iOk := ssm[k]
if !iOk {
// Either the resource or instrumentation scope were unknown.
scopeSpan = &tracepb.ScopeSpans{
Scope: InstrumentationScope(sd.InstrumentationScope()),
Scope: InstrumentationScope(scope),
Spans: []*tracepb.Span{},
SchemaUrl: sd.InstrumentationScope().SchemaURL,
SchemaUrl: scope.SchemaURL,
}
ssm[k] = scopeSpan
}
scopeSpan.Spans = append(scopeSpan.Spans, span(sd))
ssm[k] = scopeSpan
rs, rOk := rsm[rKey]
if !rOk {
@@ -90,14 +91,16 @@ func span(sd tracesdk.ReadOnlySpan) *tracepb.Span {
return nil
}
tid := sd.SpanContext().TraceID()
sid := sd.SpanContext().SpanID()
spanContext := sd.SpanContext()
tid := spanContext.TraceID()
sid := spanContext.SpanID()
sdStatus := sd.Status()
s := &tracepb.Span{
TraceId: tid[:],
SpanId: sid[:],
TraceState: sd.SpanContext().TraceState().String(),
Status: status(sd.Status().Code, sd.Status().Description),
TraceState: spanContext.TraceState().String(),
Status: status(sdStatus.Code, sdStatus.Description),
StartTimeUnixNano: uint64(max(0, sd.StartTime().UnixNano())), // nolint:gosec // Overflow checked.
EndTimeUnixNano: uint64(max(0, sd.EndTime().UnixNano())), // nolint:gosec // Overflow checked.
Links: links(sd.Links()),
@@ -110,10 +113,11 @@ func span(sd tracesdk.ReadOnlySpan) *tracepb.Span {
DroppedLinksCount: clampUint32(sd.DroppedLinks()),
}
if psid := sd.Parent().SpanID(); psid.IsValid() {
sdParent := sd.Parent()
if psid := sdParent.SpanID(); psid.IsValid() {
s.ParentSpanId = psid[:]
}
s.Flags = buildSpanFlagsWith(sd.SpanContext().TraceFlags(), sd.Parent())
s.Flags = buildSpanFlagsWith(spanContext.TraceFlags(), sdParent)
return s
}
@@ -1,7 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otlptracehttp // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
package otlptracehttp
import (
"bytes"
@@ -27,10 +27,14 @@ import (
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/counter"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/observ"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpjson"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/retry"
)
const contentTypeProto = "application/x-protobuf"
const (
contentTypeProto = "application/x-protobuf"
contentTypeJSON = "application/json"
)
// maxResponseBodySize is the maximum number of bytes to read from a response
// body. It is set to 4 MiB per the OTLP specification recommendation to
@@ -160,19 +164,11 @@ func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc
pbRequest := &coltracepb.ExportTraceServiceRequest{
ResourceSpans: protoSpans,
}
rawRequest, err := proto.Marshal(pbRequest)
if err != nil {
return err
}
ctx, cancel := c.contextWithStop(ctx)
defer cancel()
if maxSize := c.cfg.MaxRequestSize; maxSize > 0 && len(rawRequest) > maxSize {
return fmt.Errorf("request body too large: exceeded %d bytes", maxSize)
}
request, err := c.newRequest(rawRequest)
request, err := c.newRequest(pbRequest)
if err != nil {
return err
}
@@ -232,19 +228,26 @@ func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc
return nil
}
if resp.Header.Get("Content-Type") == "application/x-protobuf" {
var respProto coltracepb.ExportTraceServiceResponse
var respProto coltracepb.ExportTraceServiceResponse
switch resp.Header.Get("Content-Type") {
case contentTypeProto:
if err := proto.Unmarshal(respData.Bytes(), &respProto); err != nil {
return err
}
case contentTypeJSON:
if err := otlpjson.UnmarshalExportTraceServiceResponse(respData.Bytes(), &respProto); err != nil {
return err
}
default:
return nil
}
if respProto.PartialSuccess != nil {
msg := respProto.PartialSuccess.GetErrorMessage()
n := respProto.PartialSuccess.GetRejectedSpans()
if n != 0 || msg != "" {
err := internal.TracePartialSuccessError(n, msg)
uploadErr = errors.Join(uploadErr, err)
}
if respProto.PartialSuccess != nil {
msg := respProto.PartialSuccess.GetErrorMessage()
n := respProto.PartialSuccess.GetRejectedSpans()
if n != 0 || msg != "" {
err := internal.TracePartialSuccessError(n, msg)
uploadErr = errors.Join(uploadErr, err)
}
}
return nil
@@ -283,7 +286,24 @@ func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc
}))
}
func (c *client) newRequest(body []byte) (request, error) {
func (c *client) marshalRequest(pbRequest *coltracepb.ExportTraceServiceRequest) ([]byte, error) {
if c.cfg.Protocol == otlpconfig.ProtocolHTTPJSON {
rawRequest, err := otlpjson.MarshalExportTraceServiceRequest(pbRequest)
if err != nil {
return nil, fmt.Errorf("failed to marshal request body in json: %w", err)
}
return rawRequest, nil
}
rawRequest, err := proto.Marshal(pbRequest)
if err != nil {
return nil, fmt.Errorf("failed to marshal request body in protobuf: %w", err)
}
return rawRequest, nil
}
func (c *client) newRequest(pbRequest *coltracepb.ExportTraceServiceRequest) (request, error) {
u := url.URL{Scheme: c.getScheme(), Host: c.cfg.Endpoint, Path: c.cfg.URLPath}
r, err := http.NewRequestWithContext(context.Background(), http.MethodPost, u.String(), http.NoBody)
if err != nil {
@@ -297,6 +317,18 @@ func (c *client) newRequest(body []byte) (request, error) {
r.Header.Set(k, v)
}
r.Header.Set("Content-Type", contentTypeProto)
if c.cfg.Protocol == otlpconfig.ProtocolHTTPJSON {
r.Header.Set("Content-Type", contentTypeJSON)
}
body, err := c.marshalRequest(pbRequest)
if err != nil {
return request{Request: r}, err
}
if maxSize := c.cfg.MaxRequestSize; maxSize > 0 && len(body) > maxSize {
return request{Request: r}, fmt.Errorf("request body too large: exceeded %d bytes", maxSize)
}
req := request{Request: r}
switch Compression(c.cfg.Compression) {
@@ -334,15 +366,11 @@ func (c *client) newRequest(body []byte) (request, error) {
}
// MarshalLog is the marshaling function used by the logging system to represent this Client.
func (c *client) MarshalLog() any {
func (*client) MarshalLog() any {
return struct {
Type string
Endpoint string
Insecure bool
Type string
}{
Type: "otlptracehttp",
Endpoint: c.cfg.Endpoint,
Insecure: c.cfg.Insecure,
Type: "otlptracehttp",
}
}
@@ -376,7 +404,7 @@ func (r *request) reset(ctx context.Context) {
// retryableError represents a request failure that can be retried.
type retryableError struct {
throttle int64
throttle time.Duration
err error
}
@@ -385,16 +413,30 @@ type retryableError struct {
// if it is not nil.
func newResponseError(header http.Header, wrapped error) error {
var rErr retryableError
if s, ok := header["Retry-After"]; ok {
if t, err := strconv.ParseInt(s[0], 10, 64); err == nil {
rErr.throttle = t
}
if v := header.Get("Retry-After"); v != "" {
rErr.throttle = retryAfterDuration(v)
}
rErr.err = wrapped
return rErr
}
func retryAfterDuration(v string) time.Duration {
if t, err := strconv.ParseInt(v, 10, 64); err == nil && t >= 0 {
const maxRetryAfterSeconds = int64(1<<63-1) / int64(time.Second)
if t > maxRetryAfterSeconds {
return time.Duration(1<<63 - 1)
}
return time.Duration(t) * time.Second
}
if date, err := http.ParseTime(v); err == nil {
return max(time.Until(date), 0)
}
return 0
}
func (e retryableError) Error() string {
if e.err != nil {
return "retry-able request failure: " + e.err.Error()
@@ -436,7 +478,7 @@ func evaluate(err error) (bool, time.Duration) {
return false, 0
}
return true, time.Duration(rErr.throttle)
return true, rErr.throttle
}
func (c *client) getScheme() string {
Loaded 100 of 304 files, more files were not shown because too many files have changed in this diff. Show more