diff --git a/go.mod b/go.mod index de755ce..4561762 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module msp-admin-service -go 1.26 +go 1.26.0 require ( github.com/Masterminds/squirrel v1.5.4 @@ -9,25 +9,25 @@ require ( github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.11.1 github.com/txix-open/bgjob v1.6.0 - github.com/txix-open/isp-kit v1.71.2 + github.com/txix-open/isp-kit v1.74.0 github.com/txix-open/jsonschema v1.3.0 golang.org/x/crypto v0.54.0 golang.org/x/sync v0.22.0 - google.golang.org/grpc v1.82.1 + google.golang.org/grpc v1.83.0 ) require ( github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/beorn7/perks v1.0.1 // indirect - github.com/buger/jsonparser v1.2.0 // indirect + github.com/buger/jsonparser v1.6.0 // 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.13 // indirect - github.com/getsentry/sentry-go v0.47.0 // indirect - github.com/go-faker/faker/v4 v4.9.0 // indirect - github.com/go-logr/logr v1.4.3 // 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/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 @@ -38,10 +38,10 @@ require ( 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.0 // indirect + github.com/klauspost/compress v1.19.1 // 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.4.0 // indirect + github.com/leodido/go-urn v1.5.0 // indirect github.com/mailru/easyjson v0.9.2 // indirect github.com/mfridman/interpolate v0.0.2 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect @@ -49,15 +49,15 @@ require ( 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.2 // indirect - github.com/prometheus/client_golang v1.23.2 // 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 - github.com/prometheus/common v0.69.0 // indirect + github.com/prometheus/common v0.70.1 // indirect github.com/prometheus/procfs v0.21.1 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect - github.com/sethvargo/go-retry v0.3.0 // indirect + github.com/sethvargo/go-retry v0.4.0 // indirect github.com/txix-open/bellows v1.2.0 // indirect - github.com/txix-open/etp/v4 v4.1.1 // indirect + github.com/txix-open/etp/v4 v4.1.3 // indirect github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect @@ -71,14 +71,14 @@ require ( 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/proto/otlp v1.10.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 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-20260630182238-925bb5da69e7 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df // 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 gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index ad34751..1db9d29 100644 --- a/go.sum +++ b/go.sum @@ -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.2.0 h1:4EFcvK1kD4jyj6YqNK6skK6w+y7FHHBR+XBCtxwu/6g= -github.com/buger/jsonparser v1.2.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= +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/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= @@ -23,19 +23,19 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1 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.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM= -github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= -github.com/getsentry/sentry-go v0.47.0 h1:AnSMSyrYA5qZCIN/2xpgAAwv63sVULV+vBq37ajouc8= -github.com/getsentry/sentry-go v0.47.0/go.mod h1:h+b4VHpKnK7aUXB5wc+KDnPgp9ZtfliRD4eV85FbiSA= +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/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.9.0 h1:a4HXLwueuTCtgF93VpUsl8Zd2nG1VH2SgNWDPVEBg5U= -github.com/go-faker/faker/v4 v4.9.0/go.mod h1:u1dIRP5neLB6kTzgyVjdBOV5R1uP7BdxkcWk7tiKQXk= +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-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +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= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= @@ -74,8 +74,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.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ= -github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= +github.com/klauspost/compress v1.19.1/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= @@ -86,14 +86,14 @@ github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= -github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= -github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= +github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M= github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= -github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs= -github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= +github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ= +github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= @@ -116,26 +116,26 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE 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.2 h1:FjKNzcmMdGrQlSIu5alMSmakQtJFBgtw+A0bb1p/LC8= -github.com/pressly/goose/v3 v3.27.2/go.mod h1:qWW+/8dkVtJYjJrbIpwD5xxnEJTUKvxkQ9JKQp9LaIM= -github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= -github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA= +github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY= +github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= +github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.69.0 h1:OA85nJQS/T/MaYh/Q2CcgDKSGWqNIgrBDvDH85CuiNk= -github.com/prometheus/common v0.69.0/go.mod h1:ZzL3f6u94qUxh9p+tJTrF+FvBS1XXbbRAZCQkytAL0Y= +github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= +github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= github.com/prometheus/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.12.0 h1:V0v14Iqfs+MwHWihJt/nGS5Ulu0vw572b2Co3mwunkI= -github.com/rabbitmq/amqp091-go v1.12.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= +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/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= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE= -github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas= +github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw= +github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -153,12 +153,12 @@ github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgj 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= github.com/txix-open/bgjob v1.6.0/go.mod h1:aKbwpVclWmq82s7fchazp099yWjEpVKFkxT85i4hARM= -github.com/txix-open/etp/v4 v4.1.1 h1:Yna+0mw/kQZP7Rl6QI4spCrO6qgO8ZhP8PjHlJj2lTU= -github.com/txix-open/etp/v4 v4.1.1/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM= +github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo= +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.71.2 h1:QQ9642Bd1t/gWfnlS4uygVaBYyAhz5VtV3Q4bNwMKGw= -github.com/txix-open/isp-kit v1.71.2/go.mod h1:j2sj86byoKllCs+DaRWwg56NgcL2omr/bUzmU7+AF74= +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/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= @@ -192,8 +192,8 @@ go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRk 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/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g= -go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk= +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= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -216,12 +216,12 @@ 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= 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-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU= -google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df h1:O3ig1i5WDDzsVzRp+cCdgelT9vXnlnOFdlEeFtL4HCc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE= -google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= +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= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -232,11 +232,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA= -modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8= +modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws= +modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= -modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M= -modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s= +modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog= +modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw= diff --git a/main.go b/main.go index 66688d4..ce47ecb 100644 --- a/main.go +++ b/main.go @@ -23,7 +23,7 @@ var version = "1.0.0" //go:generate swag init -pd -ot json -eot json func main() { - boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors(), cluster.GrpcTransport) + boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport) app := boot.App logger := app.Logger() diff --git a/vendor/github.com/buger/jsonparser/.gitignore b/vendor/github.com/buger/jsonparser/.gitignore index af589f8..0584d83 100644 --- a/vendor/github.com/buger/jsonparser/.gitignore +++ b/vendor/github.com/buger/jsonparser/.gitignore @@ -16,3 +16,5 @@ PROOF_*.md REQPROOF_*.md proof-ux-log.md PROOF_UNDER_MODELED_REQUIREMENTS_PROPOSAL.md +fuzz_results/ +testdata/fuzz/ diff --git a/vendor/github.com/buger/jsonparser/CHANGELOG.md b/vendor/github.com/buger/jsonparser/CHANGELOG.md new file mode 100644 index 0000000..4a635f7 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/CHANGELOG.md @@ -0,0 +1,232 @@ +# Changelog + +## [v1.6.0] — 2026-07-29 + +### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings) + +### New API — `Append` + +```go +// Append to an array without knowing its length +data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items") +``` + +- **`Append(data, value, keys...)`** — appends `value` to the end of the JSON array addressed by `keys`. Addresses the top-level value when `keys` is empty; auto-vivifies a missing keyed path as a single-element array. Returns `MalformedArrayError` when the addressed value is not an array. Traced to SYS-REQ-009, SYS-REQ-110. + +### Known issues — all resolved (zero open) + +- **KI-2 fixed** — `ParseInt("-")` now returns an error instead of `(0, nil)`. One-line sign-only guard in `bytes.go:parseInt` (after stripping the sign byte, an empty remainder returns `(0, false, false)`). +- **KI-3 fixed** — `Set` with an array-index path component under an object parent (and vice-versa) now auto-coerces the container type instead of emitting malformed JSON. (Disposition already set to `fixed` in v1.5.x.) +- **KI-4 fixed** — `Set` on a top-level array-index beyond length now appends at the array's end (matching nested-array behavior under SYS-REQ-110) instead of returning `KeyPathNotFoundError`. Also cleans up trailing commas in malformed arrays. + +**Zero open known issues.** Every previously shipped known issue is now resolved and covered by ReqProof L3 Assurance. + +--- + +## [v1.5.1] — 2026-07-28 + +### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings) + +### Performance — 6.1x large-payload speedup + +- **Fix stringEnd unbounded backslash scan** — `stringEndConfig` was scanning the ENTIRE remaining parent document for backslashes (`bytes.IndexByte(data, '\\')`) instead of just the string body. On a 24kb large payload this walked tens of KB per string. Now bounded to `data[:firstQuote]` (the string body only). **128µs → 22µs (5.8x).** +- **SWAR string scan** — replaced two separate `bytes.IndexByte` calls (quote + backslash) with a single inline 8-byte SWAR (SIMD-Within-A-Register) loop that checks for both characters simultaneously. **22µs → 21µs (additional 8%).** +- **Benchmark suite updated** — all comparison libraries (gabs, easyjson, ffjson, etc.) updated to latest versions. Benchmark methodology documented (Apple M4 Max, Go 1.26.3, median of 5 runs). The `encoding/json` benchmark no longer uses ffjson-generated methods (the #126 ffjson measurement bug was fixed in v1.3.1). +- **README benchmarks refreshed** — all numbers now reflect real measurements on modern hardware with current library versions. + +### Updated benchmark results (Apple M4 Max, Go 1.26.3, median of 5 runs) + +| Payload | jsonparser | encoding/json | easyjson | Speedup vs encoding/json | +|---|---|---|---|---| +| Small (190B, Get) | 382 ns | 1,335 ns | 312 ns | 3.5x | +| Small (190B, EachKey) | 241 ns | — | — | 5.5x | +| Medium (2.4kB, Get) | 3,894 ns | 10,564 ns | 2,444 ns | 2.7x | +| Medium (2.4kB, EachKey) | 1,923 ns | — | — | 5.5x | +| Large (24kB) | 20,788 ns | 134,123 ns | 32,765 ns | **6.4x** | + +All jsonparser results: **0 bytes allocated, 0 allocations**. + +--- + +## [v1.5.0] — 2026-07-28 + +### Covered by [ReqProof](https://reqproof.com) — L3 Assurance + +v1.5.0 extends the formal-verification coverage to **123 requirements** (0 errors, 0 warnings) across all new APIs. Every new function is traced via source annotations, tested with MC/DC witnesses, and covered by the structure-aware fuzzer. + +### Config struct — opt-in lenient parsing (#160, #115) + +```go +var Lenient = jsonparser.Config{AllowSingleQuotes: true, AllowUnknownEscapes: true} +Lenient.Get(data, "key") // parses {'key':'value'} and unknown escapes +``` + +- **`AllowSingleQuotes`** — accept `'key':'value'` alongside `"key":"value"` (JavaScript/Python-style). The same escape rules apply inside single-quoted strings. +- **`AllowUnknownEscapes`** — pass through unknown escape sequences (`` \` ``, `\x`) literally instead of erroring. +- The default Config is strict (RFC 8259 only). Package-level functions are unchanged. +- Config methods mirror the full API: `Get`, `GetString`, `Set`, `Delete`, `ArrayEach`, `ObjectEach`. + +### Streaming ReaderParser (#132, #257) + +```go +rp := jsonparser.NewReaderParser(file) // any io.Reader +rp.Get("users", "[0]", "name") // path-based access from a stream +``` + +- Path-based access to JSON data from an `io.Reader` — **no need to load the entire document into memory**. +- Buffers data incrementally in 64KB chunks; memory is bounded by the largest value, not the document size. +- Enables parsing **10GB+ JSON files** without OOM. +- Methods: `Get`, `GetString`, `ArrayEach`. + +### Name aliases (#66) + +Canonical `EachXxx` pattern added alongside existing `XxxEach` names: + +| New (canonical) | Old (kept for compat) | +|---|---| +| `EachArray` | `ArrayEach` | +| `EachObject` | `ObjectEach` | +| `EachArrayErr` | `ArrayEachErr` | +| `EachArrayWildcard` | `ArrayEachWildcard` | + +`EachKey`, `EachKeyErr`, `EachKeyWildcard` already matched the pattern. All old names remain functional. + +### Proof + +- 2 new SYS-REQs: 115 (Config/lenient parsing), 116 (streaming ReaderParser) +- **123 requirements, 0 errors, 0 warnings, 279/279 functions traced** + +--- + +## [v1.4.0] — 2026-07-28 + +### Covered by [ReqProof](https://reqproof.com) — L3 Assurance + +v1.4.0 adds 9 new backward-compatible APIs, each traced to a formal requirement and verified with MC/DC coverage. **121 requirements, 0 errors, 0 warnings.** + +### New APIs + +**Iteration with error/break control** — resolves #53, #129, #176, #230, #255, #262 +- `ArrayEachErr` — callback returns `error` to stop early (`io.EOF` = graceful stop) +- `EachKeyErr` — same pattern for EachKey + +**Safe string handling** — resolves #144, #158, #218, #270 +- `Escape(s string) []byte` — RFC 8259 string escaping (inverse of `Unescape`) +- `SetString(data, val, keys...)` — Set with auto-quoted value + +**Container accessors** — resolves #175, #261, #271 +- `GetArrayLen` / `GetObjectLen` — count elements without a callback +- `GetUint64` — uint64 variant of `GetInt` + +**Delete found signal** — resolves #229 +- `DeleteFound(data, keys...) ([]byte, bool)` — returns whether the key was found + +**Wildcard paths** — resolves #112 +- `EachKeyWildcard`, `ArrayEachWildcard`, `SetWildcard` — `[*]` path component + +**JSONPath compiled paths** — resolves #234, #251 +- `ParsePath("$.users[0].name")` → `[]string` path +- `CompilePath` + `CompiledPath` — pre-compile and reuse with Get/Set/Delete + +### Fixes +- EachKey no longer panics with >64 key components (#56) +- Set pre-allocates output buffer, reducing allocations from 6 to 1 (#107) + +### Proof +- 3 new SYS-REQs: 112 (container length), 113 (wildcard paths), 114 (compiled paths) +- **121 requirements, 384 MC/DC witness rows, 0 uncovered** + +--- + +## [v1.3.1] — 2026-07-28 + +### Covered by [ReqProof](https://reqproof.com) — L3 Assurance + +v1.3.1 fixes 3 bugs that escaped the initial proof review, with new proof gates to prevent recurrence. + +### Bug fixes + +- **Fix Set/Delete input-buffer aliasing** (#209, #141) — `Set` and `Delete` no longer corrupt the caller's input `[]byte` when the slice has spare capacity. All mutation paths now allocate a fresh buffer. +- **Fix EachKey array-index inconsistency** (#232) — `EachKey` now descends into terminal array-index paths consistently with `Get`. +- **Fix benchmark measuring ffjson, not encoding/json** (#126) — benchmark payload types stripped of generated methods. + +### Proof strengthening + +| Bug | Proof gap | New gate | +|---|---|---| +| #209/#141 Set aliasing | No obligation said "Set must not mutate the input buffer" | New obligation `no_input_mutation` + `assertInputUnchanged` gate | +| #232 EachKey ≠ Get | No cross-API consistency obligation | New obligation `api_consistency` + differential gate | +| #126 benchmark ffjson | Proof didn't cover benchmarks | Benchmark honesty lint | + +--- + +## [v1.3.0] — 2026-07-27 + +### Formally verified by [ReqProof](https://reqproof.com) + +jsonparser v1.3.0 is the **first Go library proven to L3 assurance** by [ReqProof](https://reqproof.com), a git-native requirements-engineering and formal-verification platform. The entire codebase is now covered by: + +- **118 formal requirements** (7 stakeholder + 111 system-level), each traced to code via source annotations and verified with FRETish formalization. +- **100% Modified Condition/Decision Coverage (MC/DC)** — both code-level (every decision/condition branch exercised) and requirement-side (377/377 truth-table rows witnessed). +- **A custom structure-aware JSON fuzzer** ([github.com/probelabs/json-fuzz](https://github.com/probelabs/json-fuzz)) generating grammar-valid mutations at 250k inputs/sec, plus path-mutation and `encoding/json` differential harnesses. +- **L3 strict audit posture**: 0 errors, 0 warnings, all checks enabled. + +The proof review found and fixed **7 real bugs** that years of community use, OSS-Fuzz, and standard fuzzing had missed. [Read the root-cause analysis →](docs/proof-gap-root-cause.md) + +jsonparser serves as the **reference case study** for ReqProof — [learn more at reqproof.com](https://reqproof.com). + +### Security / bug fixes + +- **Fix Delete panic on malformed input with leading comma** (OSS-Fuzz 4649128545288192) + `Delete` panicked with `index out of range [-1]` on inputs like `,{"test":1{}`. + The `data[prevTok]` dereference is now guarded. + +- **Fix empty-string key-component panics** (8 sites) + `Get`, `GetString`, `GetInt`, `GetFloat`, `GetBoolean`, `GetUnsafeString`, `Set`, + `Delete`, `EachKey` panicked with `index out of range [0]` when a key path contained + an empty string (`""`). All 8 unguarded `keys[i][0]` dereference sites are now guarded + with `len(...) > 0`. Found by the structure-aware hazard sweep. + Reported by @c-tonneslan (#284). + +- **Fix Set data loss on scalar arrays** (#267) + `Set` on an array-index path beyond the current length silently overwrote the array + instead of appending. `Set({"a":[1,2,3]}, 99, "a", "[9]")` now returns `{"a":[1,2,3,99]}` + instead of `{"a":[99]}`. Reported by @Solaris-star (#286). + +- **Fix Set malformed-JSON output on cross-type paths** + `Set` with an array-index path component under an object parent (e.g. `Set({}, 9, "[5]")`) + produced invalid JSON (`{[9]}`). Set now auto-coerces the container type to match the + path, always producing valid JSON output. + +- **Fix Delete trailing-comma malformation** + `Delete` left a dangling trailing comma in the output when the deleted element was + followed by JSON whitespace (space/tab/LF/CR) and a comma. Found by the structure-aware + path-mutation fuzzer. + +- **Fix ArrayEach spurious callback on non-array root** + `ArrayEach` on a non-array root value (e.g. `ArrayEach({"a":1}, cb)`) invoked the + callback with a spurious element before returning an error. The callback is no longer + invoked; a clean error is returned immediately. + +- **Fix lone-Unicode-surrogate mishandling in Unescape** + `ParseString` on a string containing a lone high surrogate (e.g. `\uDB29` without a + following low surrogate) synthesized a bogus non-BMP code point from the following + literal bytes. Now substitutes U+FFFD (matching `encoding/json` behavior). + +### Performance + +- **parseInt fast-path for short numbers** — 22–37% faster on typical 1–10 digit integers. + Numbers with ≤18 digits use direct int64 accumulation, bypassing the overflow-checked + uint64 slow path. Contributed by @trevorprater (#285). + +- **stringEnd SIMD fast path** — 12× faster on no-escape strings, 4.5× faster end-to-end + on `Get` for string values. Uses `bytes.IndexByte` for the common case (no `\` before + the closing `"`). + +### Acknowledgments + +- @c-tonneslan (#284) — reported the empty-string key-component panic +- @Solaris-star (#286) — reported the Set array-index data-loss bug (#267) +- @trevorprater (#285) — contributed the parseInt performance optimization +- OSS-Fuzz (issue 4649128545288192) — the original Delete leading-comma panic +- The [probelabs/json-fuzz](https://github.com/probelabs/json-fuzz) structure-aware fuzzer diff --git a/vendor/github.com/buger/jsonparser/Dockerfile b/vendor/github.com/buger/jsonparser/Dockerfile index 37fc9fd..4d58977 100644 --- a/vendor/github.com/buger/jsonparser/Dockerfile +++ b/vendor/github.com/buger/jsonparser/Dockerfile @@ -1,4 +1,7 @@ -FROM golang:1.6 +FROM golang:1.25 + +WORKDIR /go/src/github.com/buger/jsonparser +ADD . /go/src/github.com/buger/jsonparser RUN go get github.com/Jeffail/gabs RUN go get github.com/bitly/go-simplejson @@ -7,6 +10,3 @@ RUN go get github.com/antonholmquist/jason RUN go get github.com/mreiferson/go-ujson RUN go get -tags=unsafe -u github.com/ugorji/go/codec RUN go get github.com/mailru/easyjson - -WORKDIR /go/src/github.com/buger/jsonparser -ADD . /go/src/github.com/buger/jsonparser \ No newline at end of file diff --git a/vendor/github.com/buger/jsonparser/Makefile b/vendor/github.com/buger/jsonparser/Makefile index e843368..e06ffa3 100644 --- a/vendor/github.com/buger/jsonparser/Makefile +++ b/vendor/github.com/buger/jsonparser/Makefile @@ -26,6 +26,17 @@ profile: test: $(DRUN) go test $(LDFLAGS) ./ -run $(TEST) -timeout 10s $(ARGS) -v +# Full test suite including the heavy iteration-count suites that the standard +# `proof audit` skips (property-based, reference-oracle, fuzz-harness coverage). +# Run this in the dedicated CI fuzz job or locally before a release. +test-full: + go test ./... -count=1 -race -timeout 5m + +# Structure-aware JSON fuzzer (grammar-based, far faster than generic +# libFuzzer for finding parser-specific defects). See json_fuzz_test.go. +fuzz-json: + go test -run='^$$' -fuzz=FuzzJSONStructureAware -fuzztime=$(FUZZTIME) ./... + fmt: $(DRUN) go fmt ./... diff --git a/vendor/github.com/buger/jsonparser/README.md b/vendor/github.com/buger/jsonparser/README.md index 391edba..fb97977 100644 --- a/vendor/github.com/buger/jsonparser/README.md +++ b/vendor/github.com/buger/jsonparser/README.md @@ -1,7 +1,26 @@ -[![Go Report Card](https://goreportcard.com/badge/github.com/buger/jsonparser)](https://goreportcard.com/report/github.com/buger/jsonparser) ![License](https://img.shields.io/dub/l/vibe-d.svg) +[![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 **10 times 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 **6x faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below. + +--- + +## 🔒 Formally Verified — the first Go library proven to L3 assurance by [ReqProof](https://reqproof.com) + +jsonparser is the **reference case study** for [ReqProof](https://reqproof.com) — a git-native requirements-engineering and formal-verification platform. Every public API is traced to a formal requirement, every requirement is tested with **100% Modified Condition/Decision Coverage (MC/DC)**, and the entire parser is fuzzed by a custom **structure-aware JSON fuzzer** ([github.com/probelabs/json-fuzz](https://github.com/probelabs/json-fuzz)) that generates grammar-valid mutations at 250,000 inputs/second. + +| Metric | Value | +|---|---| +| Requirements traced | 118 (7 stakeholder + 111 system) | +| Proof audit | **0 errors, 0 warnings** (L3 strict) | +| Code-level MC/DC | **100% decisions, 100% conditions** | +| Requirement-side MC/DC | **377/377 witness rows covered** | +| Fuzz executions | 16M+ (structure-aware + path-mutation + encoding/json differential) | +| Bugs found & fixed by the proof review | 7 (4 panics, 2 data-corruption, 1 encoding bug) | + +The proof review caught bugs that years of community use, OSS-Fuzz, and standard fuzzing had missed — including a panic class across 8 unchecked-dereference sites, a silent data-loss bug in `Set`, and a malformed-output bug in `Delete`. [Read the full root-cause analysis →](docs/proof-gap-root-cause.md) + +--- ## Rationale Originally I made this for a project that relies on a lot of 3rd party APIs that can be unpredictable and complex. @@ -55,16 +74,16 @@ if value, err := jsonparser.GetInt(data, "company", "size"); err == nil { size = value } -// You can use `ArrayEach` helper to iterate items [item1, item2 .... itemN] -jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) { +// You can use `EachArray` helper to iterate items [item1, item2 .... itemN] +jsonparser.EachArray(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) { fmt.Println(jsonparser.Get(value, "url")) }, "person", "avatars") // Or use can access fields by index! jsonparser.GetString(data, "person", "avatars", "[0]", "url") -// You can use `ObjectEach` helper to iterate objects { "key1":object1, "key2":object2, .... "keyN":objectN } -jsonparser.ObjectEach(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error { +// You can use `EachObject` helper to iterate objects { "key1":object1, "key2":object2, .... "keyN":objectN } +jsonparser.EachObject(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error { fmt.Printf("Key: '%s'\n Value: '%s'\n Type: %s\n", string(key), string(value), dataType) return nil }, "person", "name") @@ -90,6 +109,72 @@ jsonparser.EachKey(data, func(idx int, value []byte, vt jsonparser.ValueType, er // For more information see docs below ``` +## Lenient Parsing + +The package-level functions remain strict RFC 8259 parsers. For inputs that use +single-quoted strings or non-standard escapes, use a `Config` explicitly: + +```go +data := []byte(`{'name':'Ada','role':'engineer'}`) + +name, err := jsonparser.Lenient.GetString(data, "name") +// name == "Ada" +``` + +`Lenient` enables both compatibility options. You can also enable only the +extension your input requires: + +```go +config := jsonparser.Config{AllowUnknownEscapes: true} +data := []byte("{\"path\":\"docs\\`draft\\x\"}") + +path, err := config.GetString(data, "path") +// path == "docs`draftx" +``` + +The config-aware `Get`, `GetString`, `Set`, `Delete`, `ArrayEach`, and +`ObjectEach` methods share the same signatures and behavior as their +package-level counterparts apart from the enabled parsing extensions. +`jsonparser.DefaultConfig` is strict; `jsonparser.Lenient` enables +`AllowSingleQuotes` and `AllowUnknownEscapes`. + +## Streaming + +`ReaderParser` provides the same path-based lookup model for JSON read from an +`io.Reader`, so a large document does not need to be loaded into a single byte +slice: + +```go +file, err := os.Open("large.json") +if err != nil { + log.Fatal(err) +} +defer file.Close() + +parser := jsonparser.NewReaderParser(file) +name, err := parser.GetString("person", "name") +``` + +To process a root array incrementally, use `ArrayEach`. Each callback value is +valid for the duration of the callback; copy it if it must be retained: + +```go +parser := jsonparser.NewReaderParser(file) +err := parser.ArrayEach(func(value []byte, valueType jsonparser.ValueType, err error) { + if err != nil { + return + } + process(value, valueType) +}) +``` + +The parser reads in 64 KiB chunks and discards completed prefixes. Its default +sliding-window target is 64 MiB; customize it with +`jsonparser.Config{MaxBufferSize: size}`. A single returned value or array +element may exceed that target because its complete bytes are supplied to the +caller. Create a new `ReaderParser` for each lookup or array traversal. +`ReaderParser` also honors `AllowSingleQuotes` and `AllowUnknownEscapes`. + ## Reference Library API is really simple. You just need the `Get` method to perform any operation. The rest is just helpers around it. @@ -146,15 +231,19 @@ func GetInt(data []byte, keys ...string) (val int64, err error) If you know the key type, you can use the helpers above. If key data type do not match, it will return error. -### **`ArrayEach`** +### **`EachArray`** ```go -func ArrayEach(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string) +func EachArray(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string) ``` Needed for iterating arrays, accepts a callback function with the same return arguments as `Get`. +`ArrayEach` remains available as a backward-compatible alias. +The error-returning and wildcard variants follow the same naming convention: +use `EachArrayErr` and `EachArrayWildcard`; `ArrayEachErr` and +`ArrayEachWildcard` remain available for backward compatibility. -### **`ObjectEach`** +### **`EachObject`** ```go -func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) +func EachObject(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) ``` Needed for iterating object, accepts a callback function. Example: ```go @@ -162,8 +251,9 @@ var handler func([]byte, []byte, jsonparser.ValueType, int) error handler = func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error { //do stuff here } -jsonparser.ObjectEach(myJson, handler) +jsonparser.EachObject(myJson, handler) ``` +`ObjectEach` remains available as a backward-compatible alias. ### **`EachKey`** @@ -224,6 +314,20 @@ Accepts multiple keys to specify path to JSON value (in case of updating or crea Note that keys can be an array indexes: `jsonparser.Delete(data, "person", "avatars", "[0]", "url")` +### **`Append`** +```go +func Append(data []byte, value []byte, keys ...string) ([]byte, error) +``` +Appends `value` to the end of the JSON array addressed by `keys`. When `keys` is +empty, `Append` addresses the top-level value. If a keyed path does not exist, +`Append` creates it as a single-element array using `Set`'s auto-vivification +behavior. Returns `MalformedArrayError` if the addressed value is not an array. + +```go +// Append to an array without knowing its length +data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items") +``` + ## What makes it so fast? * It does not rely on `encoding/json`, `reflection` or `interface{}`, the only real package dependency is `bytes`. @@ -236,11 +340,12 @@ Note that keys can be an array indexes: `jsonparser.Delete(data, "person", "avat 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. -Benchmarks run on standard Linode 1024 box. + +> **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. Compared libraries: * https://golang.org/pkg/encoding/json -* https://github.com/Jeffail/gabs +* https://github.com/Jeffail/gabs/v2 * https://github.com/a8m/djson * https://github.com/bitly/go-simplejson * https://github.com/antonholmquist/jason @@ -251,42 +356,34 @@ Compared libraries: * https://github.com/buger/jsonparser #### TLDR -If you want to skip next sections we have 2 winner: `jsonparser` and `easyjson`. -`jsonparser` is up to 10 times faster than standard `encoding/json` package (depending on payload size and usage), and almost infinitely (literally) better in memory consumption because it operates with data on byte level, and provide direct slice pointers. -`easyjson` wins in CPU in medium tests and frankly i'm impressed with this package: it is remarkable results considering that it is almost drop-in replacement for `encoding/json` (require some code generation). -It's hard to fully compare `jsonparser` and `easyjson` (or `ffson`), they a true parsers and fully process record, unlike `jsonparser` which parse only keys you specified. +`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` performance heavily depends on usage, and it works best when you do not need to process full record, only some keys. The more calls you need to make, the slower it will be, in contrast `easyjson` (or `ffjson`, `encoding/json`) parser record only 1 time, and then you can make as many calls as you want. - -With great power comes great responsibility! :) - - #### Small payload Each test processes 190 bytes of http log as a JSON record. It should read multiple fields. https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_small_payload_test.go -Library | time/op | bytes/op | allocs/op - ------ | ------- | -------- | ------- -encoding/json struct | 7879 | 880 | 18 -encoding/json interface{} | 8946 | 1521 | 38 -Jeffail/gabs | 10053 | 1649 | 46 -bitly/go-simplejson | 10128 | 2241 | 36 -antonholmquist/jason | 27152 | 7237 | 101 -github.com/ugorji/go/codec | 8806 | 2176 | 31 -mreiferson/go-ujson | **7008** | **1409** | 37 -a8m/djson | 3862 | 1249 | 30 -pquerna/ffjson | **3769** | **624** | **15** -mailru/easyjson | **2002** | **192** | **9** -buger/jsonparser | **1367** | **0** | **0** -buger/jsonparser (EachKey API) | **809** | **0** | **0** +| 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** | -Winners are ffjson, easyjson and jsonparser, where jsonparser is up to 9.8x faster than encoding/json and 4.6x faster than ffjson, and slightly faster than easyjson. -If you look at memory allocation, jsonparser has no rivals, as it makes no data copy and operates with raw []byte structures and pointers to it. +`jsonparser` with `EachKey` is **5.5x faster** than `encoding/json` and **zero allocations**. #### Medium payload @@ -297,28 +394,17 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_paylo | Library | time/op | bytes/op | allocs/op | | ------- | ------- | -------- | --------- | -| encoding/json struct | 57749 | 1336 | 29 | -| encoding/json interface{} | 79297 | 10627 | 215 | -| Jeffail/gabs | 83807 | 11202 | 235 | -| bitly/go-simplejson | 88187 | 17187 | 220 | -| antonholmquist/jason | 94099 | 19013 | 247 | -| github.com/ugorji/go/codec | 114719 | 6712 | 152 | -| mreiferson/go-ujson | **56972** | 11547 | 270 | -| a8m/djson | 28525 | 10196 | 198 | -| pquerna/ffjson | **20298** | **856** | **20** | -| mailru/easyjson | **10512** | **336** | **12** | -| buger/jsonparser | **15955** | **0** | **0** | -| buger/jsonparser (EachKey API) | **8916** | **0** | **0** | - -The difference between ffjson and jsonparser in CPU usage is smaller, while the memory consumption difference is growing. On the other hand `easyjson` shows remarkable performance for medium payload. - -`gabs`, `go-simplejson` and `jason` are based on encoding/json and map[string]interface{} and actually only helpers for unstructured JSON, their performance correlate with `encoding/json interface{}`, and they will skip next round. -`go-ujson` while have its own parser, shows same performance as `encoding/json`, also skips next round. Same situation with `ugorji/go/codec`, but it showed unexpectedly bad performance for complex payloads. +| 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** | +`jsonparser` with `EachKey` beats `easyjson` on medium payload and remains zero-allocation. #### Large payload -Each test processes a 24kb JSON record (based on Discourse API) +Each test processes a 24kb JSON record (based on Discourse API). It should read 2 arrays, and for each item in array get a few fields. Basically it means processing a full JSON file. @@ -326,16 +412,14 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payloa | Library | time/op | bytes/op | allocs/op | | --- | --- | --- | --- | -| encoding/json struct | 748336 | 8272 | 307 | -| encoding/json interface{} | 1224271 | 215425 | 3395 | -| a8m/djson | 510082 | 213682 | 2845 | -| pquerna/ffjson | **312271** | **7792** | **298** | -| mailru/easyjson | **154186** | **6992** | **288** | -| buger/jsonparser | **85308** | **0** | **0** | +| 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** | -`jsonparser` now is a winner, but do not forget that it is way more lightweight parser than `ffson` or `easyjson`, and they have to parser all the data, while `jsonparser` parse only what you need. All `ffjson`, `easysjon` and `jsonparser` have their own parsing code, and does not depend on `encoding/json` or `interface{}`, thats one of the reasons why they are so fast. `easyjson` also use a bit of `unsafe` package to reduce memory consuption (in theory it can lead to some unexpected GC issue, but i did not tested enough) - -Also last benchmark did not included `EachKey` test, because in this particular case we need to read lot of Array values, and using `ArrayEach` is more efficient. +`jsonparser` is the **fastest library overall** on large payloads: **6.4x faster than encoding/json**, **1.6x faster than easyjson**, and **zero allocations**. ## Formal Verification diff --git a/vendor/github.com/buger/jsonparser/aliases.go b/vendor/github.com/buger/jsonparser/aliases.go new file mode 100644 index 0000000..c78a553 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/aliases.go @@ -0,0 +1,25 @@ +package jsonparser + +// SYS-REQ-006, SYS-REQ-028, SYS-REQ-029, SYS-REQ-052, SYS-REQ-053, SYS-REQ-055, SYS-REQ-083 +// EachArray is the canonical name; ArrayEach is kept for backward compatibility. +func EachArray(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) { + ArrayEach(data, cb, keys...) +} + +// SYS-REQ-007, SYS-REQ-030, SYS-REQ-031, SYS-REQ-032, SYS-REQ-054, SYS-REQ-084 +// EachObject is the canonical name; ObjectEach is kept for backward compatibility. +func EachObject(data []byte, cb func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) error { + return ObjectEach(data, cb, keys...) +} + +// SYS-REQ-004 +// EachArrayErr is the canonical name; ArrayEachErr is kept for backward compatibility. +func EachArrayErr(data []byte, cb func(value []byte, dataType ValueType, offset int, err error) error, keys ...string) (int, error) { + return ArrayEachErr(data, cb, keys...) +} + +// SYS-REQ-113 +// EachArrayWildcard is the canonical name; ArrayEachWildcard is kept for backward compatibility. +func EachArrayWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, offset int, err error) error, keys ...string) (int, error) { + return ArrayEachWildcard(data, cb, keys...) +} diff --git a/vendor/github.com/buger/jsonparser/append.go b/vendor/github.com/buger/jsonparser/append.go new file mode 100644 index 0000000..8e7d71a --- /dev/null +++ b/vendor/github.com/buger/jsonparser/append.go @@ -0,0 +1,49 @@ +package jsonparser + +// Append adds value to the end of the JSON array addressed by keys. +// +// When keys is empty, Append addresses the top-level value. If a keyed path +// does not exist, Append creates it as a single-element array using Set's +// auto-vivification behavior. +// +// SYS-REQ-009, SYS-REQ-110 +func Append(data []byte, value []byte, keys ...string) ([]byte, error) { + _, dataType, startOffset, endOffset, err := internalGet(data, keys...) + if err != nil { + if err != KeyPathNotFoundError || len(keys) == 0 { + return nil, err + } + + arrayValue := make([]byte, len(value)+2) + offset := WriteToBuffer(arrayValue, "[") + offset += copy(arrayValue[offset:], value) + WriteToBuffer(arrayValue[offset:], "]") + + return Set(data, arrayValue, keys...) + } + + if dataType != Array { + return nil, MalformedArrayError + } + + closeOffset := endOffset - 1 + if closeOffset <= startOffset || closeOffset >= len(data) || data[closeOffset] != ']' { + return nil, MalformedArrayError + } + + hasElements := nextToken(data[startOffset+1:closeOffset]) != -1 + extraSpace := len(value) + if hasElements { + extraSpace++ + } + + result := make([]byte, len(data)+extraSpace) + offset := copy(result, data[:closeOffset]) + if hasElements { + offset += WriteToBuffer(result[offset:], ",") + } + offset += copy(result[offset:], value) + copy(result[offset:], data[closeOffset:]) + + return result, nil +} diff --git a/vendor/github.com/buger/jsonparser/bytes.go b/vendor/github.com/buger/jsonparser/bytes.go index f5414b6..1f30d2e 100644 --- a/vendor/github.com/buger/jsonparser/bytes.go +++ b/vendor/github.com/buger/jsonparser/bytes.go @@ -7,13 +7,37 @@ const maxUint64 = 1<<64 - 1 // About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON func parseInt(bytes []byte) (v int64, ok bool, overflow bool) { - if len(bytes) == 0 { + l := len(bytes) + if l == 0 { return 0, false, false } var neg bool = false + i := 0 if bytes[0] == '-' { neg = true + i = 1 + } + if i == l { + return 0, false, false + } + + if l-i < 19 { + for ; i < l; i++ { + d := bytes[i] - '0' + if d > 9 { + return 0, false, false + } + v = 10*v + int64(d) + } + + if neg { + return -v, true, false + } + return v, true, false + } + + if neg { bytes = bytes[1:] } diff --git a/vendor/github.com/buger/jsonparser/config.go b/vendor/github.com/buger/jsonparser/config.go new file mode 100644 index 0000000..66dfc15 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/config.go @@ -0,0 +1,87 @@ +package jsonparser + +import ( + "bytes" + "fmt" +) + +// Config controls opt-in parsing extensions. The zero value is strict and +// accepts only RFC 8259 JSON strings and escapes. +// SYS-REQ-115 +type Config struct { + AllowSingleQuotes bool // #160: accept 'key':'value' alongside "key":"value" + AllowUnknownEscapes bool // #115: accept unknown escape sequences instead of erroring + MaxBufferSize int // ReaderParser sliding-window target; zero uses the 64 MiB default +} + +// DefaultConfig is the strict parser configuration used by package-level +// functions. +// SYS-REQ-115 +var DefaultConfig = Config{} + +// Lenient accepts single-quoted strings and unknown escape sequences. +// SYS-REQ-115 +var Lenient = Config{ + AllowSingleQuotes: true, + AllowUnknownEscapes: true, +} + +// Get returns the value addressed by keys using c's parsing options. +// SYS-REQ-115 +func (c Config) Get(data []byte, keys ...string) ([]byte, ValueType, int, error) { + value, dataType, _, endOffset, err := internalGetConfig(c, data, keys...) + return value, dataType, endOffset, err +} + +// GetString returns the decoded string addressed by keys using c's parsing +// options. +// SYS-REQ-115 +func (c Config) GetString(data []byte, keys ...string) (string, error) { + value, dataType, _, err := c.Get(data, keys...) + if err != nil { + return "", err + } + + if dataType != String { + if dataType == Null { + return "", NullValueError + } + return "", fmt.Errorf("Value is not a string: %s", string(value)) + } + + if bytes.IndexByte(value, '\\') == -1 { + return string(value), nil + } + + var stackbuf [unescapeStackBufSize]byte + unescaped, err := unescapeConfig(c, value, stackbuf[:]) + if err != nil { + return "", MalformedValueError + } + return string(unescaped), nil +} + +// Set replaces the value addressed by keys using c's parsing options. +// SYS-REQ-115 +func (c Config) Set(data []byte, value []byte, keys ...string) ([]byte, error) { + return setConfig(c, data, value, keys...) +} + +// Delete removes the value addressed by keys using c's parsing options. +// SYS-REQ-115 +func (c Config) Delete(data []byte, keys ...string) []byte { + result, _ := deleteFoundConfig(c, data, keys...) + return result +} + +// ArrayEach iterates over the addressed array using c's parsing options. +// SYS-REQ-115 +func (c Config) ArrayEach(data []byte, cb func([]byte, ValueType, int, error), keys ...string) (int, error) { + return arrayEachConfig(c, data, cb, keys...) +} + +// ObjectEach iterates over the addressed object using c's parsing options. +// SYS-REQ-115 +func (c Config) ObjectEach(data []byte, cb func([]byte, []byte, ValueType, int) error, keys ...string) error { + return objectEachConfig(c, data, cb, keys...) +} diff --git a/vendor/github.com/buger/jsonparser/escape.go b/vendor/github.com/buger/jsonparser/escape.go index 62be30d..992b2f5 100644 --- a/vendor/github.com/buger/jsonparser/escape.go +++ b/vendor/github.com/buger/jsonparser/escape.go @@ -15,20 +15,62 @@ const lowSurrogateOffset = 0xDC00 const basicMultilingualPlaneReservedOffset = 0xDFFF const basicMultilingualPlaneOffset = 0xFFFF +// NOTE: combineUTF16Surrogates is blocked by an unsupported `<<` shift op +// in the translator (Phase T.* gap, beyond #1/#2/#5). Even though Fix #6 +// resolves the package-const references in this body, the shift remains +// untranslated, so no lemma is attached here. func combineUTF16Surrogates(high, low rune) rune { return supplementalPlanesOffset + (high-highSurrogateOffset)<<10 + (low - lowSurrogateOffset) } const badHex = -1 +// reqproof:lemma h2I_range func(c byte) bool { +// r := h2I(c) +// return r == -1 || (r >= 0 && r <= 15) +// } +// +// reqproof:lemma h2I_decimal_digit func(c byte) bool { +// if c < '0' || c > '9' { return true } +// r := h2I(c) +// return r >= 0 && r <= 9 +// } +// +// reqproof:lemma h2I_uppercase_hex func(c byte) bool { +// if c < 'A' || c > 'F' { return true } +// r := h2I(c) +// return r >= 10 && r <= 15 +// } +// +// reqproof:lemma h2I_lowercase_hex func(c byte) bool { +// if c < 'a' || c > 'f' { return true } +// r := h2I(c) +// return r >= 10 && r <= 15 +// } +// +// reqproof:lemma h2I_nondigit_is_badhex func(c byte) bool { +// if c >= '0' && c <= '9' { return true } +// if c >= 'A' && c <= 'F' { return true } +// if c >= 'a' && c <= 'f' { return true } +// return h2I(c) == badHex +// } +// +// reqproof:lemma h2I_nonneg_implies_le_15 func(c byte) bool { +// r := h2I(c) +// if r >= 0 { +// return r <= 15 +// } +// return true +// } func h2I(c byte) int { - switch { - case c >= '0' && c <= '9': - return int(c - '0') - case c >= 'A' && c <= 'F': - return int(c - 'A' + 10) - case c >= 'a' && c <= 'f': - return int(c - 'a' + 10) + if c >= 48 && c <= 57 { // '0'..'9' + return int(c - 48) + } + if c >= 65 && c <= 70 { // 'A'..'F' + return int(c-65) + 10 + } + if c >= 97 && c <= 102 { // 'a'..'f' + return int(c-97) + 10 } return badHex } @@ -56,10 +98,28 @@ func decodeSingleUnicodeEscape(in []byte) (rune, bool) { // isUTF16EncodedRune checks if a rune is in the range for non-BMP characters, // which is used to describe UTF16 chars. // Source: https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane +// +// reqproof:lemma isUTF16EncodedRune_low_excluded func(r rune) bool { +// return !(r < 0xD800) || !isUTF16EncodedRune(r) +// } +// +// reqproof:lemma isUTF16EncodedRune_const_high_bound func(r rune) bool { +// // Fix #6: package-level const highSurrogateOffset (= 0xD800) now +// // resolves at translation time. Below the high surrogate offset +// // means definitely outside the UTF-16 surrogate range. +// return !(r < highSurrogateOffset) || !isUTF16EncodedRune(r) +// } +// +// reqproof:lemma isUTF16EncodedRune_const_bmp_bound func(r rune) bool { +// // Fix #6: package-level const basicMultilingualPlaneReservedOffset (= 0xDFFF). +// // Above the BMP-reserved offset means outside the UTF-16 surrogate range. +// return !(r > basicMultilingualPlaneReservedOffset) || !isUTF16EncodedRune(r) +// } func isUTF16EncodedRune(r rune) bool { - return highSurrogateOffset <= r && r <= basicMultilingualPlaneReservedOffset + return 0xD800 <= r && r <= 0xDFFF } +// SYS-REQ-115 func decodeUnicodeEscape(in []byte) (rune, int) { if r, ok := decodeSingleUnicodeEscape(in); !ok { // Invalid Unicode escape @@ -71,12 +131,31 @@ func decodeUnicodeEscape(in []byte) (rune, int) { // tautological and has been removed — the real discriminator is whether r // falls in the UTF-16 surrogate range. return r, 6 - } else if r2, ok := decodeSingleUnicodeEscape(in[6:]); !ok { // Note: previous decodeSingleUnicodeEscape success guarantees at least 6 bytes remain - // UTF16 "high surrogate" without manditory valid following Unicode escape for the "low surrogate" - return utf8.RuneError, -1 - } else if r2 < lowSurrogateOffset { - // Invalid UTF16 "low surrogate" + } else if r >= lowSurrogateOffset { + // Lone low surrogate (0xDC00-0xDFFF) with no preceding high surrogate. + // Per RFC 8259/WHATWG a lone surrogate in a JSON string is malformed; + // match encoding/json by substituting U+FFFD and consuming only the 6 + // bytes of this escape. + return utf8.RuneError, 6 + } else if len(in) < 8 || in[6] != '\\' || in[7] != 'u' { + // Lone high surrogate (0xD800-0xDBFF): the high-surrogate escape is not + // followed by a "\u" low-surrogate escape. decodeSingleUnicodeEscape + // assumes the \u prefix and reads hex at fixed offsets, so without this + // guard it would misread whatever bytes follow (e.g. the literal "A7FA" + // after "\uDB29") as a low surrogate and synthesize a bogus code point + // (DEFECT-260727-SNGT). Substitute U+FFFD and consume only the 6 bytes + // of the high surrogate, matching encoding/json. + return utf8.RuneError, 6 + } else if r2, ok := decodeSingleUnicodeEscape(in[6:]); !ok { + // A "\u" follows the high surrogate but the low-surrogate escape is + // itself malformed (truncated / bad hex) — the whole escape is broken. return utf8.RuneError, -1 + } else if r2 < lowSurrogateOffset || r2 > basicMultilingualPlaneReservedOffset { + // The following "\uXXXX" is not a valid low surrogate (0xDC00-0xDFFF): + // e.g. a BMP codepoint or another high surrogate. Treat the first escape + // as a lone high surrogate → U+FFFD, consuming 6 bytes; the following + // escape is reprocessed by the caller. + return utf8.RuneError, 6 } else { // Valid UTF16 surrogate pair return combineUTF16Surrogates(r, r2), 12 @@ -99,6 +178,11 @@ var backslashCharEscapeTable = [...]byte{ // how many characters were consumed from 'in' and emitted into 'out'. // If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error. func unescapeToUTF8(in, out []byte) (inLen int, outLen int) { + return unescapeToUTF8Config(DefaultConfig, in, out) +} + +// SYS-REQ-115 +func unescapeToUTF8Config(config Config, in, out []byte) (inLen int, outLen int) { if len(in) < 2 || in[0] != '\\' { // Invalid escape due to insufficient characters for any escape or no initial backslash return -1, -1 @@ -110,6 +194,11 @@ func unescapeToUTF8(in, out []byte) (inLen int, outLen int) { // Valid basic 2-character escapes (use lookup table) out[0] = backslashCharEscapeTable[e] return 2, 1 + case '\'': + if config.AllowSingleQuotes { + out[0] = e + return 2, 1 + } case 'u': // Unicode escape if r, inLen := decodeUnicodeEscape(in); inLen == -1 { @@ -122,17 +211,82 @@ func unescapeToUTF8(in, out []byte) (inLen int, outLen int) { } } + if config.AllowUnknownEscapes { + // Lenient mode treats the escaped byte as a literal and discards the + // escape marker. A trailing '\' and malformed \u escape remain errors: + // they are truncated/invalid encodings, not unknown escape names. + out[0] = in[1] + return 2, 1 + } + return -1, -1 } +const lowerHex = "0123456789abcdef" + +// Escape returns in as a JSON string literal, including the surrounding +// quotation marks. +// SYS-REQ-014 +func Escape(in string) []byte { + var stackbuf [unescapeStackBufSize]byte + out := stackbuf[:0] + out = append(out, '"') + + start := 0 + for i := 0; i < len(in); i++ { + c := in[i] + if c >= 0x20 && c != '"' && c != '\\' { + continue + } + + out = append(out, in[start:i]...) + switch c { + case '"', '\\': + out = append(out, '\\', c) + case '\b': + out = append(out, '\\', 'b') + case '\f': + out = append(out, '\\', 'f') + case '\n': + out = append(out, '\\', 'n') + case '\r': + out = append(out, '\\', 'r') + case '\t': + out = append(out, '\\', 't') + default: + out = append(out, '\\', 'u', '0', '0', lowerHex[c>>4], lowerHex[c&0x0f]) + } + start = i + 1 + } + + out = append(out, in[start:]...) + return append(out, '"') +} + +// SetString replaces the value at keys with val encoded as a JSON string. +// SYS-REQ-009 +func SetString(data []byte, val string, keys ...string) ([]byte, error) { + return Set(data, Escape(val), keys...) +} + // unescape unescapes the string contained in 'in' and returns it as a slice. // If 'in' contains no escaped characters: -// Returns 'in'. +// +// Returns 'in'. +// // Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)): -// 'out' is used to build the unescaped string and is returned with no extra allocation +// +// 'out' is used to build the unescaped string and is returned with no extra allocation +// // Else: -// A new slice is allocated and returned. +// +// A new slice is allocated and returned. func Unescape(in, out []byte) ([]byte, error) { + return unescapeConfig(DefaultConfig, in, out) +} + +// SYS-REQ-115 +func unescapeConfig(config Config, in, out []byte) ([]byte, error) { firstBackslash := bytes.IndexByte(in, '\\') if firstBackslash == -1 { return in, nil @@ -156,7 +310,7 @@ func Unescape(in, out []byte) ([]byte, error) { // leaves at least the backslash character in `in`. for { // Unescape the next escaped character - inLen, bufLen := unescapeToUTF8(in, buf) + inLen, bufLen := unescapeToUTF8Config(config, in, buf) if inLen == -1 { return nil, MalformedStringEscapeError } diff --git a/vendor/github.com/buger/jsonparser/parser.go b/vendor/github.com/buger/jsonparser/parser.go index d8df167..461eafd 100644 --- a/vendor/github.com/buger/jsonparser/parser.go +++ b/vendor/github.com/buger/jsonparser/parser.go @@ -2,8 +2,10 @@ package jsonparser import ( "bytes" + "encoding/binary" "errors" "fmt" + "io" "strconv" ) @@ -26,18 +28,57 @@ var ( const unescapeStackBufSize = 64 // SYS-REQ-044 +// +// reqproof:lemma tokenEnd_in_range func(data []byte) bool { +// r := tokenEnd(data) +// return r >= 0 && r <= len(data) +// } +// +// reqproof:lemma tokenEnd_nonneg func(data []byte) bool { +// // tokenEnd never signals via a negative sentinel — the empty-input +// // path returns len(data)==0 (still nonneg), and any hit returns the +// // loop index (also nonneg). +// return tokenEnd(data) >= 0 +// } +// +// reqproof:lemma tokenEnd_empty_zero func(data []byte) bool { +// return !(len(data) == 0) || tokenEnd(data) == 0 +// } +// +// reqproof:lemma tokenEnd_path_indexable_implies_nonneg func(data []byte) bool { +// r := tokenEnd(data) +// if r < len(data) { +// return r >= 0 +// } +// return true +// } func tokenEnd(data []byte) int { for i, c := range data { - switch c { - case ' ', '\n', '\r', '\t', ',', '}', ']': - return i + // reqproof:invariant 0 <= i + // reqproof:invariant i <= len(data) + if c != 32 && c != 10 && c != 13 && c != 9 && c != 44 && c != 125 && c != 93 { + continue } + return i } return len(data) } +// isJSONWhitespace reports whether b is one of the four JSON whitespace bytes +// (space 0x20, tab 0x09, LF 0x0A, CR 0x0D) per RFC 8259 §2. Used by Delete's +// trailing-comma cleanup to decide whether the byte at endOffset+tokEnd is +// whitespace preceding a comma, so the cleanup advances past both. The byte +// set mirrors tokenEnd's whitespace classification above. +// SYS-REQ-010, SYS-REQ-034, SYS-REQ-035 +func isJSONWhitespace(b byte) bool { + return b == ' ' || b == '\t' || b == '\n' || b == '\r' +} + // SYS-REQ-001 +// NOTE: findTokenStart's two-conditional-return body shape exposes +// the translator's __early_val scoping bug; we leave it without an +// in-range lemma. (Documented as a Phase S.2c.4 follow-up.) func findTokenStart(data []byte, token byte) int { for i := len(data) - 1; i >= 0; i-- { switch data[i] { @@ -53,7 +94,12 @@ func findTokenStart(data []byte, token byte) int { // SYS-REQ-001, SYS-REQ-020, SYS-REQ-024 func findKeyStart(data []byte, key string) (int, error) { - i := nextToken(data) + return findKeyStartConfig(DefaultConfig, data, key) +} + +// SYS-REQ-115 +func findKeyStartConfig(config Config, data []byte, key string) (int, error) { + i := nextTokenConfig(config, data) if i == -1 { return i, KeyPathNotFoundError } @@ -65,24 +111,28 @@ func findKeyStart(data []byte, key string) (int, error) { } var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings - if ku, err := Unescape(StringToBytes(key), stackbuf[:]); err == nil { + if ku, err := unescapeConfig(config, StringToBytes(key), stackbuf[:]); err == nil { key = bytesToString(&ku) } for i < ln { switch data[i] { - case '"': + case '"', '\'': + quote := data[i] + if quote == '\'' && !config.AllowSingleQuotes { + break + } i++ keyBegin := i - strEnd, keyEscaped := stringEnd(data[i:]) + strEnd, keyEscaped := stringEndConfig(config, data[i:], quote) if strEnd == -1 { break } i += strEnd keyEnd := i - 1 - valueOffset := nextToken(data[i:]) + valueOffset := nextTokenConfig(config, data[i:]) if valueOffset == -1 { break } @@ -94,7 +144,7 @@ func findKeyStart(data []byte, key string) (int, error) { // for unescape: if there are no escape sequences, this is cheap; if there are, it is a // bit more expensive, but causes no allocations unless len(key) > unescapeStackBufSize if keyEscaped { - if ku, err := Unescape(k, stackbuf[:]); err != nil { + if ku, err := unescapeConfig(config, k, stackbuf[:]); err != nil { break } else { k = ku @@ -106,12 +156,12 @@ func findKeyStart(data []byte, key string) (int, error) { } case '[': - end := blockEnd(data[i:], data[i], ']') + end := blockEndConfig(config, data[i:], data[i], ']') if end != -1 { i = i + end } case '{': - end := blockEnd(data[i:], data[i], '}') + end := blockEndConfig(config, data[i:], data[i], '}') if end != -1 { i = i + end } @@ -123,12 +173,36 @@ func findKeyStart(data []byte, key string) (int, error) { } // SYS-REQ-001 +// +// reqproof:lemma tokenStart_in_range func(data []byte) bool { +// r := tokenStart(data) +// return r >= 0 && r <= len(data) +// } +// +// reqproof:lemma tokenStart_nonneg func(data []byte) bool { +// return tokenStart(data) >= 0 +// } +// +// reqproof:lemma tokenStart_empty_zero func(data []byte) bool { +// return !(len(data) == 0) || tokenStart(data) == 0 +// } +// +// reqproof:lemma tokenStart_path_indexable_when_nonempty func(data []byte) bool { +// r := tokenStart(data) +// if len(data) > 0 { +// return r >= 0 && r < len(data) +// } +// return r == 0 +// } func tokenStart(data []byte) int { for i := len(data) - 1; i >= 0; i-- { - switch data[i] { - case '\n', '\r', '\t', ',', '{', '[': - return i + // reqproof:invariant -1 <= i + // reqproof:invariant i < len(data) + c := data[i] + if c != 10 && c != 13 && c != 9 && c != 44 && c != 123 && c != 91 { + continue } + return i } return 0 @@ -136,14 +210,42 @@ func tokenStart(data []byte) int { // SYS-REQ-001 // Find position of next character which is not whitespace +// +// reqproof:lemma nextToken_in_range func(data []byte) bool { +// r := nextToken(data) +// return r >= -1 && r < len(data) +// } +// +// reqproof:lemma nextToken_empty_neg func(data []byte) bool { +// return !(len(data) == 0) || nextToken(data) == -1 +// } +// +// reqproof:lemma nextToken_signed_disjoint func(data []byte) bool { +// r := nextToken(data) +// // Result is either -1 (sentinel) or a non-negative index — never -2 or below +// return r == -1 || r >= 0 +// } +// +// reqproof:lemma nextToken_path_indexable_implies_lt_len func(data []byte) bool { +// r := nextToken(data) +// if r >= 0 { +// return r < len(data) +// } +// return true +// } func nextToken(data []byte) int { + return nextTokenConfig(DefaultConfig, data) +} + +// SYS-REQ-115 +func nextTokenConfig(_ Config, data []byte) int { for i, c := range data { - switch c { - case ' ', '\n', '\r', '\t': + // reqproof:invariant 0 <= i + // reqproof:invariant i <= len(data) + if c == ' ' || c == '\n' || c == '\r' || c == '\t' { continue - default: - return i } + return i } return -1 @@ -151,14 +253,38 @@ func nextToken(data []byte) int { // SYS-REQ-001 // Find position of last character which is not whitespace +// +// reqproof:lemma lastToken_in_range func(data []byte) bool { +// r := lastToken(data) +// return r >= -1 && r < len(data) +// } +// +// reqproof:lemma lastToken_empty_neg func(data []byte) bool { +// return !(len(data) == 0) || lastToken(data) == -1 +// } +// +// reqproof:lemma lastToken_signed_disjoint func(data []byte) bool { +// r := lastToken(data) +// // Result is either -1 (sentinel) or a non-negative index — never -2 or below +// return r == -1 || r >= 0 +// } +// +// reqproof:lemma lastToken_path_indexable_implies_lt_len func(data []byte) bool { +// r := lastToken(data) +// if r >= 0 { +// return r < len(data) +// } +// return true +// } func lastToken(data []byte) int { for i := len(data) - 1; i >= 0; i-- { - switch data[i] { - case ' ', '\n', '\r', '\t': + // reqproof:invariant -1 <= i + // reqproof:invariant i < len(data) + c := data[i] + if c == ' ' || c == '\n' || c == '\r' || c == '\t' { continue - default: - return i } + return i } return -1 @@ -168,30 +294,72 @@ func lastToken(data []byte) int { // Tries to find the end of string // Support if string contains escaped quote symbols. func stringEnd(data []byte) (int, bool) { + return stringEndConfig(DefaultConfig, data, '"') +} + +// SYS-REQ-115 +func stringEndConfig(_ Config, data []byte, quote byte) (int, bool) { + // SWAR (SIMD-Within-A-Register) fast path: scan 8 bytes at a time for + // either the closing quote or a backslash, then a per-byte tail that + // counts the run of '\\' before each quote candidate. + // + // Investigation: easyjson's jlexer.findStringLen + // (mailru/easyjson@v0.9.2/jlexer/lexer.go:247) uses a single SIMD + // bytes.IndexByte('"') plus a backward backslash-run count, deferring the + // separate backslash scan to unescapeStringToken. That style was ported + // and benchmarked here as "single IndexByte for the quote + a bounded + // bytes.IndexByte(data[:firstQuote], '\\') for the escape flag". On + // arm64 (Apple M4 Max, NEON) the two IndexByte *function calls* cost more + // than this inline 8-byte SWAR loop, because jsonparser must compute the + // escape flag inline (its callers gate unescapeConfig on it), so the + // second scan cannot be deferred the way easyjson defers it. + // + // Measured on M4 Max (BenchmarkJsonParserLarge, median of 5): + // SWAR (this): ~21000 ns/op + // two-IndexByte port: ~22600 ns/op (-7%) + // For reference easyjson itself is ~33200 ns/op here, so jsonparser + // already leads; the easyjson technique is not beneficial on arm64. + const swarLsb = 0x0101010101010101 + const swarMsb = 0x8080808080808080 + broadcastQuote := uint64(quote) * swarLsb + broadcastBackslash := uint64('\\') * swarLsb + + i := 0 + n := len(data) + for i+8 <= n { + w := binary.LittleEndian.Uint64(data[i:]) + xq := w ^ broadcastQuote + xb := w ^ broadcastBackslash + quoteHit := (xq - swarLsb) & ^xq & swarMsb + bsHit := (xb - swarLsb) & ^xb & swarMsb + if quoteHit|bsHit == 0 { + i += 8 + continue + } + break + } escaped := false - for i, c := range data { - if c == '"' { + for ; i < n; i++ { + c := data[i] + if c == quote { if !escaped { return i + 1, false - } else { - j := i - 1 - for { - if j < 0 || data[j] != '\\' { - return i + 1, true // even number of backslashes - } - j-- - if j < 0 || data[j] != '\\' { - break // odd number of backslashes - } - j-- - + } + j := i - 1 + for { + if j < 0 || data[j] != '\\' { + return i + 1, true // even run of backslashes } + j-- + if j < 0 || data[j] != '\\' { + break // odd run of backslashes -> quote is escaped + } + j-- } } else if c == '\\' { escaped = true } } - return -1, escaped } @@ -199,14 +367,23 @@ func stringEnd(data []byte) (int, bool) { // Find end of the data structure, array or object. // For array openSym and closeSym will be '[' and ']', for object '{' and '}' func blockEnd(data []byte, openSym byte, closeSym byte) int { + return blockEndConfig(DefaultConfig, data, openSym, closeSym) +} + +// SYS-REQ-115 +func blockEndConfig(config Config, data []byte, openSym byte, closeSym byte) int { level := 0 i := 0 ln := len(data) for i < ln { switch data[i] { - case '"': // If inside string, skip it - se, _ := stringEnd(data[i+1:]) + case '"', '\'': // If inside a configured string, skip it + quote := data[i] + if quote == '\'' && !config.AllowSingleQuotes { + break + } + se, _ := stringEndConfig(config, data[i+1:], quote) if se == -1 { return -1 } @@ -227,8 +404,13 @@ func blockEnd(data []byte, openSym byte, closeSym byte) int { return -1 } -// SYS-REQ-001, SYS-REQ-020, SYS-REQ-021, SYS-REQ-022, SYS-REQ-023, SYS-REQ-047 +// SYS-REQ-001, SYS-REQ-020, SYS-REQ-021, SYS-REQ-022, SYS-REQ-023, SYS-REQ-047, SYS-REQ-111 func searchKeys(data []byte, keys ...string) int { + return searchKeysConfig(DefaultConfig, data, keys...) +} + +// SYS-REQ-115 +func searchKeysConfig(config Config, data []byte, keys ...string) int { keyLevel := 0 level := 0 i := 0 @@ -244,18 +426,22 @@ func searchKeys(data []byte, keys ...string) int { for i < ln { switch data[i] { - case '"': + case '"', '\'': + quote := data[i] + if quote == '\'' && !config.AllowSingleQuotes { + break + } i++ keyBegin := i - strEnd, keyEscaped := stringEnd(data[i:]) + strEnd, keyEscaped := stringEndConfig(config, data[i:], quote) if strEnd == -1 { return -1 } i += strEnd keyEnd := i - 1 - valueOffset := nextToken(data[i:]) + valueOffset := nextTokenConfig(config, data[i:]) if valueOffset == -1 { return -1 } @@ -275,7 +461,7 @@ func searchKeys(data []byte, keys ...string) int { var keyUnesc []byte if !keyEscaped { keyUnesc = key - } else if ku, err := Unescape(key, stackbuf[:]); err != nil { + } else if ku, err := unescapeConfig(config, key, stackbuf[:]); err != nil { return -1 } else { keyUnesc = ku @@ -307,7 +493,7 @@ func searchKeys(data []byte, keys ...string) int { // in case parent key is matched then only we will increase the level otherwise can directly // can move to the end of this block if !lastMatched { - end := blockEnd(data[i:], '{', '}') + end := blockEndConfig(config, data[i:], '{', '}') if end == -1 { return -1 } @@ -322,12 +508,14 @@ func searchKeys(data []byte, keys ...string) int { } case '[': // If we want to get array element by index - if keyLevel == level && keys[level][0] == '[' { + // guard: empty key component — not an array index, fall through to skip. + if keyLevel == level && len(keys[level]) > 0 && keys[level][0] == '[' { keyLen := len(keys[level]) // Note: keys[level][0] == '[' is guaranteed by the outer if-guard, // so the former middle term `keys[level][0] != '['` was always false // (dead code) and has been removed. - if keyLen < 3 || keys[level][keyLen-1] != ']' { + // guard: bounds-check on the same variable before the [keyLen-1] deref. + if len(keys[level]) < 3 || keys[level][keyLen-1] != ']' { return -1 } aIdx, err := strconv.Atoi(keys[level][1 : keyLen-1]) @@ -338,7 +526,7 @@ func searchKeys(data []byte, keys ...string) int { var valueFound []byte var valueOffset int curI := i - ArrayEach(data[i:], func(value []byte, dataType ValueType, offset int, err error) { + arrayEachConfig(config, data[i:], func(value []byte, dataType ValueType, offset int, err error) { if curIdx == aIdx { valueFound = value valueOffset = offset @@ -353,7 +541,7 @@ func searchKeys(data []byte, keys ...string) int { if valueFound == nil { return -1 } else { - subIndex := searchKeys(valueFound, keys[level+1:]...) + subIndex := searchKeysConfig(config, valueFound, keys[level+1:]...) if subIndex < 0 { return -1 } @@ -361,7 +549,7 @@ func searchKeys(data []byte, keys ...string) int { } } else { // Do not search for keys inside arrays - if arraySkip := blockEnd(data[i:], '[', ']'); arraySkip == -1 { + if arraySkip := blockEndConfig(config, data[i:], '[', ']'); arraySkip == -1 { return -1 } else { i += arraySkip - 1 @@ -395,7 +583,7 @@ func sameTree(p1, p2 []string) bool { const stackArraySize = 128 -// SYS-REQ-008, SYS-REQ-085 +// SYS-REQ-008, SYS-REQ-085, SYS-REQ-111 func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]string) int { var x struct{} var level, pathsMatched, i int @@ -527,14 +715,21 @@ func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]str } for pi, p := range paths { - if len(p) < level+1 || pathFlags[pi] || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) { + // guard: empty key component — skip this path (not an array index). + if len(p) < level+1 || pathFlags[pi] || len(p[level]) == 0 || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) { continue } - if len(p[level]) >= 2 { - aIdx, _ := strconv.Atoi(p[level][1 : len(p[level])-1]) - arrIdxFlags[aIdx] = x - pIdxFlags[pi] = true + + indexComponent := p[level] + if len(indexComponent) < 3 || indexComponent[len(indexComponent)-1] != ']' { + continue } + aIdx, err := strconv.Atoi(indexComponent[1 : len(indexComponent)-1]) + if err != nil { + continue + } + arrIdxFlags[aIdx] = x + pIdxFlags[pi] = true } if len(arrIdxFlags) > 0 { @@ -544,21 +739,35 @@ func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]str arrOff, _ := ArrayEach(data[i:], func(value []byte, dataType ValueType, offset int, err error) { if _, ok = arrIdxFlags[curIdx]; ok { for pi, p := range paths { - if pIdxFlags[pi] { - aIdx, _ := strconv.Atoi(p[level-1][1 : len(p[level-1])-1]) - - if curIdx == aIdx { - of := searchKeys(value, p[level:]...) - - pathsMatched++ - pathFlags[pi] = true - - if of != -1 { - v, dt, _, e := Get(value[of:]) - cb(pi, v, dt, e) - } - } + if !pIdxFlags[pi] || pathFlags[pi] { + continue } + + indexComponent := p[level-1] + aIdx, parseErr := strconv.Atoi(indexComponent[1 : len(indexComponent)-1]) + if parseErr != nil || curIdx != aIdx { + continue + } + + if level == len(p) { + // ArrayEach has already parsed the terminal value. + // In particular, string values do not include their + // quotes and therefore cannot be reparsed by Get. + pathsMatched++ + pathFlags[pi] = true + cb(pi, value, dataType, err) + continue + } + + of := searchKeys(value, p[level:]...) + if of == -1 { + continue + } + + v, dt, _, e := Get(value[of:]) + pathsMatched++ + pathFlags[pi] = true + cb(pi, v, dt, e) } } @@ -588,6 +797,237 @@ func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]str return -1 } +// EachKeyErr finds the requested paths and allows the callback to stop +// iteration by returning an error. io.EOF stops iteration gracefully. +// SYS-REQ-008 +func EachKeyErr(data []byte, cb func(idx int, value []byte, vt ValueType, err error) error, paths ...[]string) error { + var x struct{} + var level, pathsMatched, i int + ln := len(data) + + pathFlags := make([]bool, stackArraySize)[:] + if len(paths) > cap(pathFlags) { + pathFlags = make([]bool, len(paths))[:] + } + pathFlags = pathFlags[0:len(paths)] + + var maxPath int + for _, p := range paths { + if len(p) > maxPath { + maxPath = len(p) + } + } + + pathsBuf := make([]string, stackArraySize)[:] + if maxPath > cap(pathsBuf) { + pathsBuf = make([]string, maxPath)[:] + } + pathsBuf = pathsBuf[0:maxPath] + + for i < ln { + switch data[i] { + case '"': + i++ + keyBegin := i + + strEnd, keyEscaped := stringEnd(data[i:]) + if strEnd == -1 { + return nil + } + i += strEnd + + keyEnd := i - 1 + + valueOffset := nextToken(data[i:]) + if valueOffset == -1 { + return nil + } + + i += valueOffset + + if data[i] == ':' { + match := -1 + key := data[keyBegin:keyEnd] + + var keyUnesc []byte + if !keyEscaped { + keyUnesc = key + } else { + var stackbuf [unescapeStackBufSize]byte + if ku, unescapeErr := Unescape(key, stackbuf[:]); unescapeErr != nil { + return nil + } else { + keyUnesc = ku + } + } + + if maxPath >= level { + if level < 1 { + callbackErr := cb(-1, nil, Unknown, MalformedJsonError) + if callbackErr != nil && !errors.Is(callbackErr, io.EOF) { + return callbackErr + } + return nil + } + + pathsBuf[level-1] = bytesToString(&keyUnesc) + for pi, p := range paths { + if len(p) != level || pathFlags[pi] || !equalStr(&keyUnesc, p[level-1]) || !sameTree(p, pathsBuf[:level]) { + continue + } + + match = pi + + pathsMatched++ + pathFlags[pi] = true + + v, dt, _, parseErr := Get(data[i+1:]) + if callbackErr := cb(pi, v, dt, parseErr); callbackErr != nil { + if errors.Is(callbackErr, io.EOF) { + return nil + } + return callbackErr + } + + if pathsMatched == len(paths) { + break + } + } + if pathsMatched == len(paths) { + return nil + } + } + + if match == -1 { + tokenOffset := nextToken(data[i+1:]) + i += tokenOffset + } + + switch data[i] { + case '{', '}', '[', '"': + i-- + } + } else { + i-- + } + case '{': + level++ + case '}': + level-- + case '[': + var ok bool + arrIdxFlags := make(map[int]struct{}) + + pIdxFlags := make([]bool, stackArraySize)[:] + if len(paths) > cap(pIdxFlags) { + pIdxFlags = make([]bool, len(paths))[:] + } + pIdxFlags = pIdxFlags[0:len(paths)] + + if level < 0 { + callbackErr := cb(-1, nil, Unknown, MalformedJsonError) + if callbackErr != nil && !errors.Is(callbackErr, io.EOF) { + return callbackErr + } + return nil + } + + for pi, p := range paths { + if len(p) < level+1 || pathFlags[pi] || len(p[level]) == 0 || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) { + continue + } + + indexComponent := p[level] + if len(indexComponent) < 3 || indexComponent[len(indexComponent)-1] != ']' { + continue + } + aIdx, parseErr := strconv.Atoi(indexComponent[1 : len(indexComponent)-1]) + if parseErr != nil { + continue + } + arrIdxFlags[aIdx] = x + pIdxFlags[pi] = true + } + + if len(arrIdxFlags) > 0 { + level++ + + var curIdx int + var callbackErr error + var stopped bool + arrOff, _, _ := arrayEachErr(data[i:], func(value []byte, dataType ValueType, offset int, parseErr error) error { + if _, ok = arrIdxFlags[curIdx]; ok { + for pi, p := range paths { + if !pIdxFlags[pi] || pathFlags[pi] { + continue + } + + indexComponent := p[level-1] + aIdx, indexErr := strconv.Atoi(indexComponent[1 : len(indexComponent)-1]) + if indexErr != nil || curIdx != aIdx { + continue + } + + if level == len(p) { + pathsMatched++ + pathFlags[pi] = true + callbackErr = cb(pi, value, dataType, parseErr) + if callbackErr != nil { + stopped = true + return callbackErr + } + continue + } + + of := searchKeys(value, p[level:]...) + if of == -1 { + continue + } + + v, dt, _, getErr := Get(value[of:]) + pathsMatched++ + pathFlags[pi] = true + callbackErr = cb(pi, v, dt, getErr) + if callbackErr != nil { + stopped = true + return callbackErr + } + } + } + + curIdx++ + return nil + }) + + if stopped { + if errors.Is(callbackErr, io.EOF) { + return nil + } + return callbackErr + } + + if pathsMatched == len(paths) { + return nil + } + + i += arrOff - 1 + } else { + if arraySkip := blockEnd(data[i:], '[', ']'); arraySkip == -1 { + return nil + } else { + i += arraySkip - 1 + } + } + case ']': + level-- + } + + i++ + } + + return nil +} + // Data types available in valid JSON data. type ValueType int @@ -630,9 +1070,10 @@ var ( nullLiteral = []byte("null") ) -// SYS-REQ-009 +// SYS-REQ-009, SYS-REQ-110, SYS-REQ-111 func createInsertComponent(keys []string, setValue []byte, comma, object bool) []byte { - isIndex := string(keys[0][0]) == "[" + // guard: empty key component — not an array index. + isIndex := len(keys[0]) > 0 && string(keys[0][0]) == "[" offset := 0 lk := calcAllocateSpace(keys, setValue, comma, object) buffer := make([]byte, lk, lk) @@ -653,7 +1094,8 @@ func createInsertComponent(keys []string, setValue []byte, comma, object bool) [ } for i := 1; i < len(keys); i++ { - if string(keys[i][0]) == "[" { + // guard: empty key component — treat as object key, not array index. + if len(keys[i]) > 0 && string(keys[i][0]) == "[" { offset += WriteToBuffer(buffer[offset:], "[") } else { offset += WriteToBuffer(buffer[offset:], "{\"") @@ -661,9 +1103,10 @@ func createInsertComponent(keys []string, setValue []byte, comma, object bool) [ offset += WriteToBuffer(buffer[offset:], "\":") } } - offset += WriteToBuffer(buffer[offset:], string(setValue)) + offset += copy(buffer[offset:], setValue) for i := len(keys) - 1; i > 0; i-- { - if string(keys[i][0]) == "[" { + // guard: empty key component — treat as object key, not array index. + if len(keys[i]) > 0 && string(keys[i][0]) == "[" { offset += WriteToBuffer(buffer[offset:], "]") } else { offset += WriteToBuffer(buffer[offset:], "}") @@ -678,9 +1121,10 @@ func createInsertComponent(keys []string, setValue []byte, comma, object bool) [ return buffer } -// SYS-REQ-009 +// SYS-REQ-009, SYS-REQ-111 func calcAllocateSpace(keys []string, setValue []byte, comma, object bool) int { - isIndex := string(keys[0][0]) == "[" + // guard: empty key component — not an array index. + isIndex := len(keys[0]) > 0 && string(keys[0][0]) == "[" lk := 0 if comma { // , @@ -702,7 +1146,8 @@ func calcAllocateSpace(keys []string, setValue []byte, comma, object bool) int { lk += len(setValue) for i := 1; i < len(keys); i++ { - if string(keys[i][0]) == "[" { + // guard: empty key component — treat as object key, not array index. + if len(keys[i]) > 0 && string(keys[i][0]) == "[" { // [] lk += 2 } else { @@ -735,9 +1180,24 @@ Returns: */ // SYS-REQ-010, SYS-REQ-033, SYS-REQ-034, SYS-REQ-035, SYS-REQ-048, SYS-REQ-049, SYS-REQ-050, SYS-REQ-056 func Delete(data []byte, keys ...string) []byte { + result, _ := deleteFoundConfig(DefaultConfig, data, keys...) + return result +} + +// DeleteFound removes the value addressed by keys and reports whether the +// value was found and removed. When found is false, result is data unchanged. +// SYS-REQ-010 +func DeleteFound(data []byte, keys ...string) (result []byte, found bool) { + return deleteFoundConfig(DefaultConfig, data, keys...) +} + +// SYS-REQ-115 +func deleteFoundConfig(config Config, data []byte, keys ...string) (result []byte, found bool) { lk := len(keys) if lk == 0 { - return data[:0] + // Deleting the root produces an empty document whose backing array + // must not alias the caller's input. + return make([]byte, 0), true } array := false @@ -750,23 +1210,23 @@ func Delete(data []byte, keys ...string) []byte { var err error if !array { if len(keys) > 1 { - _, _, startOffset, endOffset, err = internalGet(data, keys[:lk-1]...) + _, _, startOffset, endOffset, err = internalGetConfig(config, data, keys[:lk-1]...) if err != nil { // problem parsing the data - return data + return data, false } } - keyOffset, err = findKeyStart(data[startOffset:endOffset], keys[lk-1]) + keyOffset, err = findKeyStartConfig(config, data[startOffset:endOffset], keys[lk-1]) if err == KeyPathNotFoundError { // problem parsing the data - return data + return data, false } keyOffset += startOffset var subEndOffset int - _, _, _, subEndOffset, err = internalGet(data[startOffset:endOffset], keys[lk-1]) + _, _, _, subEndOffset, err = internalGetConfig(config, data[startOffset:endOffset], keys[lk-1]) if err != nil { - return data + return data, false } endOffset = startOffset + subEndOffset tokEnd := tokenEnd(data[endOffset:]) @@ -774,21 +1234,36 @@ func Delete(data []byte, keys ...string) []byte { if endOffset+tokEnd >= len(data) { // tokenEnd sentinel: no delimiter found, input is truncated - return data + return data, false } - if data[endOffset+tokEnd] == ',' { + // guard: tokenEnd sentinel may return -1 on truncated input; bounds-check before deref. + idx := endOffset + tokEnd + // Scan forward from idx through any JSON whitespace to find the next + // real token. The original check only matched a single ' ' byte + // before the comma, so inputs like '{"a":1,\n"b":2}' or '[0,0 ,0]' + // (multiple whitespace bytes) bypassed the cleanup and left a + // dangling comma sequence. Found by FuzzPathMutation. + nextTokIdx := idx + for nextTokIdx < len(data) && isJSONWhitespace(data[nextTokIdx]) { + nextTokIdx++ + } + if len(data) > idx && data[idx] == ',' { endOffset += tokEnd + 1 - } else if data[endOffset+tokEnd] == ' ' && len(data) > endOffset+tokEnd+1 && data[endOffset+tokEnd+1] == ',' { - endOffset += tokEnd + 2 - } else if data[endOffset+tokEnd] == '}' && data[tokStart] == ',' { + } else if len(data) > nextTokIdx && data[nextTokIdx] == ',' { + // Symmetric with the array-branch case below: when the bytes + // after the deleted element are "+," (one or more JSON + // whitespace bytes then a comma), advance endOffset past all + // of them so the trailing comma is removed with the element. + endOffset += nextTokIdx - idx + tokEnd + 1 + } else if len(data) > idx && data[idx] == '}' && data[tokStart] == ',' { keyOffset = tokStart } } else { - _, _, keyOffset, endOffset, err = internalGet(data, keys...) + _, _, keyOffset, endOffset, err = internalGetConfig(config, data, keys...) if err != nil { // problem parsing the data - return data + return data, false } tokEnd := tokenEnd(data[endOffset:]) @@ -796,12 +1271,29 @@ func Delete(data []byte, keys ...string) []byte { if endOffset+tokEnd >= len(data) { // tokenEnd sentinel: no delimiter found, input is truncated - return data + return data, false } - if data[endOffset+tokEnd] == ',' { + // guard: tokenEnd sentinel may return -1 on truncated input; bounds-check before deref. + idx := endOffset + tokEnd + // Scan forward from idx through any JSON whitespace to find the next + // real token (mirrors the object-branch cleanup above). The original + // check only matched a single ' ' byte before the comma, so inputs + // like '[0,0 ,0]' or '[0,0\n\n,0]' bypassed the cleanup. Found by + // FuzzPathMutation. + nextTokIdx := idx + for nextTokIdx < len(data) && isJSONWhitespace(data[nextTokIdx]) { + nextTokIdx++ + } + if len(data) > idx && data[idx] == ',' { endOffset += tokEnd + 1 - } else if data[endOffset+tokEnd] == ']' && data[tokStart] == ',' { + } else if len(data) > nextTokIdx && data[nextTokIdx] == ',' { + // Symmetric with the object-branch case above: when the bytes + // after the deleted element are "+," (one or more JSON + // whitespace bytes then a comma), advance endOffset past all + // of them so the trailing comma is removed with the element. + endOffset += nextTokIdx - idx + tokEnd + 1 + } else if len(data) > idx && data[idx] == ']' && data[tokStart] == ',' { keyOffset = tokStart } } @@ -810,22 +1302,30 @@ func Delete(data []byte, keys ...string) []byte { // Extract nextToken once to avoid the redundant double call in the original code. prevTok := lastToken(data[:keyOffset]) remainedValue := data[endOffset:] - remainedTok := nextToken(remainedValue) + remainedTok := nextTokenConfig(config, remainedValue) var newOffset int - if remainedTok > -1 && remainedValue[remainedTok] == '}' && data[prevTok] == ',' { + // Cleanup must remove the trailing comma both for objects (close '}') and + // arrays (close ']'). The original check only handled '}', so deleting + // the last array element left a dangling ',]' / ', ]' sequence and + // produced malformed JSON output (found by FuzzPathMutation, + // e.g. Delete("[0,0 ]", "[1]") -> "[0, ]"). The array close is now + // covered symmetrically with the object close. + if prevTok > -1 && remainedTok > -1 && (remainedValue[remainedTok] == '}' || remainedValue[remainedTok] == ']') && data[prevTok] == ',' { newOffset = prevTok - } else { + } else if prevTok > -1 { newOffset = prevTok + 1 + } else { + newOffset = 0 } - // We have to make a copy here if we don't want to mangle the original data, because byte slices are - // accessed by reference and not by value - dataCopy := make([]byte, len(data)) - copy(dataCopy, data) - data = append(dataCopy[:newOffset], dataCopy[endOffset:]...) + // Allocate the exact result size so neither the copy operation nor later + // appends to the returned slice can write into the input backing array. + result = make([]byte, newOffset+len(data)-endOffset) + copy(result, data[:newOffset]) + copy(result[newOffset:], data[endOffset:]) - return data + return result, true } /* @@ -837,14 +1337,19 @@ Returns: `err` - On any parsing error */ -// SYS-REQ-009, SYS-REQ-051, SYS-REQ-068, SYS-REQ-069, SYS-REQ-070 +// SYS-REQ-009, SYS-REQ-051, SYS-REQ-068, SYS-REQ-069, SYS-REQ-070, SYS-REQ-110 func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) { + return setConfig(DefaultConfig, data, setValue, keys...) +} + +// SYS-REQ-115 +func setConfig(config Config, data []byte, setValue []byte, keys ...string) (value []byte, err error) { // ensure keys are set if len(keys) == 0 { return nil, KeyPathNotFoundError } - _, _, startOffset, endOffset, err := internalGet(data, keys...) + _, _, startOffset, endOffset, err := internalGetConfig(config, data, keys...) if err != nil { if err != KeyPathNotFoundError { // problem parsing the data @@ -854,7 +1359,7 @@ func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) // does any subpath exist? var depth int for i := range keys { - _, _, start, end, sErr := internalGet(data, keys[:i+1]...) + _, _, start, end, sErr := internalGetConfig(config, data, keys[:i+1]...) if sErr != nil { break } else { @@ -865,38 +1370,140 @@ func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) } comma := true object := false + // KI-3: when the path's next component expects one container type but + // the existing structure is the other (array-index [N] under an object, + // or an object key under an array), auto-coerce the container to the + // type expected by the path and proceed with fresh insertion. The + // mismatched container is treated as if it needs to be (re)created, so + // the output is always valid JSON. + coerceTopLevel := false + coerceStart := 0 + topLevelArrayAppend := false + topLevelArrayEmpty := false + topLevelArrayStart := 0 + topLevelArrayInsertOffset := 0 if endOffset == -1 { - firstToken := nextToken(data) - // We can't set a top-level key if data isn't an object - if firstToken < 0 || data[firstToken] != '{' { + firstToken := nextTokenConfig(config, data) + if firstToken < 0 { return nil, KeyPathNotFoundError } - // Don't need a comma if the input is an empty object - secondToken := firstToken + 1 + nextToken(data[firstToken+1:]) - if data[secondToken] == '}' { + pathIsIndex := len(keys[0]) > 0 && keys[0][0] == '[' + // An empty trailing key component is the degenerate "no path + // provided" case (SYS-REQ-111), not a real object key — it must + // keep returning KeyPathNotFoundError on a non-object root, so it + // is excluded from auto-coerce. + pathIsObjectKey := len(keys[0]) > 0 && !pathIsIndex + dataIsObject := data[firstToken] == '{' + dataIsArray := data[firstToken] == '[' + if (pathIsIndex && dataIsObject) || (pathIsObjectKey && dataIsArray) { + // SYS-REQ-009: cross-type Set at the top level — replace the + // mismatched container with a fresh container of the type the + // path expects, then perform a fresh insertion. + coerceTopLevel = true + coerceStart = firstToken comma = false + object = !pathIsIndex + endOffset = lastToken(data) + } else if pathIsIndex && dataIsArray { + // SYS-REQ-110: a missing index in a top-level array appends at + // the array's end, just as it does for a nested array. + arrayEnd := blockEndConfig(config, data[firstToken:], '[', ']') + if arrayEnd == -1 { + return nil, MalformedArrayError + } + endOffset = firstToken + arrayEnd - 1 + topLevelArrayAppend = true + topLevelArrayStart = firstToken + topLevelArrayInsertOffset = endOffset + + interior := data[firstToken+1 : endOffset] + lastInteriorToken := lastToken(interior) + if lastInteriorToken == -1 { + // createInsertComponent wraps an index component in brackets + // when comma is false, so replace the empty root array. + comma = false + topLevelArrayEmpty = true + } else if interior[lastInteriorToken] == ',' { + // Replace a trailing comma (and any whitespace after it) + // with the normal comma-prefixed append component. + beforeComma := lastToken(interior[:lastInteriorToken]) + if beforeComma == -1 { + comma = false + topLevelArrayEmpty = true + } else { + topLevelArrayInsertOffset = firstToken + 1 + lastInteriorToken + } + } + } else if !dataIsObject { + // Non-container input and the degenerate empty-key-on-non-object + // case are rejected. + return nil, KeyPathNotFoundError + } else { + // Don't need a comma if the input is an empty object + secondToken := firstToken + 1 + nextTokenConfig(config, data[firstToken+1:]) + if data[secondToken] == '}' { + comma = false + } + // Set the top level key at the end (accounting for any trailing whitespace) + // This assumes last token is valid like '}', could check and return error + endOffset = lastToken(data) } - // Set the top level key at the end (accounting for any trailing whitespace) - // This assumes last token is valid like '}', could check and return error - endOffset = lastToken(data) } depthOffset := endOffset if depth != 0 { - // if subpath is a non-empty object, add to it - // or if subpath is a non-empty array, add to it - if (data[startOffset] == '{' && data[startOffset+1+nextToken(data[startOffset+1:])] != '}') || - (data[startOffset] == '[' && data[startOffset+1+nextToken(data[startOffset+1:])] == '{') && keys[depth:][0][0] == 91 { - depthOffset-- - startOffset = depthOffset - // otherwise, over-write it with a new object - } else { + trailing := keys[depth:] + pathIsIndex := len(trailing) > 0 && len(trailing[0]) > 0 && trailing[0][0] == '[' + containerIsObject := data[startOffset] == '{' + containerIsArray := data[startOffset] == '[' + if (pathIsIndex && containerIsObject) || (!pathIsIndex && containerIsArray) { + // SYS-REQ-009: cross-type Set under a subpath — replace the + // mismatched container (data[startOffset:depthOffset]) with a + // fresh container of the type the path expects. startOffset and + // depthOffset already bound the existing container, so keep them + // and let createInsertComponent build the replacement. comma = false - object = true + object = !pathIsIndex + } else { + // if subpath is a non-empty object, add to it + // or if subpath is a non-empty array, add to it + // guard: nextToken returns -1 on truncated input; bounds-check the computed offset. + subObjOff := startOffset + 1 + nextTokenConfig(config, data[startOffset+1:]) + // The array-append condition must fire for ANY non-empty array + // (scalar, string, bool, null, nested, or object elements), not + // just arrays whose first element happens to be '{'. The former + // `data[subObjOff] == '{'` check silently destroyed scalar + // arrays on beyond-length Set (SYS-REQ-110 violation: the whole + // array was replaced with a single-element [value]). + if (containerIsObject && subObjOff >= 0 && subObjOff < len(data) && data[subObjOff] != '}') || + (containerIsArray && subObjOff >= 0 && subObjOff < len(data) && data[subObjOff] != ']' && pathIsIndex) { + depthOffset-- + startOffset = depthOffset + // otherwise, over-write it with a new object + } else { + comma = false + object = true + } } } else { - startOffset = depthOffset + if coerceTopLevel { + startOffset = coerceStart + depthOffset = endOffset + 1 + } else if topLevelArrayAppend { + if topLevelArrayEmpty { + startOffset = topLevelArrayStart + depthOffset = endOffset + 1 + } else { + startOffset = topLevelArrayInsertOffset + } + } else { + startOffset = depthOffset + } } - value = append(data[:startOffset], append(createInsertComponent(keys[depth:], setValue, comma, object), data[depthOffset:]...)...) + insertComponent := createInsertComponent(keys[depth:], setValue, comma, object) + value = make([]byte, startOffset+len(insertComponent)+len(data)-depthOffset) + offset := copy(value, data[:startOffset]) + offset += copy(value[offset:], insertComponent) + copy(value[offset:], data[depthOffset:]) } else { // path currently exists startComponent := data[:startOffset] @@ -913,13 +1520,18 @@ func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) // SYS-REQ-001, SYS-REQ-027 func getType(data []byte, offset int) ([]byte, ValueType, int, error) { + return getTypeConfig(DefaultConfig, data, offset) +} + +// SYS-REQ-115 +func getTypeConfig(config Config, data []byte, offset int) ([]byte, ValueType, int, error) { var dataType ValueType endOffset := offset // if string value - if data[offset] == '"' { + if data[offset] == '"' || (config.AllowSingleQuotes && data[offset] == '\'') { dataType = String - if idx, _ := stringEnd(data[offset+1:]); idx != -1 { + if idx, _ := stringEndConfig(config, data[offset+1:], data[offset]); idx != -1 { endOffset += idx + 1 } else { return nil, dataType, offset, MalformedStringError @@ -927,7 +1539,7 @@ func getType(data []byte, offset int) ([]byte, ValueType, int, error) { } else if data[offset] == '[' { // if array value dataType = Array // break label, for stopping nested loops - endOffset = blockEnd(data[offset:], '[', ']') + endOffset = blockEndConfig(config, data[offset:], '[', ']') if endOffset == -1 { return nil, dataType, offset, MalformedArrayError @@ -937,7 +1549,7 @@ func getType(data []byte, offset int) ([]byte, ValueType, int, error) { } else if data[offset] == '{' { // if object value dataType = Object // break label, for stopping nested loops - endOffset = blockEnd(data[offset:], '{', '}') + endOffset = blockEndConfig(config, data[offset:], '{', '}') if endOffset == -1 { return nil, dataType, offset, MalformedObjectError @@ -996,20 +1608,25 @@ func Get(data []byte, keys ...string) (value []byte, dataType ValueType, offset // SYS-REQ-001 func internalGet(data []byte, keys ...string) (value []byte, dataType ValueType, offset, endOffset int, err error) { + return internalGetConfig(DefaultConfig, data, keys...) +} + +// SYS-REQ-115 +func internalGetConfig(config Config, data []byte, keys ...string) (value []byte, dataType ValueType, offset, endOffset int, err error) { if len(keys) > 0 { - if offset = searchKeys(data, keys...); offset == -1 { + if offset = searchKeysConfig(config, data, keys...); offset == -1 { return nil, NotExist, -1, -1, KeyPathNotFoundError } } // Go to closest value - nO := nextToken(data[offset:]) + nO := nextTokenConfig(config, data[offset:]) if nO == -1 { return nil, NotExist, offset, -1, MalformedJsonError } offset += nO - value, dataType, endOffset, err = getType(data, offset) + value, dataType, endOffset, err = getTypeConfig(config, data, offset) if err != nil { return value, dataType, offset, endOffset, err } @@ -1025,24 +1642,44 @@ func internalGet(data []byte, keys ...string) (value []byte, dataType ValueType, // SYS-REQ-006, SYS-REQ-028, SYS-REQ-029, SYS-REQ-052, SYS-REQ-053, SYS-REQ-055, SYS-REQ-083 // ArrayEach is used when iterating arrays, accepts a callback function with the same return arguments as `Get`. func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error) { + return arrayEachConfig(DefaultConfig, data, cb, keys...) +} + +// SYS-REQ-115 +func arrayEachConfig(config Config, data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error) { if len(data) == 0 { return -1, MalformedObjectError } - nT := nextToken(data) + nT := nextTokenConfig(config, data) if nT == -1 { return -1, MalformedJsonError } + // Guard: when ArrayEach is called without a key path, the addressed + // root value must be an array. Without this guard, the main loop below + // happily parses the first token of a non-array value (e.g. the opening + // key of an object, or a bare number) as if it were an array element, + // invoking the callback once with bogus data before eventually returning + // MalformedArrayError. A caller performing side effects in the callback + // would observe a spurious invocation on input that is not an array at + // all. (SYS-REQ-029 partition: non-array root, no key path.) + // When a key path IS provided, the keys block below already enforces the + // same contract via its own `data[offset] != '['` check after resolving + // the path, so the guard is only needed for the no-keys case. + if len(keys) == 0 && data[nT] != '[' { + return -1, MalformedArrayError + } + offset = nT + 1 if len(keys) > 0 { - if offset = searchKeys(data, keys...); offset == -1 { + if offset = searchKeysConfig(config, data, keys...); offset == -1 { return offset, KeyPathNotFoundError } // Go to closest value - nO := nextToken(data[offset:]) + nO := nextTokenConfig(config, data[offset:]) if nO == -1 { return offset, MalformedJsonError } @@ -1056,7 +1693,7 @@ func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int offset++ } - nO := nextToken(data[offset:]) + nO := nextTokenConfig(config, data[offset:]) if nO == -1 { return offset, MalformedJsonError } @@ -1068,7 +1705,7 @@ func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int } for { - v, t, o, e := Get(data[offset:]) + v, t, o, e := config.Get(data[offset:]) if o == 0 { // When Get returns endOffset==0, it always means a parse error @@ -1088,7 +1725,7 @@ func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int offset += o - skipToToken := nextToken(data[offset:]) + skipToToken := nextTokenConfig(config, data[offset:]) if skipToToken == -1 { return offset, MalformedArrayError } @@ -1108,14 +1745,119 @@ func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int return offset, nil } +// ArrayEachErr is used when iterating arrays and allows the callback to stop +// iteration by returning an error. io.EOF stops iteration without returning an +// error. The returned count includes the element whose callback stopped the +// iteration. +// SYS-REQ-004 +func ArrayEachErr(data []byte, cb func(value []byte, dataType ValueType, offset int, err error) error, keys ...string) (count int, err error) { + _, count, err = arrayEachErr(data, cb, keys...) + return count, err +} + +// arrayEachErr also returns ArrayEach's closing-bracket offset for use by +// EachKeyErr while traversing array-index paths. +// SYS-REQ-004 +func arrayEachErr(data []byte, cb func(value []byte, dataType ValueType, offset int, err error) error, keys ...string) (offset, count int, err error) { + if len(data) == 0 { + return -1, 0, MalformedObjectError + } + + nT := nextToken(data) + if nT == -1 { + return -1, 0, MalformedJsonError + } + + if len(keys) == 0 && data[nT] != '[' { + return -1, 0, MalformedArrayError + } + + offset = nT + 1 + + if len(keys) > 0 { + if offset = searchKeys(data, keys...); offset == -1 { + return offset, 0, KeyPathNotFoundError + } + + nO := nextToken(data[offset:]) + if nO == -1 { + return offset, 0, MalformedJsonError + } + + offset += nO + + if data[offset] != '[' { + return offset, 0, MalformedArrayError + } + + offset++ + } + + nO := nextToken(data[offset:]) + if nO == -1 { + return offset, 0, MalformedJsonError + } + + offset += nO + + if data[offset] == ']' { + return offset, 0, nil + } + + for { + v, t, o, parseErr := Get(data[offset:]) + + if o == 0 { + return offset, count, parseErr + } + + count++ + if callbackErr := cb(v, t, offset+o-len(v), parseErr); callbackErr != nil { + if errors.Is(callbackErr, io.EOF) { + return offset, count, nil + } + return offset, count, callbackErr + } + + if parseErr != nil { + return offset, count, parseErr + } + + offset += o + + skipToToken := nextToken(data[offset:]) + if skipToToken == -1 { + return offset, count, MalformedArrayError + } + offset += skipToToken + + if data[offset] == ']' { + break + } + + if data[offset] != ',' { + return offset, count, MalformedArrayError + } + + offset++ + } + + return offset, count, nil +} + // SYS-REQ-007, SYS-REQ-030, SYS-REQ-031, SYS-REQ-032, SYS-REQ-054, SYS-REQ-084 // ObjectEach iterates over the key-value pairs of a JSON object, invoking a given callback for each such entry func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) { + return objectEachConfig(DefaultConfig, data, callback, keys...) +} + +// SYS-REQ-115 +func objectEachConfig(config Config, data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) { offset := 0 // Descend to the desired key, if requested if len(keys) > 0 { - if off := searchKeys(data, keys...); off == -1 { + if off := searchKeysConfig(config, data, keys...); off == -1 { return KeyPathNotFoundError } else { offset = off @@ -1123,7 +1865,7 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va } // Validate and skip past opening brace - if off := nextToken(data[offset:]); off == -1 { + if off := nextTokenConfig(config, data[offset:]); off == -1 { return MalformedObjectError } else if offset += off; data[offset] != '{' { return MalformedObjectError @@ -1132,7 +1874,7 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va } // Skip to the first token inside the object, or stop if we find the ending brace - if off := nextToken(data[offset:]); off == -1 { + if off := nextTokenConfig(config, data[offset:]); off == -1 { return MalformedJsonError } else if offset += off; data[offset] == '}' { return nil @@ -1152,6 +1894,11 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va switch data[offset] { case '"': offset++ // accept as string and skip opening quote + case '\'': + if !config.AllowSingleQuotes { + return MalformedObjectError + } + offset++ // accept as string and skip opening quote case '}': return nil // we found the end of the object; stop and return success default: @@ -1160,7 +1907,8 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va // Find the end of the key string var keyEscaped bool - if off, esc := stringEnd(data[offset:]); off == -1 { + quote := data[offset-1] + if off, esc := stringEndConfig(config, data[offset:], quote); off == -1 { return MalformedJsonError } else { key, keyEscaped = data[offset:offset+off-1], esc @@ -1170,7 +1918,7 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va // Unescape the string if needed if keyEscaped { var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings - if keyUnescaped, err := Unescape(key, stackbuf[:]); err != nil { + if keyUnescaped, err := unescapeConfig(config, key, stackbuf[:]); err != nil { return MalformedStringEscapeError } else { key = keyUnescaped @@ -1178,7 +1926,7 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va } // Step 2: skip the colon - if off := nextToken(data[offset:]); off == -1 { + if off := nextTokenConfig(config, data[offset:]); off == -1 { return MalformedJsonError } else if offset += off; data[offset] != ':' { return MalformedJsonError @@ -1187,7 +1935,7 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va } // Step 3: find the associated value, then invoke the callback - if value, valueType, off, err := Get(data[offset:]); err != nil { + if value, valueType, off, err := config.Get(data[offset:]); err != nil { return err } else if err := callback(key, value, valueType, offset+off); err != nil { // Invoke the callback here! return err @@ -1196,7 +1944,7 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va } // Step 4: skip over the next comma to the following token, or stop if we hit the ending brace - if off := nextToken(data[offset:]); off == -1 { + if off := nextTokenConfig(config, data[offset:]); off == -1 { return MalformedArrayError } else { offset += off @@ -1211,7 +1959,7 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va } // Skip to the next token after the comma - if off := nextToken(data[offset:]); off == -1 { + if off := nextTokenConfig(config, data[offset:]); off == -1 { return MalformedArrayError } else { offset += off @@ -1366,3 +2114,368 @@ func ParseInt(b []byte) (int64, error) { return v, nil } } + +// GetArrayLen returns the number of elements in the addressed JSON array. +// It scans the array without invoking a callback. +// SYS-REQ-112 +func GetArrayLen(data []byte, keys ...string) (int, error) { + offset, err := containerStart(data, '[', keys...) + if err != nil { + return 0, err + } + + return scanContainerLen(data, offset, '[') +} + +// GetObjectLen returns the number of key-value pairs in the addressed JSON +// object. It scans the object without invoking a callback. +// SYS-REQ-112 +func GetObjectLen(data []byte, keys ...string) (int, error) { + offset, err := containerStart(data, '{', keys...) + if err != nil { + return 0, err + } + + return scanContainerLen(data, offset, '{') +} + +// GetUint64 returns the value retrieved by internalGet, cast to a uint64 if +// possible. Negative values and malformed integers return MalformedValueError; +// values larger than uint64 return OverflowIntegerError. +// SYS-REQ-003 +func GetUint64(data []byte, keys ...string) (uint64, error) { + v, t, _, _, err := internalGet(data, keys...) + if err != nil { + return 0, err + } + + if t != Number { + if t == Null { + return 0, NullValueError + } + return 0, fmt.Errorf("Value is not a number: %s", string(v)) + } + + if n, ok, _ := parseInt(v); ok { + if n < 0 { + return 0, MalformedValueError + } + return uint64(n), nil + } + + n, parseErr := strconv.ParseUint(string(v), 10, 64) + if parseErr == nil { + return n, nil + } + + var numErr *strconv.NumError + if errors.As(parseErr, &numErr) && numErr.Err == strconv.ErrRange { + return 0, OverflowIntegerError + } + return 0, MalformedValueError +} + +// SYS-REQ-112 +func containerStart(data []byte, open byte, keys ...string) (int, error) { + offset := 0 + if len(keys) > 0 { + offset = searchKeys(data, keys...) + if offset == -1 { + return -1, KeyPathNotFoundError + } + } + + tokenOffset := nextToken(data[offset:]) + if tokenOffset == -1 { + return -1, KeyPathNotFoundError + } + offset += tokenOffset + + if data[offset] != open { + return -1, KeyPathNotFoundError + } + return offset, nil +} + +// SYS-REQ-112 +func scanContainerLen(data []byte, offset int, open byte) (int, error) { + const ( + scanArrayValue = iota + scanArrayPrimitive + scanArrayDelimiter + scanObjectKey + scanObjectColon + scanObjectValue + scanObjectPrimitive + scanObjectDelimiter + ) + + close := byte(']') + malformedErr := MalformedArrayError + state := scanArrayValue + if open == '{' { + close = '}' + malformedErr = MalformedObjectError + state = scanObjectKey + } + + var fixedStack [32]byte + stack := fixedStack[:1] + stack[0] = close + + count := 0 + primitiveStart := -1 + + for i := offset + 1; i < len(data); i++ { + c := data[i] + + // Only delimiters at the addressed container's top level affect its + // length. Strings and nested containers are skipped structurally. + if len(stack) > 1 { + switch c { + case '"': + stringLength, _ := stringEnd(data[i+1:]) + if stringLength == -1 { + return 0, malformedErr + } + i += stringLength + case '[': + stack = append(stack, ']') + case '{': + stack = append(stack, '}') + case ']', '}': + if c != stack[len(stack)-1] { + return 0, malformedErr + } + stack = stack[:len(stack)-1] + } + continue + } + + switch state { + case scanArrayValue: + if isContainerWhitespace(c) { + continue + } + if c == close { + if count == 0 { + return 0, nil + } + return 0, malformedErr + } + if c == ',' || c == '}' || c == ':' { + return 0, malformedErr + } + + count++ + switch c { + case '"': + stringLength, _ := stringEnd(data[i+1:]) + if stringLength == -1 { + return 0, malformedErr + } + i += stringLength + state = scanArrayDelimiter + case '[': + stack = append(stack, ']') + state = scanArrayDelimiter + case '{': + stack = append(stack, '}') + state = scanArrayDelimiter + default: + primitiveStart = i + state = scanArrayPrimitive + } + + case scanArrayPrimitive: + switch c { + case ',': + if !validContainerPrimitive(data[primitiveStart:i]) { + return 0, malformedErr + } + state = scanArrayValue + case ']': + if !validContainerPrimitive(data[primitiveStart:i]) { + return 0, malformedErr + } + return count, nil + case '}': + return 0, malformedErr + } + + case scanArrayDelimiter: + if isContainerWhitespace(c) { + continue + } + switch c { + case ',': + state = scanArrayValue + case ']': + return count, nil + default: + return 0, malformedErr + } + + case scanObjectKey: + if isContainerWhitespace(c) { + continue + } + if c == close { + if count == 0 { + return 0, nil + } + return 0, malformedErr + } + if c != '"' { + return 0, malformedErr + } + + stringLength, _ := stringEnd(data[i+1:]) + if stringLength == -1 { + return 0, malformedErr + } + i += stringLength + state = scanObjectColon + + case scanObjectColon: + if isContainerWhitespace(c) { + continue + } + if c != ':' { + return 0, malformedErr + } + state = scanObjectValue + + case scanObjectValue: + if isContainerWhitespace(c) { + continue + } + if c == ',' || c == '}' || c == ']' || c == ':' { + return 0, malformedErr + } + + count++ + switch c { + case '"': + stringLength, _ := stringEnd(data[i+1:]) + if stringLength == -1 { + return 0, malformedErr + } + i += stringLength + state = scanObjectDelimiter + case '[': + stack = append(stack, ']') + state = scanObjectDelimiter + case '{': + stack = append(stack, '}') + state = scanObjectDelimiter + default: + primitiveStart = i + state = scanObjectPrimitive + } + + case scanObjectPrimitive: + switch c { + case ',': + if !validContainerPrimitive(data[primitiveStart:i]) { + return 0, malformedErr + } + state = scanObjectKey + case '}': + if !validContainerPrimitive(data[primitiveStart:i]) { + return 0, malformedErr + } + return count, nil + case ']': + return 0, malformedErr + } + + case scanObjectDelimiter: + if isContainerWhitespace(c) { + continue + } + switch c { + case ',': + state = scanObjectKey + case '}': + return count, nil + default: + return 0, malformedErr + } + } + } + + return 0, malformedErr +} + +// SYS-REQ-112 +func isContainerWhitespace(c byte) bool { + return c == ' ' || c == '\n' || c == '\r' || c == '\t' +} + +// SYS-REQ-112 +func validContainerPrimitive(value []byte) bool { + for len(value) > 0 && isContainerWhitespace(value[len(value)-1]) { + value = value[:len(value)-1] + } + if len(value) == 0 { + return false + } + + if bytes.Equal(value, trueLiteral) || bytes.Equal(value, falseLiteral) || bytes.Equal(value, nullLiteral) { + return true + } + return validJSONNumber(value) +} + +// SYS-REQ-112 +func validJSONNumber(value []byte) bool { + i := 0 + if value[i] == '-' { + i++ + if i == len(value) { + return false + } + } + + if value[i] == '0' { + i++ + if i < len(value) && value[i] >= '0' && value[i] <= '9' { + return false + } + } else { + if value[i] < '1' || value[i] > '9' { + return false + } + for i < len(value) && value[i] >= '0' && value[i] <= '9' { + i++ + } + } + + if i < len(value) && value[i] == '.' { + i++ + start := i + for i < len(value) && value[i] >= '0' && value[i] <= '9' { + i++ + } + if i == start { + return false + } + } + + if i < len(value) && (value[i] == 'e' || value[i] == 'E') { + i++ + if i < len(value) && (value[i] == '+' || value[i] == '-') { + i++ + } + start := i + for i < len(value) && value[i] >= '0' && value[i] <= '9' { + i++ + } + if i == start { + return false + } + } + + return i == len(value) +} diff --git a/vendor/github.com/buger/jsonparser/path_compiler.go b/vendor/github.com/buger/jsonparser/path_compiler.go new file mode 100644 index 0000000..b044e7e --- /dev/null +++ b/vendor/github.com/buger/jsonparser/path_compiler.go @@ -0,0 +1,226 @@ +package jsonparser + +import ( + "errors" + "strings" +) + +var ( + errEmptyPath = errors.New("jsonparser: path must not be empty") + errMalformedPath = errors.New("jsonparser: malformed path") + errUnterminatedKey = errors.New("jsonparser: unterminated quoted key") +) + +// ParsePath converts a JSONPath-style path into the path components accepted +// by Get, Set, Delete, ArrayEach, and EachKey. +// SYS-REQ-114 +func ParsePath(jsonPath string) ([]string, error) { + if jsonPath == "" { + return nil, errEmptyPath + } + + switch { + case jsonPath == "$": + return []string{}, nil + case strings.HasPrefix(jsonPath, "$."): + jsonPath = jsonPath[2:] + case strings.HasPrefix(jsonPath, "$["): + jsonPath = jsonPath[1:] + case jsonPath[0] == '$': + return nil, errMalformedPath + } + + if jsonPath == "" { + return nil, errMalformedPath + } + + // A path component is either a dot-delimited key or bracket notation. + // Counting both separators gives an exact capacity for ordinary paths and + // a safe upper bound for quoted keys containing dots or brackets. + parts := make([]string, 0, 1+strings.Count(jsonPath, ".")+strings.Count(jsonPath, "[")) + + for pos := 0; pos < len(jsonPath); { + switch jsonPath[pos] { + case '.': + return nil, errMalformedPath + case '"': + key, next, err := parseQuotedPathKey(jsonPath, pos) + if err != nil { + return nil, err + } + parts = append(parts, key) + pos = next + case '[': + // A root array path or a bracket immediately following a dot has + // no key component before its index. + default: + start := pos + for pos < len(jsonPath) && jsonPath[pos] != '.' && jsonPath[pos] != '[' { + if jsonPath[pos] == ']' || jsonPath[pos] == '"' { + return nil, errMalformedPath + } + pos++ + } + if start == pos { + return nil, errMalformedPath + } + parts = append(parts, jsonPath[start:pos]) + } + + for pos < len(jsonPath) && jsonPath[pos] == '[' { + component, next, err := parseBracketPathComponent(jsonPath, pos) + if err != nil { + return nil, err + } + parts = append(parts, component) + pos = next + } + + if pos == len(jsonPath) { + break + } + if jsonPath[pos] != '.' { + return nil, errMalformedPath + } + + pos++ + if pos == len(jsonPath) { + return nil, errMalformedPath + } + } + + if len(parts) == 0 { + return nil, errMalformedPath + } + return parts, nil +} + +// SYS-REQ-114 +func parseQuotedPathKey(path string, start int) (string, int, error) { + contentStart := start + 1 + for pos := contentStart; pos < len(path); pos++ { + switch path[pos] { + case '\\': + // Skip the escaped byte while locating the closing quote. Unescape + // below performs complete JSON escape validation. + pos++ + if pos >= len(path) { + return "", 0, errUnterminatedKey + } + case '"': + content := path[contentStart:pos] + if strings.IndexByte(content, '\\') == -1 { + return content, pos + 1, nil + } + + unescaped, err := Unescape([]byte(content), nil) + if err != nil { + return "", 0, errMalformedPath + } + return string(unescaped), pos + 1, nil + default: + if path[pos] < 0x20 { + return "", 0, errMalformedPath + } + } + } + + return "", 0, errUnterminatedKey +} + +// SYS-REQ-114 +func parseBracketPathComponent(path string, start int) (string, int, error) { + end := start + 1 + for end < len(path) && path[end] != ']' { + if path[end] == '[' || path[end] == '"' { + return "", 0, errMalformedPath + } + end++ + } + if end == len(path) || end == start+1 { + return "", 0, errMalformedPath + } + + if path[start+1] == '*' { + if end != start+2 { + return "", 0, errMalformedPath + } + } else { + for pos := start + 1; pos < end; pos++ { + if path[pos] < '0' || path[pos] > '9' { + return "", 0, errMalformedPath + } + } + } + + return path[start : end+1], end + 1, nil +} + +// CompiledPath stores a parsed path for repeated operations. +// SYS-REQ-114 +type CompiledPath struct { + parts []string +} + +// CompilePath parses jsonPath once for reuse. +// SYS-REQ-114 +func CompilePath(jsonPath string) (CompiledPath, error) { + parts, err := ParsePath(jsonPath) + if err != nil { + return CompiledPath{}, err + } + return CompiledPath{parts: parts}, nil +} + +// Get resolves the compiled path in data. +// Verifies: SYS-REQ-001 (Get) +// SYS-REQ-114 +func (c CompiledPath) Get(data []byte) ([]byte, ValueType, int, error) { + return Get(data, c.parts...) +} + +// GetString resolves the compiled path and returns its string value. +// SYS-REQ-114 +func (c CompiledPath) GetString(data []byte) (string, error) { + return GetString(data, c.parts...) +} + +// GetInt resolves the compiled path and returns its integer value. +// SYS-REQ-114 +func (c CompiledPath) GetInt(data []byte) (int64, error) { + return GetInt(data, c.parts...) +} + +// Set writes value at the compiled path. +// Verifies: SYS-REQ-009 (Set) +// SYS-REQ-114 +func (c CompiledPath) Set(data []byte, value []byte) ([]byte, error) { + return Set(data, value, c.parts...) +} + +// Delete removes the value at the compiled path. +// SYS-REQ-114 +func (c CompiledPath) Delete(data []byte) []byte { + return Delete(data, c.parts...) +} + +// ArrayEach iterates over the array at the compiled path. +// SYS-REQ-114 +func (c CompiledPath) ArrayEach(data []byte, cb func([]byte, ValueType, int, error)) (int, error) { + return ArrayEach(data, cb, c.parts...) +} + +// EachKey resolves the compiled path using EachKey. +// SYS-REQ-114 +func (c CompiledPath) EachKey(data []byte, cb func(int, []byte, ValueType, error)) error { + EachKey(data, cb, c.parts) + return nil +} + +// Parts returns a copy of the compiled path components. +// SYS-REQ-114 +func (c CompiledPath) Parts() []string { + parts := make([]string, len(c.parts)) + copy(parts, c.parts) + return parts +} diff --git a/vendor/github.com/buger/jsonparser/proof.yaml b/vendor/github.com/buger/jsonparser/proof.yaml index 4d82bc2..f15efe7 100644 --- a/vendor/github.com/buger/jsonparser/proof.yaml +++ b/vendor/github.com/buger/jsonparser/proof.yaml @@ -1,5 +1,10 @@ project: name: jsonparser + # High-assurance posture: the library is a pure function over untrusted, + # adversarial byte input (fuzz targets, OSS-Fuzz). L3 is the strict + # non-trivial level that obligates formalization, coverage, and hazard + # review rather than informal inspection alone. + assurance_target: L3 specs: - path: specs/stakeholder prefix: STK-REQ @@ -32,14 +37,120 @@ project: - nil_safety - encoding_safety - edge_case + - no_input_mutation + - api_consistency + - element_type_partition + - non_array_root_no_callback commands: build: go build ./... - test: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1 + # Standard audit test command: runs unit + MC/DC witness tests but + # SKIPS the heavy iteration-count suites (property-based, reference- + # oracle, fuzz-harness coverage) so `proof audit` stays fast on every + # PR. Those suites run via `make test-full` (see Makefile) in the + # dedicated CI "Fuzzing" job. Go's -skip flag (1.20+) accepts a regex; + # Fuzz* functions only run under -fuzz anyway. + test: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -skip='TestProperty|TestOracle|TestFuzz.*Harness' -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1 + # Named per-language test commands consumed by code_mcdc (the MC/DC + # engine needs a discoverable go test command it can instrument and + # rerun, then collect fingerprints). Mirrors the reqforge schema. + tests: + go: + language: go + command: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -skip='TestProperty|TestOracle|TestFuzz.*Harness' -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1 + # Instrumented execution path used only when the code-level + # MC/DC engine reruns tests in its temp workspace (cwd = + # /module). The engine does NOT inject -coverprofile or + # -count into a user-provided command, so this must write the + # managed cover artifact itself: ../cover.out resolves to the + # workspace root the engine reads. -json is redirected back to + # the source workspace via REQPROOF_MCDC_ORIGINAL_SOURCE_DIR so + # test_results auto_link sees a fresh report. The ordinary + # `command` above still feeds coverage_threshold / test_results + # for the non-MC/DC path; -race still comes from test_args. + mcdc_command: go test ./... -coverprofile=../cover.out -json > "$REQPROOF_MCDC_ORIGINAL_SOURCE_DIR/.proof/test-results/go-test.json" 2>&1 # Fixtures are generated artifacts, not committed to the repo. # MC/DC coverage is enforced through test annotations instead. # To regenerate locally: # proof testgen specs/system parser --output tests/ # proof proptest specs/system parser --source z3 --output tests/parser/ + # + # Code signals — project-local OpenGrep rule packs. + # + # The jsonparser.boundary.unchecked-caller-slice-deref rule closes the + # gap exposed by the 8th empty-key panic site (parser.go:1000): the + # prior hazard sweep matched only `identifier[index][0]` and missed the + # slice-expression variant `keys[depth:][0][0]`. The rule treats + # slice-expression-then-index, direct-index-then-field, nested direct + # index, computed-offset byte-slice index, and path-segment index as + # the SAME hazard class, while excluding `len(X) > N && ...` / + # `if len(X) > N { ... }` guarded sites and bounded `for i := range` + # loops. Findings map to the boundary obligation class (already owned + # by the parser requirement family) so each one opens a real review + # item. The semantically precise class is panic_free_input_handling; + # adopting it project-wide is the right follow-up — see the rule file + # header for the migration note. + # + # Local dev / CI install of the analyzer backend: + # npm install -g @opengrep/cli@1.22.0 + # `tools.opengrep.auto_download: true` below also fetches the pinned + # version on the first `proof signals collect --provider opengrep`. + signals: + output_dir: proof/signals + # Keep audit refresh explicit so a missing analyzer in CI does not + # turn into a spurious red. Run `proof signals collect --provider + # opengrep` before merge / locally to refresh findings; the audit + # check consumes whatever cache that command writes. + refresh_on_audit: false + defaults: auto + rule_packs: + - proof/signals/rules/unchecked-caller-slice-deref.yaml + providers: + opengrep: + enabled: true + mode: run + command: + - opengrep + - scan + - '{configs}' + - --sarif + - --quiet + - --no-rewrite-rule-ids + - '{include_paths}' + format: sarif + include_paths: + - parser.go + - bytes.go + - bytes_safe.go + - bytes_unsafe.go + - escape.go + - fuzz.go + exclude_paths: + - '*_test.go' + - benchmark/** + # `go.parameter-boundary.degenerate` anchors the + # parameter_boundary_safe catalog class, DEFINED as a + # Solidity-style governance / operator setter whose value + # is later consumed in slippage / throttle / timelock + # arithmetic or truncated by a narrowing cast. This + # project is a pure-function Go JSON parser library: the + # only "setters" it exposes are top-level exported + # functions taking byte slices, none consumed in + # protection arithmetic and none cast to a narrower type. + # The class's applies_when is never satisfied here, so + # the project can neither satisfy nor violate it. The + # honest record is "rule does not apply", not "83 + # requirement-owners each adjudicated and excused the + # same site". Rule entries use the ProviderRuleID form + # (hyphenated), matching how reqforge disables the same + # rule for the same reason. + disabled_rules: + - go.parameter-boundary.degenerate + fail_if_missing: false + timeout_seconds: 120 + tools: + opengrep: + version: 1.22.0 + auto_download: true checks: solver_latency_clean: threshold: 360 @@ -53,13 +164,14 @@ project: report_path: .proof/test-results/go-test.json slow_tests: enabled: true + threshold_seconds: 60 + max_allowed: 5 code_mcdc: severity: warn - engine: go - package_pattern: ./... - coverpkg: ./... - go_test_args: - - -race + languages: + go: + test_args: + - -race min_decision_percent: 100 min_condition_percent: 100 max_incomplete_decisions: 0 @@ -68,8 +180,6 @@ project: enabled: true language: go scope: ./... - test_mcdc_annotations: - enabled: true mcdc_coverage: {} proof_complexity_clean: max_formalized_requirements: 120 @@ -80,6 +190,35 @@ project: A: 3 B: 2 C: 1 + # Worst-case-first hazard coverage gate (hazard-sweep role precondition). + # `all` is stricter than proof's built-in default `security`: every + # in-scope obligation class must carry an enumerated worst_case, so a + # missing worst-case surfaces as a finding instead of a silent gap. + hazard_consequence: + require_worst_case_scope: all + # Keep every remaining check enabled so the audit surface is fully + # honest (no silently-disabled gates). Each was verified PASS on this + # project; keeping them on catches regressions. + change_evidence_complete: + enabled: true + code_signal_obligations_reviewed: + enabled: true + code_signal_unbindable: + enabled: true + description_grammar_enumeration_complete: + enabled: true + no_authored_change_surface_reviewed: + enabled: true + property_fixtures_exist: + enabled: true + flip_fixtures_exist: + enabled: false + fixture_staleness_clean: + enabled: true + signal_fixtures_valid: + enabled: true + property_based_test_coverage: + enabled: true approval: required_for: assurance_levels: @@ -89,8 +228,25 @@ project: - system_owner - lead_engineer comment_required: true + # Agent-driven review posture (mirrors reqforge self-dogfood): an AI + # agent driving this repo may run `proof approve` at any assurance + # level so the spec/hazard review loops can close autonomously. Set + # `all: false` and enumerate levels to re-human-gate. + agent_autonomous_for: + all: true + audit: + # CI runs `proof audit --fail-level warn --scope full`; pinning the + # same posture in config makes local runs match CI exactly. + fail_level: warn + scope: full + invocation_log: + enabled: true + path: .proof/invocations.jsonl documentation: sources: - path: . type: auto threshold: 0 + verification_scope: + exclude: null + include: null diff --git a/vendor/github.com/buger/jsonparser/reader_parser.go b/vendor/github.com/buger/jsonparser/reader_parser.go new file mode 100644 index 0000000..368d2b2 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/reader_parser.go @@ -0,0 +1,696 @@ +package jsonparser + +import ( + "bytes" + "io" + "strconv" +) + +const ( + defaultReaderBufferSize = 64 * 1024 + defaultReaderMaxBufferSize = 64 * 1024 * 1024 + maxConsecutiveEmptyReads = 100 +) + +// ReaderParser provides path-based access to a JSON stream. It is intended for +// one operation per stream: call Get, GetString, or ArrayEach after creating +// the parser. ReaderParser is not safe for concurrent use. +// +// The sliding window is bounded by Config.MaxBufferSize while skipping input. +// A returned value (or one ArrayEach element) may exceed that size because its +// complete byte slice must remain available to the caller. +// SYS-REQ-116 +type ReaderParser struct { + reader io.Reader + buf []byte + bufStart int64 + pos int + config Config + + readErr error + emptyReads int +} + +// NewReaderParser creates a streaming parser. If opts contains a Config, the +// first Config controls lenient parsing and the sliding-window size. +// SYS-REQ-116 +func NewReaderParser(r io.Reader, opts ...Config) *ReaderParser { + config := DefaultConfig + if len(opts) > 0 { + config = opts[0] + } + return &ReaderParser{ + reader: r, + config: config, + } +} + +// Get returns the value addressed by keys without loading the whole document. +// As with the package-level Get, string values are returned without quotes but +// retain their JSON escapes. +// SYS-REQ-116 +func (rp *ReaderParser) Get(keys ...string) (value []byte, vt ValueType, err error) { + for _, key := range keys { + if key == "" { + return nil, NotExist, KeyPathNotFoundError + } + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return nil, NotExist, KeyPathNotFoundError + } + return nil, NotExist, err + } + + var raw []byte + if len(keys) == 0 { + raw, err = rp.captureValue() + } else { + var found bool + found, raw, err = rp.findValue(keys, 0) + if err == nil && !found { + err = KeyPathNotFoundError + } + } + if err != nil { + return nil, NotExist, err + } + + value, vt, _, err = rp.config.Get(raw) + if err != nil { + return value, vt, err + } + return value, vt, nil +} + +// GetString returns and decodes the string addressed by keys. +// SYS-REQ-116 +func (rp *ReaderParser) GetString(keys ...string) (string, error) { + value, vt, err := rp.Get(keys...) + if err != nil { + return "", err + } + if vt != String { + if vt == Null { + return "", NullValueError + } + return "", valueTypeError("string", value) + } + if bytes.IndexByte(value, '\\') == -1 { + return string(value), nil + } + + var stackbuf [unescapeStackBufSize]byte + unescaped, err := unescapeConfig(rp.config, value, stackbuf[:]) + if err != nil { + return "", MalformedValueError + } + return string(unescaped), nil +} + +// ArrayEach incrementally iterates a root JSON array. Callback value slices are +// valid for the duration of the callback and must be copied if retained. +// Memory use is bounded by the largest element plus the sliding read window. +// SYS-REQ-116 +func (rp *ReaderParser) ArrayEach(cb func(value []byte, vt ValueType, err error)) error { + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return MalformedObjectError + } + return err + } + + b, err := rp.peekByte(false) + if err != nil { + return err + } + if b != '[' { + return MalformedArrayError + } + rp.pos++ + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return MalformedArrayError + } + return err + } + b, err = rp.peekByte(false) + if err != nil { + return err + } + if b == ']' { + rp.pos++ + return nil + } + + for { + raw, captureErr := rp.captureValue() + if captureErr != nil { + cb(nil, Unknown, captureErr) + return captureErr + } + + value, vt, _, valueErr := rp.config.Get(raw) + cb(value, vt, valueErr) + if valueErr != nil { + return valueErr + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return MalformedArrayError + } + return err + } + b, err = rp.peekByte(false) + if err != nil { + return err + } + switch b { + case ']': + rp.pos++ + return nil + case ',': + rp.pos++ + default: + return MalformedArrayError + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return MalformedArrayError + } + return err + } + b, err = rp.peekByte(false) + if err != nil { + return err + } + if b == ']' { + return MalformedArrayError + } + } +} + +// findValue resolves keys[depth:] against the value at rp.pos. A not-found +// result consumes the current value so a containing object can continue past a +// duplicate key. A found result leaves the final value in the sliding buffer. +// SYS-REQ-116 +func (rp *ReaderParser) findValue(keys []string, depth int) (bool, []byte, error) { + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedJsonError + } + return false, nil, err + } + if depth == len(keys) { + raw, err := rp.captureValue() + return err == nil, raw, err + } + + b, err := rp.peekByte(false) + if err != nil { + return false, nil, err + } + switch b { + case '{': + return rp.findObjectValue(keys, depth) + case '[': + return rp.findArrayValue(keys, depth) + default: + if err := rp.skipValue(); err != nil { + return false, nil, err + } + return false, nil, nil + } +} + +// SYS-REQ-116 +func (rp *ReaderParser) findObjectValue(keys []string, depth int) (bool, []byte, error) { + rp.pos++ // opening { + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedObjectError + } + return false, nil, err + } + b, err := rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b == '}' { + rp.pos++ + return false, nil, nil + } + + for { + matches, err := rp.readObjectKey(keys[depth]) + if err != nil { + return false, nil, err + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedJsonError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b != ':' { + return false, nil, MalformedJsonError + } + rp.pos++ + + if matches { + found, raw, err := rp.findValue(keys, depth+1) + if err != nil || found { + return found, raw, err + } + } else { + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedJsonError + } + return false, nil, err + } + if err := rp.skipValue(); err != nil { + return false, nil, err + } + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedObjectError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + switch b { + case '}': + rp.pos++ + return false, nil, nil + case ',': + rp.pos++ + default: + return false, nil, MalformedObjectError + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedObjectError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b == '}' { + return false, nil, MalformedObjectError + } + } +} + +// SYS-REQ-116 +func (rp *ReaderParser) findArrayValue(keys []string, depth int) (bool, []byte, error) { + wanted, ok := parseReaderArrayIndex(keys[depth]) + if !ok { + if err := rp.skipValue(); err != nil { + return false, nil, err + } + return false, nil, nil + } + + rp.pos++ // opening [ + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedArrayError + } + return false, nil, err + } + b, err := rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b == ']' { + rp.pos++ + return false, nil, nil + } + + for index := 0; ; index++ { + if index == wanted { + found, raw, err := rp.findValue(keys, depth+1) + if err != nil || found { + return found, raw, err + } + } else { + if err := rp.skipValue(); err != nil { + return false, nil, err + } + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedArrayError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + switch b { + case ']': + rp.pos++ + return false, nil, nil + case ',': + rp.pos++ + default: + return false, nil, MalformedArrayError + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedArrayError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b == ']' { + return false, nil, MalformedArrayError + } + } +} + +// SYS-REQ-116 +func parseReaderArrayIndex(key string) (int, bool) { + if len(key) < 3 || key[0] != '[' || key[len(key)-1] != ']' { + return 0, false + } + index, err := strconv.Atoi(key[1 : len(key)-1]) + return index, err == nil && index >= 0 +} + +// SYS-REQ-116 +func (rp *ReaderParser) readObjectKey(wanted string) (bool, error) { + b, err := rp.peekByte(false) + if err != nil { + return false, err + } + if b != '"' && !(b == '\'' && rp.config.AllowSingleQuotes) { + return false, MalformedJsonError + } + + // The parent prefix is no longer needed. Discarding it before retaining the + // key ensures that an arbitrarily late key does not grow the window. + rp.discardConsumed() + start := rp.pos + if err := rp.scanString(true); err != nil { + return false, err + } + token := rp.buf[start:rp.pos] + body := token[1 : len(token)-1] + if bytes.IndexByte(body, '\\') == -1 { + return string(body) == wanted, nil + } + + var stackbuf [unescapeStackBufSize]byte + unescaped, err := unescapeConfig(rp.config, body, stackbuf[:]) + if err != nil { + return false, err + } + return string(unescaped) == wanted, nil +} + +// SYS-REQ-116 +func (rp *ReaderParser) captureValue() ([]byte, error) { + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return nil, MalformedJsonError + } + return nil, err + } + + // Retain only this value and any already-read suffix. The suffix is at most + // one read chunk; prefixes consumed while locating the value are released. + rp.discardConsumed() + start := rp.pos + if err := rp.scanValue(true); err != nil { + return nil, err + } + return rp.buf[start:rp.pos], nil +} + +// SYS-REQ-116 +func (rp *ReaderParser) skipValue() error { + return rp.scanValue(false) +} + +// SYS-REQ-116 +func (rp *ReaderParser) scanValue(retain bool) error { + b, err := rp.peekByte(retain) + if err != nil { + if err == io.EOF { + return MalformedJsonError + } + return err + } + + switch { + case b == '"' || (b == '\'' && rp.config.AllowSingleQuotes): + return rp.scanString(retain) + case b == '[' || b == '{': + return rp.scanComposite(retain, b) + default: + return rp.scanScalar(retain) + } +} + +// SYS-REQ-116 +func (rp *ReaderParser) scanString(retain bool) error { + quote, err := rp.peekByte(retain) + if err != nil { + return err + } + rp.pos++ + escaped := false + + for { + b, err := rp.peekByte(retain) + if err != nil { + if err == io.EOF { + return MalformedStringError + } + return err + } + rp.pos++ + + if escaped { + escaped = false + continue + } + if b == '\\' { + escaped = true + continue + } + if b == quote { + return nil + } + } +} + +// SYS-REQ-116 +func (rp *ReaderParser) scanComposite(retain bool, opening byte) error { + stack := []byte{closingDelimiter(opening)} + rp.pos++ + + for len(stack) > 0 { + b, err := rp.peekByte(retain) + if err != nil { + if err == io.EOF { + if opening == '[' { + return MalformedArrayError + } + return MalformedObjectError + } + return err + } + + if b == '"' || (b == '\'' && rp.config.AllowSingleQuotes) { + if err := rp.scanString(retain); err != nil { + return err + } + continue + } + + switch b { + case '{': + stack = append(stack, '}') + case '[': + stack = append(stack, ']') + case '}', ']': + if b != stack[len(stack)-1] { + return MalformedJsonError + } + stack = stack[:len(stack)-1] + } + rp.pos++ + } + return nil +} + +// SYS-REQ-116 +func closingDelimiter(opening byte) byte { + if opening == '[' { + return ']' + } + return '}' +} + +// SYS-REQ-116 +func (rp *ReaderParser) scanScalar(retain bool) error { + consumed := false + for { + b, err := rp.peekByte(retain) + if err != nil { + if err == io.EOF && consumed { + return nil + } + if err == io.EOF { + return MalformedJsonError + } + return err + } + if isReaderValueDelimiter(b) { + if !consumed { + return MalformedJsonError + } + return nil + } + consumed = true + rp.pos++ + } +} + +// SYS-REQ-116 +func isReaderValueDelimiter(b byte) bool { + return isJSONWhitespace(b) || b == ',' || b == '}' || b == ']' +} + +// SYS-REQ-116 +func (rp *ReaderParser) skipWhitespace() error { + for { + b, err := rp.peekByte(false) + if err != nil { + return err + } + if !isJSONWhitespace(b) { + return nil + } + rp.pos++ + } +} + +// peekByte returns the next byte. When retain is false, fully consumed chunks +// are discarded before reading more data. +// SYS-REQ-116 +func (rp *ReaderParser) peekByte(retain bool) (byte, error) { + for rp.pos >= len(rp.buf) { + if !retain { + rp.discardConsumed() + } + if err := rp.readMore(); err != nil { + return 0, err + } + } + return rp.buf[rp.pos], nil +} + +// SYS-REQ-116 +func (rp *ReaderParser) readMore() error { + if rp.readErr != nil { + return rp.readErr + } + if rp.reader == nil { + rp.readErr = io.EOF + return rp.readErr + } + + readSize := defaultReaderBufferSize + maxBufferSize := rp.config.MaxBufferSize + if maxBufferSize <= 0 { + maxBufferSize = defaultReaderMaxBufferSize + } + if readSize > maxBufferSize { + readSize = maxBufferSize + } + if readSize < 1 { + readSize = 1 + } + + oldLen := len(rp.buf) + if cap(rp.buf)-oldLen < readSize { + grown := make([]byte, oldLen, oldLen+readSize) + copy(grown, rp.buf) + rp.buf = grown + } + rp.buf = rp.buf[:oldLen+readSize] + n, err := rp.reader.Read(rp.buf[oldLen:]) + rp.buf = rp.buf[:oldLen+n] + + if n > 0 { + rp.emptyReads = 0 + if err != nil { + rp.readErr = err + } + return nil + } + if err != nil { + rp.readErr = err + return err + } + + rp.emptyReads++ + if rp.emptyReads >= maxConsecutiveEmptyReads { + rp.readErr = io.ErrNoProgress + return rp.readErr + } + return nil +} + +// SYS-REQ-116 +func (rp *ReaderParser) discardConsumed() { + if rp.pos == 0 { + return + } + rp.bufStart += int64(rp.pos) + rp.buf = rp.buf[rp.pos:] + rp.pos = 0 +} + +// SYS-REQ-116 +func valueTypeError(want string, value []byte) error { + return &readerTypeError{want: want, value: string(value)} +} + +type readerTypeError struct { + want string + value string +} + +// SYS-REQ-116 +func (e *readerTypeError) Error() string { + return "Value is not a " + e.want + ": " + e.value +} diff --git a/vendor/github.com/buger/jsonparser/run_fuzz_campaign.sh b/vendor/github.com/buger/jsonparser/run_fuzz_campaign.sh new file mode 100644 index 0000000..973be85 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/run_fuzz_campaign.sh @@ -0,0 +1,54 @@ +#!/bin/bash +set -u +cd "$(dirname "$0")" +mkdir -p fuzz_results/crashes +LOG=fuzz_results/campaign.log +: > "$LOG" + +TARGETS=( + DeleteNative + ParseStringNative + EachKeyNative + SetNative + ObjectEachNative + ParseFloatNative + ParseIntNative + ParseBoolNative + TokenStartNative + GetStringNative + GetFloatNative + GetIntNative + GetBooleanNative + GetUnsafeStringNative +) +PER_TARGET=${PER_TARGET:-180s} +MAX_PASSES=${MAX_PASSES:-4} + +count_crashes() { ls fuzz_results/crashes/ 2>/dev/null | wc -l | tr -d ' '; } + +prev_count=$(count_crashes) +pass=0 +while [ $pass -lt $MAX_PASSES ]; do + pass=$((pass+1)) + echo "=== $(date '+%H:%M:%S') PASS $pass start (per-target=$PER_TARGET, baseline_unique_crashes=$prev_count) ===" | tee -a "$LOG" + for t in "${TARGETS[@]}"; do + pre=$(count_crashes) + echo " -> $(date '+%H:%M:%S') Fuzz${t}" | tee -a "$LOG" + go test -run='^$' -fuzz="^Fuzz${t}$" -fuzztime="${PER_TARGET}" \ + > "fuzz_results/${t}_pass${pass}.log" 2>&1 + rc=$? + post=$(count_crashes) + delta=$((post - pre)) + summary=$(tail -n 3 "fuzz_results/${t}_pass${pass}.log" | tr '\n' ' | ') + echo " rc=$rc new_crashes=$delta total=$post :: $summary" | tee -a "$LOG" + done + new_count=$(count_crashes) + pass_delta=$((new_count - prev_count)) + echo "=== $(date '+%H:%M:%S') PASS $pass done: total_unique_crashes=$new_count (+$pass_delta this pass) ===" | tee -a "$LOG" + if [ $pass_delta -eq 0 ] && [ $pass -ge 2 ]; then + echo "=== SATURATED after pass $pass — no new crashes ===" | tee -a "$LOG" + break + fi + prev_count=$new_count +done +echo "=== $(date '+%H:%M:%S') CAMPAIGN COMPLETE total_unique_crashes=$(count_crashes) ===" | tee -a "$LOG" diff --git a/vendor/github.com/buger/jsonparser/wildcard.go b/vendor/github.com/buger/jsonparser/wildcard.go new file mode 100644 index 0000000..9c0eebc --- /dev/null +++ b/vendor/github.com/buger/jsonparser/wildcard.go @@ -0,0 +1,158 @@ +package jsonparser + +import "strconv" + +const wildcardPathComponent = "[*]" + +// EachKeyWildcard resolves a path that may contain [*] components. A wildcard +// requires an array at that position and fans out over its elements before +// resolving the rest of the path. Multiple wildcards produce one callback for +// every matching combination, in document order. +// +// idx is the zero-based order in which matches are reported. +// +// SYS-REQ-113 +func EachKeyWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, err error), path ...string) error { + nextMatch := 0 + return eachKeyWildcard(data, cb, &nextMatch, path) +} + +// SYS-REQ-113 +func eachKeyWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, err error), nextMatch *int, path []string) error { + wildcard := wildcardIndex(path) + if wildcard == -1 { + value, valueType, _, err := Get(data, path...) + if err != nil { + // A missing path has no value to report. Parsing errors for a + // located terminal value, however, follow EachKey's convention + // and are delivered to the callback as well as returned. + if err != KeyPathNotFoundError { + cb(*nextMatch, value, valueType, err) + (*nextMatch)++ + } + return err + } + + cb(*nextMatch, value, valueType, nil) + (*nextMatch)++ + return nil + } + + array, valueType, _, err := Get(data, path[:wildcard]...) + if err != nil { + return err + } + if valueType != Array { + return MalformedArrayError + } + + remaining := path[wildcard+1:] + _, err = ArrayEachErr(array, func(value []byte, elementType ValueType, _ int, parseErr error) error { + if parseErr != nil { + cb(*nextMatch, value, elementType, parseErr) + (*nextMatch)++ + return parseErr + } + + if len(remaining) == 0 { + cb(*nextMatch, value, elementType, nil) + (*nextMatch)++ + return nil + } + + return eachKeyWildcard(value, cb, nextMatch, remaining) + }) + return err +} + +// ArrayEachWildcard iterates over an array addressed by keys. A terminal [*] +// component is accepted as an explicit request for all elements; without it, +// the function behaves like ArrayEachErr. +// SYS-REQ-113 +func ArrayEachWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, offset int, err error) error, keys ...string) (int, error) { + if len(keys) > 0 && keys[len(keys)-1] == wildcardPathComponent { + keys = keys[:len(keys)-1] + } + + index := 0 + return ArrayEachErr(data, func(value []byte, valueType ValueType, offset int, err error) error { + current := index + index++ + return cb(current, value, valueType, offset, err) + }, keys...) +} + +// SetWildcard applies Set to every concrete path matched by [*]. Wildcards +// may appear at any array position and may be repeated. If a wildcard matches +// an empty array, data is returned unchanged. +// +// SYS-REQ-113 +func SetWildcard(data []byte, setValue []byte, keys ...string) ([]byte, error) { + if wildcardIndex(keys) == -1 { + return Set(data, setValue, keys...) + } + + var paths [][]string + if err := expandWildcardPaths(data, nil, keys, &paths); err != nil { + return nil, err + } + + result := data + for _, path := range paths { + var err error + result, err = Set(result, setValue, path...) + if err != nil { + return nil, err + } + } + return result, nil +} + +// SYS-REQ-113 +func expandWildcardPaths(data []byte, concrete, remaining []string, paths *[][]string) error { + wildcard := wildcardIndex(remaining) + if wildcard == -1 { + path := make([]string, len(concrete)+len(remaining)) + copy(path, concrete) + copy(path[len(concrete):], remaining) + *paths = append(*paths, path) + return nil + } + + arrayPath := make([]string, len(concrete)+wildcard) + copy(arrayPath, concrete) + copy(arrayPath[len(concrete):], remaining[:wildcard]) + + array, valueType, _, err := Get(data, arrayPath...) + if err != nil { + return err + } + if valueType != Array { + return MalformedArrayError + } + + index := 0 + _, err = ArrayEachErr(array, func(_ []byte, _ ValueType, _ int, parseErr error) error { + if parseErr != nil { + return parseErr + } + + nextPath := make([]string, len(arrayPath)+1) + copy(nextPath, arrayPath) + nextPath[len(arrayPath)] = "[" + strconv.Itoa(index) + "]" + index++ + + return expandWildcardPaths(data, nextPath, remaining[wildcard+1:], paths) + }) + return err +} + +// SYS-REQ-113 +func wildcardIndex(path []string) int { + for i, component := range path { + if component == wildcardPathComponent { + return i + } + } + return -1 +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml b/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml index 5b30cd6..835dea6 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml +++ b/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml @@ -7,6 +7,12 @@ linters: exclusions: presets: - std-error-handling + rules: + # Test fixtures construct CDF binary blobs from known small constants, so + # gosec's integer-overflow checks (G115) add no value there. + - path: internal/cdf/cdf_test\.go + linters: + - gosec enable: - gosec # Detects security problems. # Keep all extras disabled for now to focus on the integer overflow problem. @@ -31,6 +37,7 @@ linters: - unused - usestdlibvars # Detects the possibility to use variables/constants from the Go standard library. - usetesting # Reports uses of functions with replacement inside the testing package. + - asciicheck # https://daniel.haxx.se/blog/2025/05/16/detecting-malicious-unicode/ settings: govet: disable: diff --git a/vendor/github.com/gabriel-vasile/mimetype/README.md b/vendor/github.com/gabriel-vasile/mimetype/README.md index 9fe71ac..b024316 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/README.md +++ b/vendor/github.com/gabriel-vasile/mimetype/README.md @@ -13,8 +13,8 @@ Go Reference - - Go report card + + Code coverage License @@ -103,3 +103,10 @@ shows which file formats are most often misidentified and can help prioritise. When submitting a PR for detection of a new file format, please make sure to add a record to the list of testcases in [mimetype_test.go](mimetype_test.go). For complex files a record can be added in the [testdata](testdata) directory. +Code contributions must respect following rules: + - code must be test covered + - code must be formatted using the `gofmt` tool + - exported names must be documented + +**Important**: By submitting a pull request, you agree to allow the project +owner to license your work under the same license as that used by the project. diff --git a/vendor/github.com/gabriel-vasile/mimetype/codecov.yml b/vendor/github.com/gabriel-vasile/mimetype/codecov.yml new file mode 100644 index 0000000..69cb760 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/codecov.yml @@ -0,0 +1 @@ +comment: false diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go b/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go new file mode 100644 index 0000000..926cef7 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go @@ -0,0 +1,667 @@ +// Package cdf implements parsing of CDF (OLE2) files. It is greatly inspired +// by src/readcdf.c from libmagic. One difference is this implementation is +// permissive of truncated inputs. See readLimit in mimetype.go for the +// reason why truncated inputs need to be handled. +// http://sc.openoffice.org/compdocfileformat.pdf +package cdf + +import ( + "bytes" + "encoding/binary" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +type CDFType int8 + +const ( + CDFTypeGeneric CDFType = iota + CDFTypeInstaller + CDFTypeDoc + CDFTypePpt + CDFTypeXls + CDFTypeMsg +) + +// Detect parses raw as a CDF (OLE2) compound file and returns the document type +// it contains. It returns CDFTypeGeneric for input that is not a CDF file or +// whose type cannot be narrowed down. +func Detect(raw []byte) CDFType { + if len(raw) < 512 { + return CDFTypeGeneric + } + var c cdf + if !parse(raw, &c) { + return CDFTypeGeneric + } + return c.detect() +} + +// cdf holds everything we need from a CDF file to do detection. +type cdf struct { + data []byte + secSize int + shortSecSize int + minStdStream uint32 + satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input + satEntries int // number of valid SAT entries reachable through satSecs + firstSSAT int32 + dirRaw []byte // directory stream bytes (entries are decoded on demand) + sst []byte // short-stream pool (root storage's stream) + sstBuilt bool // whether sst was already loaded (it is loaded lazily) + rootStreamFirst int32 // first sector of the root storage short-stream pool + rootStreamSize uint32 // size of the root storage short-stream pool + rootStorageUUID []byte +} + +// parse reads the entire on-disk structure required for type detection. It +// returns true on success and false if the header does not look like a CDF file. +// Truncated or partially malformed bodies are tolerated: sector reads degrade +// to whatever could be collected so detection can still succeed from partial data. +func parse(raw []byte, c *cdf) bool { + if len(raw) < 512 || binary.LittleEndian.Uint64(raw) != cdfMagic { + return false + } + secP2 := binary.LittleEndian.Uint16(raw[30:32]) + shortP2 := binary.LittleEndian.Uint16(raw[32:34]) + if secP2 > 20 || shortP2 > 20 { + return false + } + c.data = raw + c.secSize = 1 << secP2 + c.shortSecSize = 1 << shortP2 + c.minStdStream = binary.LittleEndian.Uint32(raw[56:60]) + if c.secSize < dirEntrySize { + return false + } + firstDirSec := readSecID(raw[48:52]) + c.firstSSAT = readSecID(raw[60:64]) + firstMSAT := readSecID(raw[68:72]) + nMSAT := binary.LittleEndian.Uint32(raw[72:76]) + masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]} + + c.buildSAT(masterSAT, firstMSAT, nMSAT) + c.dirRaw = c.readLong(firstDirSec, 0) + + c.rootStreamFirst = -1 + var d dirEntry + for i, n := 0, c.dirLen(); i < n; i++ { + c.dirAt(i, &d) + if d.typ != dirTypeRootStorage || d.streamFirst < 0 { + continue + } + c.rootStorageUUID = d.storageUUID[:] + // Record where the short-stream pool lives; it is loaded lazily by + // shortStream the first time a short stream is actually read. + c.rootStreamFirst = d.streamFirst + c.rootStreamSize = d.size + break + } + return true +} + +func (c *cdf) detect() CDFType { + for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} { + if t, ok := c.detectFromSummary(name); ok { + return t + } + } + var d dirEntry + for i, n := 0, c.dirLen(); i < n; i++ { + c.dirAt(i, &d) + if t, ok := lookupSection(d.nameBytes(), d.typ); ok { + return t + } + } + return CDFTypeGeneric +} + +// detectFromSummary inspects a (Doc)SummaryInformation stream and tries to +// derive a CDFType from the root-storage CLSID, the property NameOfApplication, +// and finally the names of sibling user streams. +func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) { + if c.rootStorageUUID != nil && bytes.Equal(c.rootStorageUUID, msiCLSID) { + return CDFTypeInstaller, true + } + raw, ok := c.userStream(streamName) + if !ok { + return CDFTypeGeneric, false + } + if app := summaryAppName(raw); len(app) > 0 { + if t, ok := lookupSubstring(app, app2type); ok { + return t, true + } + } + for i, n := 0, c.dirLen(); i < n; i++ { + var d dirEntry + c.dirAt(i, &d) + if d.nameLen == 0 { + continue + } + if t, ok := lookupSubstring(d.nameBytes(), name2type); ok { + return t, true + } + } + return CDFTypeGeneric, true +} + +const ( + cdfMagic uint64 = 0xE11AB1A1E011CFD0 + + dirTypeUserStorage = 1 + dirTypeUserStream = 2 + dirTypeRootStorage = 5 + + dirEntrySize = 128 + masterSATSize = 109 // first 109 SAT secids live in the file header +) + +// dirEntry is a single CDF directory record. The UTF-16LE name is pre-decoded +// into an inline ASCII buffer at parse time, avoiding a per-entry heap +// allocation while keeping comparisons trivial. CDF names are at most 32 +// UTF-16 code units, so 32 bytes always suffice. +type dirEntry struct { + name [32]byte + nameLen uint8 + typ uint8 + streamFirst int32 + size uint32 + storageUUID [16]byte +} + +// nameBytes returns the decoded ASCII name without copying. +func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] } + +func (c *cdf) ssatAt(i int32) int32 { + for sid := c.firstSSAT; sid >= 0; { + if int(sid) >= c.satLen() { + break // SAT is truncated; stop collecting + } + buf, ok := c.sector(sid) + if !ok { + break + } + lbuf := int32(len(buf) / 4) //nolint:gosec // anything divided by 4 fits int32 + if i < lbuf { + return int32(binary.LittleEndian.Uint32(buf[4*i:])) //nolint:gosec // intentional two's-complement reinterpretation of a sector id + } + i -= lbuf + sid = c.satAt(sid) + } + return -1 +} + +// shortStream returns the root storage short-stream pool, loading it on first +// use. Detection often finishes (e.g. via the root CLSID or a long-stream +// summary) without ever reading a short stream, so building this eagerly would +// be wasted work. +func (c *cdf) shortStream() []byte { + if !c.sstBuilt { + c.sstBuilt = true + if c.rootStreamFirst >= 0 { + c.sst = c.readLong(c.rootStreamFirst, c.rootStreamSize) + } + } + return c.sst +} + +// int32s works like a slice of LE int32 and is backed by a slice of bytes. +// int32s could very well be type int32s []byte, but that would mean +// len function can be called on it. We don't want that, we always want to use +// the len method. +type int32s struct { + b []byte +} + +func (b int32s) at(i int) int32 { + //nolint:gosec // intentional two's-complement reinterpretation of a sector id + return int32(binary.LittleEndian.Uint32(b.b[4*i:])) +} +func (b int32s) len() int { + return len(b.b) / 4 +} + +// readSecID reinterprets four little-endian bytes as a signed sector id. +// Every 32-bit pattern is a valid id (values >= 0 are sector numbers, +// negatives are CDF sentinels such as -2 end-of-chain), so the conversion is +// an intentional two's-complement reinterpretation rather than an overflow. +func readSecID(b []byte) int32 { + return int32(binary.LittleEndian.Uint32(b)) //nolint:gosec // intentional two's-complement reinterpretation +} + +// satLen is the number of sector ids reachable through the SAT. +func (c *cdf) satLen() int { return c.satEntries } + +// satAt returns the i-th sector id from the SAT. Callers must ensure +// i < satLen(). The SAT is not materialized; the entry is fetched directly +// from the input by translating i into (SAT sector index, entry offset). +func (c *cdf) satAt(i int32) int32 { + perSec := c.secSize / 4 + secIdx := int(i) / perSec + entryIdx := int(i) % perSec + secID := c.satSecs.at(secIdx) + off := c.secSize*(1+int(secID)) + 4*entryIdx + return readSecID(c.data[off:]) +} + +// sector returns the bytes of long sector secid. If the file is truncated +// inside the requested sector the result is the available bytes (no padding). +// If the sector starts past EOF or secid is negative, then ok is false. +func (c *cdf) sector(secid int32) (_ []byte, ok bool) { + if secid < 0 { + return nil, false + } + off := int64(c.secSize) * (1 + int64(secid)) + if off >= int64(len(c.data)) { + return nil, false + } + // The returned sector might be truncated, + // but we still return it as best effort. + end := min(off+int64(c.secSize), int64(len(c.data))) + // If not even one int32 fits, then fail. + if end-off < 4 { + return nil, false + } + return c.data[off:end], true +} + +func (c *cdf) sectorIDs(secid int32) (int32s, bool) { + buf, ok := c.sector(secid) + if !ok { + return int32s{}, ok + } + return int32s{b: buf}, true +} + +// buildSAT records the list of SAT sector ids from the master-SAT (header) +// plus any extension blocks chained via firstMSAT. The SAT itself is not +// materialized: satAt computes the requested entry directly from c.data via +// satSecs. In the common case (no extension chain) satSecs is a zero-copy +// sub-slice of the input header. +func (c *cdf) buildSAT(masterSAT int32s, firstMSAT int32, nMSAT uint32) { + // Fast path: no extension chain. masterSAT is already a sub-slice of raw + // input; reuse it directly. + if firstMSAT < 0 || nMSAT == 0 { + c.satSecs = masterSAT + c.satEntries = c.computeSATLen() + return + } + + // Slow path: gather sector ids from the header plus the extension chain + // into a fresh buffer. Even here we only allocate space for ids (4 bytes + // each), not the full SAT contents. + maxIDs := len(c.data)/c.secSize + 1 + buf := make([]byte, 0, 4*masterSATSize) + for i := 0; i < masterSAT.len(); i++ { + if masterSAT.at(i) < 0 { + break + } + buf = append(buf, masterSAT.b[4*i:4*i+4]...) + } + perSec := c.secSize/4 - 1 + mid := firstMSAT +chain: + for j := uint32(0); j < nMSAT && mid >= 0; j++ { + msa, ok := c.sectorIDs(mid) + if !ok { + break + } + for k := 0; k < perSec; k++ { + if k >= msa.len() || msa.at(k) < 0 { + break chain + } + buf = append(buf, msa.b[4*k:4*k+4]...) + if len(buf)/4 > maxIDs { + break chain // cyclic MSAT chain; stop allocating + } + } + if perSec >= msa.len() { + break // no next-MSAT pointer available + } + mid = msa.at(perSec) + } + c.satSecs = int32s{b: buf} + c.satEntries = c.computeSATLen() +} + +// computeSATLen walks satSecs and counts how many SAT entries are actually +// reachable in c.data, stopping at the first sentinel id or sector that is not +// fully present in the file. +func (c *cdf) computeSATLen() int { + perSec := c.secSize / 4 + total := 0 + for i := 0; i < c.satSecs.len(); i++ { + sec := c.satSecs.at(i) + if sec < 0 { + break + } + off := int64(c.secSize) * (1 + int64(sec)) + if off >= int64(len(c.data)) { + break + } + avail := int64(len(c.data)) - off + if avail >= int64(c.secSize) { + total += perSec + continue + } + total += int(avail / 4) + break + } + return total +} + +// readLong reads a long-sector chain starting at sid. If length > 0 the +// result is truncated to that many bytes. On truncation or any other failure +// it returns whatever sectors were readable. +func (c *cdf) readLong(sid int32, length uint32) []byte { + // Fast path: when the chain is a single physically contiguous run of + // sectors (the common case for the directory and summary streams) the data + // is already laid out sequentially in the input, so return a sub-slice of + // it instead of allocating a buffer and copying every sector. + if sid >= 0 { + maxSec := len(c.data)/c.secSize + 1 + n, s := 0, sid + contiguous := true + for s >= 0 { + if int(s) >= c.satLen() { + break // SAT truncated; what remains is still contiguous + } + n++ + if n > maxSec { + contiguous = false // cyclic chain; let the slow path guard it + break + } + next := c.satAt(s) + if next >= 0 && int64(next) != int64(s)+1 { + contiguous = false + break + } + s = next + } + if contiguous { + off64 := int64(c.secSize) * (1 + int64(sid)) + if off64 >= int64(len(c.data)) { + return nil + } + end64 := min(off64+int64(n)*int64(c.secSize), int64(len(c.data))) + out := c.data[off64:end64] + if length > 0 && int64(length) < int64(len(out)) { + out = out[:length] + } + return out + } + } + + // Slow path: gather a fragmented chain into a fresh buffer. Real-world + // writers (MSI builders, edited Office documents) routinely produce + // non-contiguous directory and stream chains, so this fallback is required + // for correct detection on those files. + maxBytes := len(c.data) + out := make([]byte, 0, c.secSize) + for sid >= 0 { + if int(sid) >= c.satLen() { + break // SAT truncated; return what we have + } + buf, ok := c.sector(sid) + if !ok { + break + } + out = append(out, buf...) + if len(out) >= maxBytes { + break // chain longer than the file: cyclic SAT, stop + } + sid = c.satAt(sid) + } + if length > 0 && int64(length) < int64(len(out)) { + out = out[:length] + } + return out +} + +// readShort reads a short-sector chain at sid by indexing into the short-stream +// pool. On truncation or if the pool is unavailable it returns whatever was +// readable (possibly nil). +func (c *cdf) readShort(sid int32, length uint32) []byte { + sst := c.shortStream() + if sst == nil { + return nil + } + // TODO: anyway to avoid allocating and copying the bytes? + out := make([]byte, 0, c.shortSecSize) + for sid >= 0 { + off64 := int64(sid) * int64(c.shortSecSize) + if off64+int64(c.shortSecSize) > int64(len(sst)) { + break // short-stream pool truncated or sid out of range + } + off := int(off64) + out = append(out, sst[off:off+c.shortSecSize]...) + if len(out) >= len(sst) { + break // chain longer than the pool: cyclic SSAT, stop + } + sid = c.ssatAt(sid) + } + if length > 0 && int64(length) < int64(len(out)) { + out = out[:length] + } + return out +} + +// readChain dispatches to the long or short reader depending on stream size. +func (c *cdf) readChain(sid int32, length uint32) []byte { + if length < c.minStdStream && c.rootStreamFirst >= 0 { + return c.readShort(sid, length) + } + return c.readLong(sid, length) +} + +// dirLen returns the number of directory entries in dirRaw. +func (c *cdf) dirLen() int { return len(c.dirRaw) / dirEntrySize } + +// dirAt decodes the i-th directory entry into *out. Callers must ensure +// i < dirLen(). The UTF-16LE name is decoded into out.name, ASCII-style, +// stopping at the first NUL. +func (c *cdf) dirAt(i int, out *dirEntry) { + raw := c.dirRaw[i*dirEntrySize:] + nameLen := min(int(binary.LittleEndian.Uint16(raw[64:])), 64) + k := uint8(0) + for j := 0; j < nameLen/2; j++ { + // Names are ASCII; keep the low byte of each little-endian UTF-16 + // code unit and stop at the first NUL. + lo, hi := raw[2*j], raw[2*j+1] + if lo == 0 && hi == 0 { + break + } + out.name[k] = lo + k++ + } + out.nameLen = k + out.typ = raw[66] + out.streamFirst = readSecID(raw[116:120]) + out.size = binary.LittleEndian.Uint32(raw[120:]) + copy(out.storageUUID[:], raw[80:96]) +} + +// userStream finds a user stream by name and returns its bytes. +func (c *cdf) userStream(name string) ([]byte, bool) { + var d dirEntry + for i, n := 0, c.dirLen(); i < n; i++ { + c.dirAt(i, &d) + if d.typ == dirTypeUserStream && string(d.nameBytes()) == name { + buf := c.readChain(d.streamFirst, d.size) + if buf == nil { + return nil, false + } + return buf, true + } + } + return nil, false +} + +const ( + propIDNameOfApplication = 0x12 + + typeMask = 0x0fff + typeVector = 0x1000 + typeStringASCII = 0x1e + typeStringWide = 0x1f + + sectionDeclOffset = 0x1c // section declaration in property-set header +) + +// summaryAppName parses a (Doc)SummaryInformation stream and returns the +// value of property NameOfApplication (0x12) as printable ASCII, or nil if +// not present or the stream is malformed. This is the only summary property +// the detection logic ever consults. +func summaryAppName(stream []byte) []byte { + if len(stream) < sectionDeclOffset+20 { + return nil + } + sdOff := binary.LittleEndian.Uint32(stream[sectionDeclOffset+16:]) + if uint64(sdOff)+8 > uint64(len(stream)) { + return nil + } + section := stream[sdOff:] + shLen := binary.LittleEndian.Uint32(section[0:]) + nProps := binary.LittleEndian.Uint32(section[4:]) + if uint64(shLen) > uint64(len(section)) || nProps > 1<<16 || 8+8*nProps > shLen { + return nil + } + for i := uint32(0); i < nProps; i++ { + base := 8 + 8*i + id := binary.LittleEndian.Uint32(section[base:]) + if id != propIDNameOfApplication { + continue + } + off := binary.LittleEndian.Uint32(section[base+4:]) + if uint64(off)+8 > uint64(shLen) { + return nil + } + typ := binary.LittleEndian.Uint32(section[off:]) + if typ&typeVector != 0 { + return nil + } + step := uint32(0) + switch typ & typeMask { + case typeStringASCII: + step = 1 + case typeStringWide: + step = 2 + default: + return nil + } + slen := binary.LittleEndian.Uint32(section[off+4:]) + start := uint64(off) + 8 + end := start + uint64(slen)*uint64(step) + if end > uint64(shLen) { + return nil + } + return printableLowBytes(section[start:end], int(step)) + } + return nil +} + +// printableLowBytes copies the printable low byte of each step-byte unit +// in b, stopping at the first NUL. +func printableLowBytes(b []byte, step int) []byte { + out := make([]byte, 0, len(b)/step) + for i := 0; i+step <= len(b); i += step { + c := b[i] + if c == 0 { + break + } + if c >= 0x20 && c < 0x7f { + out = append(out, c) + } + } + return out +} + +// pattern is a case-insensitive substring → CDFType mapping. Entries are +// tested in order; first match wins. needle is stored upper-cased so it can be +// matched case-insensitively by scan.Bytes.Search with scan.IgnoreCase. +type pattern struct { + needle []byte + typ CDFType +} + +// app2type maps NameOfApplication values to CDFTypes. +// Mirrors app2mime[] in libmagic. Needles are upper-cased for case-insensitive +// matching via scan.IgnoreCase. +var app2type = []pattern{ + {[]byte("WORD"), CDFTypeDoc}, + {[]byte("EXCEL"), CDFTypeXls}, + {[]byte("POWERPOINT"), CDFTypePpt}, + {[]byte("ADVANCED INSTALLER"), CDFTypeInstaller}, + {[]byte("INSTALLSHIELD"), CDFTypeInstaller}, + {[]byte("MICROSOFT PATCH COMPILER"), CDFTypeInstaller}, + {[]byte("NANT"), CDFTypeInstaller}, + {[]byte("WINDOWS INSTALLER"), CDFTypeInstaller}, +} + +// name2type maps directory entry names to CDFTypes. +// Mirrors name2mime[] in libmagic. Needles are upper-cased for case-insensitive +// matching via scan.IgnoreCase. +var name2type = []pattern{ + {[]byte("BOOK"), CDFTypeXls}, + {[]byte("WORKBOOK"), CDFTypeXls}, + {[]byte("WORDDOCUMENT"), CDFTypeDoc}, + {[]byte("POWERPOINT"), CDFTypePpt}, + {[]byte("DIGITALSIGNATURE"), CDFTypeInstaller}, +} + +// lookupSubstring returns the CDFType for the first entry in t whose needle +// is a case-insensitive substring of v. Mirrors C's strcasestr semantics +// under the C locale. It allocates nothing: scan.IgnoreCase matches the +// upper-cased needle against input of either case. +func lookupSubstring(v []byte, t []pattern) (CDFType, bool) { + s := scan.Bytes(v) + for _, p := range t { + if i, _ := s.Search(p.needle, scan.IgnoreCase); i != -1 { + return p.typ, true + } + } + return CDFTypeGeneric, false +} + +// msiCLSID is the Microsoft Installer root-storage CLSID, in on-disk byte +// order (cdf_directory_t.d_storage_uuid stores two little-endian uint64s). +var msiCLSID = []byte{ + 0x84, 0x10, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, +} + +// section is a (directory entry name, type) → CDFType mapping. +type section struct { + name string + typ uint8 + cdf CDFType +} + +// sectionTypes maps distinctive directory entries to CDFTypes — a flattened +// equivalent of sectioninfo[] in libmagic. Used as a fallback when no +// SummaryInformation stream is present. A slice (rather than a map) lets +// lookupSection compare entry names without allocating a string key. +var sectionTypes = []section{ + // libmagic uses application/encrypted, but that is not a registered media type. + // For now, we skip identifying that and fall-back on CDFTypeGeneric + // {"EncryptedPackage", dirTypeUserStream, CDFTypeEncrypted}, + // {"EncryptedSummary", dirTypeUserStream, CDFTypeEncrypted}, + {"Book", dirTypeUserStream, CDFTypeXls}, + {"Workbook", dirTypeUserStream, CDFTypeXls}, + {"WordDocument", dirTypeUserStream, CDFTypeDoc}, + {"PowerPoint Document", dirTypeUserStream, CDFTypePpt}, + {"__properties_version1.0", dirTypeUserStream, CDFTypeMsg}, + {"__recip_version1.0_#00000000", dirTypeUserStorage, CDFTypeMsg}, +} + +// lookupSection returns the CDFType for a directory entry whose name and type +// match a sectionTypes entry exactly. The string(name) == comparison is +// optimized by the compiler to avoid allocating. +func lookupSection(name []byte, typ uint8) (CDFType, bool) { + for _, s := range sectionTypes { + if s.typ == typ && string(name) == s.name { + return s.cdf, true + } + } + return CDFTypeGeneric, false +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go b/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go index 3373274..d17e629 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go @@ -84,19 +84,8 @@ func FromPlain(content []byte) string { break } } - hasHighBit := false - for _, c := range content { - if c >= 0x80 { - hasHighBit = true - break - } - } - if hasHighBit && utf8.Valid(content) { - return "utf-8" - } - // ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8. - if ascii(origContent) { + if utf8.Valid(content) { return "utf-8" } @@ -123,15 +112,6 @@ func latin(content []byte) string { return "iso-8859-1" } -func ascii(content []byte) bool { - for _, b := range content { - if textChars[b] != T { - return false - } - } - return true -} - // FromXML returns the charset of an XML document. It relies on the XML // header and falls back on the plain // text content. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/csv/parser.go b/vendor/github.com/gabriel-vasile/mimetype/internal/csv/parser.go index 87ff697..0cd797e 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/csv/parser.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/csv/parser.go @@ -12,10 +12,10 @@ import ( type Parser struct { comma byte comment byte - s scan.Bytes + s *scan.Bytes } -func NewParser(comma, comment byte, s scan.Bytes) *Parser { +func NewParser(comma, comment byte, s *scan.Bytes) *Parser { return &Parser{ comma: comma, comment: comment, @@ -55,7 +55,7 @@ func (r *Parser) CountFields(collectIndexes bool) (fields int, fieldPos []int, h if finished { return 0, nil, false } - finished = len(r.s) == 0 && len(line) == 0 + finished = len(*r.s) == 0 && len(line) == 0 if len(line) == lengthNL(line) { line = nil continue // Skip empty lines. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go b/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go index 570889b..a1c6912 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go @@ -10,6 +10,7 @@ const ( QueryGeo = "geo" QueryHAR = "har" QueryGLTF = "gltf" + QueryCDX = "cdx" maxRecursion = 4096 ) @@ -40,6 +41,10 @@ var queries = map[string][]query{ SearchPath: [][]byte{[]byte("asset"), []byte("version")}, SearchVals: [][]byte{[]byte(`"1.0"`), []byte(`"2.0"`)}, }}, + QueryCDX: {{ + SearchPath: [][]byte{[]byte("bomFormat")}, + SearchVals: [][]byte{[]byte(`"CycloneDX"`)}, + }}, } var parserPool = sync.Pool{ diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go index a285001..ad48d8f 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go @@ -3,6 +3,8 @@ package magic import ( "bytes" "encoding/binary" + + "github.com/gabriel-vasile/mimetype/internal/mp3" ) // Flac matches a Free Lossless Audio Codec file. @@ -51,32 +53,83 @@ func AAC(raw []byte, _ uint32) bool { return len(raw) > 1 && ((raw[0] == 0xFF && raw[1] == 0xF1) || (raw[0] == 0xFF && raw[1] == 0xF9)) } -// Mp3 matches an mp3 file. -func Mp3(raw []byte, limit uint32) bool { +// MP3 matches a .mp3 file. +func MP3(raw []byte, limit uint32) bool { if len(raw) < 3 { return false } - if bytes.HasPrefix(raw, []byte("ID3")) { - // MP3s with an ID3v2 tag will start with "ID3" - // ID3v1 tags, however appear at the end of the file. + // Any ID3v2 is reported as MP3. Not entirely correct, but the mimesniff + // standard says so. https://mimesniff.spec.whatwg.org/#matching-an-audio-or-video-type-pattern + // Despite the standard only checking for "ID3", we do more validations to + // avoid false positives. + if id3v2(raw) { return true } - // Match MP3 files without tags + // If no ID3v2 tag found, then we will look for MP3 frames, but: + // a. Layer III files are a lot more prevalent than Layer I and II. + // b. Layer I frame header has looser constraints than the others: many files + // with regularly repeating 0xFFFF bytes can be misidentified as MP3. + // c. MP3 files are composed of individual frames and those frames can have + // leading garbage bytes: if we want to find all valid MP3s, we have to do a + // linear search. #775, #310 + // d. There are file formats that contain MP3s inside: .mo3 and .swa + // + // Given a, b, c and d, this code: + // - initially tries to match by first two bytes in header + // - checks for .mo3 and .swa and disqualifies them + // - does linear search for Layer III switch binary.BigEndian.Uint16(raw[:2]) & 0xFFFE { - case 0xFFFA: - // MPEG ADTS, layer III, v1 - return true - case 0xFFF2: - // MPEG ADTS, layer III, v2 - return true - case 0xFFE2: - // MPEG ADTS, layer III, v2.5 + case 0xFFFA, 0xFFF2, 0xFFE2, // layer III: v1, v2, v2.5 + 0xFFFC, 0xFFF4, // layer II: v1, v2 + 0xFFF5: // layer I: v2 return true } + // http://lclevy.free.fr/mo3/ + if bytes.HasPrefix(raw, []byte("MO3")) { + return false + } - return false + // From PRONOM: + // Macromedia licensed the MP3 technology in 1995 to use in their Shockwave + // product. .swa or Shockwave Audio was originally added as a free plugin + // (Xtras) to SoundEdit 16 to export AIFF files to .swa. + // There is no media type assigned for .swa. + if bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00}) { + return false + } + + _, size := mp3.ExtractFrame(raw) + return size > 0 +} + +// Based on https://id3.org/Developer%20Information. +func id3v2(raw []byte) bool { + if len(raw) < 10 || !bytes.HasPrefix(raw, []byte("ID3")) { + return false + } + if raw[3] < 2 || raw[3] > 4 { // Version: ID3v2.2 - ID3v2.4. + return false + } + if raw[4] != 0 { // Revision is 0 for all versions. + return false + } + + // v2.2 uses 2 bits, v2.3 uses 3 bits and v2.4 uses 4. + // For all versions least significant 4 bits should be 0 + if raw[5]&0b1111 != 0 { + return false + } + + // Size bytes are synchsafe: most significant bit always 0. + if raw[6]&0x80 != 0 || raw[7]&0x80 != 0 || raw[8]&0x80 != 0 || raw[9]&0x80 != 0 { + return false + } + + size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9]) + // Disallow too big frames, let's say 10MB. + return size > 0 && size < 10*1024*1024 } // Wav matches a Waveform Audio File Format file. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go index 37ad6a9..d217968 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go @@ -4,6 +4,7 @@ import ( "bytes" "debug/macho" "encoding/binary" + "slices" ) // Lnk matches Microsoft lnk binary format. @@ -117,13 +118,7 @@ func Dbf(raw []byte, limit uint32) bool { 0x02, 0x03, 0x04, 0x05, 0x30, 0x31, 0x32, 0x42, 0x62, 0x7B, 0x82, 0x83, 0x87, 0x8A, 0x8B, 0x8E, 0xB3, 0xCB, 0xE5, 0xF5, 0xF4, 0xFB, } - for _, b := range dbfTypes { - if raw[0] == b { - return true - } - } - - return false + return slices.Contains(dbfTypes, raw[0]) } // ElfObj matches an object file. @@ -229,3 +224,63 @@ func TzIf(raw []byte, limit uint32) bool { // Version has to be NUL (0x00), '2' (0x32) or '3' (0x33). return raw[4] == 0x00 || raw[4] == 0x32 || raw[4] == 0x33 } + +// Pyc matches a Python compiled file. +// The signatures are sourced from libmagic v5.47 +func Pyc(raw []byte, limit uint32) bool { + if len(raw) < 8 { + return false + } + + // python 1.0 through 3.7 signatures, magic/Magdir/python:13:190 + pycMagic := []uint32{ + 0x02099900, 0x03099900, 0x892e0d0a, 0x04170d0a, 0x994e0d0a, 0xfcc40d0a, + 0xfdc40d0a, 0x87c60d0a, 0x88c60d0a, 0x2aeb0d0a, 0x2beb0d0a, 0x2ded0d0a, + 0x2eed0d0a, 0x3bf20d0a, 0x3cf20d0a, 0x45f20d0a, 0x59f20d0a, 0x63f20d0a, + 0x6df20d0a, 0x6ef20d0a, 0x77f20d0a, 0x81f20d0a, 0x8bf20d0a, 0x8cf20d0a, + 0x95f20d0a, 0x9ff20d0a, 0xa9f20d0a, 0xb3f20d0a, 0xb4f20d0a, 0xc7f20d0a, + 0xd1f20d0a, 0xd2f20d0a, 0xdbf20d0a, 0xe5f20d0a, 0xeff20d0a, 0xf9f20d0a, + 0x03f30d0a, 0x04f30d0a, 0x0af30d0a, 0xb80b0d0a, 0xc20b0d0a, 0xcc0b0d0a, + 0xd60b0d0a, 0xe00b0d0a, 0xea0b0d0a, 0xf40b0d0a, 0xf50b0d0a, 0xff0b0d0a, + 0x090c0d0a, 0x130c0d0a, 0x1d0c0d0a, 0x1f0c0d0a, 0x270c0d0a, 0x3b0c0d0a, + 0x450c0d0a, 0x4f0c0d0a, 0x580c0d0a, 0x620c0d0a, 0x6c0c0d0a, 0x760c0d0a, + 0x800c0d0a, 0x8a0c0d0a, 0x940c0d0a, 0x9e0c0d0a, 0xb20c0d0a, 0xbc0c0d0a, + 0xc60c0d0a, 0xd00c0d0a, 0xda0c0d0a, 0xe40c0d0a, 0xee0c0d0a, 0xf80c0d0a, + 0x020d0d0a, 0x0c0d0d0a, 0x160d0d0a, 0x170d0d0a, 0x200d0d0a, 0x210d0d0a, + 0x2a0d0d0a, 0x2b0d0d0a, 0x2c0d0d0a, 0x2d0d0d0a, 0x2f0d0d0a, 0x300d0d0a, + 0x310d0d0a, 0x320d0d0a, 0x330d0d0a, 0x3e0d0d0a, 0x3f0d0d0a, + } + + n := binary.BigEndian.Uint32(raw) + + if slices.Contains(pycMagic, n) { + return true + } + + if raw[2] == 0x0d && raw[3] == 0x0a { + // Only two bits of flag field are currently used. + if l := binary.LittleEndian.Uint32(raw[4:]); l > 3 { + return false + } + if raw[1] == 0x0d || raw[1] == 0x0e { + return true + } + // PyPy magic numbers, magic/Magdir/python:233 + n := binary.LittleEndian.Uint16(raw) + return n == 240 || n == 256 || n == 336 || n == 384 || n == 416 + } + + return false +} + +// Pcap identifies "libpcap" capture files. +// https://www.tcpdump.org/manpages/pcap-savefile.5.html +func Pcap(raw []byte, _ uint32) bool { + if len(raw) < 4 { + return false + } + be := binary.BigEndian.Uint32(raw) + le := binary.LittleEndian.Uint32(raw) + return be == 0xa1b2c3d4 || be == 0xa1b23c4d || + le == 0xa1b2c3d4 || le == 0xa1b23c4d +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/font.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/font.go index e1dda7c..9a76d53 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/font.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/font.go @@ -3,6 +3,7 @@ package magic import ( "bytes" "encoding/binary" + "slices" ) // Woff matches a Web Open Font Format file. @@ -29,12 +30,13 @@ func Ttf(raw []byte, limit uint32) bool { if !bytes.HasPrefix(raw, []byte{0x00, 0x01, 0x00, 0x00}) { return false } + // We cannot rely on the first 4 bytes because of false-positives. + // We have to digg deeper into the SFNT tables. return hasSFNTTable(raw) } func hasSFNTTable(raw []byte) bool { - // 49 possible tables as explained below - if len(raw) < 16 || binary.BigEndian.Uint16(raw[4:]) >= 49 { + if len(raw) < 16 { return false } @@ -87,14 +89,45 @@ func hasSFNTTable(raw []byte) bool { 0x6e616d65, // "name" 0x6f706264, // "opbd" 0x4f532f32, // "OS/2" + // The above tables come from the original Apple TTF specification, + // but the later Microsoft specification has additional tables. + // Common tables: https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats + // Layout tables: https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2 + // Even if the Microsoft specification says OpenType, the tables are + // valid for TrueType as well. + 0x47535542, // "GSUB" + 0x47504f53, // "GPOS" + 0x42415345, // "BASE" + 0x4a535446, // "JSTF" + 0x47444546, // "GDEF" + 0x4d415448, // "MATH" + 0x43424454, // "CBDT" + 0x43424c43, // "CBLC" + 0x43464620, // "CFF " + 0x43464632, // "CFF2" + 0x434f4c52, // "COLR" + 0x4350414c, // "CPAL" + 0x44534947, // "DSIG" + 0x45424454, // "EBDT" + 0x45424c43, // "EBLC" + 0x48564152, // "HVAR" + 0x4c545348, // "LTSH" + 0x4d455247, // "MERG" + 0x4d564152, // "MVAR" + 0x50434c54, // "PCLT" + 0x706f7374, // "post" + 0x70726570, // "prep" + 0x73626978, // "sbix" + 0x53544154, // "STAT" + 0x53564720, // "SVG " + 0x56444d58, // "VDMX" + 0x76686561, // "vhea" + 0x766d7478, // "vmtx" + 0x564f5247, // "VORG" + 0x56564152, // "VVAR" } ourTable := binary.BigEndian.Uint32(raw[12:16]) - for _, t := range possibleTables { - if ourTable == t { - return true - } - } - return false + return slices.Contains(possibleTables, ourTable) } // Eot matches an Embedded OpenType font file. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go index cade91f..6cd479c 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go @@ -3,6 +3,7 @@ package magic import ( "bytes" "encoding/binary" + "slices" ) // Shp matches a shape format file. @@ -39,13 +40,7 @@ func Shp(raw []byte, limit uint32) bool { 31, // MultiPatch } - for _, st := range shapeTypes { - if st == int(binary.LittleEndian.Uint32(raw[108:112])) { - return true - } - } - - return false + return slices.Contains(shapeTypes, int(binary.LittleEndian.Uint32(raw[108:112]))) } // Shx matches a shape index format file. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go index 3a86858..d46faca 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go @@ -4,6 +4,8 @@ import ( "bytes" "encoding/binary" "slices" + + "github.com/gabriel-vasile/mimetype/internal/scan" ) // Png matches a Portable Network Graphics file. @@ -15,7 +17,31 @@ func Png(raw []byte, _ uint32) bool { // Apng matches an Animated Portable Network Graphics file. // https://wiki.mozilla.org/APNG_Specification func Apng(raw []byte, _ uint32) bool { - return offset(raw, []byte("acTL"), 37) + b := scan.Bytes(raw) + b.Advance(8) // the first 8 bytes matched by regular png + + // PNG chunks are composed of: + // 4 bytes: length in big endian + // 4 bytes: chunk type + // length bytes: chunk data + // 4 bytes: CRC + // + // Limit to 32, so we don't waste time on huge inputs. + // acTL chunk must come before any IDAT chunks. + // https://www.w3.org/TR/png-3/#structure + for i := 0; i < 32 && len(b) > 0; i++ { + sz, _ := b.Uint32be() + if bytes.HasPrefix(b, []byte("acTL")) { + return true + } + if bytes.HasPrefix(b, []byte("IDAT")) { + return false + } + if !b.Advance(int(sz + 8)) { + return false + } + } + return false } // Jpg matches a Joint Photographic Experts Group file. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go index 6103c12..f078ff3 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go @@ -136,6 +136,11 @@ func ftyp(raw []byte, sigs ...[]byte) bool { return false } +type shebangSig struct { + sig []byte + flag scan.Flags +} + // A valid shebang starts with the "#!" characters, // followed by any number of spaces, // followed by the path to the interpreter, @@ -146,7 +151,7 @@ func ftyp(raw []byte, sigs ...[]byte) bool { // #! /usr/bin/env php // // /usr/bin/env is the interpreter, php is the first and only argument. -func shebang(b scan.Bytes, matchFlags scan.Flags, sigs ...[]byte) bool { +func shebang(b scan.Bytes, sigs ...shebangSig) bool { line := b.Line() if len(line) < 2 || line[0] != '#' || line[1] != '!' { return false @@ -154,7 +159,7 @@ func shebang(b scan.Bytes, matchFlags scan.Flags, sigs ...[]byte) bool { line = line[2:] line.TrimLWS() for _, s := range sigs { - if line.Match(s, matchFlags) != -1 { + if line.Match(s.sig, s.flag) != -1 { return true } } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go index e689e92..62cced0 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go @@ -3,6 +3,8 @@ package magic import ( "bytes" "encoding/binary" + + "github.com/gabriel-vasile/mimetype/internal/cdf" ) // Xlsx matches a Microsoft Excel 2007 file. @@ -47,6 +49,15 @@ func Ole(raw []byte, limit uint32) bool { // Doc matches a Microsoft Word 97-2003 file. // See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py func Doc(raw []byte, _ uint32) bool { + fromParsing := cdf.Detect(raw) + if fromParsing == cdf.CDFTypeDoc { + return true + } + if fromParsing != cdf.CDFTypeGeneric { + return false + } + // Fallback for inputs where the CDF directory is past the read limit: match + // the root storage CLSID, which often lies within the first sectors. clsids := [][]byte{ // Microsoft Word 97-2003 Document (Word.Document.8) {0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, @@ -55,19 +66,25 @@ func Doc(raw []byte, _ uint32) bool { // Microsoft Word Picture (Word.Picture.8) {0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, } - for _, clsid := range clsids { if matchOleClsid(raw, clsid) { return true } } - return false } // Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation. func Ppt(raw []byte, limit uint32) bool { - // Root CLSID test is the safest way to detect identify OLE, however, the format + fromParsing := cdf.Detect(raw) + if fromParsing == cdf.CDFTypePpt { + return true + } + if fromParsing != cdf.CDFTypeGeneric { + return false + } + // Fallback for inputs where the CDF directory is past the read limit. + // Root CLSID test is the safest way to identify the OLE, however, the format // often places the root CLSID at the end of the file. if matchOleClsid(raw, []byte{ 0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11, @@ -94,18 +111,21 @@ func Ppt(raw []byte, limit uint32) bool { } } - if bytes.HasPrefix(raw[512:], []byte{0xFD, 0xFF, 0xFF, 0xFF}) && - raw[518] == 0x00 && raw[519] == 0x00 { - return true - } - return lin > 1152 && bytes.Contains(raw[1152:min(4096, lin)], []byte("P\x00o\x00w\x00e\x00r\x00P\x00o\x00i\x00n\x00t\x00 D\x00o\x00c\x00u\x00m\x00e\x00n\x00t")) } // Xls matches a Microsoft Excel 97-2003 file. func Xls(raw []byte, limit uint32) bool { - // Root CLSID test is the safest way to detect identify OLE, however, the format + fromParsing := cdf.Detect(raw) + if fromParsing == cdf.CDFTypeXls { + return true + } + if fromParsing != cdf.CDFTypeGeneric { + return false + } + // Fallback for inputs where the CDF directory is past the read limit. + // Root CLSID test is the safest way to identify the OLE, however, the format // often places the root CLSID at the end of the file. if matchOleClsid(raw, []byte{ 0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -148,6 +168,15 @@ func Pub(raw []byte, limit uint32) bool { // Msg matches a Microsoft Outlook email file. func Msg(raw []byte, limit uint32) bool { + fromParsing := cdf.Detect(raw) + if fromParsing == cdf.CDFTypeMsg { + return true + } + if fromParsing != cdf.CDFTypeGeneric { + return false + } + // Fallback for inputs where the CDF directory does not carry the streams the + // parser keys on: match the root storage CLSID instead. return matchOleClsid(raw, []byte{ 0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, @@ -157,10 +186,7 @@ func Msg(raw []byte, limit uint32) bool { // Msi matches a Microsoft Windows Installer file. // http://fileformats.archiveteam.org/wiki/Microsoft_Compound_File func Msi(raw []byte, limit uint32) bool { - return matchOleClsid(raw, []byte{ - 0x84, 0x10, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, - }) + return cdf.Detect(raw) == cdf.CDFTypeInstaller } // One matches a Microsoft OneNote file. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go index 3fa6711..d36dc3c 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go @@ -130,6 +130,14 @@ func Xfdf(raw []byte, _ uint32) bool { return xml(raw, xmlSig{[]byte(" 0 && uint64(len(in)) >= uint64(limit) + if maybeTruncated && fields < headerFields { + // Allow the last row to have any number of fields + // if the input is maybeTruncated. + // BUG: if len(input) == limit, then the input is not truncated + // but it is still allowed to have the wrong number of fields + // and it will be reported as valid CSV. + if len(s) == 0 { + break + } + } return false } if csvLines >= 10 { diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go index 23e30da..a730a24 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go @@ -49,10 +49,8 @@ func isMatroskaFileTypeMatched(in []byte, flType string) bool { // The logic of search is: find first instance of \x42\x82 and then // search for given string after n bytes of above instance. func isFileTypeNamePresent(in []byte, flType string) bool { - ind, maxInd, lenIn := 0, 4096, len(in) - if lenIn < maxInd { // restricting length to 4096 - maxInd = lenIn - } + ind, lenIn := 0, len(in) + maxInd := min(4096, lenIn) ind = bytes.Index(in[:maxInd], []byte("\x42\x82")) if ind > 0 && lenIn > ind+2 { ind += 2 diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go index f3bfa2a..9b2611b 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go @@ -187,11 +187,11 @@ func msoxml(raw scan.Bytes, searchFor zipEntries, stopAfter int) bool { return false } +var zipLocalFileHeader = []byte("PK\003\004") + // next extracts the name of the next zip entry. func (i *zipIterator) next() []byte { - pk := []byte("PK\003\004") - - n := bytes.Index(i.b, pk) + n := bytes.Index(i.b, zipLocalFileHeader) if n == -1 { return nil } @@ -212,10 +212,85 @@ func (i *zipIterator) next() []byte { return i.b[:l] } +// skipZipflingerEntry tries to detect a Zipflinger virtual entry and skips it. +// The detection is based on the following properties: +// - compression method is 0 +// - CRC32 is 0 +// - compressed size is 0 +// - uncompressed size is 0 +// - file name is empty +// Returns true if it was found and skipped. +func (i *zipIterator) skipZipflingerEntry() (skipped bool) { + // Make a backup of the data so the inspection does not loses it. + b := i.b + defer func() { + // If no zipflinger was found, restore the original data. + if !skipped { + i.b = b + } + }() + + n := bytes.Index(i.b, zipLocalFileHeader) + if n == -1 { + return false + } + if !i.b.Advance(0x08) { + return false + } + + // Check compression method + if cm, ok := i.b.Uint16(); !ok || cm != 0 { + return false + } + + // Advance up to the CRC32 field + if !i.b.Advance(0x04) { + return false + } + + // Check CRC32 + if crc32, ok := i.b.Uint32(); !ok || crc32 != 0 { + return false + } + + // Check compressed size + if compressedSize, ok := i.b.Uint32(); !ok || compressedSize != 0 { + return false + } + + // Check uncompressed size + if uncompressedSize, ok := i.b.Uint32(); !ok || uncompressedSize != 0 { + return false + } + + // Check for empty file name + if l, ok := i.b.Uint16(); !ok || l != 0 { + return false + } + + // Reached a zipflinger virtual entry: skip extra data + l, ok := i.b.Uint16() + if !ok { + return false + } + + if !i.b.Advance(int(l)) { + return false + } + return true +} + // APK matches an Android Package Archive. // The source of signatures is https://github.com/file/file/blob/1778642b8ba3d947a779a36fcd81f8e807220a19/magic/Magdir/archive#L1820-L1887 func APK(raw []byte, _ uint32) bool { - return zipHas(raw, zipEntries{{ + iter := zipIterator{raw} + + // If a Zipflinger Virtual Entry is detected, then the data is considered APK + if iter.skipZipflingerEntry() { + return true + } + + return zipHas(iter.b, zipEntries{{ name: []byte("AndroidManifest.xml"), }, { name: []byte("META-INF/com/android/build/gradle/app-metadata.properties"), diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/mp3/frame.go b/vendor/github.com/gabriel-vasile/mimetype/internal/mp3/frame.go new file mode 100644 index 0000000..e1ea6f2 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/mp3/frame.go @@ -0,0 +1,140 @@ +package mp3 + +import "bytes" + +// minTruncatedSyncMatches is the minimum number of confirmed successive +// header matches required to accept a candidate frame when the buffer ends +// before maxFrameSyncMatches confirmations can be performed. +const minTruncatedSyncMatches = 2 + +func ExtractFrame(b []byte) (start, size int) { + limit := min(len(b), 2048+headerSize) + for i := 0; i < limit-headerSize; i++ { + j := bytes.IndexByte(b[i:limit-headerSize], 0xFF) + if j < 0 { + break + } + i += j + hdr := header{b[i], b[i+1], b[i+2], b[i+3]} + if !hdr.valid() { + continue + } + frameBytes := hdr.frameBytes() + frameAndPad := frameBytes + hdr.padding() + + validHere := frameBytes > 0 && i+frameAndPad <= len(b) && matchFrame(b[i:]) + // When the buffer is exactly one frame, matchFrame cannot look ahead for + // a subsequent header to confirm the stream. Trust the validated header. + exact := i == 0 && frameAndPad == len(b) + if validHere || exact { + return i, frameAndPad + } + } + return 0, 0 +} + +// matchFrame confirms a candidate header by stepping forward and checking that +// subsequent headers are consistent. +func matchFrame(buf []byte) bool { + // maxFrameSyncMatches limits how many valid frames we look at. + const maxFrameSyncMatches = 10 + hdr := header{buf[0], buf[1], buf[2], buf[3]} + i := hdr.frameBytes() + hdr.padding() + for nmatch := 0; nmatch < maxFrameSyncMatches; nmatch++ { + if i+headerSize > len(buf) { + return nmatch >= minTruncatedSyncMatches + } + cmp := header{buf[i], buf[i+1], buf[i+2], buf[i+3]} + if !hdr.compatibleWith(cmp) { + return false + } + i += cmp.frameBytes() + cmp.padding() + } + return true +} + +const headerSize = 4 + +type header [headerSize]byte + +func (h header) isFreeFormat() bool { return h[2]&0xF0 == 0 } +func (h header) isMPEG1() bool { return h[1]&0x8 != 0 } +func (h header) isMPEG25() bool { return h[1]&0x10 == 0 } +func (h header) rawLayer() byte { return h[1] >> 1 & 3 } +func (h header) rawBitrate() byte { return h[2] >> 4 } +func (h header) rawSampleRate() byte { return h[2] >> 2 & 3 } +func (h header) rawEmphasis() byte { return h[3] & 0b11 } +func (h header) isFrame576() bool { return h[1]&14 == 2 } +func (h header) padding() int { + if h[2]&0x2 != 0 { + return 1 + } + return 0 +} + +// valid reports whether the four bytes form a syntactically valid MP3 header. +func (h header) valid() bool { + return h[0] == 0xff && + ((h[1]&0xF0) == 0xf0 || (h[1]&0xFE) == 0xe2) && + h.rawLayer() == 1 && // Layer III + h.rawBitrate() != 15 && // Not allowed by spec. + h.rawSampleRate() != 3 && + h.rawEmphasis() != 2 && + // The code for extracting frame size for free-format is tedious and + // free-format MP3s are extinct. + !h.isFreeFormat() +} + +// compatibleWith reports whether two headers describe frames belonging to the +// same MP3 stream — same MPEG version, layer, sample-rate index. +func (h header) compatibleWith(o header) bool { + return o.valid() && + (h[1]^o[1])&0xFE == 0 && + (h[2]^o[2])&0x0C == 0 +} + +// bitrateKbps returns the bitrate of the frame in kilobits per second. +func (h header) bitrateKbps() int { + // halfrate[mpeg1?][bitrate_idx] holds bitrate/2 in kbps. + halfrate := [2][15]uint8{ + {0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80}, + {0, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160}, + } + mpeg1 := 0 + if h.isMPEG1() { + mpeg1 = 1 + } + return 2 * int(halfrate[mpeg1][h.rawBitrate()]) +} + +// sampleRateHz returns the sampling rate of the frame in Hz. +func (h header) sampleRateHz() int { + base := [3]int{44100, 48000, 32000}[h.rawSampleRate()] + if !h.isMPEG1() { + base >>= 1 + } + if h.isMPEG25() { + base >>= 1 + } + return base +} + +// frameSamples returns the number of audio samples per channel encoded in +// the frame. +func (h header) frameSamples() int { + if h.isFrame576() { + return 576 + } + return 1152 +} + +// frameBytes returns the size of the frame body (header + side info + audio +// data, excluding padding) in bytes. +func (h header) frameBytes() int { + br := h.bitrateKbps() + sr := h.sampleRateHz() + if br == 0 || sr == 0 { + return 0 + } + return h.frameSamples() * br * 125 / sr +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go b/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go index 552b4ea..0503719 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go @@ -122,26 +122,6 @@ func (b *Bytes) Line() Bytes { return line } -// DropLastLine drops the last incomplete line from b. -// -// mimetype limits itself to ReadLimit bytes when performing a detection. -// This means, for file formats like CSV for NDJSON, the last line of the input -// can be an incomplete line. -// If b length is less than readLimit, it means we received an incomplete file -// and proceed with dropping the last line. -func (b *Bytes) DropLastLine(readLimit uint32) { - if readLimit == 0 || uint64(len(*b)) < uint64(readLimit) { - return - } - - for i := len(*b) - 1; i > 0; i-- { - if (*b)[i] == '\n' { - *b = (*b)[:i] - return - } - } -} - func (b *Bytes) Uint16() (uint16, bool) { if len(*b) < 2 { return 0, false @@ -151,6 +131,24 @@ func (b *Bytes) Uint16() (uint16, bool) { return v, true } +func (b *Bytes) Uint32() (uint32, bool) { + if len(*b) < 4 { + return 0, false + } + v := binary.LittleEndian.Uint32(*b) + *b = (*b)[4:] + return v, true +} + +func (b *Bytes) Uint32be() (uint32, bool) { + if len(*b) < 4 { + return 0, false + } + v := binary.BigEndian.Uint32(*b) + *b = (*b)[4:] + return v, true +} + type Flags int const ( @@ -205,10 +203,8 @@ func (b Bytes) Match(p []byte, flags Flags) int { if l == 0 { return -1 } - // If no flags, or scanning for full word at the end of pattern then - // do a fast HasPrefix check. - // For other flags it's not possible to use HasPrefix. - if flags == 0 || flags&FullWord > 0 { + // Some cases we can handle with a simple bytes.HasPrefix. + if flags == 0 || flags == FullWord { if bytes.HasPrefix(b, p) { b = b[len(p):] p = p[len(p):] @@ -232,7 +228,7 @@ func (b Bytes) Match(p []byte, flags Flags) int { return -1 } b = b[1:] - if !ByteIsWS(p[0]) { + if len(p) > 0 && !ByteIsWS(p[0]) { b.TrimLWS() } } else { diff --git a/vendor/github.com/gabriel-vasile/mimetype/mime.go b/vendor/github.com/gabriel-vasile/mimetype/mime.go index 30c41ac..5382fb1 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/mime.go +++ b/vendor/github.com/gabriel-vasile/mimetype/mime.go @@ -23,6 +23,14 @@ type MIME struct { } // String returns the string representation of the MIME type, e.g., "application/zip". +// String return values can change between releases, for example, when [IANA] +// assigns a new media type. Use [MIME.Is] to avoid breaking changes. +// +// mtype := mimetype.Detect(zipFile) +// if mtype.String() == "application/zip" { /* Plain string comparison is brittle. */ } +// if mtype.Is("application/zip") { /* Will continue to work between releases */ } +// +// [IANA]: https://www.iana.org/assignments/media-types/media-types.xhtml func (m *MIME) String() string { return m.mime } @@ -38,17 +46,19 @@ func (m *MIME) Extension() string { // Each MIME type has a non-nil parent, except for the root MIME type. // // For example, the application/json and text/html MIME types have text/plain as -// their parent because they are text files who happen to contain JSON or HTML. +// their parent because they are text files that happen to contain JSON or HTML. // Another example is the ZIP format, which is used as container // for Microsoft Office files, EPUB files, JAR files, and others. func (m *MIME) Parent() *MIME { return m.parent } -// Is checks whether this MIME type, or any of its aliases, is equal to the +// Is checks whether this MIME type, or any of its [aliases], is equal to the // expected MIME type. MIME type equality test is done on the "type/subtype" // section, ignores any optional MIME parameters, ignores any leading and // trailing whitespace, and is case insensitive. +// +// [aliases]: https://github.com/gabriel-vasile/mimetype/blob/master/supported_mimes.md func (m *MIME) Is(expectedMIME string) bool { // Parsing is needed because some detected MIME types contain parameters // that need to be stripped for the comparison. @@ -129,7 +139,7 @@ func (m *MIME) flatten() []*MIME { // hierarchy returns an easy to read list of ancestors for m. // For example, application/json would return json>txt>root. func (m *MIME) hierarchy() string { - h := "" + var h strings.Builder for m := m; m != nil; m = m.Parent() { e := strings.TrimPrefix(m.Extension(), ".") if e == "" { @@ -142,9 +152,9 @@ func (m *MIME) hierarchy() string { e = "root" } } - h += ">" + e + h.WriteString(">" + e) } - return strings.TrimPrefix(h, ">") + return strings.TrimPrefix(h.String(), ">") } // clone creates a new MIME with the provided optional MIME parameters. diff --git a/vendor/github.com/gabriel-vasile/mimetype/mimetype.go b/vendor/github.com/gabriel-vasile/mimetype/mimetype.go index 7927417..e6f1e77 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/mimetype.go +++ b/vendor/github.com/gabriel-vasile/mimetype/mimetype.go @@ -1,6 +1,6 @@ // Package mimetype uses magic number signatures to detect the MIME type of a file. // -// File formats are stored in a hierarchy with application/octet-stream at its root. +// File formats are stored in a hierarchy with "application/octet-stream" at its root. // For example, the hierarchy for HTML format is application/octet-stream -> // text/plain -> text/html. package mimetype @@ -12,14 +12,14 @@ import ( "sync/atomic" ) -const defaultLimit uint32 = 3072 +const defaultLimit uint32 = 4096 // readLimit is the maximum number of bytes from the input used when detecting. var readLimit uint32 = defaultLimit // Detect returns the MIME type found from the provided byte slice. // -// The result is always a valid MIME type, with application/octet-stream +// The result is always a valid MIME type, with "application/octet-stream" // returned when identification failed. func Detect(in []byte) *MIME { // Using atomic because readLimit can be written at the same time in other goroutine. @@ -34,7 +34,7 @@ func Detect(in []byte) *MIME { // DetectReader returns the MIME type of the provided reader. // -// The result is always a valid MIME type, with application/octet-stream +// The result is always a valid MIME type, with "application/octet-stream" // returned when identification failed with or without an error. // Any error returned is related to the reading from the input reader. // @@ -72,7 +72,7 @@ func DetectReader(r io.Reader) (*MIME, error) { // DetectFile returns the MIME type of the provided file. // -// The result is always a valid MIME type, with application/octet-stream +// The result is always a valid MIME type, with "application/octet-stream" // returned when identification failed with or without an error. // Any error returned is related to the opening and reading from the input file. func DetectFile(path string) (*MIME, error) { @@ -112,7 +112,7 @@ func SetLimit(limit uint32) { } // Extend adds detection for other file formats. -// It is equivalent to calling Extend() on the root MIME type "application/octet-stream". +// It is equivalent to calling [MIME.Extend] on the root MIME type "application/octet-stream". func Extend(detector func(raw []byte, limit uint32) bool, mime, extension string, aliases ...string) { root.Extend(detector, mime, extension, aliases...) } diff --git a/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md b/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md index 79a3617..f014ff4 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md +++ b/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md @@ -1,4 +1,4 @@ -## 199 Supported MIME types +## 204 Supported MIME types This file is automatically generated when running tests. Do not edit manually. Extension | MIME type
Aliases | Hierarchy @@ -42,7 +42,7 @@ Extension | MIME type
Aliases | Hierarchy **.oga** | **audio/ogg** | oga>ogg>root **.ogv** | **video/ogg** | ogv>ogg>root **.png** | **image/png** | png>root -**.png** | **image/vnd.mozilla.apng** | png>png>root +**.apng** | **image/apng**
image/vnd.mozilla.apng | apng>png>root **.jpg** | **image/jpeg** | jpg>root **.jxl** | **image/jxl** | jxl>root **.jp2** | **image/jp2** | jp2>root @@ -67,7 +67,6 @@ Extension | MIME type
Aliases | Hierarchy **.bmp** | **image/bmp**
image/x-bmp, image/x-ms-bmp | bmp>root **.123** | **application/vnd.lotus-1-2-3** | 123>root **.ico** | **image/x-icon** | ico>root -**.mp3** | **audio/mpeg**
audio/x-mpeg, audio/mp3 | mp3>root **.flac** | **audio/flac** | flac>root **.midi** | **audio/midi**
audio/mid, audio/sp-midi, audio/x-mid, audio/x-midi | midi>root **.ape** | **audio/ape** | ape>root @@ -95,7 +94,7 @@ Extension | MIME type
Aliases | Hierarchy **.webm** | **video/webm**
audio/webm | webm>root **.avi** | **video/x-msvideo**
video/avi, video/msvideo | avi>root **.flv** | **video/x-flv** | flv>root -**.mkv** | **video/x-matroska** | mkv>root +**.mkv** | **video/matroska**
video/x-matroska | mkv>root **.asf** | **video/x-ms-asf**
video/asf, video/x-ms-wmv | asf>root **.aac** | **audio/aac** | aac>root **.voc** | **audio/x-unknown** | voc>root @@ -116,7 +115,7 @@ Extension | MIME type
Aliases | Hierarchy **.shp** | **application/vnd.shp** | shp>shx>root **.dbf** | **application/x-dbf** | dbf>root **.dcm** | **application/dicom** | dcm>root -**.rar** | **application/x-rar-compressed**
application/x-rar | rar>root +**.rar** | **application/vnd.rar**
application/x-rar-compressed, application/x-rar | rar>root **.djvu** | **image/vnd.djvu** | djvu>root **.mobi** | **application/x-mobipocket-ebook** | mobi>root **.lit** | **application/x-ms-reader** | lit>root @@ -158,6 +157,9 @@ Extension | MIME type
Aliases | Hierarchy **.hlp** | **application/x-os2-hlp** | hlp>root **.fm** | **application/vnd.framemaker** | fm>root **.bufr** | **application/bufr** | bufr>root +**.pyc** | **application/x-bytecode.python** | pyc>root +**.pcap** | **application/vnd.tcpdump.pcap** | pcap>root +**.mp3** | **audio/mpeg**
audio/x-mpeg, audio/mp3 | mp3>root **.txt** | **text/plain** | txt>root **.svg** | **image/svg+xml** | svg>txt>root **.html** | **text/html** | html>txt>root @@ -176,6 +178,7 @@ Extension | MIME type
Aliases | Hierarchy **.xfdf** | **application/vnd.adobe.xfdf** | xfdf>xml>txt>root **.owl** | **application/owl+xml** | owl>xml>txt>root **.html** | **application/xhtml+xml** | html>xml>txt>root +**.xml** | **application/vnd.cyclonedx+xml** | xml>xml>txt>root **.php** | **text/x-php** | php>txt>root **.js** | **text/javascript**
application/x-javascript, application/javascript | js>txt>root **.lua** | **text/x-lua** | lua>txt>root @@ -186,6 +189,7 @@ Extension | MIME type
Aliases | Hierarchy **.geojson** | **application/geo+json** | geojson>json>txt>root **.har** | **application/json** | har>json>txt>root **.gltf** | **model/gltf+json** | gltf>json>txt>root +**.json** | **application/vnd.cyclonedx+json** | json>json>txt>root **.ndjson** | **application/x-ndjson** | ndjson>txt>root **.rtf** | **text/rtf**
application/rtf | rtf>txt>root **.srt** | **application/x-subrip**
application/x-srt, text/x-srt | srt>txt>root @@ -202,3 +206,4 @@ Extension | MIME type
Aliases | Hierarchy **.ppm** | **image/x-portable-pixmap** | ppm>txt>root **.pam** | **image/x-portable-arbitrarymap** | pam>txt>root **.eml** | **message/rfc822** | eml>txt>root +**.ged** | **text/vnd.familysearch.gedcom** | ged>txt>root diff --git a/vendor/github.com/gabriel-vasile/mimetype/tree.go b/vendor/github.com/gabriel-vasile/mimetype/tree.go index 55023ba..bec8b43 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/tree.go +++ b/vendor/github.com/gabriel-vasile/mimetype/tree.go @@ -19,12 +19,16 @@ var root = newMIME("application/octet-stream", "", func([]byte, uint32) bool { return true }, xpm, sevenZ, zip, pdf, fdf, ole, ps, psd, p7s, ogg, png, jpg, jxl, jp2, jpx, jpm, jxs, gif, webp, exe, elf, ar, tar, xar, bz2, fits, tiff, bmp, lotus, ico, - mp3, flac, midi, ape, musePack, amr, wav, aiff, au, mpeg, quickTime, mp4, webM, + flac, midi, ape, musePack, amr, wav, aiff, au, mpeg, quickTime, mp4, webM, avi, flv, mkv, asf, aac, voc, m3u, rmvb, gzip, class, swf, crx, ttf, woff, woff2, otf, ttc, eot, wasm, shx, dbf, dcm, rar, djvu, mobi, lit, bpg, cbor, sqlite3, dwg, nes, lnk, macho, qcp, icns, hdr, mrc, mdb, accdb, zstd, cab, rpm, xz, lzip, torrent, cpio, tzif, xcf, pat, gbr, glb, cabIS, jxr, parquet, - oneNote, chm, wpd, dxf, grib, zlib, inf, hlp, fm, bufr, + oneNote, chm, wpd, dxf, grib, zlib, inf, hlp, fm, bufr, pyc, pcap, + // MP3 is late because it does a linear search in the input. That means + // containers that embed an MP3, for example: an mp4 file, or a zip without + // compression, would pass as MP3s. + mp3, // Keep text last because it is the slowest check. text, ) @@ -82,16 +86,17 @@ var ( alias("application/x-ogg") oggAudio = newMIME("audio/ogg", ".oga", magic.OggAudio) oggVideo = newMIME("video/ogg", ".ogv", magic.OggVideo) - text = newMIME("text/plain", ".txt", magic.Text, svg, html, xml, php, js, lua, perl, python, ruby, json, ndJSON, rtf, srt, tcl, csv, tsv, vCard, iCalendar, warc, vtt, shell, netpbm, netpgm, netppm, netpam, rfc822) - xml = newMIME("text/xml", ".xml", magic.XML, rss, atom, x3d, kml, xliff, collada, gml, gpx, tcx, amf, threemf, xfdf, owl2, xhtml). + text = newMIME("text/plain", ".txt", magic.Text, svg, html, xml, php, js, lua, perl, python, ruby, json, ndJSON, rtf, srt, tcl, csv, tsv, vCard, iCalendar, warc, vtt, shell, netpbm, netpgm, netppm, netpam, rfc822, gedcom) + xml = newMIME("text/xml", ".xml", magic.XML, rss, atom, x3d, kml, xliff, collada, gml, gpx, tcx, amf, threemf, xfdf, owl2, xhtml, cdxxml). alias("application/xml") xhtml = newMIME("application/xhtml+xml", ".html", magic.XHTML) - json = newMIME("application/json", ".json", magic.JSON, geoJSON, har, gltf) + json = newMIME("application/json", ".json", magic.JSON, geoJSON, har, gltf, cdxJSON) har = newMIME("application/json", ".har", magic.HAR) csv = newMIME("text/csv", ".csv", magic.CSV) tsv = newMIME("text/tab-separated-values", ".tsv", magic.TSV) geoJSON = newMIME("application/geo+json", ".geojson", magic.GeoJSON) ndJSON = newMIME("application/x-ndjson", ".ndjson", magic.NdJSON) + cdxJSON = newMIME("application/vnd.cyclonedx+json", ".json", magic.CDXJSON) html = newMIME("text/html", ".html", magic.HTML) php = newMIME("text/x-php", ".php", magic.Php) rtf = newMIME("text/rtf", ".rtf", magic.Rtf).alias("application/rtf") @@ -104,6 +109,7 @@ var ( perl = newMIME("text/x-perl", ".pl", magic.Perl) python = newMIME("text/x-python", ".py", magic.Python). alias("text/x-script.python", "application/x-python") + pyc = newMIME("application/x-bytecode.python", ".pyc", magic.Pyc) ruby = newMIME("text/x-ruby", ".rb", magic.Ruby). alias("application/x-ruby") shell = newMIME("text/x-shellscript", ".sh", magic.Shell). @@ -127,13 +133,15 @@ var ( tcx = newMIME("application/vnd.garmin.tcx+xml", ".tcx", magic.Tcx) amf = newMIME("application/x-amf", ".amf", magic.Amf) threemf = newMIME("application/vnd.ms-package.3dmanufacturing-3dmodel+xml", ".3mf", magic.Threemf) + cdxxml = newMIME("application/vnd.cyclonedx+xml", ".xml", magic.CDXXML) png = newMIME("image/png", ".png", magic.Png, apng) - apng = newMIME("image/vnd.mozilla.apng", ".png", magic.Apng) - jpg = newMIME("image/jpeg", ".jpg", magic.Jpg) - jxl = newMIME("image/jxl", ".jxl", magic.Jxl) - jp2 = newMIME("image/jp2", ".jp2", magic.Jp2) - jpx = newMIME("image/jpx", ".jpf", magic.Jpx) - jpm = newMIME("image/jpm", ".jpm", magic.Jpm). + apng = newMIME("image/apng", ".apng", magic.Apng). + alias("image/vnd.mozilla.apng") + jpg = newMIME("image/jpeg", ".jpg", magic.Jpg) + jxl = newMIME("image/jxl", ".jxl", magic.Jxl) + jp2 = newMIME("image/jp2", ".jp2", magic.Jp2) + jpx = newMIME("image/jpx", ".jpf", magic.Jpx) + jpm = newMIME("image/jpm", ".jpm", magic.Jpm). alias("video/jpm") jxs = newMIME("image/jxs", ".jxs", magic.Jxs) xpm = newMIME("image/x-xpixmap", ".xpm", magic.Xpm) @@ -156,7 +164,7 @@ var ( heifSeq = newMIME("image/heif-sequence", ".heif", magic.HeifSequence) hdr = newMIME("image/vnd.radiance", ".hdr", magic.Hdr) avif = newMIME("image/avif", ".avif", magic.AVIF) - mp3 = newMIME("audio/mpeg", ".mp3", magic.Mp3). + mp3 = newMIME("audio/mpeg", ".mp3", magic.MP3). alias("audio/x-mpeg", "audio/mp3") flac = newMIME("audio/flac", ".flac", magic.Flac) midi = newMIME("audio/midi", ".midi", magic.Midi). @@ -192,7 +200,8 @@ var ( avi = newMIME("video/x-msvideo", ".avi", magic.Avi). alias("video/avi", "video/msvideo") flv = newMIME("video/x-flv", ".flv", magic.Flv) - mkv = newMIME("video/x-matroska", ".mkv", magic.Mkv) + mkv = newMIME("video/matroska", ".mkv", magic.Mkv). + alias("video/x-matroska") asf = newMIME("video/x-ms-asf", ".asf", magic.Asf). alias("video/asf", "video/x-ms-wmv") rmvb = newMIME("application/vnd.rn-realmedia-vbr", ".rmvb", magic.Rmvb) @@ -242,8 +251,8 @@ var ( odc = newMIME("application/vnd.oasis.opendocument.chart", ".odc", magic.Odc). alias("application/x-vnd.oasis.opendocument.chart") sxc = newMIME("application/vnd.sun.xml.calc", ".sxc", magic.Sxc) - rar = newMIME("application/x-rar-compressed", ".rar", magic.RAR). - alias("application/x-rar") + rar = newMIME("application/vnd.rar", ".rar", magic.RAR). + alias("application/x-rar-compressed", "application/x-rar") djvu = newMIME("image/vnd.djvu", ".djvu", magic.DjVu) mobi = newMIME("application/x-mobipocket-ebook", ".mobi", magic.Mobi) lit = newMIME("application/x-ms-reader", ".lit", magic.Lit) @@ -294,4 +303,6 @@ var ( hlp = newMIME("application/x-os2-hlp", ".hlp", magic.Hlp) fm = newMIME("application/vnd.framemaker", ".fm", magic.FrameMaker) bufr = newMIME("application/bufr", ".bufr", magic.BUFR) + gedcom = newMIME("text/vnd.familysearch.gedcom", ".ged", magic.GEDCOM) + pcap = newMIME("application/vnd.tcpdump.pcap", ".pcap", magic.Pcap) ) diff --git a/vendor/github.com/getsentry/sentry-go/CHANGELOG.md b/vendor/github.com/getsentry/sentry-go/CHANGELOG.md index f24c0a4..c7aae62 100644 --- a/vendor/github.com/getsentry/sentry-go/CHANGELOG.md +++ b/vendor/github.com/getsentry/sentry-go/CHANGELOG.md @@ -1,5 +1,64 @@ # Changelog +## 0.48.0 + +### Breaking Changes 🛠 + +- Remove issue creation from logging integrations by @giortzisg in [#1340](https://github.com/getsentry/sentry-go/pull/1340) + +### New Features ✨ + +- Add `ClientOptions.DataCollection` for granular control over data collected by automatic instrumentation, replacing the broad `SendDefaultPII` switch. `DataCollection` can independently configure automatic `user.*` population, cookies, request/response headers, HTTP bodies, and query parameters. When configured, it is the source of truth and `SendDefaultPII` is ignored. by @giortzisg in [#1339](https://github.com/getsentry/sentry-go/pull/1339) + - For backwards compatibility, clients that do not configure `DataCollection` keep a best-effort mapping of the previous `SendDefaultPII` behavior. To opt in to the new defaults, pass an empty `DataCollection` and then restrict individual categories as needed. + ```go + sentry.Init(sentry.ClientOptions{ + Dsn: "https://public@example.com/1", + + // Opt in to the new data collection defaults. Omitted fields use their + // defaults: user info, cookies, headers, query params, and supported HTTP + // bodies are collected, with sensitive values filtered. + DataCollection: &sentry.DataCollection{}, + }) + ``` + - To opt in while disabling automatic user info and HTTP bodies, configure those fields explicitly: + ```go + sentry.Init(sentry.ClientOptions{ + Dsn: "https://public@example.com/1", + DataCollection: &sentry.DataCollection{ + UserInfo: sentry.Set(false), + HTTPBodies: []sentry.BodyType{}, + }, + }) + ``` +- PushScope shorthand now returns the new scope reference by @DoctorJohn in [#1335](https://github.com/getsentry/sentry-go/pull/1335) + +### Bug Fixes 🐛 + +- Fix fiber route name when using middlewares by @giortzisg in [#1363](https://github.com/getsentry/sentry-go/pull/1363) +- Omit empty event id for standalone client reports by @giortzisg in [#1362](https://github.com/getsentry/sentry-go/pull/1362) +- Preserve '%' literal in log messages by @giortzisg in [#1358](https://github.com/getsentry/sentry-go/pull/1358) +- Unaligned 64-bit atomic panic on 32-bit platforms in telemetry buffers by @Kirill-INQ in [#1355](https://github.com/getsentry/sentry-go/pull/1355) +- Isolate event processor across clones by @giortzisg in [#1337](https://github.com/getsentry/sentry-go/pull/1337) + +### Internal Changes 🔧 + +#### Deps + +- Bump fiber/v2 to 2.52.14 by @giortzisg in [#1359](https://github.com/getsentry/sentry-go/pull/1359) +- Bump actions/checkout from 6.0.3 to 7.0.0 by @dependabot in [#1349](https://github.com/getsentry/sentry-go/pull/1349) +- Bump golangci/golangci-lint-action from 9.2.1 to 9.3.0 by @dependabot in [#1346](https://github.com/getsentry/sentry-go/pull/1346) +- Bump codecov/codecov-action from 6.0.0 to 7.0.0 by @dependabot in [#1347](https://github.com/getsentry/sentry-go/pull/1347) +- Bump actions/setup-go from 6.4.0 to 6.5.0 by @dependabot in [#1343](https://github.com/getsentry/sentry-go/pull/1343) +- Bump golang.org/x/crypto to 0.52.0 and golang/x/net to 0.55.0 by @giortzisg in [#1341](https://github.com/getsentry/sentry-go/pull/1341) +- Bump getsentry/github-workflows/validate-pr from c802283cd9075b7a2b7a32655019c21c21676e34 to 4013fc6e1aeb1be1f9d3b4d232624f0ec1afa613 by @dependabot in [#1344](https://github.com/getsentry/sentry-go/pull/1344) + +#### Other + +- Remove changelog-preview and codecov actions by @giortzisg in [#1357](https://github.com/getsentry/sentry-go/pull/1357) +- Add govulncheck audit action by @giortzisg in [#1342](https://github.com/getsentry/sentry-go/pull/1342) +- Limit changelog-preview secret access by @giortzisg in [#1350](https://github.com/getsentry/sentry-go/pull/1350) +- Move limited buffer under utils by @giortzisg in [#1338](https://github.com/getsentry/sentry-go/pull/1338) + ## 0.47.0 ### Breaking Changes 🛠 diff --git a/vendor/github.com/getsentry/sentry-go/client.go b/vendor/github.com/getsentry/sentry-go/client.go index e8420c4..7886bd0 100644 --- a/vendor/github.com/getsentry/sentry-go/client.go +++ b/vendor/github.com/getsentry/sentry-go/client.go @@ -172,9 +172,18 @@ type ClientOptions struct { // List of regexp strings that will be used to match against a transaction's // name. If a match is found, then the transaction will be dropped. IgnoreTransactions []string + // Deprecated: Use DataCollection for granular control over what data the + // SDK collects. When DataCollection is configured, SendDefaultPII is + // ignored. + // // If this flag is enabled, certain personally identifiable information (PII) is added by active integrations. // By default, no such data is sent. SendDefaultPII bool + // DataCollection configures what data the SDK collects automatically. All fields are optional. By default + // the SDK collects rich context for debugging while scrubbing sensitive values. + // + // See https://docs.sentry.io/platforms/go/configuration/options/#DataCollection + DataCollection *DataCollection // BeforeSend is called before error events are sent to Sentry. // You can use it to mutate the event or return nil to discard it. BeforeSend func(event *Event, hint *EventHint) *Event @@ -373,6 +382,9 @@ func NewClient(options ClientOptions) (*Client, error) { options.TraceIgnoreStatusCodes = [][]int{{404}} } + resolvedDataCollection := snapshotDataCollection(options.DataCollection, options.SendDefaultPII) + options.DataCollection = cloneDataCollection(&resolvedDataCollection) + // SENTRYGODEBUG is a comma-separated list of key=value pairs (similar // to GODEBUG). It is not a supported feature: recognized debug options // may change any time. @@ -585,7 +597,18 @@ func (client *Client) externalTraceContextFromContext(ctx context.Context) (Trac // Options return ClientOptions for the current Client. func (client *Client) Options() ClientOptions { // Note: internally, consider using `client.options` instead of `client.Options()` to avoid copying the object each time. - return client.options + opts := client.options + opts.DataCollection = cloneDataCollection(client.options.DataCollection) + return opts +} + +// GetDataCollection returns a copy of the resolved data collection +// configuration used by the client. +func (client *Client) GetDataCollection() DataCollection { + if client == nil || client.options.DataCollection == nil { + return DataCollection{} + } + return *cloneDataCollection(client.options.DataCollection) } // CaptureMessage captures an arbitrary message. @@ -686,7 +709,7 @@ func (client *Client) captureMetric(metric *Metric, _ *Scope) bool { // Recover captures a panic. // Returns EventID if successfully, or nil if there's no error to recover from. -func (client *Client) Recover(err interface{}, hint *EventHint, scope EventModifier) *EventID { +func (client *Client) Recover(err any, hint *EventHint, scope EventModifier) *EventID { if err == nil { err = recover() } @@ -703,7 +726,7 @@ func (client *Client) Recover(err interface{}, hint *EventHint, scope EventModif // Returns EventID if successfully, or nil if there's no error to recover from. func (client *Client) RecoverWithContext( ctx context.Context, - err interface{}, + err any, hint *EventHint, scope EventModifier, ) *EventID { diff --git a/vendor/github.com/getsentry/sentry-go/data_collection.go b/vendor/github.com/getsentry/sentry-go/data_collection.go new file mode 100644 index 0000000..713aba5 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/data_collection.go @@ -0,0 +1,217 @@ +package sentry + +import "slices" + +// CollectionMode controls how key-value data (headers, cookies, query params) is collected. +// +// Defaults to CollectionDenyList. +type CollectionMode int + +const ( + // CollectionDenyList keeps all keys and filters denied values. + CollectionDenyList CollectionMode = iota + + // CollectionOff disables collection of the category entirely. + CollectionOff + + // CollectionAllowList keeps all keys and sends real values only for allowed keys. + CollectionAllowList +) + +// KeyValueCollectionBehavior configures how key-value data is collected and filtered. +type KeyValueCollectionBehavior struct { + // Mode controls the collection strategy. + Mode CollectionMode + // Terms is a list of additional terms used by the active mode. + Terms []string +} + +// HeaderCollectionConfig configures how HTTP headers are collected for +// requests and responses independently. +type HeaderCollectionConfig struct { + // Request configures collection of HTTP request headers. + Request *KeyValueCollectionBehavior + // Response configures collection of HTTP response headers. + Response *KeyValueCollectionBehavior +} + +// BodyType identifies a category of HTTP body to collect. +type BodyType string + +const ( + // BodyIncomingRequest collects bodies from incoming HTTP requests + // (server-side). + BodyIncomingRequest BodyType = "incomingRequest" + + // BodyOutgoingRequest collects bodies from outgoing HTTP requests + // (client-side). + BodyOutgoingRequest BodyType = "outgoingRequest" + + // BodyIncomingResponse collects bodies from incoming HTTP responses + // (client-side). + BodyIncomingResponse BodyType = "incomingResponse" +) + +// DataCollection configures what data the SDK collects automatically. +// All fields are optional. nil or zero-value fields use the documented +// defaults, which collect rich context for debugging while scrubbing sensitive +// values via a built-in denylist. +// +// See https://docs.sentry.io/platforms/go/configuration/options/#DataCollection +type DataCollection struct { + // UserInfo controls automatic population of user.* fields from auto-instrumentation. + // + // This does NOT gate data explicitly set via Scope.SetUser(); that is + // always attached. Defaults to true. + UserInfo Option[bool] + + // Cookies configures collection of HTTP cookies. + // + // Defaults to using the built-in DenyList. + Cookies *KeyValueCollectionBehavior + + // HTTPHeaders configures collection of HTTP request and response headers + // independently. + // + // Defaults to both request and response using the built-in DenyList. + HTTPHeaders *HeaderCollectionConfig + + // HTTPBodies controls which HTTP body types are collected. + // + // Defaults to collecting all valid body types. + HTTPBodies []BodyType + + // QueryParams configures collection of URL query parameters. + // + // Defaults to using the built-in DenyList. + QueryParams *KeyValueCollectionBehavior + + // sensitiveTerms is the deny-list used for built-in sensitive-key + // scrubbing. + sensitiveTerms []string +} + +// cloneKeyValueCollectionBehavior returns a deep copy of b. +func cloneKeyValueCollectionBehavior(b *KeyValueCollectionBehavior) *KeyValueCollectionBehavior { + if b == nil { + return nil + } + cloned := &KeyValueCollectionBehavior{Mode: b.Mode} + if b.Terms != nil { + cloned.Terms = slices.Clone(b.Terms) + } + return cloned +} + +// cloneHeaderCollectionConfig returns a deep copy of c. +func cloneHeaderCollectionConfig(c *HeaderCollectionConfig) *HeaderCollectionConfig { + if c == nil { + return nil + } + return &HeaderCollectionConfig{ + Request: cloneKeyValueCollectionBehavior(c.Request), + Response: cloneKeyValueCollectionBehavior(c.Response), + } +} + +// cloneDataCollection returns a deep copy of dc. +func cloneDataCollection(dc *DataCollection) *DataCollection { + if dc == nil { + return nil + } + cloned := &DataCollection{ + UserInfo: dc.UserInfo, + Cookies: cloneKeyValueCollectionBehavior(dc.Cookies), + HTTPHeaders: cloneHeaderCollectionConfig(dc.HTTPHeaders), + QueryParams: cloneKeyValueCollectionBehavior(dc.QueryParams), + sensitiveTerms: dc.sensitiveTerms, + } + if dc.HTTPBodies != nil { + cloned.HTTPBodies = slices.Clone(dc.HTTPBodies) + } + return cloned +} + +// allBodyTypes returns all valid body types. +func allBodyTypes() []BodyType { + return []BodyType{ + BodyIncomingRequest, + BodyOutgoingRequest, + BodyIncomingResponse, + } +} + +// snapshotDataCollection builds a fully-populated DataCollection based on given options. +// It handles any unspecified values by applying the defaults. If the given opts are nil, this +// provides a best-effort snapshot to align with sendDefaultPII for backwards compatibility. +func snapshotDataCollection(opts *DataCollection, sendDefaultPII bool) DataCollection { + if opts == nil { + return legacyDataCollection(sendDefaultPII) + } + return resolveDataCollection(opts) +} + +func resolveDataCollection(dc *DataCollection) DataCollection { + var resolved DataCollection + if cloned := cloneDataCollection(dc); cloned != nil { + resolved = *cloned + } + + if !resolved.UserInfo.IsSet { + resolved.UserInfo = Set(true) + } + if resolved.Cookies == nil { + resolved.Cookies = &KeyValueCollectionBehavior{} + } + if resolved.HTTPHeaders == nil { + resolved.HTTPHeaders = &HeaderCollectionConfig{} + } + if resolved.HTTPHeaders.Request == nil { + resolved.HTTPHeaders.Request = &KeyValueCollectionBehavior{} + } + if resolved.HTTPHeaders.Response == nil { + resolved.HTTPHeaders.Response = &KeyValueCollectionBehavior{} + } + if resolved.HTTPBodies == nil { + resolved.HTTPBodies = allBodyTypes() + } + if resolved.QueryParams == nil { + resolved.QueryParams = &KeyValueCollectionBehavior{} + } + return resolved +} + +func legacyDataCollection(sendDefaultPII bool) DataCollection { + if sendDefaultPII { + return resolveDataCollection(&DataCollection{ + UserInfo: Set(true), + Cookies: &KeyValueCollectionBehavior{}, + HTTPHeaders: &HeaderCollectionConfig{Request: &KeyValueCollectionBehavior{}, Response: &KeyValueCollectionBehavior{}}, + HTTPBodies: allBodyTypes(), + QueryParams: &KeyValueCollectionBehavior{}, + }) + } + + return resolveDataCollection(&DataCollection{ + UserInfo: Set(false), + HTTPBodies: []BodyType{}, + Cookies: &KeyValueCollectionBehavior{Mode: CollectionOff}, + HTTPHeaders: &HeaderCollectionConfig{ + Request: &KeyValueCollectionBehavior{Mode: CollectionDenyList}, + Response: &KeyValueCollectionBehavior{Mode: CollectionDenyList}, + }, + QueryParams: &KeyValueCollectionBehavior{Mode: CollectionDenyList}, + sensitiveTerms: extendedSensitiveTerms, + }) +} + +// extendedSensitiveTerms are additional privacy terms that cover +// user-identifying data such as IP forwarding headers and user IDs. Used for +// backwards compatibility with SendDefaultPII=false. +var extendedSensitiveTerms = []string{ + "forwarded", + "-ip", + "remote-", + "via", + "-user", +} diff --git a/vendor/github.com/getsentry/sentry-go/data_collection_filter.go b/vendor/github.com/getsentry/sentry-go/data_collection_filter.go new file mode 100644 index 0000000..438093a --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/data_collection_filter.go @@ -0,0 +1,308 @@ +package sentry + +import ( + "encoding/json" + "net/url" + "strings" +) + +// defaultSensitiveTerms is the canonical list of case-insensitive, +// partial-match terms used for scrubbing. +// +// See https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist +var defaultSensitiveTerms = []string{ + "auth", + "bearer", + "credentials", + "csrf", + "identity", + "jwt", + "key", + "passwd", + "password", + "pwd", + "saml", + "secret", + "session", + "sid", + "sso", + "token", + "xsrf", +} + +// filteredValue is the replacement for sensitive values. +const filteredValue = "[Filtered]" + +// filterKeyValues applies a KeyValueCollectionBehavior to a map of key-value +// pairs. Keys are always preserved and values are replaced with "[Filtered]". +// +// Returns nil when the mode is CollectionOff. +func (dc DataCollection) filterKeyValues(data map[string]string, behavior *KeyValueCollectionBehavior) map[string]string { + if behavior == nil { + behavior = &KeyValueCollectionBehavior{} + } + if behavior.Mode == CollectionOff { + return nil + } + result := make(map[string]string, len(data)) + for k, v := range data { + if dc.shouldFilterKey(k, behavior) { + result[k] = filteredValue + } else { + result[k] = v + } + } + return result +} + +// FilterRequestHeaders applies the configured request-header collection behavior. +func (dc DataCollection) FilterRequestHeaders(headers map[string]string) map[string]string { + var behavior *KeyValueCollectionBehavior + if dc.HTTPHeaders != nil { + behavior = dc.HTTPHeaders.Request + } + return dc.filterKeyValues(headers, behavior) +} + +// FilterResponseHeaders applies the configured response-header collection behavior. +func (dc DataCollection) FilterResponseHeaders(headers map[string]string) map[string]string { + var behavior *KeyValueCollectionBehavior + if dc.HTTPHeaders != nil { + behavior = dc.HTTPHeaders.Response + } + return dc.filterKeyValues(headers, behavior) +} + +// CollectHTTPBody reports whether the given body type should be collected. +func (dc *DataCollection) CollectHTTPBody(bt BodyType) bool { + if dc == nil || dc.HTTPBodies == nil { + return true + } + for _, t := range dc.HTTPBodies { + if t == bt { + return true + } + } + return false +} + +// CollectCookies reports whether cookies should be collected. +func (dc *DataCollection) CollectCookies() bool { + return dc == nil || dc.Cookies == nil || dc.Cookies.Mode != CollectionOff +} + +// CollectQueryParams reports whether query parameters should be collected. +func (dc DataCollection) CollectQueryParams() bool { + return dc.QueryParams == nil || dc.QueryParams.Mode != CollectionOff +} + +// FilterQueryString applies the configured query-parameter collection behavior. +func (dc DataCollection) FilterQueryString(rawQuery string) string { + if rawQuery == "" { + return "" + } + values, _ := url.ParseQuery(rawQuery) + return dc.filterURLValues(values, dc.QueryParams) +} + +// FilterURL applies query-parameter filtering to u and returns its redacted string form. +func (dc DataCollection) FilterURL(u *url.URL) string { + if u == nil { + return "" + } + filtered := *u + filtered.RawQuery = dc.FilterQueryString(u.RawQuery) + return filtered.Redacted() +} + +// FilterCookies applies the configured cookie collection behavior. +func (dc DataCollection) FilterCookies(values []string) string { + parsed := parseKeyValueStrings(values, ';') + if len(parsed) == 0 { + return "" + } + filtered := dc.filterKeyValues(parsed, dc.Cookies) + if len(filtered) == 0 { + return "" + } + + parts := make([]string, 0, len(filtered)) + for key, value := range filtered { + parts = append(parts, key+"="+value) + } + return strings.Join(parts, "; ") +} + +// FilterSetCookies applies the configured cookie collection behavior to +// Set-Cookie header values. +func (dc DataCollection) FilterSetCookies(values []string) string { + filtered := make([]string, 0, len(values)) + for _, value := range values { + if cookie := dc.filterSetCookie(value); cookie != "" { + filtered = append(filtered, cookie) + } + } + return strings.Join(filtered, ", ") +} + +func (dc DataCollection) filterSetCookie(setCookie string) string { + if !dc.CollectCookies() { + return "" + } + parts := strings.Split(setCookie, ";") + name, value, ok := strings.Cut(parts[0], "=") + name = strings.TrimSpace(name) + if !ok || name == "" { + return "" + } + if dc.shouldFilterKey(name, dc.Cookies) { + value = filteredValue + } + parts[0] = name + "=" + value + + for i := 1; i < len(parts); i++ { + attribute, _, ok := strings.Cut(parts[i], "=") + if !ok { + continue + } + if name := strings.TrimSpace(attribute); name != "" && dc.shouldFilterKey(name, dc.Cookies) { + parts[i] = attribute + "=" + filteredValue + } + } + + return strings.Join(parts, ";") +} + +// FilterHTTPBody applies sensitive-key filtering to parseable HTTP body data. +// Opaque raw bodies are replaced entirely. +func (dc DataCollection) FilterHTTPBody(body []byte, contentType string) string { + if len(body) == 0 { + return "" + } + + if strings.Contains(strings.ToLower(contentType), "application/json") || looksLikeJSON(body) { + var value any + if err := json.Unmarshal(body, &value); err == nil { + filteredJSON := dc.filterJSONValue(value, nil) + filtered, err := json.Marshal(filteredJSON) + if err == nil { + return string(filtered) + } + } + } + + if strings.Contains(strings.ToLower(contentType), "application/x-www-form-urlencoded") { + if values, err := url.ParseQuery(string(body)); err == nil { + return dc.filterURLValues(values, nil) + } + } + + return filteredValue +} + +func looksLikeJSON(body []byte) bool { + trimmed := strings.TrimSpace(string(body)) + return strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") +} + +func (dc DataCollection) filterURLValues(values url.Values, behavior *KeyValueCollectionBehavior) string { + if behavior == nil { + behavior = &KeyValueCollectionBehavior{} + } + if behavior.Mode == CollectionOff { + return "" + } + for key := range values { + if dc.shouldFilterKey(key, behavior) { + values.Set(key, filteredValue) + } + } + return strings.ReplaceAll(values.Encode(), url.QueryEscape(filteredValue), filteredValue) +} + +func (dc DataCollection) filterJSONValue(value any, behavior *KeyValueCollectionBehavior) any { + return dc.filterJSONNode(value, behavior, false) +} + +// filterJSONNode recursively filters a decoded JSON value. +func (dc DataCollection) filterJSONNode(value any, behavior *KeyValueCollectionBehavior, keyed bool) any { + if behavior != nil && behavior.Mode == CollectionOff { + return nil + } + + switch value := value.(type) { + case map[string]any: + filtered := make(map[string]any, len(value)) + for key, child := range value { + if dc.shouldFilterKey(key, behavior) { + filtered[key] = filteredValue + } else { + filtered[key] = dc.filterJSONNode(child, behavior, true) + } + } + return filtered + case []any: + filtered := make([]any, len(value)) + for i, child := range value { + filtered[i] = dc.filterJSONNode(child, behavior, keyed) + } + return filtered + default: + if !keyed { + return filteredValue + } + return value + } +} + +// shouldFilterKey reports whether a key's value should be redacted under the +// given behavior. It combines the built-in sensitive terms with the behavior's +// user-provided terms. +func (dc DataCollection) shouldFilterKey(key string, behavior *KeyValueCollectionBehavior) bool { + if behavior == nil { + behavior = &KeyValueCollectionBehavior{} + } + + sensitive := matchesDenyTerms(key, defaultSensitiveTerms) || matchesDenyTerms(key, dc.sensitiveTerms) + + switch behavior.Mode { + case CollectionOff: + return true + case CollectionAllowList: + return sensitive || !matchesDenyTerms(key, behavior.Terms) + default: + return sensitive || matchesDenyTerms(key, behavior.Terms) + } +} + +// matchesDenyTerms reports whether the key (case-insensitive) contains any of +// the given terms as a substring. +func matchesDenyTerms(key string, terms []string) bool { + lower := strings.ToLower(key) + for _, term := range terms { + if strings.Contains(lower, strings.ToLower(term)) { + return true + } + } + return false +} + +// parseKeyValueStrings splits strings like "a=1; b=2" into a map. +// Malformed parts without '=' and parts with empty keys are skipped. +func parseKeyValueStrings(values []string, separator rune) map[string]string { + result := make(map[string]string) + for _, value := range values { + for _, part := range strings.Split(value, string(separator)) { + part = strings.TrimSpace(part) + if part == "" { + continue + } + key, value, ok := strings.Cut(part, "=") + if !ok || strings.TrimSpace(key) == "" { + continue + } + result[key] = value + } + } + return result +} diff --git a/vendor/github.com/getsentry/sentry-go/go.work.sum b/vendor/github.com/getsentry/sentry-go/go.work.sum index aab9ffc..7b27915 100644 --- a/vendor/github.com/getsentry/sentry-go/go.work.sum +++ b/vendor/github.com/getsentry/sentry-go/go.work.sum @@ -36,7 +36,6 @@ github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/T github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI= github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs= github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgraph-io/badger/v2 v2.2007.4 h1:TRWBQg8UrlUhaFdco01nO2uXwzKS7zd+HVdwV/GHc4o= github.com/dgraph-io/badger/v2 v2.2007.4/go.mod h1:vSw/ax2qojzbN6eXHIx6KPKtCSHJN/Uz0X0VPruTIhk= github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de h1:t0UHb5vdojIDUqktM6+xJAfScFBsVpXZmqC9dsgJmeA= @@ -119,7 +118,6 @@ github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c/go.mod h1:RqIHx9QI github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw= github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= @@ -128,7 +126,6 @@ github.com/rogpeppe/fastuuid v1.2.0 h1:Ppwyp6VYCF1nvBTXL3trRso7mXMlRrw9ooo375wvi github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= -github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc= github.com/shirou/gopsutil/v3 v3.23.2 h1:PAWSuiAszn7IhPMBtXsbSCafej7PqUOvY6YywlQUExU= github.com/shirou/gopsutil/v3 v3.23.2/go.mod h1:gv0aQw33GLo3pG8SiWKiQrbDzbRY1K80RyZJ7V4Th1M= @@ -147,6 +144,9 @@ github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7Am github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYms= github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= github.com/valyala/fasthttp v1.58.0/go.mod h1:SYXvHHaFp7QZHGKSHmoMipInhrI5StHrhDTYVEjK/Kw= +github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= +github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= +github.com/yuin/goldmark v1.4.1 h1:/vn0k+RBvwlxEmP5E7SZMqNxPhfMVFEJiykr15/0XKM= github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= @@ -163,6 +163,7 @@ golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= 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/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= @@ -184,6 +185,7 @@ golang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4/go.mod h1:g5NllXBEermZ golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa/go.mod h1:kHjTxDEnAu6/Nl9lDkzjWpR+bmKfxeiRuSDlsMb70gE= 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/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= @@ -192,6 +194,7 @@ golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= 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/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= gonum.org/v1/plot v0.15.2 h1:Tlfh/jBk2tqjLZ4/P8ZIwGrLEWQSPDLRm/SNWKNXiGI= diff --git a/vendor/github.com/getsentry/sentry-go/interfaces.go b/vendor/github.com/getsentry/sentry-go/interfaces.go index d4b4964..4d14df6 100644 --- a/vendor/github.com/getsentry/sentry-go/interfaces.go +++ b/vendor/github.com/getsentry/sentry-go/interfaces.go @@ -247,50 +247,43 @@ type Request struct { Env map[string]string `json:"env,omitempty"` } -func sendDefaultPIIEnabled(client *Client) bool { - return client != nil && client.options.SendDefaultPII -} - -func newRequest(r *http.Request, sendDefaultPII bool) *Request { +func newRequest(r *http.Request, client *Client) *Request { prot := protocol.SchemeHTTP if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" { prot = protocol.SchemeHTTPS } url := fmt.Sprintf("%s://%s%s", prot, r.Host, r.URL.Path) + dc := client.GetDataCollection() + var cookies string - var env map[string]string - headers := map[string]string{} - - if sendDefaultPII { - // We read only the first Cookie header because of the specification: - // https://tools.ietf.org/html/rfc6265#section-5.4 - // When the user agent generates an HTTP request, the user agent MUST NOT - // attach more than one Cookie header field. - cookies = r.Header.Get("Cookie") - - headers = make(map[string]string, len(r.Header)) - for k, v := range r.Header { - headers[k] = strings.Join(v, ",") + headers := make(map[string]string, len(r.Header)+1) + if dc.CollectCookies() { + cookies = dc.FilterCookies(r.Header.Values("Cookie")) + if cookies != "" { + headers["Cookie"] = cookies } + } + for k, v := range r.Header { + if strings.EqualFold(k, "Cookie") { + continue + } + headers[k] = strings.Join(v, ",") + } + headers["Host"] = r.Host + headers = dc.FilterRequestHeaders(headers) + var env map[string]string + if dc.UserInfo.Value { if addr, port, err := net.SplitHostPort(r.RemoteAddr); err == nil { env = map[string]string{"REMOTE_ADDR": addr, "REMOTE_PORT": port} } - } else { - for k, v := range r.Header { - if !IsSensitiveHeader(k) { - headers[k] = strings.Join(v, ",") - } - } } - headers["Host"] = r.Host - return &Request{ URL: url, Method: r.Method, - QueryString: r.URL.RawQuery, + QueryString: dc.FilterQueryString(r.URL.RawQuery), Cookies: cookies, Headers: headers, Env: env, @@ -302,7 +295,7 @@ func newRequest(r *http.Request, sendDefaultPII bool) *Request { // NewRequest avoids operations that depend on network access. In particular, it // does not read r.Body. func NewRequest(r *http.Request) *Request { - return newRequest(r, sendDefaultPIIEnabled(CurrentHub().Client())) + return newRequest(r, CurrentHub().Client()) } // Mechanism is the mechanism by which an exception was generated and handled. diff --git a/vendor/github.com/getsentry/sentry-go/internal/httputils/body.go b/vendor/github.com/getsentry/sentry-go/internal/httputils/body.go new file mode 100644 index 0000000..4488c86 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/httputils/body.go @@ -0,0 +1,78 @@ +package httputils + +import ( + "bytes" + "io" +) + +// MaxBodyBytes is the maximum number of bytes the SDK captures from an HTTP +// body for attaching to events or spans. Bodies larger than this are dropped +// rather than truncated, to avoid invalid partial structured payloads. +const MaxBodyBytes = 10 * 1024 + +// ReadCloser combines an io.Reader and an io.Closer to implement io.ReadCloser. +type ReadCloser struct { + io.Reader + io.Closer +} + +// LimitedBuffer is like a bytes.Buffer, but limited to store at most Capacity +// bytes. Any writes past the capacity are silently discarded, similar to +// io.Discard. +type LimitedBuffer struct { + Capacity int + + bytes.Buffer + overflow bool +} + +// NewLimitedBuffer returns a LimitedBuffer with the given capacity. +func NewLimitedBuffer(capacity int) *LimitedBuffer { + return &LimitedBuffer{Capacity: capacity} +} + +// NewLimitedBufferFromBytes returns a LimitedBuffer initialized from b. +func NewLimitedBufferFromBytes(capacity int, b []byte) *LimitedBuffer { + buf := NewLimitedBuffer(capacity) + if len(b) > capacity { + buf.overflow = true + b = b[:capacity] + } + buf.Buffer = *bytes.NewBuffer(b) + return buf +} + +// Write implements io.Writer. +func (b *LimitedBuffer) Write(p []byte) (n int, err error) { + originalLen := len(p) + if b.overflow { + return originalLen, nil + } + left := b.Capacity - b.Len() + if left < 0 { + left = 0 + } + if len(p) > left { + b.overflow = true + p = p[:left] + } + _, err = b.Buffer.Write(p) + return originalLen, err +} + +// Overflow returns true if the LimitedBuffer discarded bytes written to it. +func (b *LimitedBuffer) Overflow() bool { + return b.overflow +} + +// ReadBody reads up to MaxBodyBytes from r and returns the bytes read. +func ReadBody(r io.Reader) []byte { + if r == nil { + return nil + } + data, err := io.ReadAll(io.LimitReader(r, MaxBodyBytes+1)) + if err != nil || len(data) == 0 || len(data) > MaxBodyBytes { + return nil + } + return data +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go b/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go new file mode 100644 index 0000000..51bf910 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go @@ -0,0 +1,199 @@ +package httputils + +import ( + "bufio" + "io" + "net" + "net/http" +) + +// This wrapper is derived from https://github.com/go-chi/chi/blob/master/middleware/wrap_writer.go +// Copyright (c) 2015-present Peter Kieltyka (https://github.com/pkieltyka), Google Inc. + +// MIT License + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to +// hook into various parts of the response process. + +func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter { + _, fl := w.(http.Flusher) + + bw := basicWriter{ResponseWriter: w, code: http.StatusOK} + + if protoMajor == 2 { + _, ps := w.(http.Pusher) + if fl && ps { + return &http2FancyWriter{bw} + } + } else { + _, hj := w.(http.Hijacker) + _, rf := w.(io.ReaderFrom) + if fl && hj && rf { + return &httpFancyWriter{bw} + } + } + if fl { + return &flushWriter{bw} + } + + return &bw +} + +// WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook +// into various parts of the response process. +type WrapResponseWriter interface { + http.ResponseWriter + // Status returns the HTTP status of the request, or 200 if one has not + // yet been sent. + Status() int + // BytesWritten returns the total number of bytes sent to the client. + BytesWritten() int + // Tee causes the response body to be written to the given io.Writer in + // addition to proxying the writes through. Only one io.Writer can be + // tee'd to at once: setting a second one will overwrite the first. + // Writes will be sent to the proxy before being written to this + // io.Writer. It is illegal for the tee'd writer to be modified + // concurrently with writes. + Tee(io.Writer) + // Unwrap returns the original proxied target. + Unwrap() http.ResponseWriter +} + +// basicWriter wraps a http.ResponseWriter that implements the minimal +// http.ResponseWriter interface. +type basicWriter struct { + http.ResponseWriter + tee io.Writer + code int + bytes int + wroteHeader bool +} + +func (b *basicWriter) WriteHeader(code int) { + if !b.wroteHeader { + b.code = code + b.wroteHeader = true + } + b.ResponseWriter.WriteHeader(code) +} + +func (b *basicWriter) Write(buf []byte) (int, error) { + b.maybeWriteHeader() + n, err := b.ResponseWriter.Write(buf) + if b.tee != nil { + _, err2 := b.tee.Write(buf[:n]) + // Prefer errors generated by the proxied writer. + if err == nil { + err = err2 + } + } + b.bytes += n + return n, err +} + +func (b *basicWriter) maybeWriteHeader() { + if !b.wroteHeader { + b.WriteHeader(http.StatusOK) + } +} + +func (b *basicWriter) Status() int { + return b.code +} + +func (b *basicWriter) BytesWritten() int { + return b.bytes +} + +func (b *basicWriter) Tee(w io.Writer) { + b.tee = w +} + +func (b *basicWriter) Unwrap() http.ResponseWriter { + return b.ResponseWriter +} + +type flushWriter struct { + basicWriter +} + +func (f *flushWriter) Flush() { + f.wroteHeader = true + + fl := f.ResponseWriter.(http.Flusher) + fl.Flush() +} + +var _ http.Flusher = &flushWriter{} + +// httpFancyWriter is a HTTP writer that additionally satisfies +// http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case +// of wrapping the http.ResponseWriter that package http gives you, in order to +// make the proxied object support the full method set of the proxied object. +type httpFancyWriter struct { + basicWriter +} + +func (f *httpFancyWriter) Flush() { + f.wroteHeader = true + f.ResponseWriter.(http.Flusher).Flush() +} + +func (f *httpFancyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return f.ResponseWriter.(http.Hijacker).Hijack() +} + +func (f *http2FancyWriter) Push(target string, opts *http.PushOptions) error { + return f.ResponseWriter.(http.Pusher).Push(target, opts) +} + +func (f *httpFancyWriter) ReadFrom(r io.Reader) (int64, error) { + if f.tee != nil { + n, err := io.Copy(&f.basicWriter, r) + f.bytes += int(n) + return n, err + } + rf := f.ResponseWriter.(io.ReaderFrom) + f.maybeWriteHeader() + n, err := rf.ReadFrom(r) + f.bytes += int(n) + return n, err +} + +var _ http.Flusher = &httpFancyWriter{} +var _ http.Hijacker = &httpFancyWriter{} +var _ http.Pusher = &http2FancyWriter{} +var _ io.ReaderFrom = &httpFancyWriter{} + +// http2FancyWriter is a HTTP2 writer that additionally satisfies +// http.Flusher, and io.ReaderFrom. It exists for the common case +// of wrapping the http.ResponseWriter that package http gives you, in order to +// make the proxied object support the full method set of the proxied object. +type http2FancyWriter struct { + basicWriter +} + +func (f *http2FancyWriter) Flush() { + f.wroteHeader = true + + f.basicWriter.ResponseWriter.(http.Flusher).Flush() +} + +var _ http.Flusher = &http2FancyWriter{} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go index 51d1222..024053c 100644 --- a/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go @@ -17,7 +17,7 @@ type Envelope struct { // EnvelopeHeader represents the header of a Sentry envelope. type EnvelopeHeader struct { // EventID is the unique identifier for this event - EventID string `json:"event_id"` + EventID string `json:"event_id,omitempty"` // SentAt is the timestamp when the event was sent from the SDK as string in RFC 3339 format. // Used for clock drift correction of the event timestamp. The time zone must be UTC. diff --git a/vendor/github.com/getsentry/sentry-go/internal/telemetry/bucketed_buffer.go b/vendor/github.com/getsentry/sentry-go/internal/telemetry/bucketed_buffer.go index d6f7f46..81ee3ba 100644 --- a/vendor/github.com/getsentry/sentry-go/internal/telemetry/bucketed_buffer.go +++ b/vendor/github.com/getsentry/sentry-go/internal/telemetry/bucketed_buffer.go @@ -46,8 +46,10 @@ type BucketedBuffer[T any] struct { timeout time.Duration lastFlushTime time.Time - offered int64 - dropped int64 + // atomic.Int64 instead of int64 + atomic ops: 64-bit atomics on plain + // mid-struct fields panic on 32-bit platforms (4-byte field alignment). + offered atomic.Int64 + dropped atomic.Int64 onDropped func(item T, reason string) } @@ -94,7 +96,7 @@ func NewBucketedBuffer[T any]( } func (b *BucketedBuffer[T]) Offer(item T) bool { - atomic.AddInt64(&b.offered, 1) + b.offered.Add(1) traceID := "" if ta, ok := any(item).(TraceAware); ok { @@ -152,7 +154,7 @@ func (b *BucketedBuffer[T]) handleOverflow(item T, traceID string) bool { oldestBucket := b.buckets[b.head] if oldestBucket == nil { b.recordDroppedItem(item) - atomic.AddInt64(&b.dropped, 1) + b.dropped.Add(1) if b.onDropped != nil { b.onDropped(item, "buffer_full_invalid_state") } @@ -162,7 +164,7 @@ func (b *BucketedBuffer[T]) handleOverflow(item T, traceID string) bool { delete(b.traceIndex, oldestBucket.traceID) } droppedCount := len(oldestBucket.items) - atomic.AddInt64(&b.dropped, int64(droppedCount)) + b.dropped.Add(int64(droppedCount)) for _, di := range oldestBucket.items { b.recordDroppedItem(di) if b.onDropped != nil { @@ -183,14 +185,14 @@ func (b *BucketedBuffer[T]) handleOverflow(item T, traceID string) bool { b.totalItems++ return true case OverflowPolicyDropNewest: - atomic.AddInt64(&b.dropped, 1) + b.dropped.Add(1) b.recordDroppedItem(item) if b.onDropped != nil { b.onDropped(item, "buffer_full_drop_newest") } return false default: - atomic.AddInt64(&b.dropped, 1) + b.dropped.Add(1) b.recordDroppedItem(item) if b.onDropped != nil { b.onDropped(item, "unknown_overflow_policy") @@ -351,8 +353,8 @@ func (b *BucketedBuffer[T]) Utilization() float64 { } return float64(b.totalItems) / float64(b.itemCapacity) } -func (b *BucketedBuffer[T]) OfferedCount() int64 { return atomic.LoadInt64(&b.offered) } -func (b *BucketedBuffer[T]) DroppedCount() int64 { return atomic.LoadInt64(&b.dropped) } +func (b *BucketedBuffer[T]) OfferedCount() int64 { return b.offered.Load() } +func (b *BucketedBuffer[T]) DroppedCount() int64 { return b.dropped.Load() } func (b *BucketedBuffer[T]) AcceptedCount() int64 { return b.OfferedCount() - b.DroppedCount() } func (b *BucketedBuffer[T]) DropRate() float64 { off := b.OfferedCount() diff --git a/vendor/github.com/getsentry/sentry-go/internal/telemetry/ring_buffer.go b/vendor/github.com/getsentry/sentry-go/internal/telemetry/ring_buffer.go index ea6c705..8ef0e0f 100644 --- a/vendor/github.com/getsentry/sentry-go/internal/telemetry/ring_buffer.go +++ b/vendor/github.com/getsentry/sentry-go/internal/telemetry/ring_buffer.go @@ -30,8 +30,10 @@ type RingBuffer[T any] struct { timeout time.Duration lastFlushTime time.Time - offered int64 - dropped int64 + // atomic.Int64 instead of int64 + atomic ops: 64-bit atomics on plain + // mid-struct fields panic on 32-bit platforms (4-byte field alignment). + offered atomic.Int64 + dropped atomic.Int64 onDropped func(item T, reason string) } @@ -72,7 +74,7 @@ func (b *RingBuffer[T]) SetDroppedCallback(callback func(item T, reason string)) } func (b *RingBuffer[T]) Offer(item T) bool { - atomic.AddInt64(&b.offered, 1) + b.offered.Add(1) b.mu.Lock() defer b.mu.Unlock() @@ -91,7 +93,7 @@ func (b *RingBuffer[T]) Offer(item T) bool { b.head = (b.head + 1) % b.capacity b.tail = (b.tail + 1) % b.capacity - atomic.AddInt64(&b.dropped, 1) + b.dropped.Add(1) b.recordDroppedItem(oldItem) if b.onDropped != nil { b.onDropped(oldItem, "buffer_full_drop_oldest") @@ -99,7 +101,7 @@ func (b *RingBuffer[T]) Offer(item T) bool { return true case OverflowPolicyDropNewest: - atomic.AddInt64(&b.dropped, 1) + b.dropped.Add(1) b.recordDroppedItem(item) if b.onDropped != nil { b.onDropped(item, "buffer_full_drop_newest") @@ -107,7 +109,7 @@ func (b *RingBuffer[T]) Offer(item T) bool { return false default: - atomic.AddInt64(&b.dropped, 1) + b.dropped.Add(1) b.recordDroppedItem(item) if b.onDropped != nil { b.onDropped(item, "unknown_overflow_policy") @@ -244,11 +246,11 @@ func (b *RingBuffer[T]) Utilization() float64 { } func (b *RingBuffer[T]) OfferedCount() int64 { - return atomic.LoadInt64(&b.offered) + return b.offered.Load() } func (b *RingBuffer[T]) DroppedCount() int64 { - return atomic.LoadInt64(&b.dropped) + return b.dropped.Load() } func (b *RingBuffer[T]) AcceptedCount() int64 { diff --git a/vendor/github.com/getsentry/sentry-go/log.go b/vendor/github.com/getsentry/sentry-go/log.go index 979ca3b..0279bd8 100644 --- a/vendor/github.com/getsentry/sentry-go/log.go +++ b/vendor/github.com/getsentry/sentry-go/log.go @@ -101,7 +101,7 @@ func (l *sentryLogger) Write(p []byte) (int, error) { return len(p), nil } -func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, message string, entryAttrs map[string]attribute.Value, args ...interface{}) { +func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, message string, entryAttrs map[string]attribute.Value, format bool, args ...interface{}) { if message == "" { return } @@ -138,6 +138,11 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me attrs[k] = v } + body := message + if format { + body = fmt.Sprintf(message, args...) + } + if len(args) > 0 { attrs["sentry.message.template"] = attribute.StringValue(message) for i, p := range args { @@ -151,14 +156,14 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me SpanID: spanID, Level: level, Severity: severity, - Body: fmt.Sprintf(message, args...), + Body: body, Attributes: attrs, } log.approximateSize = computeLogSize(log) client.captureLog(log, scope) if client.options.Debug { - debuglog.Printf(message, args...) + debuglog.Print(body) } } @@ -327,7 +332,7 @@ func (e *logEntry) Uint64(key string, value uint64) LogEntry { } func (e *logEntry) Emit(args ...interface{}) { - e.logger.log(e.ctx, e.level, e.severity, fmt.Sprint(args...), e.attributes) + e.logger.log(e.ctx, e.level, e.severity, fmt.Sprint(args...), e.attributes, false) if e.level == LogLevelFatal { if e.shouldPanic { @@ -340,7 +345,7 @@ func (e *logEntry) Emit(args ...interface{}) { } func (e *logEntry) Emitf(format string, args ...interface{}) { - e.logger.log(e.ctx, e.level, e.severity, format, e.attributes, args...) + e.logger.log(e.ctx, e.level, e.severity, format, e.attributes, true, args...) if e.level == LogLevelFatal { if e.shouldPanic { diff --git a/vendor/github.com/getsentry/sentry-go/option.go b/vendor/github.com/getsentry/sentry-go/option.go new file mode 100644 index 0000000..4941ab3 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/option.go @@ -0,0 +1,23 @@ +package sentry + +// Option represents an optional configuration value. +// +// The zero value is unset. Use Set to distinguish an explicitly configured +// zero value, such as false, 0, or "", from an unset option. +type Option[T any] struct { + Value T + IsSet bool +} + +// Set returns an Option containing v. +func Set[T any](v T) Option[T] { + return Option[T]{Value: v, IsSet: true} +} + +// Or returns the option value when set, or defaultValue otherwise. +func (o Option[T]) Or(defaultValue T) T { + if o.IsSet { + return o.Value + } + return defaultValue +} diff --git a/vendor/github.com/getsentry/sentry-go/scope.go b/vendor/github.com/getsentry/sentry-go/scope.go index 118fb8d..c7a6067 100644 --- a/vendor/github.com/getsentry/sentry-go/scope.go +++ b/vendor/github.com/getsentry/sentry-go/scope.go @@ -1,7 +1,6 @@ package sentry import ( - "bytes" "context" "io" "maps" @@ -11,6 +10,7 @@ import ( "github.com/getsentry/sentry-go/attribute" "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/httputils" "github.com/getsentry/sentry-go/internal/ratelimit" "github.com/getsentry/sentry-go/report" ) @@ -128,15 +128,15 @@ func (scope *Scope) SetRequest(r *http.Request) { } // Don't buffer request body if we know it is oversized. - if r.ContentLength > maxRequestBodyBytes { + if r.ContentLength > httputils.MaxBodyBytes { return } // Don't buffer if there is no body. if r.Body == nil || r.Body == http.NoBody { return } - buf := &limitedBuffer{Capacity: maxRequestBodyBytes} - r.Body = readCloser{ + buf := httputils.NewLimitedBuffer(httputils.MaxBodyBytes) + r.Body = httputils.ReadCloser{ Reader: io.TeeReader(r.Body, buf), Closer: r.Body, } @@ -152,59 +152,7 @@ func (scope *Scope) SetRequestBody(b []byte) { scope.mu.Lock() defer scope.mu.Unlock() - capacity := maxRequestBodyBytes - overflow := false - if len(b) > capacity { - overflow = true - b = b[:capacity] - } - scope.requestBody = &limitedBuffer{ - Capacity: capacity, - Buffer: *bytes.NewBuffer(b), - overflow: overflow, - } -} - -// maxRequestBodyBytes is the default maximum request body size to send to -// Sentry. -const maxRequestBodyBytes = 10 * 1024 - -// A limitedBuffer is like a bytes.Buffer, but limited to store at most Capacity -// bytes. Any writes past the capacity are silently discarded, similar to -// io.Discard. -type limitedBuffer struct { - Capacity int - - bytes.Buffer - overflow bool -} - -// Write implements io.Writer. -func (b *limitedBuffer) Write(p []byte) (n int, err error) { - // Silently ignore writes after overflow. - if b.overflow { - return len(p), nil - } - left := b.Capacity - b.Len() - if left < 0 { - left = 0 - } - if len(p) > left { - b.overflow = true - p = p[:left] - } - return b.Buffer.Write(p) -} - -// Overflow returns true if the limitedBuffer discarded bytes written to it. -func (b *limitedBuffer) Overflow() bool { - return b.overflow -} - -// readCloser combines an io.Reader and an io.Closer to implement io.ReadCloser. -type readCloser struct { - io.Reader - io.Closer + scope.requestBody = httputils.NewLimitedBufferFromBytes(httputils.MaxBodyBytes, b) } // SetAttributes adds attributes to the current scope. @@ -346,7 +294,7 @@ func (scope *Scope) Clone() *Scope { clone.level = scope.level clone.request = scope.request clone.requestBody = scope.requestBody - clone.eventProcessors = scope.eventProcessors + clone.eventProcessors = scope.eventProcessors[:len(scope.eventProcessors):len(scope.eventProcessors)] clone.propagationContext = scope.propagationContext clone.span = scope.span return clone @@ -463,7 +411,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) } if event.Request == nil && scope.request != nil { - event.Request = newRequest(scope.request, sendDefaultPIIEnabled(client)) + event.Request = newRequest(scope.request, client) // NOTE: The SDK does not attempt to send partial request body data. // // The reason being that Sentry's ingest pipeline and UI are optimized @@ -473,8 +421,9 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) // // Users can still send more data along their events if they want to, // for example using Event.Contexts. - if scope.requestBody != nil && !scope.requestBody.Overflow() { - event.Request.Data = string(scope.requestBody.Bytes()) + dc := client.GetDataCollection() + if scope.requestBody != nil && !scope.requestBody.Overflow() && dc.CollectHTTPBody(BodyIncomingRequest) { + event.Request.Data = dc.FilterHTTPBody(scope.requestBody.Bytes(), scope.request.Header.Get("Content-Type")) } } diff --git a/vendor/github.com/getsentry/sentry-go/sentry.go b/vendor/github.com/getsentry/sentry-go/sentry.go index be5ab4f..b315c37 100644 --- a/vendor/github.com/getsentry/sentry-go/sentry.go +++ b/vendor/github.com/getsentry/sentry-go/sentry.go @@ -6,7 +6,7 @@ import ( ) // The version of the SDK. -const SDKVersion = "0.47.0" +const SDKVersion = "0.48.0" // apiVersion is the minimum version of the Sentry API compatible with the // sentry-go SDK. @@ -101,9 +101,9 @@ func ConfigureScope(f func(scope *Scope)) { } // PushScope is a shorthand for CurrentHub().PushScope. -func PushScope() { +func PushScope() *Scope { hub := CurrentHub() - hub.PushScope() + return hub.PushScope() } // PopScope is a shorthand for CurrentHub().PopScope. diff --git a/vendor/github.com/getsentry/sentry-go/util.go b/vendor/github.com/getsentry/sentry-go/util.go index 11be8e6..f81ef1d 100644 --- a/vendor/github.com/getsentry/sentry-go/util.go +++ b/vendor/github.com/getsentry/sentry-go/util.go @@ -111,45 +111,6 @@ func Pointer[T any](v T) *T { return &v } -var sensitiveHeaders = map[string]struct{}{ - "_csrf": {}, - "_csrf_token": {}, - "_session": {}, - "_xsrf": {}, - "api-key": {}, - "apikey": {}, - "auth": {}, - "authorization": {}, - "cookie": {}, - "credentials": {}, - "csrf": {}, - "csrf-token": {}, - "csrftoken": {}, - "ip-address": {}, - "passwd": {}, - "password": {}, - "private-key": {}, - "privatekey": {}, - "proxy-authorization": {}, - "remote-addr": {}, - "secret": {}, - "session": {}, - "sessionid": {}, - "token": {}, - "user-session": {}, - "x-api-key": {}, - "x-csrftoken": {}, - "x-forwarded-for": {}, - "x-real-ip": {}, - "xsrf-token": {}, -} - -// IsSensitiveHeader reports whether a header or metadata key should be treated as sensitive. -func IsSensitiveHeader(key string) bool { - _, ok := sensitiveHeaders[strings.ToLower(key)] - return ok -} - // eventIdentifier returns a human-readable identifier for the event to be used in log messages. // Format: " []". func eventIdentifier(event *Event) string { diff --git a/vendor/github.com/go-faker/faker/v4/.golangci.yaml b/vendor/github.com/go-faker/faker/v4/.golangci.yaml index 0b8124c..6ff5c54 100644 --- a/vendor/github.com/go-faker/faker/v4/.golangci.yaml +++ b/vendor/github.com/go-faker/faker/v4/.golangci.yaml @@ -39,6 +39,9 @@ linters: - legacy - std-error-handling rules: + - linters: + - goconst + path: lorem.go - linters: - misspell path: person.go diff --git a/vendor/github.com/go-faker/faker/v4/README.md b/vendor/github.com/go-faker/faker/v4/README.md index 7e99336..491fe6e 100644 --- a/vendor/github.com/go-faker/faker/v4/README.md +++ b/vendor/github.com/go-faker/faker/v4/README.md @@ -99,8 +99,8 @@ Support For : Unfortunately this library has some limitation - It does not support private fields. Make sure your structs fields you intend to generate fake data for are public, it would otherwise trigger a panic. You can however omit fields using a tag skip `faker:"-"` on your private fields. -- It does not support the `interface{}` data type. How could we generate anything without knowing its data type? -- It does not support the `map[interface{}]interface{}`, `map[any_type]interface{}` & `map[interface{}]any_type` data types. Once again, we cannot generate values for an unknown data type. +- It does not support the `any` (empty interface) data type. How could we generate anything without knowing its data type? +- 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. diff --git a/vendor/github.com/go-faker/faker/v4/address.go b/vendor/github.com/go-faker/faker/v4/address.go index 7c3da38..59962b3 100644 --- a/vendor/github.com/go-faker/faker/v4/address.go +++ b/vendor/github.com/go-faker/faker/v4/address.go @@ -42,10 +42,10 @@ func GetAddress() Addresser { // Addresser is logical layer for Address type Addresser interface { - Latitude(v reflect.Value) (interface{}, error) - Longitude(v reflect.Value) (interface{}, error) - RealWorld(v reflect.Value) (interface{}, error) - CountryInfo(v reflect.Value) (interface{}, error) + Latitude(v reflect.Value) (any, error) + Longitude(v reflect.Value) (any, error) + RealWorld(v reflect.Value) (any, error) + CountryInfo(v reflect.Value) (any, error) } // Address struct @@ -56,7 +56,7 @@ func (i Address) latitude() float32 { } // Latitude sets latitude of the address -func (i Address) Latitude(v reflect.Value) (interface{}, error) { +func (i Address) Latitude(v reflect.Value) (any, error) { kind := v.Kind() val := i.latitude() if kind == reflect.Float32 { @@ -70,7 +70,7 @@ func (i Address) longitude() float32 { } // Longitude sets longitude of the address -func (i Address) Longitude(v reflect.Value) (interface{}, error) { +func (i Address) Longitude(v reflect.Value) (any, error) { kind := v.Kind() val := i.longitude() if kind == reflect.Float32 { @@ -87,18 +87,18 @@ func (i Address) countryInfo() CountryInfo { return countries[rand.Intn(len(countries))] } -func (i Address) CountryInfo(_ reflect.Value) (interface{}, error) { +func (i Address) CountryInfo(_ reflect.Value) (any, error) { return i.countryInfo(), nil } // RealWorld sets real world address -func (i Address) RealWorld(_ reflect.Value) (interface{}, error) { +func (i Address) RealWorld(_ reflect.Value) (any, error) { return i.realWorld(), nil } // Longitude get fake longitude randomly func Longitude(opts ...options.OptionFunc) float64 { - return singleFakeData(LONGITUDE, func() interface{} { + return singleFakeData(LONGITUDE, func() any { address := Address{} return float64(address.longitude()) }, opts...).(float64) @@ -106,7 +106,7 @@ func Longitude(opts ...options.OptionFunc) float64 { // Latitude get fake latitude randomly func Latitude(opts ...options.OptionFunc) float64 { - return singleFakeData(LATITUDE, func() interface{} { + return singleFakeData(LATITUDE, func() any { address := Address{} return float64(address.latitude()) }, opts...).(float64) @@ -127,7 +127,7 @@ type RealAddress struct { // GetRealAddress get real world address randomly func GetRealAddress(opts ...options.OptionFunc) RealAddress { - return singleFakeData(RealAddressTag, func() interface{} { + return singleFakeData(RealAddressTag, func() any { address := Address{} return address.realWorld() }, opts...).(RealAddress) @@ -142,7 +142,7 @@ type CountryInfo struct { } func GetCountryInfo(opts ...options.OptionFunc) CountryInfo { - return singleFakeData(CountryInfoTag, func() interface{} { + return singleFakeData(CountryInfoTag, func() any { address := Address{} return address.countryInfo() }, opts...).(CountryInfo) diff --git a/vendor/github.com/go-faker/faker/v4/blood.go b/vendor/github.com/go-faker/faker/v4/blood.go index feb80ec..5e4dbea 100644 --- a/vendor/github.com/go-faker/faker/v4/blood.go +++ b/vendor/github.com/go-faker/faker/v4/blood.go @@ -19,9 +19,9 @@ func GetBlood(opts ...options.OptionFunc) Blooder { } type Blooder interface { - BloodType(v reflect.Value) (interface{}, error) - BloodRHFactor(v reflect.Value) (interface{}, error) - BloodGroup(v reflect.Value) (interface{}, error) + BloodType(v reflect.Value) (any, error) + BloodRHFactor(v reflect.Value) (any, error) + BloodGroup(v reflect.Value) (any, error) } // Internet struct @@ -33,7 +33,7 @@ func (b Blood) bloodType() string { return randomElementFromSliceString(bloodTypes) } -func (b Blood) BloodType(v reflect.Value) (interface{}, error) { +func (b Blood) BloodType(v reflect.Value) (any, error) { return b.bloodType(), nil } @@ -41,7 +41,7 @@ func (b Blood) bloodRhFactor() string { return randomElementFromSliceString(bloodRhFactors) } -func (b Blood) BloodRHFactor(v reflect.Value) (interface{}, error) { +func (b Blood) BloodRHFactor(v reflect.Value) (any, error) { return b.bloodRhFactor(), nil } @@ -49,6 +49,6 @@ func (b Blood) bloodGroup() string { return fmt.Sprintf("%s%s", b.bloodType(), b.bloodRhFactor()) } -func (b Blood) BloodGroup(v reflect.Value) (interface{}, error) { +func (b Blood) BloodGroup(v reflect.Value) (any, error) { return b.bloodGroup(), nil } diff --git a/vendor/github.com/go-faker/faker/v4/datetime.go b/vendor/github.com/go-faker/faker/v4/datetime.go index e71d334..b548a5c 100644 --- a/vendor/github.com/go-faker/faker/v4/datetime.go +++ b/vendor/github.com/go-faker/faker/v4/datetime.go @@ -606,17 +606,17 @@ const ( // A DateTimer contains random Time generators, returning time string in certain particular format type DateTimer interface { - UnixTime(v reflect.Value) (interface{}, error) - Date(v reflect.Value) (interface{}, error) - Time(v reflect.Value) (interface{}, error) - MonthName(v reflect.Value) (interface{}, error) - Year(v reflect.Value) (interface{}, error) - DayOfWeek(v reflect.Value) (interface{}, error) - DayOfMonth(v reflect.Value) (interface{}, error) - Timestamp(v reflect.Value) (interface{}, error) - Century(v reflect.Value) (interface{}, error) - TimeZone(v reflect.Value) (interface{}, error) - TimePeriod(v reflect.Value) (interface{}, error) + UnixTime(v reflect.Value) (any, error) + Date(v reflect.Value) (any, error) + Time(v reflect.Value) (any, error) + MonthName(v reflect.Value) (any, error) + Year(v reflect.Value) (any, error) + DayOfWeek(v reflect.Value) (any, error) + DayOfMonth(v reflect.Value) (any, error) + Timestamp(v reflect.Value) (any, error) + Century(v reflect.Value) (any, error) + TimeZone(v reflect.Value) (any, error) + TimePeriod(v reflect.Value) (any, error) } // GetDateTimer returns a new DateTimer interface of DateTime @@ -634,7 +634,7 @@ func (d DateTime) unixtime() int64 { } // UnixTime get unix time -func (d DateTime) UnixTime(v reflect.Value) (interface{}, error) { +func (d DateTime) UnixTime(v reflect.Value) (any, error) { kind := v.Kind() var val int64 if kind == reflect.Int64 { @@ -648,7 +648,7 @@ func (d DateTime) UnixTime(v reflect.Value) (interface{}, error) { // UnixTime get unix time randomly func UnixTime(opts ...options.OptionFunc) int64 { - return singleFakeData(UnixTimeTag, func() interface{} { + return singleFakeData(UnixTimeTag, func() any { datetime := DateTime{} return datetime.unixtime() }, opts...).(int64) @@ -659,13 +659,13 @@ func (d DateTime) date() string { } // Date formats DateTime using example BaseDateFormat const -func (d DateTime) Date(v reflect.Value) (interface{}, error) { +func (d DateTime) Date(v reflect.Value) (any, error) { return d.date(), nil } // Date get fake date in string randomly func Date(opts ...options.OptionFunc) string { - return singleFakeData(DATE, func() interface{} { + return singleFakeData(DATE, func() any { datetime := DateTime{} return datetime.date() }, opts...).(string) @@ -676,13 +676,13 @@ func (d DateTime) time() string { } // Time formats DateTime using example Time const -func (d DateTime) Time(v reflect.Value) (interface{}, error) { +func (d DateTime) Time(v reflect.Value) (any, error) { return d.time(), nil } // TimeString get time randomly in string format func TimeString(opts ...options.OptionFunc) string { - return singleFakeData(TIME, func() interface{} { + return singleFakeData(TIME, func() any { datetime := DateTime{} return datetime.time() }, opts...).(string) @@ -693,13 +693,13 @@ func (d DateTime) monthName() string { } // MonthName formats DateTime using example Month const -func (d DateTime) MonthName(v reflect.Value) (interface{}, error) { +func (d DateTime) MonthName(v reflect.Value) (any, error) { return d.monthName(), nil } // MonthName get month name randomly in string format func MonthName(opts ...options.OptionFunc) string { - return singleFakeData(MonthNameTag, func() interface{} { + return singleFakeData(MonthNameTag, func() any { datetime := DateTime{} return datetime.monthName() }, opts...).(string) @@ -710,13 +710,13 @@ func (d DateTime) year() string { } // Year formats DateTime using example Year const -func (d DateTime) Year(v reflect.Value) (interface{}, error) { +func (d DateTime) Year(v reflect.Value) (any, error) { return d.year(), nil } // YearString get year randomly in string format func YearString(opts ...options.OptionFunc) string { - return singleFakeData(YEAR, func() interface{} { + return singleFakeData(YEAR, func() any { datetime := DateTime{} return datetime.year() }, opts...).(string) @@ -727,13 +727,13 @@ func (d DateTime) dayOfWeek() string { } // DayOfWeek formats DateTime using example Day const -func (d DateTime) DayOfWeek(v reflect.Value) (interface{}, error) { +func (d DateTime) DayOfWeek(v reflect.Value) (any, error) { return d.dayOfWeek(), nil } // DayOfWeek get day of week randomly in string format func DayOfWeek(opts ...options.OptionFunc) string { - return singleFakeData(DayOfWeekTag, func() interface{} { + return singleFakeData(DayOfWeekTag, func() any { datetime := DateTime{} return datetime.dayOfWeek() }, opts...).(string) @@ -744,13 +744,13 @@ func (d DateTime) dayOfMonth() string { } // DayOfMonth formats DateTime using example DayOfMonth const -func (d DateTime) DayOfMonth(v reflect.Value) (interface{}, error) { +func (d DateTime) DayOfMonth(v reflect.Value) (any, error) { return d.dayOfMonth(), nil } // DayOfMonth get month randomly in string format func DayOfMonth(opts ...options.OptionFunc) string { - return singleFakeData(DayOfMonthTag, func() interface{} { + return singleFakeData(DayOfMonthTag, func() any { datetime := DateTime{} return datetime.dayOfMonth() }, opts...).(string) @@ -761,13 +761,13 @@ func (d DateTime) timestamp() string { } // Timestamp formats DateTime using example Timestamp const -func (d DateTime) Timestamp(v reflect.Value) (interface{}, error) { +func (d DateTime) Timestamp(v reflect.Value) (any, error) { return d.timestamp(), nil } // Timestamp get timestamp randomly in string format: 2006-01-02 15:04:05 func Timestamp(opts ...options.OptionFunc) string { - return singleFakeData(TIMESTAMP, func() interface{} { + return singleFakeData(TIMESTAMP, func() any { datetime := DateTime{} return datetime.timestamp() }, opts...).(string) @@ -778,13 +778,13 @@ func (d DateTime) century() string { } // Century returns a random century -func (d DateTime) Century(v reflect.Value) (interface{}, error) { +func (d DateTime) Century(v reflect.Value) (any, error) { return d.century(), nil } // Century get century randomly in string func Century(opts ...options.OptionFunc) string { - return singleFakeData(CENTURY, func() interface{} { + return singleFakeData(CENTURY, func() any { datetime := DateTime{} return datetime.century() }, opts...).(string) @@ -795,13 +795,13 @@ func (d DateTime) timezone() string { } // TimeZone returns a random timezone -func (d DateTime) TimeZone(v reflect.Value) (interface{}, error) { +func (d DateTime) TimeZone(v reflect.Value) (any, error) { return d.timezone(), nil } // Timezone get timezone randomly in string func Timezone(opts ...options.OptionFunc) string { - return singleFakeData(TIMEZONE, func() interface{} { + return singleFakeData(TIMEZONE, func() any { datetime := DateTime{} return datetime.timezone() }, opts...).(string) @@ -812,13 +812,13 @@ func (d DateTime) period() string { } // TimePeriod formats DateTime using example TimePeriod const -func (d DateTime) TimePeriod(v reflect.Value) (interface{}, error) { +func (d DateTime) TimePeriod(v reflect.Value) (any, error) { return d.period(), nil } // Timeperiod get timeperiod randomly in string (AM/PM) func Timeperiod(opts ...options.OptionFunc) string { - return singleFakeData(TimePeriodTag, func() interface{} { + return singleFakeData(TimePeriodTag, func() any { datetime := DateTime{} return datetime.period() }, opts...).(string) diff --git a/vendor/github.com/go-faker/faker/v4/faker.go b/vendor/github.com/go-faker/faker/v4/faker.go index aa1f5f3..6b66d8b 100644 --- a/vendor/github.com/go-faker/faker/v4/faker.go +++ b/vendor/github.com/go-faker/faker/v4/faker.go @@ -12,6 +12,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" fakerErrors "github.com/go-faker/faker/v4/pkg/errors" @@ -124,7 +125,7 @@ func (m *mapperTagCustom) Load(key string) (interfaces.TaggedFunction, bool) { if ok { return tagFunc, ok } - tagPureFunc, ok := mappedTagFunc.(func(v reflect.Value) (interface{}, error)) + tagPureFunc, ok := mappedTagFunc.(func(v reflect.Value) (any, error)) if ok { return tagPureFunc, ok } @@ -290,7 +291,27 @@ var ( SetRandomNumberBoundaries = options.SetRandomNumberBoundaries ) +// mapperTagHasDefaults reports whether mapperTag currently holds the default +// (no-option) generator functions. The common no-option case skips the +// redundant re-store while this is true, avoiding repeated work and lock +// contention under high volume. An option call overwrites mapperTag and clears +// the flag, so the next no-option call restores the defaults. +var mapperTagHasDefaults atomic.Bool + func initMapperTagWithOption(opts ...options.OptionFunc) { + if len(opts) == 0 { + if mapperTagHasDefaults.Load() { + return + } + storeMapperTagWithOption() + mapperTagHasDefaults.Store(true) + return + } + storeMapperTagWithOption(opts...) + mapperTagHasDefaults.Store(false) +} + +func storeMapperTagWithOption(opts ...options.OptionFunc) { mapperTag.Store(EmailTag, GetNetworker(opts...).Email) mapperTag.Store(MacAddressTag, GetNetworker(opts...).MacAddress) mapperTag.Store(DomainNameTag, GetNetworker(opts...).DomainName) @@ -310,11 +331,11 @@ func initOption(opt ...options.OptionFunc) *options.Options { // FakeData is the main function. Will generate a fake data based on your struct. You can use this for automation testing, or anything that need automated data. // You don't need to Create your own data for your testing. -func FakeData(a interface{}, opt ...options.OptionFunc) error { +func FakeData(a any, opt ...options.OptionFunc) error { opts := initOption(opt...) reflectType := reflect.TypeOf(a) - if reflectType.Kind() != reflect.Ptr { + if reflectType.Kind() != reflect.Pointer { return errors.New(fakerErrors.ErrValueNotPtr) } @@ -401,7 +422,7 @@ func RemoveProvider(tag string) error { return nil } -func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, error) { +func getFakedValue(item any, opts *options.Options) (reflect.Value, error) { t := reflect.TypeOf(item) if t == nil { if opts.IgnoreInterface { @@ -418,7 +439,7 @@ func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, erro }() k := t.Kind() switch k { - case reflect.Ptr: + case reflect.Pointer: v := reflect.New(t.Elem()) var val reflect.Value var err error @@ -454,7 +475,7 @@ func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, erro } v := reflect.MakeSlice(t, length, length) innerOpts := opts.Nested() - for i := 0; i < length; i++ { + for i := range length { val, err := getFakedValue(v.Index(i).Interface(), &innerOpts) if err != nil { return reflect.Value{}, err @@ -527,7 +548,7 @@ func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, erro } v := reflect.MakeMap(t) innerOpts := opts.Nested() - for i := 0; i < length; i++ { + for range length { keyInstance := reflect.New(t.Key()).Elem().Interface() key, err := getFakedValue(keyInstance, &innerOpts) if err != nil { @@ -558,7 +579,7 @@ func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, erro } -func getFakedValueForStruct(item interface{}, t reflect.Type, opts *options.Options) (reflect.Value, error) { +func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (reflect.Value, error) { if structTypeProvider, f := opts.StructTypeProviders[t]; f { ft, err := structTypeProvider() return reflect.ValueOf(ft), err @@ -641,7 +662,7 @@ func getFakedValueForStruct(item interface{}, t reflect.Type, opts *options.Opti } value := v.Field(i).Interface() uniqueVal, _ := uniqueValues.Load(tags.fieldType) - uniqueValArr, _ := uniqueVal.([]interface{}) + uniqueValArr, _ := uniqueVal.([]any) if slice.ContainsValue(uniqueValArr, value) { // Retry if unique value already found i-- retry++ @@ -724,12 +745,12 @@ type structTag struct { } func setDataWithTag(v reflect.Value, tag string, opt options.Options) error { - if v.Kind() != reflect.Ptr { + if v.Kind() != reflect.Pointer { return errors.New(fakerErrors.ErrValueNotPtr) } v = reflect.Indirect(v) switch v.Kind() { - case reflect.Ptr: + case reflect.Pointer: if _, exist := mapperTag.Load(tag); !exist { newv := reflect.New(v.Type().Elem()) if err := setDataWithTag(newv, tag, opt); err != nil { @@ -806,7 +827,7 @@ func userDefinedMap(v reflect.Value, tag string, opt options.Options) error { } innerOpt := opt.Nested() definedMap := reflect.MakeMap(v.Type()) - for i := 0; i < length; i++ { + for range length { key, err := getValueWithTag(v.Type().Key(), tag, innerOpt) if err != nil { return err @@ -821,7 +842,7 @@ func userDefinedMap(v reflect.Value, tag string, opt options.Options) error { return nil } -func getValueWithTag(t reflect.Type, tag string, opt options.Options) (interface{}, error) { +func getValueWithTag(t reflect.Type, tag string, opt options.Options) (any, error) { switch t.Kind() { case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: @@ -841,7 +862,7 @@ func getValueWithTag(t reflect.Type, tag string, opt options.Options) (interface } } -func getNumberWithBoundary(t reflect.Type, boundary interfaces.RandomIntegerBoundary) (interface{}, error) { +func getNumberWithBoundary(t reflect.Type, boundary interfaces.RandomIntegerBoundary) (any, error) { switch t.Kind() { case reflect.Uint: return uint(randomIntegerWithBoundary(boundary)), nil @@ -868,7 +889,7 @@ func getNumberWithBoundary(t reflect.Type, boundary interfaces.RandomIntegerBoun } } -func getValueWithNoTag(t reflect.Type, opt options.Options) (interface{}, error) { +func getValueWithNoTag(t reflect.Type, opt options.Options) (any, error) { switch t.Kind() { case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: @@ -947,7 +968,7 @@ func userDefinedArray(v reflect.Value, tag string, opt options.Options) error { } func userDefinedString(v reflect.Value, tag string, opt options.Options) error { - var res interface{} + var res any var err error if tagFunc, ok := mapperTag.Load(tag); ok { @@ -970,7 +991,7 @@ func userDefinedString(v reflect.Value, tag string, opt options.Options) error { } func userDefinedNumber(v reflect.Value, tag string) error { - var res interface{} + var res any var err error if tagFunc, ok := mapperTag.Load(tag); ok { @@ -1014,7 +1035,7 @@ func extractSliceLengthFromTag(tag string, opt options.Options) (int, error) { return randomSliceAndMapSize(opt), nil //Returns random slice length if the sliceLength tag isn't set } -func extractStringFromTag(tag string, opts options.Options) (interface{}, error) { +func extractStringFromTag(tag string, opts options.Options) (any, error) { var err error strlen := opts.RandomStringLength strlng := opts.StringLanguage @@ -1075,7 +1096,7 @@ func extractLangFromTag(tag string) (*interfaces.LangRuneBoundary, error) { } } -func extractNumberFromTag(tag string, t reflect.Type) (interface{}, error) { +func extractNumberFromTag(tag string, t reflect.Type) (any, error) { hasOneOf := strings.Contains(tag, ONEOF) hasBoundaryStart := strings.Contains(tag, BoundaryStart) hasBoundaryEnd := strings.Contains(tag, BoundaryEnd) @@ -1348,10 +1369,7 @@ func randomSliceAndMapSize(opt options.Options) int { maxSize = opt.RandomNestedMaxSliceSize minSize = opt.RandomNestedMinSliceSize } - r := maxSize - minSize - if r < 1 { - r = 1 - } + r := max(maxSize-minSize, 1) return minSize + rand.Intn(r) } @@ -1413,11 +1431,11 @@ func RandomInt(parameters ...int) (p []int, err error) { return p, err } -func generateUnique(dataType string, fn func() interface{}) (interface{}, error) { - for i := 0; i < maxRetry; i++ { +func generateUnique(dataType string, fn func() any) (any, error) { + for range maxRetry { value := fn() uniqueVal, _ := uniqueValues.Load(dataType) - uniqueValArr, _ := uniqueVal.([]interface{}) + uniqueValArr, _ := uniqueVal.([]any) if !slice.ContainsValue(uniqueValArr, value) { // Retry if unique value already found uniqueValues.Store(dataType, append(uniqueValArr, value)) return value, nil @@ -1426,7 +1444,7 @@ func generateUnique(dataType string, fn func() interface{}) (interface{}, error) return reflect.Value{}, fmt.Errorf(fakerErrors.ErrUniqueFailure, dataType) } -func singleFakeData(dataType string, fn func() interface{}, opts ...options.OptionFunc) interface{} { +func singleFakeData(dataType string, fn func() any, opts ...options.OptionFunc) any { ops := initOption(opts...) if ops.GenerateUniqueValues { v, err := generateUnique(dataType, fn) diff --git a/vendor/github.com/go-faker/faker/v4/internet.go b/vendor/github.com/go-faker/faker/v4/internet.go index 3035ad8..9f4357a 100644 --- a/vendor/github.com/go-faker/faker/v4/internet.go +++ b/vendor/github.com/go-faker/faker/v4/internet.go @@ -46,15 +46,15 @@ func GetNetworker(opts ...options.OptionFunc) Networker { // Networker is logical layer for Internet type Networker interface { - Email(v reflect.Value) (interface{}, error) - MacAddress(v reflect.Value) (interface{}, error) - DomainName(v reflect.Value) (interface{}, error) - URL(v reflect.Value) (interface{}, error) - UserName(v reflect.Value) (interface{}, error) - IPv4(v reflect.Value) (interface{}, error) - IPv6(v reflect.Value) (interface{}, error) - Password(v reflect.Value) (interface{}, error) - Jwt(v reflect.Value) (interface{}, error) + Email(v reflect.Value) (any, error) + MacAddress(v reflect.Value) (any, error) + DomainName(v reflect.Value) (any, error) + URL(v reflect.Value) (any, error) + UserName(v reflect.Value) (any, error) + IPv4(v reflect.Value) (any, error) + IPv6(v reflect.Value) (any, error) + Password(v reflect.Value) (any, error) + Jwt(v reflect.Value) (any, error) } // Internet struct @@ -84,13 +84,13 @@ func (internet Internet) email() (string, error) { } // Email generates random email id -func (internet Internet) Email(v reflect.Value) (interface{}, error) { +func (internet Internet) Email(v reflect.Value) (any, error) { return internet.email() } // Email get email randomly in string func Email(opts ...options.OptionFunc) string { - return singleFakeData(EmailTag, func() interface{} { + return singleFakeData(EmailTag, func() any { opt := options.BuildOptions(opts) i := Internet{fakerOption: *opt} r, err := i.email() @@ -103,20 +103,20 @@ func Email(opts ...options.OptionFunc) string { func (internet Internet) macAddress() string { ip := make([]byte, 6) - for i := 0; i < 6; i++ { + for i := range 6 { ip[i] = byte(rand.Intn(256)) } return net.HardwareAddr(ip).String() } // MacAddress generates random MacAddress -func (internet Internet) MacAddress(v reflect.Value) (interface{}, error) { +func (internet Internet) MacAddress(v reflect.Value) (any, error) { return internet.macAddress(), nil } // MacAddress get mac address randomly in string func MacAddress(opts ...options.OptionFunc) string { - return singleFakeData(MacAddressTag, func() interface{} { + return singleFakeData(MacAddressTag, func() any { opt := options.BuildOptions(opts) i := Internet{fakerOption: *opt} return i.macAddress() @@ -132,13 +132,13 @@ func (internet Internet) domainName() (string, error) { } // DomainName generates random domain name -func (internet Internet) DomainName(v reflect.Value) (interface{}, error) { +func (internet Internet) DomainName(v reflect.Value) (any, error) { return internet.domainName() } // DomainName get email domain name in string func DomainName(opts ...options.OptionFunc) string { - return singleFakeData(DomainNameTag, func() interface{} { + return singleFakeData(DomainNameTag, func() any { opt := options.BuildOptions(opts) i := Internet{fakerOption: *opt} d, err := i.domainName() @@ -167,13 +167,13 @@ func (internet Internet) url() (string, error) { } // URL generates random URL standardized in urlFormats const -func (internet Internet) URL(v reflect.Value) (interface{}, error) { +func (internet Internet) URL(v reflect.Value) (any, error) { return internet.url() } // URL get Url randomly in string func URL(opts ...options.OptionFunc) string { - return singleFakeData(URLTag, func() interface{} { + return singleFakeData(URLTag, func() any { opt := options.BuildOptions(opts) i := Internet{fakerOption: *opt} u, err := i.url() @@ -189,13 +189,13 @@ func (internet Internet) username() (string, error) { } // UserName generates random username -func (internet Internet) UserName(v reflect.Value) (interface{}, error) { +func (internet Internet) UserName(v reflect.Value) (any, error) { return internet.username() } // Username get username randomly in string func Username(opts ...options.OptionFunc) string { - return singleFakeData(UserNameTag, func() interface{} { + return singleFakeData(UserNameTag, func() any { opt := options.BuildOptions(opts) i := Internet{fakerOption: *opt} u, err := i.username() @@ -209,20 +209,20 @@ func Username(opts ...options.OptionFunc) string { func (internet Internet) ipv4() string { size := 4 ip := make([]byte, size) - for i := 0; i < size; i++ { + for i := range size { ip[i] = byte(rand.Intn(256)) } return net.IP(ip).To4().String() } // IPv4 generates random IPv4 address -func (internet Internet) IPv4(v reflect.Value) (interface{}, error) { +func (internet Internet) IPv4(v reflect.Value) (any, error) { return internet.ipv4(), nil } // IPv4 get IPv4 randomly in string func IPv4(opts ...options.OptionFunc) string { - return singleFakeData(IPV4Tag, func() interface{} { + return singleFakeData(IPV4Tag, func() any { opt := options.BuildOptions(opts) i := Internet{fakerOption: *opt} return i.ipv4() @@ -232,20 +232,20 @@ func IPv4(opts ...options.OptionFunc) string { func (internet Internet) ipv6() string { size := 16 ip := make([]byte, size) - for i := 0; i < size; i++ { + for i := range size { ip[i] = byte(rand.Intn(256)) } return net.IP(ip).To16().String() } // IPv6 generates random IPv6 address -func (internet Internet) IPv6(v reflect.Value) (interface{}, error) { +func (internet Internet) IPv6(v reflect.Value) (any, error) { return internet.ipv6(), nil } // IPv6 get IPv6 randomly in string func IPv6(opts ...options.OptionFunc) string { - return singleFakeData(IPV6Tag, func() interface{} { + return singleFakeData(IPV6Tag, func() any { opt := options.BuildOptions(opts) i := Internet{fakerOption: *opt} return i.ipv6() @@ -257,13 +257,13 @@ func (internet Internet) password() (string, error) { } // Password returns a hashed password -func (internet Internet) Password(v reflect.Value) (interface{}, error) { +func (internet Internet) Password(v reflect.Value) (any, error) { return internet.password() } // Password get password randomly in string func Password(opts ...options.OptionFunc) string { - return singleFakeData(PASSWORD, func() interface{} { + return singleFakeData(PASSWORD, func() any { opt := options.BuildOptions(opts) i := Internet{fakerOption: *opt} p, err := i.password() @@ -284,13 +284,13 @@ func (internet Internet) jwt() (string, error) { } // Jwt returns a jwt-like random string in xxxx.yyyy.zzzz style -func (internet Internet) Jwt(v reflect.Value) (interface{}, error) { +func (internet Internet) Jwt(v reflect.Value) (any, error) { return internet.jwt() } // Jwt get jwt-like string func Jwt(opts ...options.OptionFunc) string { - return singleFakeData(JWT, func() interface{} { + return singleFakeData(JWT, func() any { opt := options.BuildOptions(opts) i := Internet{fakerOption: *opt} p, err := i.jwt() diff --git a/vendor/github.com/go-faker/faker/v4/lorem.go b/vendor/github.com/go-faker/faker/v4/lorem.go index 27c1144..a6f7a11 100644 --- a/vendor/github.com/go-faker/faker/v4/lorem.go +++ b/vendor/github.com/go-faker/faker/v4/lorem.go @@ -52,9 +52,9 @@ var wordList = []string{ // DataFaker generates randomized Words, Sentences and Paragraphs type DataFaker interface { - Word(v reflect.Value) (interface{}, error) - Sentence(v reflect.Value) (interface{}, error) - Paragraph(v reflect.Value) (interface{}, error) + Word(v reflect.Value) (any, error) + Sentence(v reflect.Value) (any, error) + Paragraph(v reflect.Value) (any, error) } // GetLorem returns a new DataFaker interface of Lorem struct @@ -72,14 +72,14 @@ func (l Lorem) word() string { } // Word returns a word from the wordList const -func (l Lorem) Word(v reflect.Value) (interface{}, error) { +func (l Lorem) Word(v reflect.Value) (any, error) { return l.word(), nil } // Word get a word randomly in string func Word(opts ...options.OptionFunc) string { i := Lorem{} - return singleFakeData(WORD, func() interface{} { + return singleFakeData(WORD, func() any { return i.word() }, opts...).(string) } @@ -103,7 +103,7 @@ func (l Lorem) sentence(sentence *strings.Builder) *strings.Builder { } // Sentence returns a sentence using the wordList const -func (l Lorem) Sentence(_ reflect.Value) (interface{}, error) { +func (l Lorem) Sentence(_ reflect.Value) (any, error) { sentence := l.sentence(&strings.Builder{}) return sentence.String(), nil } @@ -111,7 +111,7 @@ func (l Lorem) Sentence(_ reflect.Value) (interface{}, error) { // Sentence get a sentence randomly in string func Sentence(opts ...options.OptionFunc) string { i := Lorem{} - return singleFakeData(SENTENCE, func() interface{} { + return singleFakeData(SENTENCE, func() any { return i.sentence(&strings.Builder{}).String() }, opts...).(string) } @@ -119,7 +119,7 @@ func Sentence(opts ...options.OptionFunc) string { func (l Lorem) paragraph() string { paragraph := &strings.Builder{} size := rand.Intn(10) + 1 - for i := 0; i < size; i++ { + for i := range size { l.sentence(paragraph) if i != size-1 { paragraph.WriteString(" ") @@ -129,14 +129,14 @@ func (l Lorem) paragraph() string { } // Paragraph returns a series of sentences as a paragraph using the wordList const -func (l Lorem) Paragraph(v reflect.Value) (interface{}, error) { +func (l Lorem) Paragraph(v reflect.Value) (any, error) { return l.paragraph(), nil } // Paragraph get a paragraph randomly in string func Paragraph(opts ...options.OptionFunc) string { i := Lorem{} - return singleFakeData(PARAGRAPH, func() interface{} { + return singleFakeData(PARAGRAPH, func() any { return i.paragraph() }, opts...).(string) } diff --git a/vendor/github.com/go-faker/faker/v4/payment.go b/vendor/github.com/go-faker/faker/v4/payment.go index 55ca11e..1bb8776 100644 --- a/vendor/github.com/go-faker/faker/v4/payment.go +++ b/vendor/github.com/go-faker/faker/v4/payment.go @@ -38,8 +38,8 @@ func GetPayment() Render { // Render contains Whole Random Credit Card Generators with their types type Render interface { - CreditCardType(v reflect.Value) (interface{}, error) - CreditCardNumber(v reflect.Value) (interface{}, error) + CreditCardType(v reflect.Value) (any, error) + CreditCardNumber(v reflect.Value) (any, error) } // Payment struct @@ -61,13 +61,13 @@ func (p Payment) cctype() string { // CreditCardType returns one of the following credit values: // VISA, MasterCard, American Express, Discover, JCB and Diners Club -func (p Payment) CreditCardType(v reflect.Value) (interface{}, error) { +func (p Payment) CreditCardType(v reflect.Value) (any, error) { return p.cctype(), nil } // CCType get a credit card type randomly in string (VISA, MasterCard, etc) func CCType(opts ...options.OptionFunc) string { - return singleFakeData(CreditCardType, func() interface{} { + return singleFakeData(CreditCardType, func() any { p := Payment{} return p.cctype() }, opts...).(string) @@ -87,13 +87,13 @@ func (p Payment) ccnumber() string { } // CreditCardNumber generated credit card number according to the card number rules -func (p Payment) CreditCardNumber(v reflect.Value) (interface{}, error) { +func (p Payment) CreditCardNumber(v reflect.Value) (any, error) { return p.ccnumber(), nil } // CCNumber get a credit card number randomly in string (VISA, MasterCard, etc) func CCNumber(opts ...options.OptionFunc) string { - return singleFakeData(CreditCardNumber, func() interface{} { + return singleFakeData(CreditCardNumber, func() any { p := Payment{} return p.ccnumber() }, opts...).(string) diff --git a/vendor/github.com/go-faker/faker/v4/person.go b/vendor/github.com/go-faker/faker/v4/person.go index 35fb849..4af7892 100644 --- a/vendor/github.com/go-faker/faker/v4/person.go +++ b/vendor/github.com/go-faker/faker/v4/person.go @@ -9,23 +9,23 @@ import ( // Dowser provides interfaces to generate random logical Names with their initials type Dowser interface { - TitleMale(v reflect.Value) (interface{}, error) - TitleFeMale(v reflect.Value) (interface{}, error) - FirstName(v reflect.Value) (interface{}, error) - FirstNameMale(v reflect.Value) (interface{}, error) - FirstNameFemale(v reflect.Value) (interface{}, error) - LastName(v reflect.Value) (interface{}, error) - Name(v reflect.Value) (interface{}, error) - Gender(v reflect.Value) (interface{}, error) - ChineseFirstName(v reflect.Value) (interface{}, error) - ChineseLastName(v reflect.Value) (interface{}, error) - ChineseName(v reflect.Value) (interface{}, error) - RussianFirstNameMale(v reflect.Value) (interface{}, error) - RussianMiddleNameMale(v reflect.Value) (interface{}, error) - RussianLastNameMale(v reflect.Value) (interface{}, error) - RussianFirstNameFemale(v reflect.Value) (interface{}, error) - RussianMiddleNameFemale(v reflect.Value) (interface{}, error) - RussianLastNameFemale(v reflect.Value) (interface{}, error) + TitleMale(v reflect.Value) (any, error) + TitleFeMale(v reflect.Value) (any, error) + FirstName(v reflect.Value) (any, error) + FirstNameMale(v reflect.Value) (any, error) + FirstNameFemale(v reflect.Value) (any, error) + LastName(v reflect.Value) (any, error) + Name(v reflect.Value) (any, error) + Gender(v reflect.Value) (any, error) + ChineseFirstName(v reflect.Value) (any, error) + ChineseLastName(v reflect.Value) (any, error) + ChineseName(v reflect.Value) (any, error) + RussianFirstNameMale(v reflect.Value) (any, error) + RussianMiddleNameMale(v reflect.Value) (any, error) + RussianLastNameMale(v reflect.Value) (any, error) + RussianFirstNameFemale(v reflect.Value) (any, error) + RussianMiddleNameFemale(v reflect.Value) (any, error) + RussianLastNameFemale(v reflect.Value) (any, error) } var titlesMale = []string{ @@ -637,13 +637,13 @@ func (p Person) titlemale() string { } // TitleMale generates random titles for males -func (p Person) TitleMale(v reflect.Value) (interface{}, error) { +func (p Person) TitleMale(v reflect.Value) (any, error) { return p.titlemale(), nil } // TitleMale get a title male randomly in string ("Mr.", "Dr.", "Prof.", "Lord", "King", "Prince") func TitleMale(opts ...options.OptionFunc) string { - return singleFakeData(TitleMaleTag, func() interface{} { + return singleFakeData(TitleMaleTag, func() any { p := Person{} return p.titlemale() }, opts...).(string) @@ -654,13 +654,13 @@ func (p Person) titleFemale() string { } // TitleFeMale generates random titles for females -func (p Person) TitleFeMale(v reflect.Value) (interface{}, error) { +func (p Person) TitleFeMale(v reflect.Value) (any, error) { return p.titleFemale(), nil } // TitleFemale get a title female randomly in string ("Mrs.", "Ms.", "Miss", "Dr.", "Prof.", "Lady", "Queen", "Princess") func TitleFemale(opts ...options.OptionFunc) string { - return singleFakeData(TitleFemaleTag, func() interface{} { + return singleFakeData(TitleFemaleTag, func() any { p := Person{} return p.titleFemale() }, opts...).(string) @@ -671,13 +671,13 @@ func (p Person) firstname() string { } // FirstName returns first names -func (p Person) FirstName(v reflect.Value) (interface{}, error) { +func (p Person) FirstName(v reflect.Value) (any, error) { return p.firstname(), nil } // FirstName get fake firstname func FirstName(opts ...options.OptionFunc) string { - return singleFakeData(FirstNameTag, func() interface{} { + return singleFakeData(FirstNameTag, func() any { p := Person{} return p.firstname() }, opts...).(string) @@ -688,13 +688,13 @@ func (p Person) firstnamemale() string { } // FirstNameMale returns first names for males -func (p Person) FirstNameMale(v reflect.Value) (interface{}, error) { +func (p Person) FirstNameMale(v reflect.Value) (any, error) { return p.firstnamemale(), nil } // FirstNameMale get fake firstname for male func FirstNameMale(opts ...options.OptionFunc) string { - return singleFakeData(FirstNameMaleTag, func() interface{} { + return singleFakeData(FirstNameMaleTag, func() any { p := Person{} return p.firstnamemale() }, opts...).(string) @@ -705,13 +705,13 @@ func (p Person) firstnamefemale() string { } // FirstNameFemale returns first names for females -func (p Person) FirstNameFemale(v reflect.Value) (interface{}, error) { +func (p Person) FirstNameFemale(v reflect.Value) (any, error) { return p.firstnamefemale(), nil } // FirstNameFemale get fake firstname for female func FirstNameFemale(opts ...options.OptionFunc) string { - return singleFakeData(FirstNameFemaleTag, func() interface{} { + return singleFakeData(FirstNameFemaleTag, func() any { p := Person{} return p.firstnamefemale() }, opts...).(string) @@ -722,13 +722,13 @@ func (p Person) lastname() string { } // LastName returns last name -func (p Person) LastName(v reflect.Value) (interface{}, error) { +func (p Person) LastName(v reflect.Value) (any, error) { return p.lastname(), nil } // LastName get fake lastname func LastName(opts ...options.OptionFunc) string { - return singleFakeData(LastNameTag, func() interface{} { + return singleFakeData(LastNameTag, func() any { p := Person{} return p.lastname() }, opts...).(string) @@ -742,20 +742,20 @@ func (p Person) name() string { } // Name returns a random name -func (p Person) Name(v reflect.Value) (interface{}, error) { +func (p Person) Name(v reflect.Value) (any, error) { return p.name(), nil } // Name get fake name func Name(opts ...options.OptionFunc) string { - return singleFakeData(NAME, func() interface{} { + return singleFakeData(NAME, func() any { p := Person{} return p.name() }, opts...).(string) } // Gender returns a random gender -func (p Person) Gender(v reflect.Value) (interface{}, error) { +func (p Person) Gender(v reflect.Value) (any, error) { return p.gender(), nil } @@ -765,14 +765,14 @@ func (p Person) gender() string { // Gender get fake gender func Gender(opts ...options.OptionFunc) string { - return singleFakeData(GENDER, func() interface{} { + return singleFakeData(GENDER, func() any { p := Person{} return p.gender() }, opts...).(string) } // ChineseFirstName returns a random chinese first name -func (p Person) ChineseFirstName(v reflect.Value) (interface{}, error) { +func (p Person) ChineseFirstName(v reflect.Value) (any, error) { return p.chineseFirstName(), nil } @@ -782,14 +782,14 @@ func (p Person) chineseFirstName() string { // ChineseFirstName get chinese first name func ChineseFirstName(opts ...options.OptionFunc) string { - return singleFakeData(ChineseFirstNameTag, func() interface{} { + return singleFakeData(ChineseFirstNameTag, func() any { p := Person{} return p.chineseFirstName() }, opts...).(string) } // ChineseLastName returns a random chinese last name -func (p Person) ChineseLastName(v reflect.Value) (interface{}, error) { +func (p Person) ChineseLastName(v reflect.Value) (any, error) { return p.chineseLastName(), nil } @@ -799,14 +799,14 @@ func (p Person) chineseLastName() string { // ChineseLastName get chinese lsst name func ChineseLastName(opts ...options.OptionFunc) string { - return singleFakeData(ChineseLastNameTag, func() interface{} { + return singleFakeData(ChineseLastNameTag, func() any { p := Person{} return p.chineseLastName() }, opts...).(string) } // ChineseName returns a random nhinese name -func (p Person) ChineseName(v reflect.Value) (interface{}, error) { +func (p Person) ChineseName(v reflect.Value) (any, error) { return p.chineseName(), nil } @@ -816,7 +816,7 @@ func (p Person) chineseName() string { // ChineseName get chinese lsst name func ChineseName(opts ...options.OptionFunc) string { - return singleFakeData(ChineseNameTag, func() interface{} { + return singleFakeData(ChineseNameTag, func() any { p := Person{} return p.chineseName() }, opts...).(string) @@ -847,31 +847,31 @@ func (p Person) russianLastNameFemale() string { } // RussianFirstNameMale returns russian male firstname -func (p Person) RussianFirstNameMale(v reflect.Value) (interface{}, error) { +func (p Person) RussianFirstNameMale(v reflect.Value) (any, error) { return p.russianFirstNameMale(), nil } // RussianMiddleNameMale returns russian male middlename -func (p Person) RussianMiddleNameMale(v reflect.Value) (interface{}, error) { +func (p Person) RussianMiddleNameMale(v reflect.Value) (any, error) { return p.russianMiddleNameMale(), nil } // RussianLastNameMale returns russian male lastname -func (p Person) RussianLastNameMale(v reflect.Value) (interface{}, error) { +func (p Person) RussianLastNameMale(v reflect.Value) (any, error) { return p.russianLastNameMale(), nil } // RussianFirstNameFemale returns russian female firstname -func (p Person) RussianFirstNameFemale(v reflect.Value) (interface{}, error) { +func (p Person) RussianFirstNameFemale(v reflect.Value) (any, error) { return p.russianFirstNameFemale(), nil } // RussianMiddleNameFemale returns russian female middlename -func (p Person) RussianMiddleNameFemale(v reflect.Value) (interface{}, error) { +func (p Person) RussianMiddleNameFemale(v reflect.Value) (any, error) { return p.russianMiddleNameFemale(), nil } // RussianLastNameFemale returns russian female lastname -func (p Person) RussianLastNameFemale(v reflect.Value) (interface{}, error) { +func (p Person) RussianLastNameFemale(v reflect.Value) (any, error) { return p.russianLastNameFemale(), nil } diff --git a/vendor/github.com/go-faker/faker/v4/phone.go b/vendor/github.com/go-faker/faker/v4/phone.go index 1dddf77..87e8bc2 100644 --- a/vendor/github.com/go-faker/faker/v4/phone.go +++ b/vendor/github.com/go-faker/faker/v4/phone.go @@ -17,9 +17,9 @@ func GetPhoner() Phoner { // Phoner serves overall tele-phonic contact generator type Phoner interface { - PhoneNumber(v reflect.Value) (interface{}, error) - TollFreePhoneNumber(v reflect.Value) (interface{}, error) - E164PhoneNumber(v reflect.Value) (interface{}, error) + PhoneNumber(v reflect.Value) (any, error) + TollFreePhoneNumber(v reflect.Value) (any, error) + E164PhoneNumber(v reflect.Value) (any, error) } // Phone struct @@ -33,40 +33,40 @@ func (p Phone) phonenumber() string { } // PhoneNumber generates phone numbers of type: "201-886-0269" -func (p Phone) PhoneNumber(v reflect.Value) (interface{}, error) { +func (p Phone) PhoneNumber(v reflect.Value) (any, error) { return p.phonenumber(), nil } // Phonenumber get fake phone number func Phonenumber(opts ...options.OptionFunc) string { - return singleFakeData(PhoneNumber, func() interface{} { + return singleFakeData(PhoneNumber, func() any { p := Phone{} return p.phonenumber() }, opts...).(string) } func (p Phone) tollfreephonenumber() string { - out := "" + var out strings.Builder boxDigitsStart := []string{"777", "888"} ints, _ := RandomInt(1, 9) for index, v := range slice.IntToString(ints) { if index == 3 { - out += "-" + out.WriteString("-") } - out += v + out.WriteString(v) } - return fmt.Sprintf("(%s) %s", boxDigitsStart[rand.Intn(len(boxDigitsStart))], out) + return fmt.Sprintf("(%s) %s", boxDigitsStart[rand.Intn(len(boxDigitsStart))], out.String()) } // TollFreePhoneNumber generates phone numbers of type: "(888) 937-7238" -func (p Phone) TollFreePhoneNumber(v reflect.Value) (interface{}, error) { +func (p Phone) TollFreePhoneNumber(v reflect.Value) (any, error) { return p.tollfreephonenumber(), nil } // TollFreePhoneNumber get fake TollFreePhoneNumber func TollFreePhoneNumber(opts ...options.OptionFunc) string { - return singleFakeData(TollFreeNumber, func() interface{} { + return singleFakeData(TollFreeNumber, func() any { p := Phone{} return p.tollfreephonenumber() }, opts...).(string) @@ -84,13 +84,13 @@ func (p Phone) e164PhoneNumber() string { } // E164PhoneNumber generates phone numbers of type: "+27113456789" -func (p Phone) E164PhoneNumber(v reflect.Value) (interface{}, error) { +func (p Phone) E164PhoneNumber(v reflect.Value) (any, error) { return p.e164PhoneNumber(), nil } // E164PhoneNumber get fake E164PhoneNumber func E164PhoneNumber(opts ...options.OptionFunc) string { - return singleFakeData(E164PhoneNumberTag, func() interface{} { + return singleFakeData(E164PhoneNumberTag, func() any { p := Phone{} return p.e164PhoneNumber() }, opts...).(string) diff --git a/vendor/github.com/go-faker/faker/v4/pkg/interfaces/type.go b/vendor/github.com/go-faker/faker/v4/pkg/interfaces/type.go index 5742ed0..61da7c4 100644 --- a/vendor/github.com/go-faker/faker/v4/pkg/interfaces/type.go +++ b/vendor/github.com/go-faker/faker/v4/pkg/interfaces/type.go @@ -3,8 +3,8 @@ package interfaces import "reflect" // CustomProviderFunction used as the standard layout function for custom providers -type CustomProviderFunction func() (interface{}, error) +type CustomProviderFunction func() (any, error) // TaggedFunction used as the standard layout function for tag providers in struct. // This type also can be used for custom provider. -type TaggedFunction func(v reflect.Value) (interface{}, error) +type TaggedFunction func(v reflect.Value) (any, error) diff --git a/vendor/github.com/go-faker/faker/v4/pkg/options/options.go b/vendor/github.com/go-faker/faker/v4/pkg/options/options.go index 14c18e0..cf68aaa 100644 --- a/vendor/github.com/go-faker/faker/v4/pkg/options/options.go +++ b/vendor/github.com/go-faker/faker/v4/pkg/options/options.go @@ -135,7 +135,7 @@ func BuildOptions(optFuncs []OptionFunc) *Options { func DefaultOption() *Options { ops := &Options{} ops.StructTypeProviders = make(map[reflect.Type]interfaces.CustomProviderFunction) - ops.StructTypeProviders[reflect.TypeOf(time.Time{})] = func() (interface{}, error) { + ops.StructTypeProviders[reflect.TypeFor[time.Time]()] = func() (any, error) { return time.Now().Add(time.Duration(rand.Int63())), nil } ops.MaxDepthOption = &MaxDepthOption{ @@ -209,7 +209,7 @@ func WithMaxFieldDepthOption(depth int) OptionFunc { } // WithStructTypeProviders used for configuring the custom provider of struct type -func WithStructTypeProviders(t interface{}, provider interfaces.CustomProviderFunction) OptionFunc { +func WithStructTypeProviders(t any, provider interfaces.CustomProviderFunction) OptionFunc { if reflect.TypeOf(t).Kind() != reflect.Struct { panic(fakerErrors.ErrOnlyStructTypeSupported) } diff --git a/vendor/github.com/go-faker/faker/v4/pkg/slice/helpers.go b/vendor/github.com/go-faker/faker/v4/pkg/slice/helpers.go index c85c74b..a596667 100644 --- a/vendor/github.com/go-faker/faker/v4/pkg/slice/helpers.go +++ b/vendor/github.com/go-faker/faker/v4/pkg/slice/helpers.go @@ -1,17 +1,13 @@ package slice import ( + "slices" "strconv" ) // Contains Check item in slice string type func Contains(slice []string, item string) bool { - for _, s := range slice { - if s == item { - return true - } - } - return false + return slices.Contains(slice, item) } // ContainsRune Check item in map rune type @@ -21,21 +17,14 @@ func ContainsRune(set map[rune]struct{}, item rune) bool { } // ContainsValue check if value exists in slice, no matter its type -func ContainsValue(slice []interface{}, value interface{}) bool { - for _, v := range slice { - if v == value { - return true - } - } - return false +func ContainsValue(slice []any, value any) bool { + return slices.Contains(slice, value) } // IntToString Convert slice int to slice string func IntToString(intSl []int) (str []string) { - for i := range intSl { - number := intSl[i] - text := strconv.Itoa(number) - str = append(str, text) + for _, number := range intSl { + str = append(str, strconv.Itoa(number)) } return str } diff --git a/vendor/github.com/go-faker/faker/v4/price.go b/vendor/github.com/go-faker/faker/v4/price.go index 756d67a..60fc159 100644 --- a/vendor/github.com/go-faker/faker/v4/price.go +++ b/vendor/github.com/go-faker/faker/v4/price.go @@ -34,9 +34,9 @@ var currencies = []string{ // Money provides an interface to generate a custom price with or without a random currency code type Money interface { - Currency(v reflect.Value) (interface{}, error) - Amount(v reflect.Value) (interface{}, error) - AmountWithCurrency(v reflect.Value) (interface{}, error) + Currency(v reflect.Value) (any, error) + Amount(v reflect.Value) (any, error) + AmountWithCurrency(v reflect.Value) (any, error) } // Price struct @@ -53,13 +53,13 @@ func (p Price) currency() string { } // Currency returns a random currency from currencies -func (p Price) Currency(v reflect.Value) (interface{}, error) { +func (p Price) Currency(v reflect.Value) (any, error) { return p.currency(), nil } // Currency get fake Currency (IDR, USD) func Currency(opts ...options.OptionFunc) string { - return singleFakeData(CurrencyTag, func() interface{} { + return singleFakeData(CurrencyTag, func() any { p := Price{} return p.currency() }, opts...).(string) @@ -71,7 +71,7 @@ func (p Price) amount() float64 { // Amount returns a random floating price amount // with a random precision of [1,2] up to (10**8 - 1) -func (p Price) Amount(v reflect.Value) (interface{}, error) { +func (p Price) Amount(v reflect.Value) (any, error) { kind := v.Kind() val := p.amount() if kind == reflect.Float32 { @@ -88,13 +88,13 @@ func (p Price) amountwithcurrency() string { } // AmountWithCurrency combines both price and currency together -func (p Price) AmountWithCurrency(v reflect.Value) (interface{}, error) { +func (p Price) AmountWithCurrency(v reflect.Value) (any, error) { return p.amountwithcurrency(), nil } // AmountWithCurrency get fake AmountWithCurrency USD 49257.100 func AmountWithCurrency(opts ...options.OptionFunc) string { - return singleFakeData(AmountWithCurrencyTag, func() interface{} { + return singleFakeData(AmountWithCurrencyTag, func() any { p := Price{} return p.amountwithcurrency() }, opts...).(string) diff --git a/vendor/github.com/go-faker/faker/v4/tag_argument_extractor.go b/vendor/github.com/go-faker/faker/v4/tag_argument_extractor.go index ae087c9..55774a0 100644 --- a/vendor/github.com/go-faker/faker/v4/tag_argument_extractor.go +++ b/vendor/github.com/go-faker/faker/v4/tag_argument_extractor.go @@ -8,7 +8,7 @@ import ( fakerErrors "github.com/go-faker/faker/v4/pkg/errors" ) -func extractFloat64FromTagArgs(args []string) (interface{}, error) { +func extractFloat64FromTagArgs(args []string) (any, error) { bytes := 64 var floatValues []float64 for _, i := range args { @@ -23,7 +23,7 @@ func extractFloat64FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractFloat32FromTagArgs(args []string) (interface{}, error) { +func extractFloat32FromTagArgs(args []string) (any, error) { bytes := 32 var floatValues []float32 for _, i := range args { @@ -38,7 +38,7 @@ func extractFloat32FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractInt64FromTagArgs(args []string) (interface{}, error) { +func extractInt64FromTagArgs(args []string) (any, error) { bytes := 64 var floatValues []int64 for _, i := range args { @@ -53,7 +53,7 @@ func extractInt64FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractInt32FromTagArgs(args []string) (interface{}, error) { +func extractInt32FromTagArgs(args []string) (any, error) { bytes := 32 var floatValues []int32 for _, i := range args { @@ -68,7 +68,7 @@ func extractInt32FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractInt16FromTagArgs(args []string) (interface{}, error) { +func extractInt16FromTagArgs(args []string) (any, error) { bytes := 16 var floatValues []int16 for _, i := range args { @@ -83,7 +83,7 @@ func extractInt16FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractInt8FromTagArgs(args []string) (interface{}, error) { +func extractInt8FromTagArgs(args []string) (any, error) { bytes := 8 var floatValues []int8 for _, i := range args { @@ -98,7 +98,7 @@ func extractInt8FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractIntFromTagArgs(args []string) (interface{}, error) { +func extractIntFromTagArgs(args []string) (any, error) { bytes := 0 var floatValues []int for _, i := range args { @@ -113,7 +113,7 @@ func extractIntFromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractUint64FromTagArgs(args []string) (interface{}, error) { +func extractUint64FromTagArgs(args []string) (any, error) { bytes := 64 var floatValues []uint64 for _, i := range args { @@ -128,7 +128,7 @@ func extractUint64FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractUint32FromTagArgs(args []string) (interface{}, error) { +func extractUint32FromTagArgs(args []string) (any, error) { bytes := 32 var floatValues []uint32 for _, i := range args { @@ -143,7 +143,7 @@ func extractUint32FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractUint16FromTagArgs(args []string) (interface{}, error) { +func extractUint16FromTagArgs(args []string) (any, error) { bytes := 16 var floatValues []uint16 for _, i := range args { @@ -158,7 +158,7 @@ func extractUint16FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractUint8FromTagArgs(args []string) (interface{}, error) { +func extractUint8FromTagArgs(args []string) (any, error) { bytes := 8 var floatValues []uint8 for _, i := range args { @@ -173,7 +173,7 @@ func extractUint8FromTagArgs(args []string) (interface{}, error) { return toRet, nil } -func extractUintFromTagArgs(args []string) (interface{}, error) { +func extractUintFromTagArgs(args []string) (any, error) { bytes := 0 var floatValues []uint for _, i := range args { diff --git a/vendor/github.com/go-faker/faker/v4/user_agent.go b/vendor/github.com/go-faker/faker/v4/user_agent.go index 6ba6cc9..6b5d2eb 100644 --- a/vendor/github.com/go-faker/faker/v4/user_agent.go +++ b/vendor/github.com/go-faker/faker/v4/user_agent.go @@ -38,13 +38,13 @@ func GetUserAgent() UserAgenter { } type UserAgenter interface { - UserAgent(v reflect.Value) (interface{}, error) + UserAgent(v reflect.Value) (any, error) } // UserAgent implements logic loosely based on https://fakerphp.org/formatters/user-agent/. type UserAgent struct{} -func (ua UserAgent) UserAgent(reflect.Value) (interface{}, error) { +func (ua UserAgent) UserAgent(reflect.Value) (any, error) { browserType := randomElementFromSliceString(browserTypes) switch browserType { case "chrome": diff --git a/vendor/github.com/go-faker/faker/v4/uuid.go b/vendor/github.com/go-faker/faker/v4/uuid.go index f63eb0d..d31509d 100644 --- a/vendor/github.com/go-faker/faker/v4/uuid.go +++ b/vendor/github.com/go-faker/faker/v4/uuid.go @@ -15,8 +15,8 @@ func GetIdentifier() Identifier { // Identifier ... type Identifier interface { - Digit(v reflect.Value) (interface{}, error) - Hyphenated(v reflect.Value) (interface{}, error) + Digit(v reflect.Value) (any, error) + Hyphenated(v reflect.Value) (any, error) } // UUID struct @@ -46,13 +46,13 @@ func (u UUID) hyphenated() (string, error) { } // Hyphenated returns a 36 byte hyphenated UUID -func (u UUID) Hyphenated(v reflect.Value) (interface{}, error) { +func (u UUID) Hyphenated(v reflect.Value) (any, error) { return u.hyphenated() } // UUIDHyphenated get fake Hyphenated UUID func UUIDHyphenated(opts ...options.OptionFunc) string { - return singleFakeData(HyphenatedID, func() interface{} { + return singleFakeData(HyphenatedID, func() any { u := UUID{} res, _ := u.hyphenated() return res @@ -69,13 +69,13 @@ func (u UUID) digit() (string, error) { } // Digit returns a 32 bytes UUID -func (u UUID) Digit(v reflect.Value) (interface{}, error) { +func (u UUID) Digit(v reflect.Value) (any, error) { return u.digit() } // UUIDDigit get fake Digit UUID func UUIDDigit(opts ...options.OptionFunc) string { - return singleFakeData(ID, func() interface{} { + return singleFakeData(ID, func() any { u := UUID{} res, _ := u.digit() return res diff --git a/vendor/github.com/go-logr/logr/context_noslog.go b/vendor/github.com/go-logr/logr/context_noslog.go index f012f9a..0a3d1a1 100644 --- a/vendor/github.com/go-logr/logr/context_noslog.go +++ b/vendor/github.com/go-logr/logr/context_noslog.go @@ -1,5 +1,4 @@ //go:build !go1.21 -// +build !go1.21 /* Copyright 2019 The logr Authors. diff --git a/vendor/github.com/go-logr/logr/context_slog.go b/vendor/github.com/go-logr/logr/context_slog.go index 065ef0b..c69eb01 100644 --- a/vendor/github.com/go-logr/logr/context_slog.go +++ b/vendor/github.com/go-logr/logr/context_slog.go @@ -1,5 +1,4 @@ //go:build go1.21 -// +build go1.21 /* Copyright 2019 The logr Authors. diff --git a/vendor/github.com/go-logr/logr/funcr/funcr.go b/vendor/github.com/go-logr/logr/funcr/funcr.go index b22c57d..7f4996e 100644 --- a/vendor/github.com/go-logr/logr/funcr/funcr.go +++ b/vendor/github.com/go-logr/logr/funcr/funcr.go @@ -426,7 +426,7 @@ func (f Formatter) colon() byte { } func (f Formatter) pretty(value any) string { - return f.prettyWithFlags(value, 0, 0) + return f.prettyWithFlags(value, 0, 0, 0, nil) } const ( @@ -434,7 +434,13 @@ const ( ) // TODO: This is not fast. Most of the overhead goes here. -func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string { +// value: The value to render +// flags: Bitmask of flags (see above) +// depth: The current depth of nested structs, slices, arrays, and maps +// ptrDepth: The current depth of including pointer dereferences +// ptrMap: A map of pointers already seen, to avoid infinite recursion (usually +// nil unless ptrDepth is large) +func (f Formatter) prettyWithFlags(value any, flags uint32, depth int, ptrDepth int, ptrMap map[uintptr]bool) string { if depth > f.opts.MaxLogDepth { return `""` } @@ -504,7 +510,7 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string { // arbitrary keys might need escaping buf.WriteString(prettyString(k)) buf.WriteByte(f.colon()) - buf.WriteString(f.prettyWithFlags(v[i+1], 0, depth+1)) + buf.WriteString(f.prettyWithFlags(v[i+1], 0, depth+1, ptrDepth+1, ptrMap)) } if flags&flagRawStruct == 0 { buf.WriteByte('}') @@ -576,7 +582,7 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string { } printComma = true // if we got here, we are rendering a field if fld.Anonymous && fld.Type.Kind() == reflect.Struct && name == "" { - buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), flags|flagRawStruct, depth+1)) + buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), flags|flagRawStruct, depth+1, ptrDepth+1, ptrMap)) continue } if name == "" { @@ -585,7 +591,7 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string { // field names can't contain characters which need escaping buf.WriteString(f.quoted(name, false)) buf.WriteByte(f.colon()) - buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), 0, depth+1)) + buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), 0, depth+1, ptrDepth+1, ptrMap)) } if flags&flagRawStruct == 0 { buf.WriteByte('}') @@ -612,7 +618,7 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string { buf.WriteByte(f.comma()) } e := v.Index(i) - buf.WriteString(f.prettyWithFlags(e.Interface(), 0, depth+1)) + buf.WriteString(f.prettyWithFlags(e.Interface(), 0, depth+1, ptrDepth+1, ptrMap)) } buf.WriteByte(']') return buf.String() @@ -637,7 +643,8 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string { keystr = prettyString(keystr) } else { // prettyWithFlags will produce already-escaped values - keystr = f.prettyWithFlags(it.Key().Interface(), 0, depth+1) + // key depth is unrelated to overall depth + keystr = f.prettyWithFlags(it.Key().Interface(), 0, 0, ptrDepth, ptrMap) if t.Key().Kind() != reflect.String { // JSON only does string keys. Unlike Go's standard JSON, we'll // convert just about anything to a string. @@ -646,16 +653,34 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string { } buf.WriteString(keystr) buf.WriteByte(f.colon()) - buf.WriteString(f.prettyWithFlags(it.Value().Interface(), 0, depth+1)) + buf.WriteString(f.prettyWithFlags(it.Value().Interface(), 0, depth+1, ptrDepth+1, ptrMap)) i++ } buf.WriteByte('}') return buf.String() - case reflect.Ptr, reflect.Interface: + case reflect.Pointer, reflect.Interface: if v.IsNil() { return "null" } - return f.prettyWithFlags(v.Elem().Interface(), 0, depth) + // Special case: recursive pointers. For normal use we do not want to + // count pointer dereferences as depth, but if we see the same pointer + // again we have a recursion and need to stop. After a large number of + // pointer dereferences we will start tracking pointers to avoid the + // perf hit of doing it in the normal path. + // + // This should not happen accidentally (e.g. json decoding should never + // do this) but we can handle it gracefully. + if ptrMap != nil && ptrMap[uintptr(v.Pointer())] { + depth = f.opts.MaxLogDepth + 1 // force a depth error + } + const maxDepthFactor = 4 // arbitrary, but we want it large enough to not false-alert + if ptrDepth > f.opts.MaxLogDepth*maxDepthFactor && ptrMap == nil { + ptrMap = map[uintptr]bool{} + } + if ptrMap != nil { + ptrMap[(uintptr)(v.Pointer())] = true + } + return f.prettyWithFlags(v.Elem().Interface(), 0, depth, ptrDepth+1, ptrMap) } return fmt.Sprintf(`""`, t.Kind().String()) } @@ -697,7 +722,7 @@ func isEmpty(v reflect.Value) bool { return v.Float() == 0 case reflect.Complex64, reflect.Complex128: return v.Complex() == 0 - case reflect.Interface, reflect.Ptr: + case reflect.Interface, reflect.Pointer: return v.IsNil() } return false diff --git a/vendor/github.com/go-logr/logr/funcr/slogsink.go b/vendor/github.com/go-logr/logr/funcr/slogsink.go index 7bd8476..8b519c9 100644 --- a/vendor/github.com/go-logr/logr/funcr/slogsink.go +++ b/vendor/github.com/go-logr/logr/funcr/slogsink.go @@ -1,5 +1,4 @@ //go:build go1.21 -// +build go1.21 /* Copyright 2023 The logr Authors. @@ -33,7 +32,7 @@ const extraSlogSinkDepth = 3 // 2 for slog, 1 for SlogSink func (l fnlogger) Handle(_ context.Context, record slog.Record) error { kvList := make([]any, 0, 2*record.NumAttrs()) record.Attrs(func(attr slog.Attr) bool { - kvList = attrToKVs(attr, kvList) + kvList = attrToKVs(attr, kvList, l.opts.MaxLogDepth) return true }) @@ -49,7 +48,7 @@ func (l fnlogger) Handle(_ context.Context, record slog.Record) error { func (l fnlogger) WithAttrs(attrs []slog.Attr) logr.SlogSink { kvList := make([]any, 0, 2*len(attrs)) for _, attr := range attrs { - kvList = attrToKVs(attr, kvList) + kvList = attrToKVs(attr, kvList, l.opts.MaxLogDepth) } l.AddValues(kvList) return &l @@ -61,14 +60,25 @@ func (l fnlogger) WithGroup(name string) logr.SlogSink { } // attrToKVs appends a slog.Attr to a logr-style kvList. It handle slog Groups -// and other details of slog. -func attrToKVs(attr slog.Attr, kvList []any) []any { +// and other details of slog. maxDepth bounds recursion into nested groups so a +// deeply-nested slog.Group cannot exhaust the stack; it is decremented per group +// level and starts at the Formatter's MaxLogDepth (past which the formatter would +// truncate the rendering anyway). +func attrToKVs(attr slog.Attr, kvList []any, maxDepth int) []any { attrVal := attr.Value.Resolve() if attrVal.Kind() == slog.KindGroup { + if maxDepth <= 0 { + // Nesting is too deep to build without risking a stack overflow. + // Stop here; the formatter truncates below MaxLogDepth regardless. + if attr.Key != "" { + kvList = append(kvList, attr.Key, "") + } + return kvList + } groupVal := attrVal.Group() grpKVs := make([]any, 0, 2*len(groupVal)) for _, attr := range groupVal { - grpKVs = attrToKVs(attr, grpKVs) + grpKVs = attrToKVs(attr, grpKVs, maxDepth-1) } if attr.Key == "" { // slog says we have to inline these diff --git a/vendor/github.com/go-logr/logr/sloghandler.go b/vendor/github.com/go-logr/logr/sloghandler.go index 82d1ba4..befaf55 100644 --- a/vendor/github.com/go-logr/logr/sloghandler.go +++ b/vendor/github.com/go-logr/logr/sloghandler.go @@ -1,5 +1,4 @@ //go:build go1.21 -// +build go1.21 /* Copyright 2023 The logr Authors. diff --git a/vendor/github.com/go-logr/logr/slogr.go b/vendor/github.com/go-logr/logr/slogr.go index 28a83d0..bfe80eb 100644 --- a/vendor/github.com/go-logr/logr/slogr.go +++ b/vendor/github.com/go-logr/logr/slogr.go @@ -1,5 +1,4 @@ //go:build go1.21 -// +build go1.21 /* Copyright 2023 The logr Authors. diff --git a/vendor/github.com/go-logr/logr/slogsink.go b/vendor/github.com/go-logr/logr/slogsink.go index 4060fcb..ab76ea9 100644 --- a/vendor/github.com/go-logr/logr/slogsink.go +++ b/vendor/github.com/go-logr/logr/slogsink.go @@ -1,5 +1,4 @@ //go:build go1.21 -// +build go1.21 /* Copyright 2023 The logr Authors. diff --git a/vendor/github.com/klauspost/compress/README.md b/vendor/github.com/klauspost/compress/README.md index fb023f2..0e9f170 100644 --- a/vendor/github.com/klauspost/compress/README.md +++ b/vendor/github.com/klauspost/compress/README.md @@ -27,6 +27,18 @@ Use the links above for more information on each. # changelog +* Jul 1st, 2026 [1.19.0](https://github.com/klauspost/compress/releases/tag/v1.19.0) + * zstd: Add true concurrent stream encodingin https://github.com/klauspost/compress/pull/1136 + * zstd: arm64 decoder asm by @lizthegrey in https://github.com/klauspost/compress/pull/1160 + * flate: Add inflate checkpoints in https://github.com/klauspost/compress/pull/1154 + * zstd: avoid unused BuildDict encoder allocation by @snissn in https://github.com/klauspost/compress/pull/1147 + * snappy/s2: Limit length of varint in `decodedLen` by @eustas in https://github.com/klauspost/compress/pull/1148 + * gzhttp: match qvalue parameter case-insensitively (RFC 7231) by @z9z in https://github.com/klauspost/compress/pull/1149 + * zip: add NameDecoder callback for legacy encoding rewrite by @SAY-5 in https://github.com/klauspost/compress/pull/1150 + * huff0: Allow building tables from histogram in https://github.com/klauspost/compress/pull/1155 + * huff0: Allow building table from oversized histogram in https://github.com/klauspost/compress/pull/1156 + * s2sx: Clean symlink targets in https://github.com/klauspost/compress/pull/1163 + * Feb 9th, 2026 [1.18.4](https://github.com/klauspost/compress/releases/tag/v1.18.4) * gzhttp: Add zstandard to server handler wrapper https://github.com/klauspost/compress/pull/1121 * zstd: Add ResetWithOptions to encoder/decoder https://github.com/klauspost/compress/pull/1122 diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s b/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s index 661761f..77ee391 100644 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s @@ -28,7 +28,10 @@ TEXT ·buildDtable_asm(SB), $0-24 init_main_loop: ADD R8<<1, R1, R15 MOVH (R15), R9 - CMN $1, R9 + AND $0xffff, R9, R15 + MOVD $-1, R16 + AND $0xffff, R16, R16 + CMP R16, R15 BNE do_not_update_high_threshold ADD R7<<3, R5, R15 MOVB R8, 1(R15) @@ -126,9 +129,13 @@ build_table_main_table: RET build_table_check1_ok: - TST R1, R1 + AND $0xff, R1, R15 + AND $0xff, R1, R16 + TST R16, R15 BNE build_table_check2_ok - CMP R6, R7 + AND $0xffff, R7, R15 + AND $0xffff, R6, R16 + CMP R16, R15 BNE build_table_check2_ok MOVD ctx+8(FP), R0 MOVD R7, 24(R0) diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s b/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s index 75b19d7..a468e5f 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s @@ -670,9 +670,9 @@ error_overread: MOVD R16, ret+24(FP) RET -// skipped sequenceDecs_decode_bmi2 (BMI2 not available on arm64) +// skipped sequenceDecs_decode_bmi2 (generic twin preferred on arm64) -// skipped sequenceDecs_decode_56_bmi2 (BMI2 not available on arm64) +// skipped sequenceDecs_decode_56_bmi2 (generic twin preferred on arm64) // func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool // Requires: SSE @@ -1966,7 +1966,7 @@ error_not_enough_space: MOVD R16, ret+24(FP) RET -// skipped sequenceDecs_decodeSync_bmi2 (BMI2 not available on arm64) +// skipped sequenceDecs_decodeSync_bmi2 (generic twin preferred on arm64) // func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE @@ -2702,4 +2702,4 @@ error_not_enough_space: MOVD R16, ret+24(FP) RET -// skipped sequenceDecs_decodeSync_safe_bmi2 (BMI2 not available on arm64) +// skipped sequenceDecs_decodeSync_safe_bmi2 (generic twin preferred on arm64) diff --git a/vendor/github.com/klauspost/compress/zstd/snappy.go b/vendor/github.com/klauspost/compress/zstd/snappy.go index 336c288..36c56f3 100644 --- a/vendor/github.com/klauspost/compress/zstd/snappy.go +++ b/vendor/github.com/klauspost/compress/zstd/snappy.go @@ -334,9 +334,10 @@ func decodeSnappy(blk *blockEnc, src []byte) error { return errUnsupportedLiteralLength } - //if length > snappyMaxBlockSize-d || uint32(length) > len(src)-s { - // return ErrSnappyCorrupt - //} + if length > len(src)-s { + println("length > len(src)-s", length, len(src)-s) + return ErrSnappyCorrupt + } blk.literals = append(blk.literals, src[s:s+length]...) //println(length, "litLen") diff --git a/vendor/github.com/leodido/go-urn/machine.go b/vendor/github.com/leodido/go-urn/machine.go index aec1ba6..82d0586 100644 --- a/vendor/github.com/leodido/go-urn/machine.go +++ b/vendor/github.com/leodido/go-urn/machine.go @@ -24,6 +24,7 @@ var ( err8141QComponentStart = "expecting only one q-component (starting with the ?= sequence) [col %d]" err8141MalformedRComp = "expecting a non-empty r-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]" err8141MalformedQComp = "expecting a non-empty q-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]" + errInvalidSyntax = "invalid URN syntax [col %d]" ) var _toStateActions []byte = []byte{ 0, 0, 0, 0, 0, 0, 0, 0, @@ -4358,7 +4359,7 @@ func (m *machine) Parse(input []byte) (*URN, error) { if m.parsingMode != RFC8141Only { // Throw an error when: - // - we are entering here matching the the prefix in the namespace identifier part + // - we are entering here matching the prefix in the namespace identifier part // - looking ahead (3 chars) we find a colon if pos := m.p + 3; pos < m.pe && m.data[pos] == 58 && output.prefix != "" { m.err = fmt.Errorf(errNoUrnWithinID, pos) @@ -5026,6 +5027,9 @@ func (m *machine) Parse(input []byte) (*URN, error) { } if m.cs < firstFinal || m.cs == enFail { + if m.err == nil { + m.err = fmt.Errorf(errInvalidSyntax, m.p) + } return nil, m.err } diff --git a/vendor/github.com/leodido/go-urn/machine.go.rl b/vendor/github.com/leodido/go-urn/machine.go.rl index 0a17421..481e12f 100644 --- a/vendor/github.com/leodido/go-urn/machine.go.rl +++ b/vendor/github.com/leodido/go-urn/machine.go.rl @@ -24,6 +24,7 @@ var ( err8141QComponentStart = "expecting only one q-component (starting with the ?= sequence) [col %d]" err8141MalformedRComp = "expecting a non-empty r-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]" err8141MalformedQComp = "expecting a non-empty q-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]" + errInvalidSyntax = "invalid URN syntax [col %d]" ) %%{ @@ -48,7 +49,7 @@ action set_pre { action throw_pre_urn_err { if m.parsingMode != RFC8141Only { // Throw an error when: - // - we are entering here matching the the prefix in the namespace identifier part + // - we are entering here matching the prefix in the namespace identifier part // - looking ahead (3 chars) we find a colon if pos := m.p + 3; pos < m.pe && m.data[pos] == 58 && output.prefix != "" { m.err = fmt.Errorf(errNoUrnWithinID, pos) @@ -366,6 +367,9 @@ func (m *machine) Parse(input []byte) (*URN, error) { %% write exec; if m.cs < first_final || m.cs == en_fail { + if m.err == nil { + m.err = fmt.Errorf(errInvalidSyntax, m.p) + } return nil, m.err } @@ -383,4 +387,4 @@ func (m *machine) WithParsingMode(x ParsingMode) { m.startParsingAt = en_scim_only } m.parsingModeSet = true -} \ No newline at end of file +} diff --git a/vendor/github.com/leodido/go-urn/urn.go b/vendor/github.com/leodido/go-urn/urn.go index 894d625..3c2110d 100644 --- a/vendor/github.com/leodido/go-urn/urn.go +++ b/vendor/github.com/leodido/go-urn/urn.go @@ -8,7 +8,7 @@ import ( const errInvalidURN = "invalid URN: %s" -// URN represents an Uniform Resource Name. +// URN represents a Uniform Resource Name. // // The general form represented is: // @@ -32,7 +32,7 @@ type URN struct { // Normalize turns the receiving URN into its norm version. // -// Which means: lowercase prefix, lowercase namespace identifier, and immutate namespace specific string chars (except tokens which are lowercased). +// Which means: lowercase prefix, lowercase namespace identifier, and leave namespace-specific string chars unchanged (except tokens which are lowercased). func (u *URN) Normalize() *URN { return &URN{ prefix: "urn", @@ -82,10 +82,10 @@ func (u *URN) String() string { return res } -// Parse is responsible to create an URN instance from a byte array matching the correct URN syntax (RFC 2141). +// Parse is responsible for creating a URN instance from a byte array matching the correct URN syntax (RFC 2141). func Parse(u []byte, options ...Option) (*URN, bool) { urn, err := NewMachine(options...).Parse(u) - if err != nil { + if err != nil || urn == nil { return nil, false } diff --git a/vendor/github.com/pressly/goose/v3/CHANGELOG.md b/vendor/github.com/pressly/goose/v3/CHANGELOG.md index 900cf23..315fe5a 100644 --- a/vendor/github.com/pressly/goose/v3/CHANGELOG.md +++ b/vendor/github.com/pressly/goose/v3/CHANGELOG.md @@ -7,6 +7,12 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +## [v3.27.3] - 2026-07-22 + +### Changed + +- Various dependency upgrades + ## [v3.27.2] - 2026-06-30 ### Changed @@ -319,7 +325,8 @@ Here's a quick summary: - Add new `context.Context`-aware functions and methods, for both sql and go migrations. - Return error when no migration files found or dir is not a directory. -[Unreleased]: https://github.com/pressly/goose/compare/v3.27.2...HEAD +[Unreleased]: https://github.com/pressly/goose/compare/v3.27.3...HEAD +[v3.27.3]: https://github.com/pressly/goose/compare/v3.27.2...v3.27.3 [v3.27.2]: https://github.com/pressly/goose/compare/v3.27.1...v3.27.2 [v3.27.1]: https://github.com/pressly/goose/compare/v3.27.0...v3.27.1 [v3.27.0]: https://github.com/pressly/goose/compare/v3.26.0...v3.27.0 diff --git a/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go b/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go index 8547c8d..820bf43 100644 --- a/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go +++ b/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go @@ -90,7 +90,7 @@ loop: s = skipSpace(s[1:]) } } - return + return specs } func skipSpace(s string) (rest string) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_go116.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_go116.go deleted file mode 100644 index effc578..0000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_go116.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2021 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build !go1.17 -// +build !go1.17 - -package collectors - -import "github.com/prometheus/client_golang/prometheus" - -// NewGoCollector returns a collector that exports metrics about the current Go -// process. This includes memory stats. To collect those, runtime.ReadMemStats -// is called. This requires to “stop the world”, which usually only happens for -// garbage collection (GC). Take the following implications into account when -// deciding whether to use the Go collector: -// -// 1. The performance impact of stopping the world is the more relevant the more -// frequently metrics are collected. However, with Go1.9 or later the -// stop-the-world time per metrics collection is very short (~25µs) so that the -// performance impact will only matter in rare cases. However, with older Go -// versions, the stop-the-world duration depends on the heap size and can be -// quite significant (~1.7 ms/GiB as per -// https://go-review.googlesource.com/c/go/+/34937). -// -// 2. During an ongoing GC, nothing else can stop the world. Therefore, if the -// metrics collection happens to coincide with GC, it will only complete after -// GC has finished. Usually, GC is fast enough to not cause problems. However, -// with a very large heap, GC might take multiple seconds, which is enough to -// cause scrape timeouts in common setups. To avoid this problem, the Go -// collector will use the memstats from a previous collection if -// runtime.ReadMemStats takes more than 1s. However, if there are no previously -// collected memstats, or their collection is more than 5m ago, the collection -// will block until runtime.ReadMemStats succeeds. -// -// NOTE: The problem is solved in Go 1.15, see -// https://github.com/golang/go/issues/19812 for the related Go issue. -func NewGoCollector() prometheus.Collector { - return prometheus.NewGoCollector() -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go index cc4ef10..d29ade6 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go @@ -90,13 +90,13 @@ func WithGoCollectorMemStatsMetricsDisabled() func(options *internal.GoCollector // GoRuntimeMetricsRule allow enabling and configuring particular group of runtime/metrics. // TODO(bwplotka): Consider adding ability to adjust buckets. type GoRuntimeMetricsRule struct { - // Matcher represents RE2 expression will match the runtime/metrics from https://golang.bg/src/runtime/metrics/description.go + // Matcher represents RE2 expression will match the runtime/metrics from https://pkg.go.dev/runtime/metrics // Use `regexp.MustCompile` or `regexp.Compile` to create this field. Matcher *regexp.Regexp } // WithGoCollectorRuntimeMetrics allows enabling and configuring particular group of runtime/metrics. -// See the list of metrics https://golang.bg/src/runtime/metrics/description.go (pick the Go version you use there!). +// See the list of metrics https://pkg.go.dev/runtime/metrics (pick the Go version you use there!). // You can use this option in repeated manner, which will add new rules. The order of rules is important, the last rule // that matches particular metrics is applied. func WithGoCollectorRuntimeMetrics(rules ...GoRuntimeMetricsRule) func(options *internal.GoCollectorOptions) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter.go b/vendor/github.com/prometheus/client_golang/prometheus/counter.go index 4ce84e7..7d963d3 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/counter.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/counter.go @@ -85,11 +85,12 @@ type CounterVecOpts struct { // Both internal tracking values are added up in the Write method. This has to // be taken into account when it comes to precision and overflow behavior. func NewCounter(opts CounterOpts) Counter { - desc := NewDesc( + desc := V2.NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, - nil, + UnconstrainedLabels(nil), opts.ConstLabels, + WithUnit(opts.Unit), ) if opts.now == nil { opts.now = time.Now @@ -205,6 +206,7 @@ func (v2) NewCounterVec(opts CounterVecOpts) *CounterVec { opts.Help, opts.VariableLabels, opts.ConstLabels, + WithUnit(opts.Unit), ) if opts.now == nil { opts.now = time.Now @@ -349,10 +351,11 @@ type CounterFunc interface { // // Check out the ExampleGaugeFunc examples for the similar GaugeFunc. func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc { - return newValueFunc(NewDesc( + return newValueFunc(V2.NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, - nil, + UnconstrainedLabels(nil), opts.ConstLabels, + WithUnit(opts.Unit), ), CounterValue, function) } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc.go b/vendor/github.com/prometheus/client_golang/prometheus/desc.go index 2331b8b..a3c92e7 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/desc.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/desc.go @@ -47,6 +47,8 @@ type Desc struct { fqName string // help provides some helpful information about this metric. help string + // unit provides the unit of this metric. + unit string // constLabelPairs contains precalculated DTO label pairs based on // the constant labels. constLabelPairs []*dto.LabelPair @@ -66,6 +68,16 @@ type Desc struct { err error } +// DescOpt allows setting optional fields for NewDesc. +type DescOpt func(*Desc) + +// WithUnit sets the unit for a Desc. +func WithUnit(unit string) DescOpt { + return func(d *Desc) { + d.unit = unit + } +} + // NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc // and will be reported on registration time. variableLabels and constLabels can // be nil if no such labels should be set. fqName must not be empty. @@ -89,14 +101,17 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) * // // For constLabels, the label values are constant. Therefore, they are fully // specified in the Desc. See the Collector example for a usage pattern. -func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, constLabels Labels) *Desc { +func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, constLabels Labels, opts ...DescOpt) *Desc { d := &Desc{ fqName: fqName, help: help, variableLabels: variableLabels.compile(), } - //nolint:staticcheck // TODO: Don't use deprecated model.NameValidationScheme. - if !model.NameValidationScheme.IsValidMetricName(fqName) { + + for _, opt := range opts { + opt(d) + } + if !model.UTF8Validation.IsValidMetricName(fqName) { d.err = fmt.Errorf("%q is not a valid metric name", fqName) return d } @@ -150,11 +165,13 @@ func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, const d.id = xxh.Sum64() // Sort labelNames so that order doesn't matter for the hash. sort.Strings(labelNames) - // Now hash together (in this order) the help string and the sorted + // Now hash together (in this order) the help string, the unit string and the sorted // label names. xxh.Reset() xxh.WriteString(help) xxh.Write(separatorByteSlice) + xxh.WriteString(d.unit) + xxh.Write(separatorByteSlice) for _, labelName := range labelNames { xxh.WriteString(labelName) xxh.Write(separatorByteSlice) @@ -182,6 +199,15 @@ func NewInvalidDesc(err error) *Desc { } } +// Err returns an error that occurred during construction, if any. +// +// Calling this method is optional. It can be used to detect construction +// errors early, before invoking other methods on the Desc. If an error is +// present, later operations may not behave as expected. +func (d *Desc) Err() error { + return d.err +} + func (d *Desc) String() string { lpStrings := make([]string, 0, len(d.constLabelPairs)) for _, lp := range d.constLabelPairs { @@ -202,9 +228,10 @@ func (d *Desc) String() string { } } return fmt.Sprintf( - "Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: {%s}}", + "Desc{fqName: %q, help: %q, unit: %q, constLabels: {%s}, variableLabels: {%s}}", d.fqName, d.help, + d.unit, strings.Join(lpStrings, ","), strings.Join(vlStrings, ","), ) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go index de5a856..327746f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go @@ -47,14 +47,14 @@ func (e *expvarCollector) Collect(ch chan<- Metric) { if expVar == nil { continue } - var v interface{} + var v any labels := make([]string, len(desc.variableLabels.names)) if err := json.Unmarshal([]byte(expVar.String()), &v); err != nil { ch <- NewInvalidMetric(desc, err) continue } - var processValue func(v interface{}, i int) - processValue = func(v interface{}, i int) { + var processValue func(v any, i int) + processValue = func(v any, i int) { if i >= len(labels) { copiedLabels := append(make([]string, 0, len(labels)), labels...) switch v := v.(type) { @@ -72,7 +72,7 @@ func (e *expvarCollector) Collect(ch chan<- Metric) { ch <- m return } - vm, ok := v.(map[string]interface{}) + vm, ok := v.(map[string]any) if !ok { return } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go index dd2eac9..41e54bf 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go @@ -76,11 +76,12 @@ type GaugeVecOpts struct { // scenarios for Gauges and Counters, where the former tends to be Set-heavy and // the latter Inc-heavy. func NewGauge(opts GaugeOpts) Gauge { - desc := NewDesc( + desc := V2.NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, - nil, + UnconstrainedLabels(nil), opts.ConstLabels, + WithUnit(opts.Unit), ) result := &gauge{desc: desc, labelPairs: desc.constLabelPairs} result.init(result) // Init self-collection. @@ -163,6 +164,7 @@ func (v2) NewGaugeVec(opts GaugeVecOpts) *GaugeVec { opts.Help, opts.VariableLabels, opts.ConstLabels, + WithUnit(opts.Unit), ) return &GaugeVec{ MetricVec: NewMetricVec(desc, func(lvs ...string) Metric { @@ -302,10 +304,11 @@ type GaugeFunc interface { // value of 1. Example: // https://github.com/prometheus/common/blob/8558a5b7db3c84fa38b4766966059a7bd5bfa2ee/version/info.go#L36-L56 func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc { - return newValueFunc(NewDesc( + return newValueFunc(V2.NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, - nil, + UnconstrainedLabels(nil), opts.ConstLabels, + WithUnit(opts.Unit), ), GaugeValue, function) } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_go116.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_go116.go deleted file mode 100644 index 897a6e9..0000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_go116.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2021 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build !go1.17 -// +build !go1.17 - -package prometheus - -import ( - "runtime" - "sync" - "time" -) - -type goCollector struct { - base baseGoCollector - - // ms... are memstats related. - msLast *runtime.MemStats // Previously collected memstats. - msLastTimestamp time.Time - msMtx sync.Mutex // Protects msLast and msLastTimestamp. - msMetrics memStatsMetrics - msRead func(*runtime.MemStats) // For mocking in tests. - msMaxWait time.Duration // Wait time for fresh memstats. - msMaxAge time.Duration // Maximum allowed age of old memstats. -} - -// NewGoCollector is the obsolete version of collectors.NewGoCollector. -// See there for documentation. -// -// Deprecated: Use collectors.NewGoCollector instead. -func NewGoCollector() Collector { - msMetrics := goRuntimeMemStats() - msMetrics = append(msMetrics, struct { - desc *Desc - eval func(*runtime.MemStats) float64 - valType ValueType - }{ - // This metric is omitted in Go1.17+, see https://github.com/prometheus/client_golang/issues/842#issuecomment-861812034 - desc: NewDesc( - memstatNamespace("gc_cpu_fraction"), - "The fraction of this program's available CPU time used by the GC since the program started.", - nil, nil, - ), - eval: func(ms *runtime.MemStats) float64 { return ms.GCCPUFraction }, - valType: GaugeValue, - }) - return &goCollector{ - base: newBaseGoCollector(), - msLast: &runtime.MemStats{}, - msRead: runtime.ReadMemStats, - msMaxWait: time.Second, - msMaxAge: 5 * time.Minute, - msMetrics: msMetrics, - } -} - -// Describe returns all descriptions of the collector. -func (c *goCollector) Describe(ch chan<- *Desc) { - c.base.Describe(ch) - for _, i := range c.msMetrics { - ch <- i.desc - } -} - -// Collect returns the current state of all metrics of the collector. -func (c *goCollector) Collect(ch chan<- Metric) { - var ( - ms = &runtime.MemStats{} - done = make(chan struct{}) - ) - // Start reading memstats first as it might take a while. - go func() { - c.msRead(ms) - c.msMtx.Lock() - c.msLast = ms - c.msLastTimestamp = time.Now() - c.msMtx.Unlock() - close(done) - }() - - // Collect base non-memory metrics. - c.base.Collect(ch) - - timer := time.NewTimer(c.msMaxWait) - select { - case <-done: // Our own ReadMemStats succeeded in time. Use it. - timer.Stop() // Important for high collection frequencies to not pile up timers. - c.msCollect(ch, ms) - return - case <-timer.C: // Time out, use last memstats if possible. Continue below. - } - c.msMtx.Lock() - if time.Since(c.msLastTimestamp) < c.msMaxAge { - // Last memstats are recent enough. Collect from them under the lock. - c.msCollect(ch, c.msLast) - c.msMtx.Unlock() - return - } - // If we are here, the last memstats are too old or don't exist. We have - // to wait until our own ReadMemStats finally completes. For that to - // happen, we have to release the lock. - c.msMtx.Unlock() - <-done - c.msCollect(ch, ms) -} - -func (c *goCollector) msCollect(ch chan<- Metric, ms *runtime.MemStats) { - for _, i := range c.msMetrics { - ch <- MustNewConstMetric(i.desc, i.valType, i.eval(ms)) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go index 6b86847..1db1c4b 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go @@ -98,7 +98,7 @@ type goCollector struct { // snapshot is always produced by Collect. mu sync.Mutex - // Contains all samples that has to retrieved from runtime/metrics (not all of them will be exposed). + // Contains all samples that have to be retrieved from runtime/metrics (not all of them will be exposed). sampleBuf []metrics.Sample // sampleMap allows lookup for MemStats metrics and runtime/metrics histograms for exact sums. sampleMap map[string]*metrics.Sample @@ -210,16 +210,26 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector { sampleBuf = append(sampleBuf, metrics.Sample{Name: d.Name}) sampleMap[d.Name] = &sampleBuf[len(sampleBuf)-1] + // Extract unit from the runtime/metrics name (e.g., "/gc/heap/allocs:bytes" -> "bytes") + // and sanitize to match Prometheus naming conventions (e.g., "cpu-seconds" -> "cpu_seconds") + var unit string + if idx := strings.IndexRune(d.Name, ':'); idx >= 0 { + unit = d.Name[idx+1:] + unit = strings.ReplaceAll(unit, "-", "_") + unit = strings.ReplaceAll(unit, "*", "_") + unit = strings.ReplaceAll(unit, "/", "_per_") + } + var m collectorMetric if d.Kind == metrics.KindFloat64Histogram { _, hasSum := opt.RuntimeMetricSumForHist[d.Name] - unit := d.Name[strings.IndexRune(d.Name, ':')+1:] m = newBatchHistogram( - NewDesc( + V2.NewDesc( BuildFQName(namespace, subsystem, name), help, + UnconstrainedLabels(nil), nil, - nil, + WithUnit(unit), ), internal.RuntimeMetricsBucketsForUnit(bucketsMap[d.Name], unit), hasSum, @@ -230,6 +240,7 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector { Subsystem: subsystem, Name: name, Help: help, + Unit: unit, }, ) } else { @@ -238,6 +249,7 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector { Subsystem: subsystem, Name: name, Help: help, + Unit: unit, }) } metricSet = append(metricSet, m) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go index c453b75..88bae3b 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go @@ -378,6 +378,9 @@ type HistogramOpts struct { // string. Help string + // Unit provides the unit of this Histogram. + Unit string + // ConstLabels are used to attach fixed labels to this metric. Metrics // with the same fully-qualified name must have the same label names in // their ConstLabels. @@ -522,11 +525,12 @@ type HistogramVecOpts struct { // for each bucket. func NewHistogram(opts HistogramOpts) Histogram { return newHistogram( - NewDesc( + V2.NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, - nil, + UnconstrainedLabels(nil), opts.ConstLabels, + WithUnit(opts.Unit), ), opts, ) @@ -966,7 +970,7 @@ func (h *histogram) maybeReset( // We are using the possibly mocked h.now() rather than // time.Since(h.lastResetTime) to enable testing. if h.nativeHistogramMinResetDuration == 0 || // No reset configured. - h.resetScheduled || // Do not interefere if a reset is already scheduled. + h.resetScheduled || // Do not interfere if a reset is already scheduled. h.now().Sub(h.lastResetTime) < h.nativeHistogramMinResetDuration { return false } @@ -1053,8 +1057,8 @@ func (h *histogram) maybeWidenZeroBucket(hot, cold *histogramCounts) bool { atomic.StoreUint64(&cold.nativeHistogramZeroThresholdBits, math.Float64bits(newZeroThreshold)) // ...and then merge the newly deleted buckets into the wider zero // bucket. - mergeAndDeleteOrAddAndReset := func(hotBuckets, coldBuckets *sync.Map) func(k, v interface{}) bool { - return func(k, v interface{}) bool { + mergeAndDeleteOrAddAndReset := func(hotBuckets, coldBuckets *sync.Map) func(k, v any) bool { + return func(k, v any) bool { key := k.(int) bucket := v.(*int64) if key == smallestKey { @@ -1107,8 +1111,8 @@ func (h *histogram) doubleBucketWidth(hot, cold *histogramCounts) { // ...adjust the schema in the cold counts, too... atomic.StoreInt32(&cold.nativeHistogramSchema, coldSchema) // ...and then merge the cold buckets into the wider hot buckets. - merge := func(hotBuckets *sync.Map) func(k, v interface{}) bool { - return func(k, v interface{}) bool { + merge := func(hotBuckets *sync.Map) func(k, v any) bool { + return func(k, v any) bool { key := k.(int) bucket := v.(*int64) // Adjust key to match the bucket to merge into. @@ -1190,6 +1194,7 @@ func (v2) NewHistogramVec(opts HistogramVecOpts) *HistogramVec { opts.Help, opts.VariableLabels, opts.ConstLabels, + WithUnit(opts.Unit), ) return &HistogramVec{ MetricVec: NewMetricVec(desc, func(lvs ...string) Metric { @@ -1476,7 +1481,7 @@ func pickSchema(bucketFactor float64) int32 { func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) { var ii []int - buckets.Range(func(k, v interface{}) bool { + buckets.Range(func(k, v any) bool { ii = append(ii, k.(int)) return true }) @@ -1553,8 +1558,8 @@ func addToBucket(buckets *sync.Map, key int, increment int64) bool { // according to the buckets ranged through. It then resets all buckets ranged // through to 0 (but leaves them in place so that they don't need to get // recreated on the next scrape). -func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v interface{}) bool { - return func(k, v interface{}) bool { +func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v any) bool { + return func(k, v any) bool { bucket := v.(*int64) if addToBucket(hotBuckets, k.(int), atomic.LoadInt64(bucket)) { atomic.AddUint32(bucketNumber, 1) @@ -1565,7 +1570,7 @@ func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v interface } func deleteSyncMap(m *sync.Map) { - m.Range(func(k, v interface{}) bool { + m.Range(func(k, v any) bool { m.Delete(k) return true }) @@ -1573,7 +1578,7 @@ func deleteSyncMap(m *sync.Map) { func findSmallestKey(m *sync.Map) int { result := math.MaxInt32 - m.Range(func(k, v interface{}) bool { + m.Range(func(k, v any) bool { key := k.(int) if key < result { result = key diff --git a/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go b/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go index 7bac0da..2db270f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go @@ -78,7 +78,7 @@ type OpCode struct { // notion, pairing up elements that appear uniquely in each sequence. // That, and the method here, appear to yield more intuitive difference // reports than does diff. This method appears to be the least vulnerable -// to synching up on blocks of "junk lines", though (like blank lines in +// to syncing up on blocks of "junk lines", though (like blank lines in // ordinary text files, or maybe "

" lines in HTML files). That may be // because this is the only method of the 3 that has a *concept* of // "junk" . @@ -567,7 +567,7 @@ type UnifiedDiff struct { func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { buf := bufio.NewWriter(writer) defer buf.Flush() - wf := func(format string, args ...interface{}) error { + wf := func(format string, args ...any) error { _, err := fmt.Fprintf(buf, format, args...) return err } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/labels.go b/vendor/github.com/prometheus/client_golang/prometheus/labels.go index 5fe8d3b..a028548 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/labels.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/labels.go @@ -184,6 +184,5 @@ func validateLabelValues(vals []string, expectedNumberOfValues int) error { } func checkLabelName(l string) bool { - //nolint:staticcheck // TODO: Don't use deprecated model.NameValidationScheme. - return model.NameValidationScheme.IsValidLabelName(l) && !strings.HasPrefix(l, reservedLabelPrefix) + return model.UTF8Validation.IsValidLabelName(l) && !strings.HasPrefix(l, reservedLabelPrefix) } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric.go b/vendor/github.com/prometheus/client_golang/prometheus/metric.go index 76e59f1..c5cb90a 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/metric.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/metric.go @@ -81,6 +81,9 @@ type Opts struct { // string. Help string + // Unit provides the unit of this metric as per https://prometheus.io/docs/specs/om + Unit string + // ConstLabels are used to attach fixed labels to this metric. Metrics // with the same fully-qualified name must have the same label names in // their ConstLabels. diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go index b32c95f..2b16298 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go @@ -72,7 +72,13 @@ func getOpenFileCount() (float64, error) { } func (c *processCollector) processCollect(ch chan<- Metric) { - if procs, err := unix.SysctlKinfoProcSlice("kern.proc.pid", os.Getpid()); err == nil { + pid, err := c.pidFn() + if err != nil { + c.reportError(ch, nil, err) + return + } + + if procs, err := unix.SysctlKinfoProcSlice("kern.proc.pid", pid); err == nil { if len(procs) == 1 { startTime := float64(procs[0].Proc.P_starttime.Nano() / 1e9) ch <- MustNewConstMetric(c.startTime, GaugeValue, startTime) @@ -84,6 +90,11 @@ func (c *processCollector) processCollect(ch chan<- Metric) { c.reportError(ch, c.startTime, err) } + if pid != os.Getpid() { + c.reportError(ch, nil, fmt.Errorf("collecting metrics for pid %d is not supported on darwin: process metrics collection is limited to the current process (pid %d)", pid, os.Getpid())) + return + } + // The proc structure returned by kern.proc.pid above has an Rusage member, // but it is not filled in, so it needs to be fetched by getrusage(2). For // that call, the UTime, STime, and Maxrss members are filled out, but not diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go index fa47428..c08dd05 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go @@ -30,6 +30,10 @@ var ( procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo") procGetProcessHandleCount = modkernel32.NewProc("GetProcessHandleCount") + + openProcess = windows.OpenProcess + closeHandle = windows.CloseHandle + getProcessTimes = windows.GetProcessTimes ) type processMemoryCounters struct { @@ -79,10 +83,21 @@ func getProcessHandleCount(handle windows.Handle) (uint32, error) { } func (c *processCollector) processCollect(ch chan<- Metric) { - h := windows.CurrentProcess() + pid, err := c.pidFn() + if err != nil { + c.reportError(ch, nil, err) + return + } + + h, err := openProcess(windows.PROCESS_QUERY_INFORMATION|windows.PROCESS_VM_READ, false, uint32(pid)) + if err != nil { + c.reportError(ch, nil, err) + return + } + defer closeHandle(h) var startTime, exitTime, kernelTime, userTime windows.Filetime - err := windows.GetProcessTimes(h, &startTime, &exitTime, &kernelTime, &userTime) + err = getProcessTimes(h, &startTime, &exitTime, &kernelTime, &userTime) if err != nil { c.reportError(ch, nil, err) return diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go index 763d99e..c28af5c 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go @@ -37,10 +37,12 @@ import ( "fmt" "io" "net/http" + "slices" "strconv" "sync" "time" + dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" "github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil" @@ -74,11 +76,118 @@ func defaultCompressionFormats() []Compression { } var gzipPool = sync.Pool{ - New: func() interface{} { + New: func() any { return gzip.NewWriter(nil) }, } +// coalescingGatherer wraps a TransactionalGatherer to deduplicate concurrent +// Gather calls. When a Gather is already in flight, new callers join the +// existing cycle and receive the same result once it completes. The underlying +// done function is called exactly once, when the last joined caller releases. +// +// This prevents goroutine pile-up when the scrape rate is faster than the +// time collectors need to produce metrics. +type coalescingGatherer struct { + g prometheus.TransactionalGatherer + mu sync.Mutex + cycle *gatherCycle +} + +// gatherCycle tracks a single in-flight Gather and all HTTP handlers sharing it. +type gatherCycle struct { + ready chan struct{} // closed when Gather completes; happens-before reads of mfs/err/done + mfs []*dto.MetricFamily // canonical result, set before ready is closed; callers get a slices.Clone, the element values stay shared and must not be mutated + err error // set before ready is closed + done func() // underlying done callback; set before ready is closed + refs int // number of handlers using this cycle; protected by coalescingGatherer.mu +} + +var _ prometheus.TransactionalGatherer = (*coalescingGatherer)(nil) // compile-time interface check + +// errGatherPanicked is returned to callers that joined an in-flight coalesced +// Gather whose underlying gatherer panicked. See the panic guard in Gather for +// why joiners receive this error instead of the panic itself. +var errGatherPanicked = errors.New("coalesced gather panicked") + +func (c *coalescingGatherer) Gather() ([]*dto.MetricFamily, func(), error) { + c.mu.Lock() + if cy := c.cycle; cy != nil { + // c.cycle is non-nil while Gather runs or handlers are still consuming its results. + cy.refs++ + c.mu.Unlock() + <-cy.ready + // Each caller gets its own slice header so it can filter or reorder + // without racing other callers sharing this cycle. The *dto.MetricFamily + // values remain shared and must not be mutated in place. + return slices.Clone(cy.mfs), c.releaseFunc(cy), cy.err + } + cy := &gatherCycle{ + ready: make(chan struct{}), + done: func() {}, + refs: 1, + } + c.cycle = cy + c.mu.Unlock() + + // Guard against a panic in c.g.Gather. The common case, a panicking + // Collector, never reaches here: Registry.Gather recovers Collector panics + // and returns them as an error. This guard only covers the rare case where + // the wrapped gatherer itself panics. + // + // We deliberately do not recover: the leader's panic propagates and is + // handled by net/http exactly as it would be without coalescing. We only + // set cy.err before closing cy.ready so joiners waiting on <-cy.ready fail + // with that error instead of silently returning an empty, successful + // response, and we clear c.cycle so the next Gather starts a fresh cycle. + // + // The leader never runs its own releaseFunc on this path, so its ref is + // not decremented; that is harmless because the cycle is detached (c.cycle + // = nil) and cy.done is still the no-op set at construction (c.g.Gather + // panicked before assigning a real done). If cy.done is ever made non-nil + // before c.g.Gather runs, this path would need to release it. + panicked := true + defer func() { + if panicked { + c.mu.Lock() + if c.cycle == cy { + c.cycle = nil + } + c.mu.Unlock() + cy.err = errGatherPanicked // set before close: happens-before joiners' reads + close(cy.ready) + } + }() + cy.mfs, cy.done, cy.err = c.g.Gather() + panicked = false + close(cy.ready) // happens-before joiners' reads of cy.mfs/err/done + + // Clone here too so cy.mfs stays the write-once canonical slice: joiners + // read it concurrently via slices.Clone, so the leader must not hand out + // (and potentially reorder) the same backing array. + return slices.Clone(cy.mfs), c.releaseFunc(cy), cy.err +} + +// releaseFunc returns the done callback for one caller sharing cy. +// When the last caller releases, the underlying done is invoked and the +// cycle is cleared so the next Gather starts fresh. +func (c *coalescingGatherer) releaseFunc(cy *gatherCycle) func() { + return func() { + c.mu.Lock() + cy.refs-- + if cy.refs > 0 { + c.mu.Unlock() + return + } + // Last caller. + if c.cycle == cy { + c.cycle = nil + } + c.mu.Unlock() + cy.done() // called outside the lock to avoid holding it during done + } +} + // Handler returns an http.Handler for the prometheus.DefaultGatherer, using // default HandlerOpts, i.e. it reports the first error as an HTTP error, it has // no error logging, and it applies compression if requested by the client. @@ -89,6 +198,10 @@ var gzipPool = sync.Pool{ // metrics used for instrumentation will be shared between them, providing // global scrape counts. // +// The handler supports filtering metrics by name using the `name[]` query parameter. +// Multiple metric names can be specified by providing the parameter multiple times. +// When no name[] parameters are provided, all metrics are returned. +// // This function is meant to cover the bulk of basic use cases. If you are doing // anything that requires more customization (including using a non-default // Gatherer, different instrumentation, and non-default HandlerOpts), use the @@ -105,6 +218,10 @@ func Handler() http.Handler { // Gatherers, with non-default HandlerOpts, and/or with custom (or no) // instrumentation. Use the InstrumentMetricHandler function to apply the same // kind of instrumentation as it is used by the Handler function. +// +// The handler supports filtering metrics by name using the `name[]` query parameter. +// Multiple metric names can be specified by providing the parameter multiple times. +// When no name[] parameters are provided, all metrics are returned. func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler { return HandlerForTransactional(prometheus.ToTransactionalGatherer(reg), opts) } @@ -112,7 +229,15 @@ func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler { // HandlerForTransactional is like HandlerFor, but it uses transactional gather, which // can safely change in-place returned *dto.MetricFamily before call to `Gather` and after // call to `done` of that `Gather`. +// +// The handler supports filtering metrics by name using the `name[]` query parameter. +// Multiple metric names can be specified by providing the parameter multiple times. +// When no name[] parameters are provided, all metrics are returned. func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerOpts) http.Handler { + if opts.CoalesceGather { + reg = &coalescingGatherer{g: reg} + } + var ( inFlightSem chan struct{} errCnt = prometheus.NewCounterVec( @@ -214,12 +339,14 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO rsp.Header().Set(contentEncodingHeader, encodingHeader) } - var enc expfmt.Encoder + var ( + enc expfmt.Encoder + encOpts []expfmt.EncoderOption + ) if opts.EnableOpenMetricsTextCreatedSamples { - enc = expfmt.NewEncoder(w, contentType, expfmt.WithCreatedLines()) - } else { - enc = expfmt.NewEncoder(w, contentType) + encOpts = append(encOpts, expfmt.WithCreatedLines()) } + enc = expfmt.NewEncoder(w, contentType, encOpts...) // handleError handles the error according to opts.ErrorHandling // and returns true if we have to abort after the handling. @@ -245,7 +372,24 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO return false } + // Build metric name filter set from query params (if any). The URL + // can be nil on hand-constructed requests. + var metricFilter map[string]struct{} + if req.URL != nil { + if metricNames := req.URL.Query()["name[]"]; len(metricNames) > 0 { + metricFilter = make(map[string]struct{}, len(metricNames)) + for _, name := range metricNames { + metricFilter[name] = struct{}{} + } + } + } + for _, mf := range mfs { + if metricFilter != nil { + if _, ok := metricFilter[mf.GetName()]; !ok { + continue + } + } if handleError(enc.Encode(mf)) { return } @@ -353,7 +497,7 @@ const ( // log.Logger from the standard library implements this interface, and it is // easy to implement by custom loggers, if they don't do so already anyway. type Logger interface { - Println(v ...interface{}) + Println(v ...any) } // HandlerOpts specifies options how to serve metrics via an http.Handler. The @@ -400,6 +544,40 @@ type HandlerOpts struct { // Service Unavailable and a suitable message in the body. If // MaxRequestsInFlight is 0 or negative, no limit is applied. MaxRequestsInFlight int + // CoalesceGather, if true, deduplicates concurrent Gather calls so that + // only one collection runs at a time. Additional requests that arrive + // while a Gather is in flight will receive the same result once it + // completes. This prevents goroutine pile-up when the scrape rate is + // faster than the time collectors need to produce metrics. + // + // When enabled, concurrent scrapers share a single metric snapshot per + // collection cycle. Each request receives its own copy of the returned + // slice, so filtering or reordering it (for example via name[] query + // parameters) is safe. The pointed-to MetricFamily values are still + // shared: the built-in handler only reads them, so this is safe in + // practice, but a custom TransactionalGatherer that mutates the returned + // families in place after Gather returns must not use this option. + // + // Because the snapshot is shared, a request that arrives while a cycle is + // in flight receives that cycle's result even though collection began + // before the request; two scrapers joined to one cycle observe the same + // timestamps rather than independently gathered data. + // + // Consider using CoalesceGather together with Timeout. Timeout bounds the + // client-facing response time and keeps at most one collection running at + // a time, but it does not cancel the underlying Gather: a joined request + // that times out still holds a MaxRequestsInFlight slot until the shared + // collection completes. + // + // Panic handling: a panicking Collector is already turned into an error by + // the registry, so joiners receive that error like any other. In the rare + // case where the wrapped gatherer itself panics, the panicking request's + // panic propagates as usual (handled by net/http), while requests that + // joined the same cycle receive an error rather than an empty response. + // + // NOTE: This option is experimental and may change or be removed in a + // future release. + CoalesceGather bool // If handling a request takes longer than Timeout, it is responded to // with 503 ServiceUnavailable and a suitable Message. No timeout is // applied if Timeout is 0 or negative. Note that with the current @@ -407,8 +585,9 @@ type HandlerOpts struct { // described above (and even that only if sending of the body hasn't // started yet), while the bulk work of gathering all the metrics keeps // running in the background (with the eventual result to be thrown - // away). Until the implementation is improved, it is recommended to - // implement a separate timeout in potentially slow Collectors. + // away). When CoalesceGather is enabled, only one such background Gather + // can be in flight at a time. It is also recommended to implement a + // separate timeout in potentially slow Collectors. Timeout time.Duration // If true, the experimental OpenMetrics encoding is added to the // possible options during content negotiation. Note that Prometheus @@ -460,7 +639,7 @@ func httpError(rsp http.ResponseWriter, err error) { // negotiateEncodingWriter reads the Accept-Encoding header from a request and // selects the right compression based on an allow-list of supported -// compressions. It returns a writer implementing the compression and an the +// compressions. It returns a writer implementing the compression and the // correct value that the caller can set in the response header. func negotiateEncodingWriter(r *http.Request, rw io.Writer, compressions []string) (_ io.Writer, encodingHeaderValue string, closeWriter func(), _ error) { if len(compressions) == 0 { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go index d3482c4..0248579 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go @@ -75,10 +75,10 @@ func InstrumentRoundTripperCounter(counter *prometheus.CounterVec, next http.Rou resp, err := next.RoundTrip(r) if err == nil { l := labels(code, method, r.Method, resp.StatusCode, rtOpts.extraMethods...) - for label, resolve := range rtOpts.extraLabelsFromCtx { - l[label] = resolve(resp.Request.Context()) + for label, resolve := range rtOpts.extraLabelsFromRequest { + l[label] = resolve(resp.Request) } - addWithExemplar(counter.With(l), 1, rtOpts.getExemplarFn(r.Context())) + addWithExemplar(counter.With(l), 1, rtOpts.getExemplarFn(r)) } return resp, err } @@ -119,10 +119,10 @@ func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundT resp, err := next.RoundTrip(r) if err == nil { l := labels(code, method, r.Method, resp.StatusCode, rtOpts.extraMethods...) - for label, resolve := range rtOpts.extraLabelsFromCtx { - l[label] = resolve(resp.Request.Context()) + for label, resolve := range rtOpts.extraLabelsFromRequest { + l[label] = resolve(resp.Request) } - observeWithExemplar(obs.With(l), time.Since(start).Seconds(), rtOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), time.Since(start).Seconds(), rtOpts.getExemplarFn(r)) } return resp, err } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go index 9332b02..9dec091 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go @@ -28,24 +28,36 @@ import ( // magicString is used for the hacky label test in checkLabels. Remove once fixed. const magicString = "zZgWfBxLqvG8kc8IMv3POi2Bb0tZI3vAnBx+gBaFi9FyPzB/CzKUer1yufDa" -// observeWithExemplar is a wrapper for [prometheus.ExemplarAdder.ExemplarObserver], -// which falls back to [prometheus.Observer.Observe] if no labels are provided. +// observeWithExemplar records val on obs. If labels is non-nil and obs +// implements [prometheus.ExemplarObserver], the exemplar is attached via +// ObserveWithExemplar; otherwise the exemplar is dropped and the value is +// recorded with a plain [prometheus.Observer.Observe]. This mirrors the +// safe-cast pattern in [prometheus.Timer.ObserveDurationWithExemplar] and +// ensures we never panic when callers pass an ObserverVec backed by a +// summary, which cannot carry exemplars in the Prometheus exposition format. func observeWithExemplar(obs prometheus.Observer, val float64, labels map[string]string) { - if labels == nil { - obs.Observe(val) - return + if labels != nil { + if eo, ok := obs.(prometheus.ExemplarObserver); ok { + eo.ObserveWithExemplar(val, labels) + return + } } - obs.(prometheus.ExemplarObserver).ObserveWithExemplar(val, labels) + obs.Observe(val) } -// addWithExemplar is a wrapper for [prometheus.ExemplarAdder.AddWithExemplar], -// which falls back to [prometheus.Counter.Add] if no labels are provided. -func addWithExemplar(obs prometheus.Counter, val float64, labels map[string]string) { - if labels == nil { - obs.Add(val) - return +// addWithExemplar records val on c. If labels is non-nil and c implements +// [prometheus.ExemplarAdder], the exemplar is attached via AddWithExemplar; +// otherwise the exemplar is dropped and the value is recorded with a plain +// [prometheus.Counter.Add]. The safe-cast keeps the helper robust against +// custom Counter implementations that do not advertise exemplar support. +func addWithExemplar(c prometheus.Counter, val float64, labels map[string]string) { + if labels != nil { + if ea, ok := c.(prometheus.ExemplarAdder); ok { + ea.AddWithExemplar(val, labels) + return + } } - obs.(prometheus.ExemplarAdder).AddWithExemplar(val, labels) + c.Add(val) } // InstrumentHandlerInFlight is a middleware that wraps the provided @@ -97,10 +109,10 @@ func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler, op next.ServeHTTP(d, r) l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...) - for label, resolve := range hOpts.extraLabelsFromCtx { - l[label] = resolve(r.Context()) + for label, resolve := range hOpts.extraLabelsFromRequest { + l[label] = resolve(r) } - observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r)) } } @@ -108,10 +120,10 @@ func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler, op now := time.Now() next.ServeHTTP(w, r) l := labels(code, method, r.Method, 0, hOpts.extraMethods...) - for label, resolve := range hOpts.extraLabelsFromCtx { - l[label] = resolve(r.Context()) + for label, resolve := range hOpts.extraLabelsFromRequest { + l[label] = resolve(r) } - observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r)) } } @@ -147,10 +159,10 @@ func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler, next.ServeHTTP(d, r) l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...) - for label, resolve := range hOpts.extraLabelsFromCtx { - l[label] = resolve(r.Context()) + for label, resolve := range hOpts.extraLabelsFromRequest { + l[label] = resolve(r) } - addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context())) + addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r)) } } @@ -158,10 +170,10 @@ func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler, next.ServeHTTP(w, r) l := labels(code, method, r.Method, 0, hOpts.extraMethods...) - for label, resolve := range hOpts.extraLabelsFromCtx { - l[label] = resolve(r.Context()) + for label, resolve := range hOpts.extraLabelsFromRequest { + l[label] = resolve(r) } - addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context())) + addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r)) } } @@ -200,10 +212,10 @@ func InstrumentHandlerTimeToWriteHeader(obs prometheus.ObserverVec, next http.Ha now := time.Now() d := newDelegator(w, func(status int) { l := labels(code, method, r.Method, status, hOpts.extraMethods...) - for label, resolve := range hOpts.extraLabelsFromCtx { - l[label] = resolve(r.Context()) + for label, resolve := range hOpts.extraLabelsFromRequest { + l[label] = resolve(r) } - observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r)) }) next.ServeHTTP(d, r) } @@ -244,10 +256,10 @@ func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler, size := computeApproximateRequestSize(r) l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...) - for label, resolve := range hOpts.extraLabelsFromCtx { - l[label] = resolve(r.Context()) + for label, resolve := range hOpts.extraLabelsFromRequest { + l[label] = resolve(r) } - observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r)) } } @@ -256,10 +268,10 @@ func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler, size := computeApproximateRequestSize(r) l := labels(code, method, r.Method, 0, hOpts.extraMethods...) - for label, resolve := range hOpts.extraLabelsFromCtx { - l[label] = resolve(r.Context()) + for label, resolve := range hOpts.extraLabelsFromRequest { + l[label] = resolve(r) } - observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r)) } } @@ -296,10 +308,10 @@ func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler next.ServeHTTP(d, r) l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...) - for label, resolve := range hOpts.extraLabelsFromCtx { - l[label] = resolve(r.Context()) + for label, resolve := range hOpts.extraLabelsFromRequest { + l[label] = resolve(r) } - observeWithExemplar(obs.With(l), float64(d.Written()), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), float64(d.Written()), hOpts.getExemplarFn(r)) }) } @@ -366,7 +378,7 @@ func checkLabels(c prometheus.Collector) (code, method bool) { panic("metric partitioned with non-supported labels") } } - return + return code, method } func isLabelCurried(c prometheus.Collector, label string) bool { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go index 5d4383a..d4c0954 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go @@ -15,6 +15,7 @@ package promhttp import ( "context" + "net/http" "github.com/prometheus/client_golang/prometheus" ) @@ -24,28 +25,31 @@ type Option interface { apply(*options) } +// LabelValueFromRequest is used to compute the label value from request. +type LabelValueFromRequest func(request *http.Request) string + // LabelValueFromCtx are used to compute the label value from request context. // Context can be filled with values from request through middleware. type LabelValueFromCtx func(ctx context.Context) string // options store options for both a handler or round tripper. type options struct { - extraMethods []string - getExemplarFn func(requestCtx context.Context) prometheus.Labels - extraLabelsFromCtx map[string]LabelValueFromCtx + extraMethods []string + getExemplarFn func(req *http.Request) prometheus.Labels + extraLabelsFromRequest map[string]LabelValueFromRequest } func defaultOptions() *options { return &options{ - getExemplarFn: func(ctx context.Context) prometheus.Labels { return nil }, - extraLabelsFromCtx: map[string]LabelValueFromCtx{}, + getExemplarFn: func(req *http.Request) prometheus.Labels { return nil }, + extraLabelsFromRequest: map[string]LabelValueFromRequest{}, } } func (o *options) emptyDynamicLabels() prometheus.Labels { labels := prometheus.Labels{} - for label := range o.extraLabelsFromCtx { + for label := range o.extraLabelsFromRequest { labels[label] = "" } @@ -66,12 +70,30 @@ func WithExtraMethods(methods ...string) Option { }) } -// WithExemplarFromContext allows to inject function that will get exemplar from context that will be put to counter and histogram metrics. +// WithExemplarFromRequest allows you to inject a function that will get exemplar from request that will be put to counter and histogram metrics. +// If the function returns nil labels or the metric does not support exemplars, no exemplar will be added (noop), but +// metric will continue to observe/increment. +func WithExemplarFromRequest(getExemplarFn func(req *http.Request) prometheus.Labels) Option { + return optionApplyFunc(func(o *options) { + o.getExemplarFn = getExemplarFn + }) +} + +// WithExemplarFromContext allows you to inject a function that will get exemplar from context that will be put to counter and histogram metrics. // If the function returns nil labels or the metric does not support exemplars, no exemplar will be added (noop), but // metric will continue to observe/increment. func WithExemplarFromContext(getExemplarFn func(requestCtx context.Context) prometheus.Labels) Option { return optionApplyFunc(func(o *options) { - o.getExemplarFn = getExemplarFn + o.getExemplarFn = func(req *http.Request) prometheus.Labels { + return getExemplarFn(req.Context()) + } + }) +} + +// WithLabelFromRequest registers a label for dynamic resolution with access to the request. +func WithLabelFromRequest(name string, valueFn LabelValueFromRequest) Option { + return optionApplyFunc(func(o *options) { + o.extraLabelsFromRequest[name] = valueFn }) } @@ -79,6 +101,8 @@ func WithExemplarFromContext(getExemplarFn func(requestCtx context.Context) prom // See the example for ExampleInstrumentHandlerWithLabelResolver for example usage func WithLabelFromCtx(name string, valueFn LabelValueFromCtx) Option { return optionApplyFunc(func(o *options) { - o.extraLabelsFromCtx[name] = valueFn + o.extraLabelsFromRequest[name] = func(req *http.Request) string { + return valueFn(req.Context()) + } }) } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry.go b/vendor/github.com/prometheus/client_golang/prometheus/registry.go index c6fd2f5..ed0681c 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/registry.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/registry.go @@ -214,6 +214,19 @@ func (err AlreadyRegisteredError) Error() string { // by a Gatherer to report multiple errors during MetricFamily gathering. type MultiError []error +// SafeMultiError is a thread-safe wrapper around MultiError using a mutex. +type SafeMultiError struct { + mu sync.Mutex + errs MultiError +} + +// Appends the provided error to the contained MultiError in a thread-safe way. +func (s *SafeMultiError) Append(err error) { + s.mu.Lock() + s.errs.Append(err) + s.mu.Unlock() +} + // Error formats the contained errors as a bullet point list, preceded by the // total number of errors. Note that this results in a multi-line string. func (errs MultiError) Error() string { @@ -408,6 +421,16 @@ func (r *Registry) MustRegister(cs ...Collector) { } } +// MustGather implements Gatherer. +// Wraps around Gather and panics if Gather fails for any reason. +func (r *Registry) MustGather() []*dto.MetricFamily { + mfs, err := r.Gather() + if err != nil { + panic(err) + } + return mfs +} + // Gather implements Gatherer. func (r *Registry) Gather() ([]*dto.MetricFamily, error) { r.mtx.RLock() @@ -423,7 +446,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { uncheckedMetricChan = make(chan Metric, capMetricChan) metricHashes = map[uint64]struct{}{} wg sync.WaitGroup - errs MultiError // The collected errors to return in the end. + safeErrs = &SafeMultiError{} // To collect errors in a threadsafe way registeredDescIDs map[uint64]struct{} // Only used for pedantic checks ) @@ -453,9 +476,9 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { for { select { case collector := <-checkedCollectors: - collector.Collect(checkedMetricChan) + safeErrs.Append((safeCollect(collector, checkedMetricChan))) case collector := <-uncheckedCollectors: - collector.Collect(uncheckedMetricChan) + safeErrs.Append(safeCollect(collector, uncheckedMetricChan)) default: return } @@ -499,7 +522,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { cmc = nil break } - errs.Append(processMetric( + safeErrs.Append(processMetric( metric, metricFamiliesByName, metricHashes, registeredDescIDs, @@ -509,7 +532,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { umc = nil break } - errs.Append(processMetric( + safeErrs.Append(processMetric( metric, metricFamiliesByName, metricHashes, nil, @@ -526,7 +549,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { cmc = nil break } - errs.Append(processMetric( + safeErrs.Append(processMetric( metric, metricFamiliesByName, metricHashes, registeredDescIDs, @@ -536,7 +559,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { umc = nil break } - errs.Append(processMetric( + safeErrs.Append(processMetric( metric, metricFamiliesByName, metricHashes, nil, @@ -556,7 +579,8 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { break } } - return internal.NormalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap() + + return internal.NormalizeMetricFamilies(metricFamiliesByName), safeErrs.errs.MaybeUnwrap() } // Describe implements Collector. @@ -571,6 +595,24 @@ func (r *Registry) Describe(ch chan<- *Desc) { } } +// Helper wrapper around Collector.Collect. +// It tries to collect from the channel, recovers on panic and +// if it has recovered from a panic, then it sends an InvalidMetric into +// the channel with an InvalidDesc, and an error that includes a stack trace. +func safeCollect(c Collector, ch chan<- Metric) (err error) { + defer func() { + if r := recover(); r != nil { + buf := make([]byte, 64<<10) // 64 KB + n := runtime.Stack(buf, false) + err = fmt.Errorf("prometheus collector panic recovered: type=%T: error=%v\nstack trace=%s", c, r, buf[:n]) + ch <- NewInvalidMetric(NewInvalidDesc(err), err) + } + }() + c.Collect(ch) + + return err +} + // Collect implements Collector. func (r *Registry) Collect(ch chan<- Metric) { r.mtx.RLock() @@ -599,10 +641,12 @@ func WriteToTextfile(filename string, g Gatherer) error { mfs, err := g.Gather() if err != nil { + tmp.Close() return err } for _, mf := range mfs { if _, err := expfmt.MetricFamilyToText(tmp, mf); err != nil { + tmp.Close() return err } } @@ -685,6 +729,9 @@ func processMetric( metricFamily = &dto.MetricFamily{} metricFamily.Name = proto.String(desc.fqName) metricFamily.Help = proto.String(desc.help) + if desc.unit != "" { + metricFamily.Unit = proto.String(desc.unit) + } // TODO(beorn7): Simplify switch once Desc has type. switch { case dtoMetric.Gauge != nil: diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go index ac5203c..c12b8d1 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/summary.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go @@ -101,6 +101,9 @@ type SummaryOpts struct { // string. Help string + // Unit provides the unit of this Summary. + Unit string + // ConstLabels are used to attach fixed labels to this metric. Metrics // with the same fully-qualified name must have the same label names in // their ConstLabels. @@ -181,11 +184,12 @@ type SummaryVecOpts struct { // NewSummary creates a new Summary based on the provided SummaryOpts. func NewSummary(opts SummaryOpts) Summary { return newSummary( - NewDesc( + V2.NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, - nil, + UnconstrainedLabels(nil), opts.ConstLabels, + WithUnit(opts.Unit), ), opts, ) @@ -578,6 +582,7 @@ func (v2) NewSummaryVec(opts SummaryVecOpts) *SummaryVec { opts.Help, opts.VariableLabels, opts.ConstLabels, + WithUnit(opts.Unit), ) return &SummaryVec{ MetricVec: NewMetricVec(desc, func(lvs ...string) Metric { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/timer.go b/vendor/github.com/prometheus/client_golang/prometheus/timer.go index 52344fe..c1318ff 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/timer.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/timer.go @@ -37,10 +37,10 @@ type Timer struct { // or // // func TimeMeWithExemplar() { -// timer := NewTimer(myHistogram) -// defer timer.ObserveDurationWithExemplar(exemplar) -// // Do actual work. -// } +// timer := NewTimer(myHistogram) +// defer timer.ObserveDurationWithExemplar(exemplar) +// // Do actual work. +// } func NewTimer(o Observer) *Timer { return &Timer{ begin: time.Now(), @@ -66,7 +66,7 @@ func (t *Timer) ObserveDuration() time.Duration { // ObserveDurationWithExemplar is like ObserveDuration, but it will also // observe exemplar with the duration unless exemplar is nil or provided Observer can't -// be casted to ExemplarObserver. +// be cast to ExemplarObserver. func (t *Timer) ObserveDurationWithExemplar(exemplar Labels) time.Duration { d := time.Since(t.begin) eo, ok := t.observer.(ExemplarObserver) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec.go b/vendor/github.com/prometheus/client_golang/prometheus/vec.go index 487b466..121d2a9 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/vec.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/vec.go @@ -193,9 +193,11 @@ func (m *MetricVec) CurryWith(labels Labels) (*MetricVec, error) { // // Keeping the Metric for later use is possible (and should be considered if // performance is critical), but keep in mind that Reset, DeleteLabelValues and -// Delete can be used to delete the Metric from the MetricVec. In that case, the -// Metric will still exist, but it will not be exported anymore, even if a -// Metric with the same label values is created later. +// Delete can be used to delete the Metric from the MetricVec. In that case, if +// you have previously kept a reference to that Metric, the Metric object still +// exists and can be used, but it will not be exported anymore. If a Metric with +// the same label values is created later, updates to the old Metric reference +// will not be exported. // // An error is returned if the number of label values is not the same as the // number of variable labels in Desc (minus any curried labels). @@ -657,7 +659,7 @@ func inlineLabelValues(lvs []string, curry []curriedLabelValue) []string { } var labelsPool = &sync.Pool{ - New: func() interface{} { + New: func() any { return make(Labels) }, } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/wrap.go b/vendor/github.com/prometheus/client_golang/prometheus/wrap.go index 2ed1285..697f555 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/wrap.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/wrap.go @@ -230,6 +230,7 @@ func wrapDesc(desc *Desc, prefix string, labels Labels) *Desc { return &Desc{ fqName: desc.fqName, help: desc.help, + unit: desc.unit, variableLabels: desc.variableLabels, constLabelPairs: desc.constLabelPairs, err: fmt.Errorf("attempted wrapping with already existing label name %q", ln), @@ -238,8 +239,8 @@ func wrapDesc(desc *Desc, prefix string, labels Labels) *Desc { constLabels[ln] = lv } // NewDesc will do remaining validations. - newDesc := V2.NewDesc(prefix+desc.fqName, desc.help, desc.variableLabels, constLabels) - // Propagate errors if there was any. This will override any errer + newDesc := V2.NewDesc(prefix+desc.fqName, desc.help, desc.variableLabels, constLabels, WithUnit(desc.unit)) + // Propagate errors if there was any. This will override any error // created by NewDesc above, i.e. earlier errors get precedence. if desc.err != nil { newDesc.err = desc.err diff --git a/vendor/github.com/sethvargo/go-retry/README.md b/vendor/github.com/sethvargo/go-retry/README.md index 4773182..3464965 100644 --- a/vendor/github.com/sethvargo/go-retry/README.md +++ b/vendor/github.com/sethvargo/go-retry/README.md @@ -1,6 +1,6 @@ # Retry -[![GoDoc](https://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://pkg.go.dev/mod/github.com/sethvargo/go-retry) +[![Test](https://github.com/sethvargo/go-retry/actions/workflows/test.yml/badge.svg)](https://github.com/sethvargo/go-retry/actions/workflows/test.yml)[![GoDoc](https://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://pkg.go.dev/mod/github.com/sethvargo/go-retry) Retry is a Go library for facilitating retry logic and backoff. It's highly extensible with full control over how and when retries occur. You can also write @@ -115,7 +115,7 @@ also write custom middleware. ### Jitter -To reduce the changes of a thundering herd, add random jitter to the returned +To reduce the chances of a thundering herd, add random jitter to the returned value. ```golang @@ -126,6 +126,9 @@ b = WithJitter(500*time.Millisecond, b) // Return the next value, +/- 5% of the result b = WithJitterPercent(5, b) + +// Return a random value in [0, next value) +b = WithFullJitter(b) ``` ### MaxRetries @@ -178,8 +181,8 @@ Benchmark/sethvargo-7 203,914,245 5.73 ns/op ## Notes and Caveats -- Randomization uses `math/rand` seeded with the Unix timestamp instead of - `crypto/rand`. +- Randomization uses `math/rand/v2` (non-cryptographic, automatically seeded), + not `crypto/rand`. - Ordering of addition of multiple modifiers will make a difference. For example; ensure you add `CappedDuration` before `WithMaxDuration`, otherwise it may early out too early. Another example is you could add `Jitter` before or after capping depending on your desired outcome. diff --git a/vendor/github.com/sethvargo/go-retry/backoff.go b/vendor/github.com/sethvargo/go-retry/backoff.go index de3974f..47f7475 100644 --- a/vendor/github.com/sethvargo/go-retry/backoff.go +++ b/vendor/github.com/sethvargo/go-retry/backoff.go @@ -1,6 +1,7 @@ package retry import ( + "math/rand/v2" "sync" "time" ) @@ -26,19 +27,18 @@ func (b BackoffFunc) Next() (time.Duration, bool) { // returned 20s, the value could be between 15 and 25 seconds. The value can // never be less than 0. func WithJitter(j time.Duration, next Backoff) Backoff { - r := newLockedRandom(time.Now().UnixNano()) - return BackoffFunc(func() (time.Duration, bool) { val, stop := next.Next() if stop { return 0, true } - diff := time.Duration(r.Int63n(int64(j)*2) - int64(j)) - val = val + diff - if val < 0 { - val = 0 + if j <= 0 { + return val, false } + + diff := time.Duration(rand.Int64N(int64(j)*2) - int64(j)) + val = max(val+diff, 0) return val, false }) } @@ -48,26 +48,48 @@ func WithJitter(j time.Duration, next Backoff) Backoff { // the backoff returned 20s, the value could be between 19 and 21 seconds. The // value can never be less than 0 or greater than 100. func WithJitterPercent(j uint64, next Backoff) Backoff { - r := newLockedRandom(time.Now().UnixNano()) - return BackoffFunc(func() (time.Duration, bool) { val, stop := next.Next() if stop { return 0, true } + if j <= 0 { + return val, false + } + // Get a value between -j and j, the convert to a percentage - top := r.Int63n(int64(j)*2) - int64(j) + top := rand.Int64N(int64(j)*2) - int64(j) pct := 1 - float64(top)/100.0 - val = time.Duration(float64(val) * pct) - if val < 0 { - val = 0 - } + val = max(time.Duration(float64(val)*pct), 0) return val, false }) } +// WithFullJitter wraps a backoff function and returns a random value between +// zero (inclusive) and the wrapped backoff's returned value (exclusive). For +// example, if the backoff returned 20s, the value could be anywhere in [0, 20s). +// +// Unlike WithJitter, which applies "+/- j" around the value, full jitter +// spreads the wait across the entire range, which spreads out retrying clients +// more effectively. See +// https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/. +func WithFullJitter(next Backoff) Backoff { + return BackoffFunc(func() (time.Duration, bool) { + val, stop := next.Next() + if stop { + return 0, true + } + + if val <= 0 { + return val, false + } + + return time.Duration(rand.Int64N(int64(val))), false + }) +} + // WithMaxRetries executes the backoff function up until the maximum attempts. func WithMaxRetries(max uint64, next Backoff) Backoff { var l sync.Mutex diff --git a/vendor/github.com/sethvargo/go-retry/backoff_constant.go b/vendor/github.com/sethvargo/go-retry/backoff_constant.go index ef01fa0..e25ebf4 100644 --- a/vendor/github.com/sethvargo/go-retry/backoff_constant.go +++ b/vendor/github.com/sethvargo/go-retry/backoff_constant.go @@ -13,7 +13,7 @@ func Constant(ctx context.Context, t time.Duration, f RetryFunc) error { // NewConstant creates a new constant backoff using the value t. The wait time // is the provided constant value. It panics if the given base is less than -// zero. +// or equal to zero. func NewConstant(t time.Duration) Backoff { if t <= 0 { panic("t must be greater than 0") diff --git a/vendor/github.com/sethvargo/go-retry/backoff_exponential.go b/vendor/github.com/sethvargo/go-retry/backoff_exponential.go index a85b498..4fc2788 100644 --- a/vendor/github.com/sethvargo/go-retry/backoff_exponential.go +++ b/vendor/github.com/sethvargo/go-retry/backoff_exponential.go @@ -9,7 +9,7 @@ import ( type exponentialBackoff struct { base time.Duration - attempt uint64 + attempt atomic.Uint64 } // Exponential is a wrapper around Retry that uses an exponential backoff. See @@ -37,11 +37,15 @@ func NewExponential(base time.Duration) Backoff { // Next implements Backoff. It is safe for concurrent use. func (b *exponentialBackoff) Next() (time.Duration, bool) { - next := b.base << (atomic.AddUint64(&b.attempt, 1) - 1) - if next <= 0 { - atomic.AddUint64(&b.attempt, ^uint64(0)) - next = math.MaxInt64 - } + for { + attempt := b.attempt.Load() + next := b.base << attempt + if next <= 0 { + return math.MaxInt64, false + } - return next, false + if b.attempt.CompareAndSwap(attempt, attempt+1) { + return next, false + } + } } diff --git a/vendor/github.com/sethvargo/go-retry/backoff_fibonacci.go b/vendor/github.com/sethvargo/go-retry/backoff_fibonacci.go index 250a026..747bf40 100644 --- a/vendor/github.com/sethvargo/go-retry/backoff_fibonacci.go +++ b/vendor/github.com/sethvargo/go-retry/backoff_fibonacci.go @@ -5,13 +5,12 @@ import ( "math" "sync/atomic" "time" - "unsafe" ) type state [2]time.Duration type fibonacciBackoff struct { - state unsafe.Pointer + state atomic.Pointer[state] } // Fibonacci is a wrapper around Retry that uses a Fibonacci backoff. See @@ -33,23 +32,22 @@ func NewFibonacci(base time.Duration) Backoff { panic("base must be greater than 0") } - return &fibonacciBackoff{ - state: unsafe.Pointer(&state{0, base}), - } + b := new(fibonacciBackoff) + b.state.Store(&state{0, base}) + return b } // Next implements Backoff. It is safe for concurrent use. func (b *fibonacciBackoff) Next() (time.Duration, bool) { for { - curr := atomic.LoadPointer(&b.state) - currState := (*state)(curr) - next := currState[0] + currState[1] + curr := b.state.Load() + next := curr[0] + curr[1] if next <= 0 { return math.MaxInt64, false } - if atomic.CompareAndSwapPointer(&b.state, curr, unsafe.Pointer(&state{currState[1], next})) { + if b.state.CompareAndSwap(curr, &state{curr[1], next}) { return next, false } } diff --git a/vendor/github.com/sethvargo/go-retry/rand.go b/vendor/github.com/sethvargo/go-retry/rand.go deleted file mode 100644 index 4799fb0..0000000 --- a/vendor/github.com/sethvargo/go-retry/rand.go +++ /dev/null @@ -1,54 +0,0 @@ -package retry - -import ( - "math/rand" - "sync" -) - -type lockedSource struct { - src *rand.Rand - mu sync.Mutex -} - -var _ rand.Source64 = (*lockedSource)(nil) - -func newLockedRandom(seed int64) *lockedSource { - return &lockedSource{src: rand.New(rand.NewSource(seed))} -} - -// Int63 mimics math/rand.(*Rand).Int63 with mutex locked. -func (r *lockedSource) Int63() int64 { - r.mu.Lock() - defer r.mu.Unlock() - return r.src.Int63() -} - -// Seed mimics math/rand.(*Rand).Seed with mutex locked. -func (r *lockedSource) Seed(seed int64) { - r.mu.Lock() - defer r.mu.Unlock() - r.src.Seed(seed) -} - -// Uint64 mimics math/rand.(*Rand).Uint64 with mutex locked. -func (r *lockedSource) Uint64() uint64 { - r.mu.Lock() - defer r.mu.Unlock() - return r.src.Uint64() -} - -// Int63n mimics math/rand.(*Rand).Int63n with mutex locked. -func (r *lockedSource) Int63n(n int64) int64 { - if n <= 0 { - panic("invalid argument to Int63n") - } - if n&(n-1) == 0 { // n is power of two, can mask - return r.Int63() & (n - 1) - } - max := int64((1 << 63) - 1 - (1<<63)%uint64(n)) - v := r.Int63() - for v > max { - v = r.Int63() - } - return v % n -} diff --git a/vendor/github.com/sethvargo/go-retry/retry.go b/vendor/github.com/sethvargo/go-retry/retry.go index a3eeadc..46453a9 100644 --- a/vendor/github.com/sethvargo/go-retry/retry.go +++ b/vendor/github.com/sethvargo/go-retry/retry.go @@ -54,10 +54,8 @@ func DoValue[T any](ctx context.Context, b Backoff, f RetryFuncValue[T]) (T, err for { // Return immediately if ctx is canceled - select { - case <-ctx.Done(): - return nilT, ctx.Err() - default: + if err := context.Cause(ctx); err != nil { + return nilT, err } v, err := f(ctx) @@ -76,20 +74,13 @@ func DoValue[T any](ctx context.Context, b Backoff, f RetryFuncValue[T]) (T, err return nilT, rerr.Unwrap() } - // ctx.Done() has priority, so we test it alone first - select { - case <-ctx.Done(): - return nilT, ctx.Err() - default: - } - + // Wait until next attempt or until the context expires. Any error will + // be caught at the top of the loop. t := time.NewTimer(next) select { case <-ctx.Done(): t.Stop() - return nilT, ctx.Err() case <-t.C: - continue } } } diff --git a/vendor/github.com/txix-open/etp/v4/.gitignore b/vendor/github.com/txix-open/etp/v4/.gitignore index fd2fff0..e2b76f6 100644 --- a/vendor/github.com/txix-open/etp/v4/.gitignore +++ b/vendor/github.com/txix-open/etp/v4/.gitignore @@ -72,3 +72,5 @@ fabric.properties google/ package.json yarn.lock + +.DS_Store \ No newline at end of file diff --git a/vendor/github.com/txix-open/etp/v4/.version b/vendor/github.com/txix-open/etp/v4/.version index 2582ddd..8c7fafd 100644 --- a/vendor/github.com/txix-open/etp/v4/.version +++ b/vendor/github.com/txix-open/etp/v4/.version @@ -1 +1 @@ -4.1.1 \ No newline at end of file +4.1.3 \ No newline at end of file diff --git a/vendor/github.com/txix-open/etp/v4/CHANGELOG.md b/vendor/github.com/txix-open/etp/v4/CHANGELOG.md index 2680544..c931073 100644 --- a/vendor/github.com/txix-open/etp/v4/CHANGELOG.md +++ b/vendor/github.com/txix-open/etp/v4/CHANGELOG.md @@ -1,3 +1,7 @@ +### v4.1.3 +* fix panic if `OnError` handler is `nil` +### v4.1.2 +* implement `Store.Delete` ### v4.1.1 * `EncodeEvent` returns error ### v4.1.0 diff --git a/vendor/github.com/txix-open/etp/v4/keeper.go b/vendor/github.com/txix-open/etp/v4/keeper.go index c1a4a41..333e1bd 100644 --- a/vendor/github.com/txix-open/etp/v4/keeper.go +++ b/vendor/github.com/txix-open/etp/v4/keeper.go @@ -38,7 +38,7 @@ func (k *keeper) readAndHandleMessage(ctx context.Context) error { event, err := k.conn.codec.UnmarshalEvent(data) if err != nil { - k.mux.onError(k.conn, err) + k.mux.handleError(k.conn, err) return nil } @@ -60,7 +60,7 @@ func (k *keeper) readAndHandleMessage(ctx context.Context) error { } err := k.conn.emit(ctx, message) if err != nil { - k.mux.onError(k.conn, err) + k.mux.handleError(k.conn, err) } }() diff --git a/vendor/github.com/txix-open/etp/v4/store/store.go b/vendor/github.com/txix-open/etp/v4/store/store.go index d0b41ca..fe25915 100644 --- a/vendor/github.com/txix-open/etp/v4/store/store.go +++ b/vendor/github.com/txix-open/etp/v4/store/store.go @@ -36,6 +36,14 @@ func (s *Store) Get(key string) any { return s.data[key] } +// Delete removes a value by key. +func (s *Store) Delete(key string) { + s.lock.Lock() + defer s.lock.Unlock() + + delete(s.data, key) +} + // Range iterates over all key-value pairs in the store. // The iteration stops if the function f returns false. func (s *Store) Range(f func(key string, value any) bool) { diff --git a/vendor/github.com/txix-open/isp-kit/app/app.go b/vendor/github.com/txix-open/isp-kit/app/app.go index b1394be..2058dbc 100644 --- a/vendor/github.com/txix-open/isp-kit/app/app.go +++ b/vendor/github.com/txix-open/isp-kit/app/app.go @@ -36,8 +36,8 @@ package app import ( "context" - "github.com/pkg/errors" "github.com/txix-open/isp-kit/config" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/log" ) diff --git a/vendor/github.com/txix-open/isp-kit/bgjobx/client.go b/vendor/github.com/txix-open/isp-kit/bgjobx/client.go index 05b71b6..605a6df 100644 --- a/vendor/github.com/txix-open/isp-kit/bgjobx/client.go +++ b/vendor/github.com/txix-open/isp-kit/bgjobx/client.go @@ -4,9 +4,9 @@ import ( "context" "sync" - "github.com/pkg/errors" "github.com/txix-open/bgjob" "github.com/txix-open/isp-kit/dbx" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/metrics" "github.com/txix-open/isp-kit/metrics/bgjob_metrics" diff --git a/vendor/github.com/txix-open/isp-kit/bgjobx/handler/result.go b/vendor/github.com/txix-open/isp-kit/bgjobx/handler/result.go index bc97e78..ef5a5d2 100644 --- a/vendor/github.com/txix-open/isp-kit/bgjobx/handler/result.go +++ b/vendor/github.com/txix-open/isp-kit/bgjobx/handler/result.go @@ -3,8 +3,8 @@ package handler import ( "time" - "github.com/pkg/errors" "github.com/robfig/cron/v3" + "github.com/txix-open/isp-kit/errors" ) // Result defines the outcome of job processing. diff --git a/vendor/github.com/txix-open/isp-kit/bootstrap/README.md b/vendor/github.com/txix-open/isp-kit/bootstrap/README.md index 064f3de..355872c 100644 --- a/vendor/github.com/txix-open/isp-kit/bootstrap/README.md +++ b/vendor/github.com/txix-open/isp-kit/bootstrap/README.md @@ -17,13 +17,13 @@ Обработать критические ошибки с уведомлением в Sentry -#### `New(moduleVersion string, remoteConfig any, endpoints []cluster.EndpointDescriptor, transport string) *Bootstrap` +#### `New(moduleVersion string, remoteConfig any, endpointsResolver cluster.EndpointsResolver, transport string) *Bootstrap` Конструктор с параметрами: - `moduleVersion` - версия модуля - `remoteConfig` - структура для динамической конфигурации -- `endpoints` - список эндпоинтов модуля, для транспорта `http` у каждого `endpoint`'а должен быть указан `HttpMethod` +- `endpointsResolver` - резолвер эндпоинтов модуля; используйте `cluster.Endpoints(...)` для статического списка или реализуйте интерфейс `cluster.EndpointsResolver` для динамического; для транспорта `http` у каждого `endpoint`'а должен быть указан `HttpMethod` - `transport` - тип сервера, `grpc`, `http` или `empty` #### `NewStandalone(moduleVersion string) *StandaloneBootstrap` @@ -82,7 +82,7 @@ type remoteConfig struct { func noopHandler() {} func main() { - endpoints := []cluster.EndpointDescriptor{{ + endpointsResolver := cluster.Endpoints([]cluster.EndpointDescriptor{{ Path: "/api/service/private", Inner: true, Handler: noopHandler, @@ -90,8 +90,8 @@ func main() { Path: "/api/service/public", Inner: false, Handler: noopHandler, - }} - boot := bootstrap.New("1.0.0", remoteConfig{}, endpoints, cluster.GrpcTransport) + }}) + boot := bootstrap.New("1.0.0", remoteConfig{}, endpointsResolver, cluster.GrpcTransport) shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */ log.Println("shutting down...") diff --git a/vendor/github.com/txix-open/isp-kit/bootstrap/base_bootstrap.go b/vendor/github.com/txix-open/isp-kit/bootstrap/base_bootstrap.go index eb63498..07bb996 100644 --- a/vendor/github.com/txix-open/isp-kit/bootstrap/base_bootstrap.go +++ b/vendor/github.com/txix-open/isp-kit/bootstrap/base_bootstrap.go @@ -8,9 +8,9 @@ import ( "strconv" "time" - "github.com/pkg/errors" "github.com/txix-open/isp-kit/app" "github.com/txix-open/isp-kit/config" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/healthcheck" "github.com/txix-open/isp-kit/infra" "github.com/txix-open/isp-kit/infra/pprof" diff --git a/vendor/github.com/txix-open/isp-kit/bootstrap/bootstrap.go b/vendor/github.com/txix-open/isp-kit/bootstrap/bootstrap.go index 0bdd1b0..57b86e0 100644 --- a/vendor/github.com/txix-open/isp-kit/bootstrap/bootstrap.go +++ b/vendor/github.com/txix-open/isp-kit/bootstrap/bootstrap.go @@ -11,7 +11,7 @@ // boot := bootstrap.New( // "1.0.0", // module version // &RemoteConfig{}, // remote config struct -// []cluster.EndpointDescriptor{}, // service endpoints +// cluster.Endpoints([]cluster.EndpointDescriptor{}), // service endpoints // cluster.HttpTransport, // transport type // ) // @@ -50,9 +50,9 @@ import ( "os" "strconv" - "github.com/pkg/errors" "github.com/txix-open/isp-kit/app" "github.com/txix-open/isp-kit/cluster" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/observability/sentry" @@ -88,7 +88,7 @@ type Bootstrap struct { // Parameters: // - moduleVersion: Version string of the module (e.g., "1.0.0") // - remoteConfig: Pointer to a struct defining the remote configuration schema -// - endpoints: List of service endpoint descriptors for cluster discovery +// - endpointsResolver: Resolver providing service endpoint descriptors for cluster discovery // - transport: Transport type (e.g., cluster.HttpTransport or cluster.GrpcTransport) // // Returns a fully initialized Bootstrap instance with: @@ -107,15 +107,15 @@ type Bootstrap struct { // boot := bootstrap.New( // "1.2.3", // &MyRemoteConfig{}, -// []cluster.EndpointDescriptor{ +// cluster.Endpoints([]cluster.EndpointDescriptor{ // {Path: "/api/v1", HttpMethod: "GET"}, -// }, +// }), // cluster.HttpTransport, // ) func New( moduleVersion string, remoteConfig any, - endpoints []cluster.EndpointDescriptor, + endpointsResolver cluster.EndpointsResolver, transport string, ) *Bootstrap { isDev := isOnDevMode() @@ -124,8 +124,8 @@ func New( stdlog.Fatal(err) } - if transport == cluster.HttpTransport { - for _, endpoint := range endpoints { + if transport == cluster.HttpTransport && endpointsResolver != nil { + for _, endpoint := range endpointsResolver.Endpoints() { if endpoint.HttpMethod == "" { app.Logger().Fatal( app.Context(), @@ -178,7 +178,7 @@ func New( transport, remoteConfig, moduleVersion, - endpoints, + endpointsResolver, ) if err != nil { err = errors.WithMessage(err, "create bootstrap") @@ -196,7 +196,7 @@ func newClustered( transport string, remoteConfig any, moduleVersion string, - endpoints []cluster.EndpointDescriptor, + endpointsResolver cluster.EndpointsResolver, ) (*Bootstrap, error) { broadcastHost, err := resolveBroadcastHost(localConfig) if err != nil { @@ -223,7 +223,7 @@ func newClustered( moduleVersion, transport, broadcastHost, - endpoints, + endpointsResolver, wrappedLogger, ) if err != nil { @@ -294,7 +294,7 @@ func initClusterClient( moduleVersion string, transport string, broadcastHost string, - endpoints []cluster.EndpointDescriptor, + endpointsResolver cluster.EndpointsResolver, logger log.Logger, ) (*cluster.Client, error) { moduleInfo := cluster.ModuleInfo{ @@ -306,7 +306,7 @@ func initClusterClient( IP: broadcastHost, Port: strconv.Itoa(localConfig.GrpcOuterAddress.Port), }, - Endpoints: endpoints, + EndpointsResolver: endpointsResolver, MetricsAutodiscovery: metricsServiceDiscovery(localConfig, broadcastHost), } diff --git a/vendor/github.com/txix-open/isp-kit/bootstrap/standalone.go b/vendor/github.com/txix-open/isp-kit/bootstrap/standalone.go index b50c17c..40ab308 100644 --- a/vendor/github.com/txix-open/isp-kit/bootstrap/standalone.go +++ b/vendor/github.com/txix-open/isp-kit/bootstrap/standalone.go @@ -4,7 +4,7 @@ import ( stdlog "log" "os" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/observability/sentry" diff --git a/vendor/github.com/txix-open/isp-kit/bootstrap/utils.go b/vendor/github.com/txix-open/isp-kit/bootstrap/utils.go index bab1273..076385a 100644 --- a/vendor/github.com/txix-open/isp-kit/bootstrap/utils.go +++ b/vendor/github.com/txix-open/isp-kit/bootstrap/utils.go @@ -7,8 +7,8 @@ import ( "runtime/debug" "strings" - "github.com/pkg/errors" "github.com/txix-open/isp-kit/config" + "github.com/txix-open/isp-kit/errors" ) func isOnDevMode() bool { diff --git a/vendor/github.com/txix-open/isp-kit/cluster/README.md b/vendor/github.com/txix-open/isp-kit/cluster/README.md index a9fde89..7854774 100644 --- a/vendor/github.com/txix-open/isp-kit/cluster/README.md +++ b/vendor/github.com/txix-open/isp-kit/cluster/README.md @@ -103,11 +103,11 @@ func main() { moduleInfo := cluster.ModuleInfo{ ModuleName: "noop-service", Version: "1.0.0", - Endpoints: []cluster.EndpointDescriptor{{ + EndpointsResolver: cluster.Endpoints([]cluster.EndpointDescriptor{{ Path: "/api/foo", Inner: false, Handler: noopHandler, - }}, + }}), } defaultRemoteConfig := []byte{...} configData := cluster.ConfigData{ diff --git a/vendor/github.com/txix-open/isp-kit/cluster/client.go b/vendor/github.com/txix-open/isp-kit/cluster/client.go index 2401a42..9c542d9 100644 --- a/vendor/github.com/txix-open/isp-kit/cluster/client.go +++ b/vendor/github.com/txix-open/isp-kit/cluster/client.go @@ -23,8 +23,8 @@ import ( "sync/atomic" "time" - "github.com/pkg/errors" "github.com/txix-open/etp/v4" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/lb" "github.com/txix-open/isp-kit/log" @@ -135,6 +135,29 @@ func (c *Client) Close() error { return nil } +// SendModuleReady sends a ModuleReady event to the isp-config-service, +// announcing the module's availability and its dependencies. +func (c *Client) SendModuleReady(ctx context.Context) error { + cli := c.cli.Load() + if cli == nil { + return errors.New("client not connected") + } + if c.eventHandler == nil { + return errors.New("event handler not initialized") + } + + requiredModules := make([]string, 0, len(c.eventHandler.requiredModules)) + for moduleName := range c.eventHandler.requiredModules { + requiredModules = append(requiredModules, moduleName) + } + requirements := ModuleRequirements{ + RequiredModules: requiredModules, + RequireRoutes: c.eventHandler.routesReceiver != nil, + } + + return c.notifyModuleReady(ctx, cli, requirements) +} + // Healthcheck returns an error if the session is inactive, otherwise returns nil. func (c *Client) Healthcheck(ctx context.Context) error { if c.sessionIsActive.Load() { @@ -310,11 +333,17 @@ func (c *Client) notifyModuleReady(ctx context.Context, cli *clientWrapper, requ } moduleDependencies = append(moduleDependencies, dep) } + + endpoints := make([]EndpointDescriptor, 0) + if c.moduleInfo.EndpointsResolver != nil { + endpoints = c.moduleInfo.EndpointsResolver.Endpoints() + } + declaration := BackendDeclaration{ ModuleName: c.moduleInfo.ModuleName, Version: c.moduleInfo.ModuleVersion, LibVersion: c.moduleInfo.LibVersion, - Endpoints: c.moduleInfo.Endpoints, + Endpoints: endpoints, Transport: c.moduleInfo.Transport, RequiredModules: moduleDependencies, Address: c.moduleInfo.GrpcOuterAddress, diff --git a/vendor/github.com/txix-open/isp-kit/cluster/domain.go b/vendor/github.com/txix-open/isp-kit/cluster/domain.go index 1eefdc7..2b592c3 100644 --- a/vendor/github.com/txix-open/isp-kit/cluster/domain.go +++ b/vendor/github.com/txix-open/isp-kit/cluster/domain.go @@ -27,14 +27,14 @@ type ConfigData struct { } // ModuleInfo describes a module's metadata, including its name, version, transport -// configuration, exposed endpoints, and metrics autodiscovery settings. +// configuration, endpoint resolver, and metrics autodiscovery settings. type ModuleInfo struct { ModuleName string ModuleVersion string LibVersion string Transport string GrpcOuterAddress AddressConfiguration - Endpoints []EndpointDescriptor + EndpointsResolver EndpointsResolver MetricsAutodiscovery *MetricsAutodiscovery } diff --git a/vendor/github.com/txix-open/isp-kit/cluster/endpoint_descriptors.go b/vendor/github.com/txix-open/isp-kit/cluster/endpoint_descriptors.go new file mode 100644 index 0000000..5e5ac2e --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/cluster/endpoint_descriptors.go @@ -0,0 +1,32 @@ +package cluster + +// EndpointsResolver provides the list of endpoints for a module. +// Implement this interface when endpoints must be resolved dynamically at runtime. +// Use the Endpoints helper for static endpoint lists. +type EndpointsResolver interface { + Endpoints() []EndpointDescriptor +} + +// StaticEndpointResolver wraps a fixed slice of EndpointDescriptors. +// It implements EndpointsResolver for cases where the endpoint list is known at startup +// and does not change. +type StaticEndpointResolver []EndpointDescriptor + +// Endpoints returns the underlying slice of EndpointDescriptors. +func (s StaticEndpointResolver) Endpoints() []EndpointDescriptor { + return s +} + +// Endpoints wraps a slice of EndpointDescriptors into a StaticEndpointResolver. +// Use this helper when constructing ModuleInfo or calling bootstrap.New with a known +// set of endpoints: +// +// bootstrap.New( +// "1.0.0", +// &config{}, +// cluster.Endpoints([]cluster.EndpointDescriptor{{Path: "/api", HttpMethod: "GET"}}), +// cluster.HttpTransport, +// ) +func Endpoints(arr []EndpointDescriptor) StaticEndpointResolver { + return StaticEndpointResolver(arr) +} diff --git a/vendor/github.com/txix-open/isp-kit/cluster/hide_secret.go b/vendor/github.com/txix-open/isp-kit/cluster/hide_secret.go index f5aec25..c0c5e0c 100644 --- a/vendor/github.com/txix-open/isp-kit/cluster/hide_secret.go +++ b/vendor/github.com/txix-open/isp-kit/cluster/hide_secret.go @@ -3,8 +3,8 @@ package cluster import ( "strings" - "github.com/pkg/errors" "github.com/txix-open/bellows" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/json" ) diff --git a/vendor/github.com/txix-open/isp-kit/cluster/offline_client.go b/vendor/github.com/txix-open/isp-kit/cluster/offline_client.go index d6ad1b5..710aa3d 100644 --- a/vendor/github.com/txix-open/isp-kit/cluster/offline_client.go +++ b/vendor/github.com/txix-open/isp-kit/cluster/offline_client.go @@ -4,7 +4,7 @@ import ( "context" "os" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" ) // OfflineClient provides configuration loading from a local file instead of a remote diff --git a/vendor/github.com/txix-open/isp-kit/cluster/wrapper.go b/vendor/github.com/txix-open/isp-kit/cluster/wrapper.go index e3429d8..737028e 100644 --- a/vendor/github.com/txix-open/isp-kit/cluster/wrapper.go +++ b/vendor/github.com/txix-open/isp-kit/cluster/wrapper.go @@ -5,9 +5,9 @@ import ( "sync" "time" - "github.com/pkg/errors" "github.com/txix-open/etp/v4" "github.com/txix-open/etp/v4/msg" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/requestid" diff --git a/vendor/github.com/txix-open/isp-kit/config/config.go b/vendor/github.com/txix-open/isp-kit/config/config.go index a44fdc5..a81c434 100644 --- a/vendor/github.com/txix-open/isp-kit/config/config.go +++ b/vendor/github.com/txix-open/isp-kit/config/config.go @@ -36,8 +36,8 @@ import ( "strings" "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" "github.com/txix-open/bellows" + "github.com/txix-open/isp-kit/errors" ) // Validator defines an interface for validating configuration values. diff --git a/vendor/github.com/txix-open/isp-kit/config/yaml_config.go b/vendor/github.com/txix-open/isp-kit/config/yaml_config.go index aa931de..0de9e82 100644 --- a/vendor/github.com/txix-open/isp-kit/config/yaml_config.go +++ b/vendor/github.com/txix-open/isp-kit/config/yaml_config.go @@ -4,8 +4,8 @@ import ( "fmt" "os" - "github.com/pkg/errors" "github.com/txix-open/bellows" + "github.com/txix-open/isp-kit/errors" "gopkg.in/yaml.v3" ) diff --git a/vendor/github.com/txix-open/isp-kit/db/db.go b/vendor/github.com/txix-open/isp-kit/db/db.go index 1043488..6d48c25 100644 --- a/vendor/github.com/txix-open/isp-kit/db/db.go +++ b/vendor/github.com/txix-open/isp-kit/db/db.go @@ -10,7 +10,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/stdlib" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/metrics/sql_metrics" ) diff --git a/vendor/github.com/txix-open/isp-kit/dbrx/client.go b/vendor/github.com/txix-open/isp-kit/dbrx/client.go index aefa2ba..d331767 100644 --- a/vendor/github.com/txix-open/isp-kit/dbrx/client.go +++ b/vendor/github.com/txix-open/isp-kit/dbrx/client.go @@ -13,9 +13,9 @@ import ( "github.com/txix-open/isp-kit/log" - "github.com/pkg/errors" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/dbx" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/metrics" "github.com/txix-open/isp-kit/metrics/pgx_metrics" "github.com/txix-open/isp-kit/metrics/sql_metrics" diff --git a/vendor/github.com/txix-open/isp-kit/dbx/db.go b/vendor/github.com/txix-open/isp-kit/dbx/db.go index bf6a557..c9be953 100644 --- a/vendor/github.com/txix-open/isp-kit/dbx/db.go +++ b/vendor/github.com/txix-open/isp-kit/dbx/db.go @@ -11,9 +11,9 @@ import ( "time" "github.com/jackc/pgx/v5" - "github.com/pkg/errors" "github.com/pressly/goose/v3" "github.com/txix-open/isp-kit/db" + "github.com/txix-open/isp-kit/errors" ) // nolint:gochecknoglobals diff --git a/vendor/github.com/txix-open/isp-kit/dbx/migration/runner.go b/vendor/github.com/txix-open/isp-kit/dbx/migration/runner.go index 5244382..96cdcab 100644 --- a/vendor/github.com/txix-open/isp-kit/dbx/migration/runner.go +++ b/vendor/github.com/txix-open/isp-kit/dbx/migration/runner.go @@ -12,8 +12,8 @@ import ( "strings" "time" - "github.com/pkg/errors" "github.com/pressly/goose/v3" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/log" ) diff --git a/vendor/github.com/txix-open/isp-kit/errors/README.md b/vendor/github.com/txix-open/isp-kit/errors/README.md new file mode 100644 index 0000000..ee0106f --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/errors/README.md @@ -0,0 +1,65 @@ +# Package `errors` + +Пакет `errors` предоставляет функции для создания, оборачивания и проверки ошибок, используя стандартные пакеты Go +`errors` и `fmt`. + +Пакет заменяет привычные вызовы из `github.com/pkg/errors`. + +## Functions + +#### `New(text string) error` + +Создает новую ошибку с переданным текстом. + +#### `Errorf(format string, args ...any) error` + +Создает новую ошибку с форматированием. Если формат содержит `%w`, ошибка будет обернута стандартным механизмом Go. + +#### `WithMessage(err error, message string) error` + +Добавляет сообщение к ошибке через стандартное оборачивание `%w`. + +#### `WithMessagef(err error, format string, args ...any) error` + +Добавляет форматированное сообщение к ошибке через стандартное оборачивание `%w`. + +#### `Is(err, target error) bool` + +Проверяет, содержит ли цепочка ошибок `target`. + +#### `As(err error, target any) bool` + +Находит в цепочке ошибок ошибку подходящего типа и записывает ее в `target`. + +#### `AsType[E error](err error) (E, bool)` + +Generic-версия `As`, возвращающая найденную ошибку и признак успешного поиска. + +#### `Unwrap(err error) error` + +Возвращает ошибку, обернутую внутри `err`. + +#### `Join(errs ...error) error` + +Объединяет несколько ошибок в одну. + +## Usage + +```go +package main + +import ( + "database/sql" + + "github.com/txix-open/isp-kit/errors" +) + +func getUser(userId string) error { + err := sql.ErrNoRows + if err != nil { + return errors.WithMessagef(err, "get user %s", userId) + } + + return nil +} +``` diff --git a/vendor/github.com/txix-open/isp-kit/errors/errors.go b/vendor/github.com/txix-open/isp-kit/errors/errors.go new file mode 100644 index 0000000..4a1d41b --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/errors/errors.go @@ -0,0 +1,56 @@ +// Package errors provides helpers for creating, wrapping, and inspecting errors +// using the standard library errors and fmt packages. +package errors + +import ( + stderrors "errors" + "fmt" +) + +// ErrUnsupported indicates that an operation is not supported. +var ErrUnsupported = stderrors.ErrUnsupported + +// New returns an error with the supplied text. +func New(text string) error { + return stderrors.New(text) //nolint:err113 +} + +// Errorf formats according to a format specifier and returns an error. +func Errorf(format string, args ...any) error { + return fmt.Errorf(format, args...) //nolint:err113 +} + +// WithMessage wraps err with message using standard error wrapping. +func WithMessage(err error, message string) error { + return Errorf("%s: %w", message, err) +} + +// WithMessagef wraps err with a formatted message using standard error wrapping. +func WithMessagef(err error, format string, args ...any) error { + return Errorf("%s: %w", fmt.Sprintf(format, args...), err) +} + +// Is reports whether err's tree contains target. +func Is(err, target error) bool { + return stderrors.Is(err, target) +} + +// As finds the first error in err's tree that matches target. +func As(err error, target any) bool { + return stderrors.As(err, target) +} + +// AsType finds the first error in err's tree that matches E. +func AsType[E error](err error) (E, bool) { + return stderrors.AsType[E](err) +} + +// Unwrap returns the result of calling err's Unwrap method. +func Unwrap(err error) error { + return stderrors.Unwrap(err) +} + +// Join returns an error that wraps the given errors. +func Join(errs ...error) error { + return stderrors.Join(errs...) +} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/apierrors/error.go b/vendor/github.com/txix-open/isp-kit/grpc/apierrors/error.go index 8b61e7c..5bfafe2 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/apierrors/error.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/apierrors/error.go @@ -9,7 +9,7 @@ package apierrors import ( "fmt" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc/isp" "github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/log" diff --git a/vendor/github.com/txix-open/isp-kit/grpc/auth_data.go b/vendor/github.com/txix-open/isp-kit/grpc/auth_data.go index 73f1c79..ed868be 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/auth_data.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/auth_data.go @@ -3,7 +3,7 @@ package grpc import ( "strconv" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "google.golang.org/grpc/metadata" ) diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/client.go b/vendor/github.com/txix-open/isp-kit/grpc/client/client.go index 521fa48..2dc9498 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/client.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/client/client.go @@ -10,8 +10,8 @@ import ( "strings" "sync/atomic" - "github.com/pkg/errors" "github.com/txix-open/isp-kit/codec" + "github.com/txix-open/isp-kit/errors" grpc2 "github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/grpc/client/request" "github.com/txix-open/isp-kit/grpc/isp" diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/request/builder.go b/vendor/github.com/txix-open/isp-kit/grpc/client/request/builder.go index 06b8b83..014b097 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/request/builder.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/client/request/builder.go @@ -7,7 +7,7 @@ import ( "strconv" "time" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/grpc/isp" "github.com/txix-open/isp-kit/json" diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/caller.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/caller.go index a0f5439..066c1ba 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/caller.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/caller.go @@ -4,7 +4,7 @@ import ( "context" "reflect" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc/isp" ) diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_request.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_request.go index f3f2124..b635e3e 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_request.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_request.go @@ -5,7 +5,7 @@ import ( "reflect" "unicode" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc/apierrors" "github.com/txix-open/isp-kit/grpc/isp" "github.com/txix-open/isp-kit/json" diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_response.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_response.go index 5acecec..86a0703 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_response.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_response.go @@ -1,7 +1,7 @@ package endpoint import ( - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc/isp" "github.com/txix-open/isp-kit/json" ) diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/middlewares.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/middlewares.go index 9b09fdc..c0d4ab9 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/middlewares.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/middlewares.go @@ -5,8 +5,8 @@ import ( "strings" "github.com/getsentry/sentry-go" - "github.com/pkg/errors" "github.com/txix-open/isp-kit/codec" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/grpc/isp" "github.com/txix-open/isp-kit/log" diff --git a/vendor/github.com/txix-open/isp-kit/grpc/mux.go b/vendor/github.com/txix-open/isp-kit/grpc/mux.go index d69ce72..213b23b 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/mux.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/mux.go @@ -3,7 +3,7 @@ package grpc import ( "context" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc/isp" "github.com/txix-open/isp-kit/log" "google.golang.org/grpc/codes" diff --git a/vendor/github.com/txix-open/isp-kit/grpc/server.go b/vendor/github.com/txix-open/isp-kit/grpc/server.go index 02fe93d..39d4340 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/server.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/server.go @@ -11,7 +11,7 @@ import ( "net" "sync/atomic" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc/isp" "google.golang.org/grpc" ) diff --git a/vendor/github.com/txix-open/isp-kit/http/httpclix/client_balancer.go b/vendor/github.com/txix-open/isp-kit/http/httpclix/client_balancer.go index 947f383..d4840b0 100644 --- a/vendor/github.com/txix-open/isp-kit/http/httpclix/client_balancer.go +++ b/vendor/github.com/txix-open/isp-kit/http/httpclix/client_balancer.go @@ -5,7 +5,7 @@ import ( "net/http" "strings" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/lb" ) diff --git a/vendor/github.com/txix-open/isp-kit/infra/server.go b/vendor/github.com/txix-open/isp-kit/infra/server.go index 49ce119..8cae91e 100644 --- a/vendor/github.com/txix-open/isp-kit/infra/server.go +++ b/vendor/github.com/txix-open/isp-kit/infra/server.go @@ -7,7 +7,7 @@ import ( "net/http" "time" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" ) // Server is a wrapper around http.Server that simplifies HTTP server setup diff --git a/vendor/github.com/txix-open/isp-kit/log/file/file_output.go b/vendor/github.com/txix-open/isp-kit/log/file/file_output.go index 1ec25ac..44a9ee7 100644 --- a/vendor/github.com/txix-open/isp-kit/log/file/file_output.go +++ b/vendor/github.com/txix-open/isp-kit/log/file/file_output.go @@ -6,7 +6,7 @@ import ( "net/url" "strconv" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "go.uber.org/zap" "gopkg.in/natefinch/lumberjack.v2" ) diff --git a/vendor/github.com/txix-open/isp-kit/log/logger.go b/vendor/github.com/txix-open/isp-kit/log/logger.go index 89c9b1e..e2faa50 100644 --- a/vendor/github.com/txix-open/isp-kit/log/logger.go +++ b/vendor/github.com/txix-open/isp-kit/log/logger.go @@ -5,7 +5,7 @@ import ( "fmt" "log" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) diff --git a/vendor/github.com/txix-open/isp-kit/metrics/registry.go b/vendor/github.com/txix-open/isp-kit/metrics/registry.go index f612b0b..8bedca8 100644 --- a/vendor/github.com/txix-open/isp-kit/metrics/registry.go +++ b/vendor/github.com/txix-open/isp-kit/metrics/registry.go @@ -17,11 +17,11 @@ import ( "sync" "time" - "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/collectors" "github.com/prometheus/client_golang/prometheus/promhttp" io_prometheus_client "github.com/prometheus/client_model/go" + "github.com/txix-open/isp-kit/errors" ) const ( diff --git a/vendor/github.com/txix-open/isp-kit/observability/sentry/hub.go b/vendor/github.com/txix-open/isp-kit/observability/sentry/hub.go index 3dce86f..2f6302a 100644 --- a/vendor/github.com/txix-open/isp-kit/observability/sentry/hub.go +++ b/vendor/github.com/txix-open/isp-kit/observability/sentry/hub.go @@ -36,7 +36,7 @@ import ( "time" "github.com/getsentry/sentry-go" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/requestid" ) diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/provider.go b/vendor/github.com/txix-open/isp-kit/observability/tracing/provider.go index cc22e82..88ce6e6 100644 --- a/vendor/github.com/txix-open/isp-kit/observability/tracing/provider.go +++ b/vendor/github.com/txix-open/isp-kit/observability/tracing/provider.go @@ -4,7 +4,7 @@ import ( "context" "github.com/go-logr/stdr" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/log" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/sql_tracing/tracer.go b/vendor/github.com/txix-open/isp-kit/observability/tracing/sql_tracing/tracer.go index 7f542b0..15bbb4f 100644 --- a/vendor/github.com/txix-open/isp-kit/observability/tracing/sql_tracing/tracer.go +++ b/vendor/github.com/txix-open/isp-kit/observability/tracing/sql_tracing/tracer.go @@ -7,7 +7,7 @@ import ( "strings" "github.com/jackc/pgx/v5" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/metrics/sql_metrics" "github.com/txix-open/isp-kit/observability/tracing" "github.com/txix-open/isp-kit/requestid" diff --git a/vendor/github.com/txix-open/isp-kit/panic_recovery/README.md b/vendor/github.com/txix-open/isp-kit/panic_recovery/README.md index 59d135c..ed9583f 100644 --- a/vendor/github.com/txix-open/isp-kit/panic_recovery/README.md +++ b/vendor/github.com/txix-open/isp-kit/panic_recovery/README.md @@ -20,7 +20,7 @@ package main import ( "fmt" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/panic_recovery" ) @@ -38,4 +38,3 @@ func testPanic() { return } ``` - diff --git a/vendor/github.com/txix-open/isp-kit/panic_recovery/recover.go b/vendor/github.com/txix-open/isp-kit/panic_recovery/recover.go index df04e7e..38a58f8 100644 --- a/vendor/github.com/txix-open/isp-kit/panic_recovery/recover.go +++ b/vendor/github.com/txix-open/isp-kit/panic_recovery/recover.go @@ -9,7 +9,7 @@ package panic_recovery import ( "runtime" - "github.com/pkg/errors" + "github.com/txix-open/isp-kit/errors" ) const ( diff --git a/vendor/github.com/txix-open/isp-kit/rc/config.go b/vendor/github.com/txix-open/isp-kit/rc/config.go index a8c4e4a..98f07ec 100644 --- a/vendor/github.com/txix-open/isp-kit/rc/config.go +++ b/vendor/github.com/txix-open/isp-kit/rc/config.go @@ -7,8 +7,8 @@ import ( "maps" "sync" - "github.com/pkg/errors" "github.com/txix-open/bellows" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/json" ) diff --git a/vendor/github.com/txix-open/isp-kit/test/dbt/test_db.go b/vendor/github.com/txix-open/isp-kit/test/dbt/test_db.go index db8dec6..972d7c0 100644 --- a/vendor/github.com/txix-open/isp-kit/test/dbt/test_db.go +++ b/vendor/github.com/txix-open/isp-kit/test/dbt/test_db.go @@ -10,10 +10,10 @@ import ( "runtime" "time" - "github.com/pkg/errors" "github.com/stretchr/testify/require" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/dbx" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/test" ) @@ -81,7 +81,10 @@ func (db *TestDb) Close() error { return errors.WithMessage(err, "drop schema") } err = db.Client.Close() - return errors.WithMessage(err, "close db") + if err != nil { + return errors.WithMessage(err, "close db") + } + return nil } // must provides database operations that automatically assert no errors. diff --git a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go index 304f647..cef3580 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go @@ -194,7 +194,7 @@ type AnyValue_StringValueStrindex struct { // Profiling signal and process the data as if this value were absent or // empty, ignoring its semantic content for the non-Profiling signal. // - // Status: [Development] + // Status: [Alpha] StringValueStrindex int32 `protobuf:"varint,8,opt,name=string_value_strindex,json=stringValueStrindex,proto3,oneof"` } @@ -330,7 +330,7 @@ type KeyValue struct { unknownFields protoimpl.UnknownFields // The key name of the pair. - // key_ref MUST NOT be set if key is used. + // key_strindex MUST NOT be set if key is used. Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // The value of the pair. Value *AnyValue `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` @@ -344,7 +344,7 @@ type KeyValue struct { // Profiling signal and process the data as if this value were absent or // empty, ignoring its semantic content for the non-Profiling signal. // - // Status: [Development] + // Status: [Alpha] KeyStrindex int32 `protobuf:"varint,3,opt,name=key_strindex,json=keyStrindex,proto3" json:"key_strindex,omitempty"` } diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index c4bca52..b27c7e8 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -24,12 +24,10 @@ import ( "fmt" "math" "net/url" - "os" "slices" "strings" "sync" "sync/atomic" - "syscall" "time" "google.golang.org/grpc/balancer" @@ -1573,26 +1571,13 @@ func (ac *addrConn) createTransport(ctx context.Context, addr resolver.Address, // to the provided transport.GoAwayInfo, as specified by gRFC A94: // https://github.com/grpc/proposal/blob/master/A94-grpc-subchannel-disconnections-metrics.md func disconnectErrorString(info transport.GoAwayInfo) string { - err := info.Err - var sysErr syscall.Errno - switch { - case info.Reason != transport.GoAwayInvalid: + if info.Reason != transport.GoAwayInvalid { return fmt.Sprintf("GOAWAY %s", info.GoAwayCode.String()) - case err == nil: - return "unknown" - case errors.Is(err, context.Canceled): - return "subchannel shutdown" - case errors.Is(err, syscall.ECONNRESET): - return "connection reset" - case errors.Is(err, syscall.ETIMEDOUT), errors.Is(err, context.DeadlineExceeded), errors.Is(err, os.ErrDeadlineExceeded): - return "connection timed out" - case errors.Is(err, syscall.ECONNABORTED): - return "connection aborted" - case errors.As(err, &sysErr): - return "socket error" - default: + } + if info.Err == nil { return "unknown" } + return disconnectErrorLabel(info.Err) } // startHealthCheck starts the health checking stream (RPC) to watch the health diff --git a/vendor/google.golang.org/grpc/clientconn_disconnect_reason_noplan9.go b/vendor/google.golang.org/grpc/clientconn_disconnect_reason_noplan9.go new file mode 100644 index 0000000..f0fcd88 --- /dev/null +++ b/vendor/google.golang.org/grpc/clientconn_disconnect_reason_noplan9.go @@ -0,0 +1,48 @@ +//go:build !plan9 + +/* + * + * Copyright 2026 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpc + +import ( + "context" + "errors" + "os" + "syscall" +) + +// disconnectErrorLabel returns the grpc.disconnect_error metric label for a +// transport error, as specified by gRFC A94. +func disconnectErrorLabel(err error) string { + var sysErr syscall.Errno + switch { + case errors.Is(err, context.Canceled): + return "subchannel shutdown" + case errors.Is(err, syscall.ECONNRESET): + return "connection reset" + case errors.Is(err, syscall.ETIMEDOUT), errors.Is(err, context.DeadlineExceeded), errors.Is(err, os.ErrDeadlineExceeded): + return "connection timed out" + case errors.Is(err, syscall.ECONNABORTED): + return "connection aborted" + case errors.As(err, &sysErr): + return "socket error" + default: + return "unknown" + } +} diff --git a/vendor/google.golang.org/grpc/clientconn_disconnect_reason_plan9.go b/vendor/google.golang.org/grpc/clientconn_disconnect_reason_plan9.go new file mode 100644 index 0000000..930b126 --- /dev/null +++ b/vendor/google.golang.org/grpc/clientconn_disconnect_reason_plan9.go @@ -0,0 +1,39 @@ +/* + * + * Copyright 2026 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpc + +import ( + "context" + "errors" + "os" +) + +// disconnectErrorLabel returns the grpc.disconnect_error metric label for a +// transport error, as specified by gRFC A94. syscall.Errno does not exist on +// plan9, so only the portable classifications are available. +func disconnectErrorLabel(err error) string { + switch { + case errors.Is(err, context.Canceled): + return "subchannel shutdown" + case errors.Is(err, context.DeadlineExceeded), errors.Is(err, os.ErrDeadlineExceeded): + return "connection timed out" + default: + return "unknown" + } +} diff --git a/vendor/google.golang.org/grpc/internal/envconfig/xds.go b/vendor/google.golang.org/grpc/internal/envconfig/xds.go index a2312f8..e4b6919 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/xds.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/xds.go @@ -69,9 +69,8 @@ var ( // https://github.com/grpc/proposal/blob/master/A87-mtls-spiffe-support.md XDSSPIFFEEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_MTLS_SPIFFE", false) - // XDSHTTPConnectEnabled is true if gRPC should parse custom Metadata - // configuring use of an HTTP CONNECT proxy via xDS from cluster resources. - // For more details, see: + // XDSHTTPConnectEnabled controls support for dynamic HTTP CONNECT proxying + // configured via the xDS control plane. For more details, see: // https://github.com/grpc/proposal/blob/master/A86-xds-http-connect.md XDSHTTPConnectEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_HTTP_CONNECT", false) @@ -88,7 +87,7 @@ var ( // XDSORCAToLRSPropEnabled controls whether ORCA metrics are explicitly // filtered and prefix-propagated to the LRS server. For more details, see: // https://github.com/grpc/proposal/blob/master/A85-lrs-custom-metrics-changes.md - XDSORCAToLRSPropEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_ORCA_LRS_PROPAGATION", false) + XDSORCAToLRSPropEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_ORCA_LRS_PROPAGATION", true) // XDSClientExtProcEnabled indicates whether ExtProc filter is enabled on // the client side. For more details, see: diff --git a/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go b/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go index 9b6d8a1..d4999fc 100644 --- a/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go +++ b/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go @@ -20,10 +20,15 @@ package grpcsync import ( "context" + "errors" "google.golang.org/grpc/internal/buffer" ) +// ErrSerializerClosed is returned by ScheduleAndWait if the CallbackSerializer +// was closed before the callback could be scheduled. +var ErrSerializerClosed = errors.New("callback serializer is closed") + // CallbackSerializer provides a mechanism to schedule callbacks in a // synchronized manner. It provides a FIFO guarantee on the order of execution // of scheduled callbacks. New callbacks can be scheduled by invoking the @@ -77,6 +82,27 @@ func (cs *CallbackSerializer) ScheduleOr(f func(ctx context.Context), onFailure } } +// ScheduleAndWait schedules the provided callback function f to be executed in +// the order it was added and blocks until f has run. If the context passed to +// NewCallbackSerializer was canceled before this method is called, f is not run +// and ScheduleAndWait returns ErrSerializerClosed. +// +// Callbacks are expected to honor the context when performing any blocking +// operations, and should return early when the context is canceled. +func (cs *CallbackSerializer) ScheduleAndWait(f func(ctx context.Context)) error { + done := make(chan struct{}) + var err error + cs.ScheduleOr(func(ctx context.Context) { + f(ctx) + close(done) + }, func() { + err = ErrSerializerClosed + close(done) + }) + <-done + return err +} + func (cs *CallbackSerializer) run(ctx context.Context) { defer close(cs.done) diff --git a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go index 6320e9b..238950b 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go +++ b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go @@ -24,7 +24,6 @@ import ( "sync" "google.golang.org/grpc/internal/serviceconfig" - "google.golang.org/grpc/metadata" "google.golang.org/grpc/resolver" ) @@ -52,82 +51,7 @@ type RPCConfig struct { Context context.Context MethodConfig serviceconfig.MethodConfig // configuration to use for this RPC OnCommitted func() // Called when the RPC has been committed (retries no longer possible) - Interceptor ClientInterceptor -} - -// ClientStream is the same as grpc.ClientStream, but defined here for circular -// dependency reasons. -type ClientStream interface { - // Header returns the header metadata received from the server if there - // is any. It blocks if the metadata is not ready to read. - Header() (metadata.MD, error) - // Trailer returns the trailer metadata from the server, if there is any. - // It must only be called after stream.CloseAndRecv has returned, or - // stream.Recv has returned a non-nil error (including io.EOF). - Trailer() metadata.MD - // CloseSend closes the send direction of the stream. It closes the stream - // when non-nil error is met. It is also not safe to call CloseSend - // concurrently with SendMsg. - CloseSend() error - // Context returns the context for this stream. - // - // It should not be called until after Header or RecvMsg has returned. Once - // called, subsequent client-side retries are disabled. - Context() context.Context - // SendMsg is generally called by generated code. On error, SendMsg aborts - // the stream. If the error was generated by the client, the status is - // returned directly; otherwise, io.EOF is returned and the status of - // the stream may be discovered using RecvMsg. - // - // SendMsg blocks until: - // - There is sufficient flow control to schedule m with the transport, or - // - The stream is done, or - // - The stream breaks. - // - // SendMsg does not wait until the message is received by the server. An - // untimely stream closure may result in lost messages. To ensure delivery, - // users should ensure the RPC completed successfully using RecvMsg. - // - // It is safe to have a goroutine calling SendMsg and another goroutine - // calling RecvMsg on the same stream at the same time, but it is not safe - // to call SendMsg on the same stream in different goroutines. It is also - // not safe to call CloseSend concurrently with SendMsg. - SendMsg(m any) error - // RecvMsg blocks until it receives a message into m or the stream is - // done. It returns io.EOF when the stream completes successfully. On - // any other error, the stream is aborted and the error contains the RPC - // status. - // - // It is safe to have a goroutine calling SendMsg and another goroutine - // calling RecvMsg on the same stream at the same time, but it is not - // safe to call RecvMsg on the same stream in different goroutines. - RecvMsg(m any) error -} - -// ClientInterceptor is an interceptor for gRPC client streams. -type ClientInterceptor interface { - // NewStream creates a ClientStream for an RPC. - // - // Implementations must delegate stream creation to the provided newStream - // function. To intercept or override stream behavior, implementations - // may wrap the ClientStream returned by the delegate. - // - // Note: RPCInfo.Context is currently unused and will be nil. - // - // The done function is invoked when the RPC has finished using its - // underlying connection or if a connection could not be assigned. Because - // interceptors operate at the application layer, RPC operations may - // continue on the ClientStream even after done has been called. The - // caller must ensure done is non-nil. - // - // To ensure RPC completion notifications propagate through the entire - // interceptor chain, implementations must ensure that the done function - // passed to the delegate newStream invokes the done function passed to - // NewStream. - NewStream(ctx context.Context, ri RPCInfo, done func(), newStream func(ctx context.Context, done func()) (ClientStream, error)) (ClientStream, error) - // Close closes the interceptor. Once called, no new calls to NewStream are - // accepted. Ongoing calls to NewStream are allowed to complete. - Close() + Interceptor any } // ServerInterceptor is an interceptor for incoming RPC's on gRPC server side. diff --git a/vendor/google.golang.org/grpc/internal/transport/client_stream.go b/vendor/google.golang.org/grpc/internal/transport/client_stream.go index ad382b0..046f0a5 100644 --- a/vendor/google.golang.org/grpc/internal/transport/client_stream.go +++ b/vendor/google.golang.org/grpc/internal/transport/client_stream.go @@ -39,9 +39,8 @@ const nonGRPCDataMaxLen = 1024 type ClientStream struct { Stream // Embed for common stream functionality. - ct *http2Client - done chan struct{} // closed at the end of stream to unblock writers. - doneFunc func() // invoked at the end of stream. + ct *http2Client + done chan struct{} // closed at the end of stream to unblock writers. headerChan chan struct{} // closed to indicate the end of header metadata. header metadata.MD // the received header metadata diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/vendor/google.golang.org/grpc/internal/transport/http2_client.go index 822c09b..c19b450 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -498,7 +498,6 @@ func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr, handler s ct: t, done: make(chan struct{}), headerChan: make(chan struct{}), - doneFunc: callHdr.DoneFunc, statsHandler: handler, } s.Stream.buf.init() @@ -998,9 +997,6 @@ func (t *http2Client) closeStream(s *ClientStream, err error, rst bool, rstCode t.controlBuf.executeAndPut(addBackStreamQuota, cleanup) // This will unblock write. close(s.done) - if s.doneFunc != nil { - s.doneFunc() - } } // Close kicks off the shutdown process of the transport. This should be called diff --git a/vendor/google.golang.org/grpc/internal/transport/transport.go b/vendor/google.golang.org/grpc/internal/transport/transport.go index 6dfae39..d2e4953 100644 --- a/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -594,8 +594,6 @@ type CallHdr struct { PreviousAttempts int // value of grpc-previous-rpc-attempts header to set - DoneFunc func() // called when the stream is finished - // Authority is used to explicitly override the `:authority` header. // // This value comes from one of two sources: diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index 4aac644..51aff85 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -201,6 +201,15 @@ func endOfClientStream(cc *ClientConn, err error, opts ...CallOption) { } } +// clientInterceptor is structurally identical to the ClientInterceptor defined +// in internal/xds/httpfilter/httpfilter.go. It is defined locally here so that +// we can type-assert the generic Interceptor field in iresolver.RPCConfig +// without introducing a dependency on xDS packages. +type clientInterceptor interface { + NewStream(ctx context.Context, ri iresolver.RPCInfo, newStream func(ctx context.Context, opts ...CallOption) (ClientStream, error), opts ...CallOption) (ClientStream, error) + Close() +} + func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { if channelz.IsOn() { cc.incrCallsStarted() @@ -244,8 +253,11 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth mc := &emptyMethodConfig var onCommit func() - newStream := func(ctx context.Context, done func()) (iresolver.ClientStream, error) { - return newClientStreamWithParams(ctx, desc, cc, method, mc, onCommit, done, nameResolutionDelayed, opts...) + newStream := func(ctx context.Context, filterOpts ...CallOption) (ClientStream, error) { + if filterOpts != nil { + opts = combine(opts, filterOpts) + } + return newClientStreamWithParams(ctx, desc, cc, method, mc, onCommit, nameResolutionDelayed, opts...) } rpcInfo := iresolver.RPCInfo{Context: ctx, Method: method} @@ -270,20 +282,24 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth if rpcConfig.Interceptor != nil { rpcInfo.Context = nil ns := newStream - newStream = func(ctx context.Context, done func()) (iresolver.ClientStream, error) { - cs, err := rpcConfig.Interceptor.NewStream(ctx, rpcInfo, done, ns) - if err != nil { - return nil, toRPCErr(err) + if interceptor, ok := rpcConfig.Interceptor.(clientInterceptor); ok { + newStream = func(ctx context.Context, filterOpts ...CallOption) (ClientStream, error) { + cs, err := interceptor.NewStream(ctx, rpcInfo, ns, filterOpts...) + if err != nil { + return nil, toRPCErr(err) + } + return cs, nil } - return cs, nil + } else { + return nil, status.Errorf(codes.Internal, "invalid client interceptor type %T", rpcConfig.Interceptor) } } } - return newStream(ctx, func() {}) + return newStream(ctx) } -func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, mc *serviceconfig.MethodConfig, onCommit, doneFunc func(), nameResolutionDelayed bool, opts ...CallOption) (_ iresolver.ClientStream, err error) { +func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, mc *serviceconfig.MethodConfig, onCommit func(), nameResolutionDelayed bool, opts ...CallOption) (_ ClientStream, err error) { callInfo := defaultCallInfo() if mc.WaitForReady != nil { callInfo.failFast = !*mc.WaitForReady @@ -321,7 +337,6 @@ func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *Client Host: cc.authority, Method: method, ContentSubtype: callInfo.contentSubtype, - DoneFunc: doneFunc, Authority: callInfo.authority, } if allowed := callInfo.acceptedResponseCompressors; len(allowed) > 0 { diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go index 53c737f..4083c03 100644 --- a/vendor/google.golang.org/grpc/version.go +++ b/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.82.1" +const Version = "1.83.0" diff --git a/vendor/modules.txt b/vendor/modules.txt index 80d7132..698c525 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -7,7 +7,7 @@ github.com/bahlo/generic-list-go # github.com/beorn7/perks v1.0.1 ## explicit; go 1.11 github.com/beorn7/perks/quantile -# github.com/buger/jsonparser v1.2.0 +# github.com/buger/jsonparser v1.6.0 ## explicit; go 1.13 github.com/buger/jsonparser # github.com/cenkalti/backoff/v5 v5.0.3 @@ -26,22 +26,25 @@ github.com/coder/websocket/internal/wsjs # github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc ## explicit github.com/davecgh/go-spew/spew -# github.com/gabriel-vasile/mimetype v1.4.13 +# github.com/gabriel-vasile/mimetype v1.4.15 ## explicit; go 1.21 github.com/gabriel-vasile/mimetype +github.com/gabriel-vasile/mimetype/internal/cdf github.com/gabriel-vasile/mimetype/internal/charset github.com/gabriel-vasile/mimetype/internal/csv github.com/gabriel-vasile/mimetype/internal/json github.com/gabriel-vasile/mimetype/internal/magic github.com/gabriel-vasile/mimetype/internal/markup +github.com/gabriel-vasile/mimetype/internal/mp3 github.com/gabriel-vasile/mimetype/internal/scan -# github.com/getsentry/sentry-go v0.47.0 +# github.com/getsentry/sentry-go v0.48.0 ## explicit; go 1.25.0 github.com/getsentry/sentry-go github.com/getsentry/sentry-go/attribute github.com/getsentry/sentry-go/internal/debug github.com/getsentry/sentry-go/internal/debuglog github.com/getsentry/sentry-go/internal/http +github.com/getsentry/sentry-go/internal/httputils github.com/getsentry/sentry-go/internal/otel/baggage github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage github.com/getsentry/sentry-go/internal/protocol @@ -49,14 +52,14 @@ github.com/getsentry/sentry-go/internal/ratelimit github.com/getsentry/sentry-go/internal/telemetry github.com/getsentry/sentry-go/internal/util github.com/getsentry/sentry-go/report -# github.com/go-faker/faker/v4 v4.9.0 -## explicit; go 1.24.0 +# github.com/go-faker/faker/v4 v4.10.1 +## explicit; go 1.26.0 github.com/go-faker/faker/v4 github.com/go-faker/faker/v4/pkg/errors github.com/go-faker/faker/v4/pkg/interfaces github.com/go-faker/faker/v4/pkg/options github.com/go-faker/faker/v4/pkg/slice -# github.com/go-logr/logr v1.4.3 +# github.com/go-logr/logr v1.4.4 ## explicit; go 1.18 github.com/go-logr/logr github.com/go-logr/logr/funcr @@ -113,7 +116,7 @@ github.com/jmoiron/sqlx/reflectx # github.com/json-iterator/go v1.1.12 ## explicit; go 1.12 github.com/json-iterator/go -# github.com/klauspost/compress v1.19.0 +# github.com/klauspost/compress v1.19.1 ## explicit; go 1.24 github.com/klauspost/compress github.com/klauspost/compress/fse @@ -129,8 +132,8 @@ github.com/lann/builder # github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 ## explicit github.com/lann/ps -# github.com/leodido/go-urn v1.4.0 -## explicit; go 1.18 +# github.com/leodido/go-urn v1.5.0 +## explicit; go 1.24.0 github.com/leodido/go-urn github.com/leodido/go-urn/scim/schema # github.com/mailru/easyjson v0.9.2 @@ -158,7 +161,7 @@ github.com/pkg/errors # github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 ## explicit github.com/pmezard/go-difflib/difflib -# github.com/pressly/goose/v3 v3.27.2 +# github.com/pressly/goose/v3 v3.27.3 ## explicit; go 1.25.7 github.com/pressly/goose/v3 github.com/pressly/goose/v3/database @@ -171,8 +174,8 @@ github.com/pressly/goose/v3/internal/sqlparser github.com/pressly/goose/v3/lock github.com/pressly/goose/v3/lock/internal/store github.com/pressly/goose/v3/lock/internal/table -# github.com/prometheus/client_golang v1.23.2 -## explicit; go 1.23.0 +# github.com/prometheus/client_golang v1.24.1 +## explicit; go 1.25.0 github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header github.com/prometheus/client_golang/prometheus @@ -183,7 +186,7 @@ github.com/prometheus/client_golang/prometheus/promhttp/internal # github.com/prometheus/client_model v0.6.2 ## explicit; go 1.22.0 github.com/prometheus/client_model/go -# github.com/prometheus/common v0.69.0 +# github.com/prometheus/common v0.70.1 ## explicit; go 1.25.0 github.com/prometheus/common/expfmt github.com/prometheus/common/model @@ -195,8 +198,8 @@ github.com/prometheus/procfs/internal/util # github.com/robfig/cron/v3 v3.0.1 ## explicit; go 1.12 github.com/robfig/cron/v3 -# github.com/sethvargo/go-retry v0.3.0 -## explicit; go 1.21 +# github.com/sethvargo/go-retry v0.4.0 +## explicit; go 1.25 github.com/sethvargo/go-retry # github.com/stretchr/testify v1.11.1 ## explicit; go 1.17 @@ -210,15 +213,15 @@ github.com/txix-open/bellows # github.com/txix-open/bgjob v1.6.0 ## explicit; go 1.24 github.com/txix-open/bgjob -# github.com/txix-open/etp/v4 v4.1.1 +# github.com/txix-open/etp/v4 v4.1.3 ## explicit; go 1.26 github.com/txix-open/etp/v4 github.com/txix-open/etp/v4/bpool github.com/txix-open/etp/v4/internal github.com/txix-open/etp/v4/msg github.com/txix-open/etp/v4/store -# github.com/txix-open/isp-kit v1.71.2 -## explicit; go 1.26 +# github.com/txix-open/isp-kit v1.74.0 +## explicit; go 1.26.0 github.com/txix-open/isp-kit/app github.com/txix-open/isp-kit/bgjobx github.com/txix-open/isp-kit/bgjobx/handler @@ -232,6 +235,7 @@ github.com/txix-open/isp-kit/db/query github.com/txix-open/isp-kit/dbrx github.com/txix-open/isp-kit/dbx github.com/txix-open/isp-kit/dbx/migration +github.com/txix-open/isp-kit/errors github.com/txix-open/isp-kit/grpc github.com/txix-open/isp-kit/grpc/apierrors github.com/txix-open/isp-kit/grpc/client @@ -353,8 +357,8 @@ go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded go.opentelemetry.io/otel/trace/internal/telemetry go.opentelemetry.io/otel/trace/noop -# go.opentelemetry.io/proto/otlp v1.10.0 -## explicit; go 1.24.0 +# go.opentelemetry.io/proto/otlp v1.11.0 +## explicit; go 1.25.0 go.opentelemetry.io/proto/otlp/collector/trace/v1 go.opentelemetry.io/proto/otlp/common/v1 go.opentelemetry.io/proto/otlp/resource/v1 @@ -414,13 +418,13 @@ golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm golang.org/x/text/width -# google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 +# google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 ## explicit; go 1.25.0 google.golang.org/genproto/googleapis/api/httpbody -# google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df +# google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 ## explicit; go 1.25.0 google.golang.org/genproto/googleapis/rpc/status -# google.golang.org/grpc v1.82.1 +# google.golang.org/grpc v1.83.0 ## explicit; go 1.25.0 google.golang.org/grpc google.golang.org/grpc/attributes