From aab8ee1f183047f285d057fab2c988d387956330 Mon Sep 17 00:00:00 2001 From: directduck Date: Wed, 29 Oct 2025 15:42:32 +0300 Subject: [PATCH] Update appkit & zenrpc --- .github/workflows/golangci-lint.yml | 2 +- Makefile | 2 +- go.mod | 38 +- go.sum | 76 +- pkg/app/app.go | 2 +- pkg/app/handlers.go | 5 +- pkg/app/vfs.go | 4 +- pkg/db/logger.go | 4 +- pkg/rpc/server.go | 2 +- pkg/vt/server.go | 2 +- pkg/vt/vt_zenrpc.go | 2 +- .../mimetype/CODE_OF_CONDUCT.md | 76 - .../gabriel-vasile/mimetype/CONTRIBUTING.md | 12 - .../gabriel-vasile/mimetype/README.md | 35 +- .../mimetype/internal/charset/charset.go | 230 +- .../mimetype/internal/csv/parser.go | 125 + .../mimetype/internal/json/parser.go | 30 +- .../mimetype/internal/magic/document.go | 47 +- .../mimetype/internal/magic/magic.go | 81 +- .../mimetype/internal/magic/ms_office.go | 31 +- .../mimetype/internal/magic/netpbm.go | 111 + .../mimetype/internal/magic/text.go | 146 +- .../mimetype/internal/magic/text_csv.go | 80 +- .../mimetype/internal/magic/zip.go | 186 +- .../mimetype/internal/markup/markup.go | 103 + .../mimetype/internal/scan/bytes.go | 213 ++ .../gabriel-vasile/mimetype/mime.go | 26 +- .../mimetype/supported_mimes.md | 22 +- .../gabriel-vasile/mimetype/tree.go | 62 +- .../getsentry/sentry-go/CHANGELOG.md | 58 + .../github.com/getsentry/sentry-go/Makefile | 2 +- .../getsentry/sentry-go/batch_logger.go | 3 +- .../github.com/getsentry/sentry-go/client.go | 67 +- vendor/github.com/getsentry/sentry-go/dsn.go | 218 +- .../sentry-go/dynamic_sampling_context.go | 4 +- .../getsentry/sentry-go/exception.go | 132 + vendor/github.com/getsentry/sentry-go/hub.go | 16 +- .../getsentry/sentry-go/integrations.go | 8 +- .../getsentry/sentry-go/interfaces.go | 138 +- .../sentry-go/internal/debuglog/log.go | 35 + .../sentry-go/internal/http/transport.go | 571 ++++ .../sentry-go/internal/protocol/dsn.go | 236 ++ .../sentry-go/internal/protocol/envelope.go | 213 ++ .../sentry-go/internal/protocol/interfaces.go | 40 + .../sentry-go/internal/protocol/types.go | 15 + .../sentry-go/internal/ratelimit/category.go | 44 + vendor/github.com/getsentry/sentry-go/log.go | 29 +- .../getsentry/sentry-go/log_fallback.go | 7 +- .../github.com/getsentry/sentry-go/scope.go | 4 +- .../github.com/getsentry/sentry-go/sentry.go | 2 +- .../getsentry/sentry-go/span_recorder.go | 4 +- .../github.com/getsentry/sentry-go/tracing.go | 76 +- .../getsentry/sentry-go/transport.go | 114 +- vendor/github.com/getsentry/sentry-go/util.go | 13 +- .../go-playground/validator/v10/README.md | 7 +- .../go-playground/validator/v10/baked_in.go | 39 + .../go-playground/validator/v10/doc.go | 13 + .../go-playground/validator/v10/regexes.go | 2 + .../validator/v10/validator_instance.go | 60 +- .../prometheus/common/expfmt/decode.go | 14 +- .../common/expfmt/openmetrics_create.go | 59 +- .../prometheus/common/expfmt/text_create.go | 58 +- .../prometheus/common/expfmt/text_parse.go | 102 +- .../prometheus/procfs/.golangci.yml | 28 +- vendor/github.com/prometheus/procfs/Makefile | 2 +- .../prometheus/procfs/Makefile.common | 2 +- vendor/github.com/prometheus/procfs/arp.go | 9 +- .../github.com/prometheus/procfs/buddyinfo.go | 10 +- .../github.com/prometheus/procfs/cmdline.go | 2 +- .../github.com/prometheus/procfs/cpuinfo.go | 2 +- .../prometheus/procfs/cpuinfo_armx.go | 2 +- .../prometheus/procfs/cpuinfo_loong64.go | 2 +- .../prometheus/procfs/cpuinfo_mipsx.go | 2 +- .../prometheus/procfs/cpuinfo_others.go | 2 +- .../prometheus/procfs/cpuinfo_ppcx.go | 2 +- .../prometheus/procfs/cpuinfo_riscvx.go | 2 +- .../prometheus/procfs/cpuinfo_s390x.go | 2 +- .../prometheus/procfs/cpuinfo_x86.go | 2 +- vendor/github.com/prometheus/procfs/crypto.go | 2 +- vendor/github.com/prometheus/procfs/doc.go | 2 +- vendor/github.com/prometheus/procfs/fs.go | 2 +- .../prometheus/procfs/fs_statfs_notype.go | 2 +- .../prometheus/procfs/fs_statfs_type.go | 2 +- .../github.com/prometheus/procfs/fscache.go | 9 +- .../prometheus/procfs/internal/fs/fs.go | 2 +- .../prometheus/procfs/internal/util/parse.go | 2 +- .../procfs/internal/util/readfile.go | 2 +- .../procfs/internal/util/sysreadfile.go | 2 +- .../internal/util/sysreadfile_compat.go | 2 +- .../procfs/internal/util/valueparser.go | 2 +- vendor/github.com/prometheus/procfs/ipvs.go | 2 +- .../prometheus/procfs/kernel_hung.go | 45 + .../prometheus/procfs/kernel_random.go | 2 +- .../github.com/prometheus/procfs/loadavg.go | 2 +- vendor/github.com/prometheus/procfs/mdstat.go | 118 +- .../github.com/prometheus/procfs/meminfo.go | 4 +- .../github.com/prometheus/procfs/mountinfo.go | 23 +- .../prometheus/procfs/mountstats.go | 4 +- .../prometheus/procfs/net_conntrackstat.go | 2 +- .../github.com/prometheus/procfs/net_dev.go | 2 +- .../prometheus/procfs/net_dev_snmp6.go | 7 +- .../prometheus/procfs/net_ip_socket.go | 2 +- .../prometheus/procfs/net_protocols.go | 4 +- .../github.com/prometheus/procfs/net_route.go | 2 +- .../prometheus/procfs/net_sockstat.go | 5 +- .../prometheus/procfs/net_softnet.go | 2 +- .../github.com/prometheus/procfs/net_tcp.go | 2 +- .../prometheus/procfs/net_tls_stat.go | 2 +- .../github.com/prometheus/procfs/net_udp.go | 2 +- .../github.com/prometheus/procfs/net_unix.go | 2 +- .../prometheus/procfs/net_wireless.go | 2 +- .../github.com/prometheus/procfs/net_xfrm.go | 2 +- .../github.com/prometheus/procfs/netstat.go | 2 +- .../prometheus/procfs/nfnetlink_queue.go | 85 + vendor/github.com/prometheus/procfs/proc.go | 4 +- .../prometheus/procfs/proc_cgroup.go | 2 +- .../prometheus/procfs/proc_cgroups.go | 8 +- .../prometheus/procfs/proc_environ.go | 2 +- .../prometheus/procfs/proc_fdinfo.go | 13 +- .../prometheus/procfs/proc_interrupts.go | 2 +- .../github.com/prometheus/procfs/proc_io.go | 2 +- .../prometheus/procfs/proc_limits.go | 7 +- .../github.com/prometheus/procfs/proc_maps.go | 2 +- .../prometheus/procfs/proc_netstat.go | 2 +- .../github.com/prometheus/procfs/proc_ns.go | 2 +- .../github.com/prometheus/procfs/proc_psi.go | 2 +- .../prometheus/procfs/proc_smaps.go | 2 +- .../github.com/prometheus/procfs/proc_snmp.go | 2 +- .../prometheus/procfs/proc_snmp6.go | 2 +- .../github.com/prometheus/procfs/proc_stat.go | 2 +- .../prometheus/procfs/proc_statm.go | 4 +- .../prometheus/procfs/proc_status.go | 9 +- .../github.com/prometheus/procfs/proc_sys.go | 2 +- .../github.com/prometheus/procfs/schedstat.go | 2 +- vendor/github.com/prometheus/procfs/slab.go | 2 +- .../github.com/prometheus/procfs/softirqs.go | 2 +- vendor/github.com/prometheus/procfs/stat.go | 5 +- vendor/github.com/prometheus/procfs/swaps.go | 2 +- vendor/github.com/prometheus/procfs/thread.go | 2 +- vendor/github.com/prometheus/procfs/vm.go | 2 +- .../github.com/prometheus/procfs/zoneinfo.go | 8 +- vendor/github.com/vmkteam/appkit/Makefile | 5 +- vendor/github.com/vmkteam/appkit/README.md | 81 +- vendor/github.com/vmkteam/appkit/appkit.go | 2 + vendor/github.com/vmkteam/appkit/client.go | 132 + vendor/github.com/vmkteam/appkit/echo.go | 3 +- .../{zenrpc-middleware => appkit}/handler.go | 29 +- vendor/github.com/vmkteam/appkit/metadata.go | 3 + .../github.com/vmkteam/appkit/middleware.go | 155 ++ .../github.com/vmkteam/appkit/xrequestid.go | 38 + vendor/github.com/vmkteam/rpcgen/v2/README.md | 45 + .../github.com/vmkteam/rpcgen/v2/gen/gen.go | 2 +- .../github.com/vmkteam/rpcgen/v2/generator.go | 5 + .../vmkteam/rpcgen/v2/golang/go_template.go | 28 +- .../vmkteam/rpcgen/v2/kotlin/kotlin_client.go | 493 ++++ .../rpcgen/v2/kotlin/kotlin_template.go | 84 + .../rpcgen/v2/typescript/typescript_client.go | 5 + .../v2/typescript/typescript_template.go | 24 + vendor/github.com/vmkteam/vfs/README.md | 38 + vendor/github.com/vmkteam/vfs/db/logger.go | 6 + .../vmkteam/zenrpc-middleware/Makefile | 20 + .../vmkteam/zenrpc-middleware/README.md | 50 - .../vmkteam/zenrpc-middleware/logger.go | 23 +- .../vmkteam/zenrpc-middleware/metrics.go | 3 +- .../vmkteam/zenrpc-middleware/middleware.go | 103 +- .../vmkteam/zenrpc-middleware/sentry.go | 103 +- .../vmkteam/zenrpc-middleware/sql_logger.go | 42 +- .../vmkteam/zenrpc-middleware/xrequestid.go | 27 +- .../vmkteam/zenrpc/v2/.golangci.yml | 487 +++- .../github.com/vmkteam/zenrpc/v2/MAINTAINERS | 4 - vendor/github.com/vmkteam/zenrpc/v2/Makefile | 9 +- vendor/github.com/vmkteam/zenrpc/v2/README.md | 1 - .../github.com/vmkteam/zenrpc/v2/handlers.go | 87 +- .../github.com/vmkteam/zenrpc/v2/jsonrpc2.go | 61 +- .../vmkteam/zenrpc/v2/middleware.go | 24 +- .../vmkteam/zenrpc/v2/parser/helpers.go | 4 +- .../vmkteam/zenrpc/v2/parser/parser.go | 32 +- .../vmkteam/zenrpc/v2/parser/struct.go | 14 +- vendor/github.com/vmkteam/zenrpc/v2/server.go | 65 +- .../github.com/vmkteam/zenrpc/v2/smd/model.go | 2 +- .../vmkteam/zenrpc/v2/zenrpc/main.go | 97 +- .../vmkteam/zenrpc/v2/zenrpc/template.go | 4 +- vendor/golang.org/x/net/html/atom/atom.go | 78 - vendor/golang.org/x/net/html/atom/table.go | 785 ------ vendor/golang.org/x/net/html/const.go | 111 - vendor/golang.org/x/net/html/doc.go | 122 - vendor/golang.org/x/net/html/doctype.go | 156 -- vendor/golang.org/x/net/html/entity.go | 2253 --------------- vendor/golang.org/x/net/html/escape.go | 339 --- vendor/golang.org/x/net/html/foreign.go | 221 -- vendor/golang.org/x/net/html/iter.go | 56 - vendor/golang.org/x/net/html/node.go | 229 -- vendor/golang.org/x/net/html/parse.go | 2464 ----------------- vendor/golang.org/x/net/html/render.go | 293 -- vendor/golang.org/x/net/html/token.go | 1286 --------- vendor/golang.org/x/net/http2/config.go | 17 +- vendor/golang.org/x/net/http2/config_go125.go | 15 + vendor/golang.org/x/net/http2/config_go126.go | 15 + vendor/golang.org/x/net/http2/frame.go | 25 +- vendor/golang.org/x/net/http2/http2.go | 1 - vendor/golang.org/x/net/http2/server.go | 61 +- vendor/golang.org/x/net/http2/transport.go | 6 +- vendor/golang.org/x/net/http2/writesched.go | 2 + ...rity.go => writesched_priority_rfc7540.go} | 104 +- .../net/http2/writesched_priority_rfc9128.go | 209 ++ .../x/net/http2/writesched_roundrobin.go | 2 +- .../x/net/internal/httpcommon/request.go | 4 +- .../golang.org/x/sys/unix/affinity_linux.go | 9 + vendor/golang.org/x/sys/unix/fdset.go | 4 +- vendor/golang.org/x/sys/unix/ifreq_linux.go | 4 +- vendor/golang.org/x/sys/unix/mkall.sh | 1 + vendor/golang.org/x/sys/unix/syscall_linux.go | 4 +- .../golang.org/x/sys/unix/syscall_netbsd.go | 17 + .../x/sys/windows/syscall_windows.go | 2 + .../golang.org/x/sys/windows/types_windows.go | 16 + .../x/sys/windows/zsyscall_windows.go | 18 + vendor/golang.org/x/text/unicode/bidi/core.go | 11 +- vendor/golang.org/x/time/rate/rate.go | 2 +- vendor/golang.org/x/time/rate/sometimes.go | 4 +- vendor/golang.org/x/tools/go/ast/edge/edge.go | 295 ++ .../x/tools/go/ast/inspector/cursor.go | 502 ++++ .../x/tools/go/ast/inspector/inspector.go | 311 +++ .../x/tools/go/ast/inspector/iter.go | 85 + .../x/tools/go/ast/inspector/typeof.go | 227 ++ .../x/tools/go/ast/inspector/walk.go | 341 +++ .../golang.org/x/tools/go/packages/golist.go | 6 - .../golang.org/x/tools/go/packages/visit.go | 85 +- .../x/tools/go/types/objectpath/objectpath.go | 5 +- .../x/tools/go/types/typeutil/map.go | 19 +- .../x/tools/internal/event/core/event.go | 5 - .../x/tools/internal/gcimporter/iexport.go | 1 - .../internal/gcimporter/iimport_go122.go | 53 - .../x/tools/internal/stdlib/deps.go | 596 ++-- .../x/tools/internal/stdlib/manifest.go | 58 +- .../x/tools/internal/typesinternal/fx.go | 49 + .../x/tools/internal/typesinternal/isnamed.go | 71 + .../tools/internal/typesinternal/qualifier.go | 8 + .../x/tools/internal/typesinternal/types.go | 48 +- .../tools/internal/typesinternal/zerovalue.go | 17 +- .../protobuf/internal/filedesc/desc.go | 52 +- .../protobuf/internal/filedesc/desc_init.go | 14 + .../protobuf/internal/filedesc/desc_lazy.go | 20 + .../protobuf/internal/version/version.go | 2 +- vendor/modules.txt | 69 +- 244 files changed, 8404 insertions(+), 10602 deletions(-) delete mode 100644 vendor/github.com/gabriel-vasile/mimetype/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/gabriel-vasile/mimetype/CONTRIBUTING.md create mode 100644 vendor/github.com/gabriel-vasile/mimetype/internal/csv/parser.go create mode 100644 vendor/github.com/gabriel-vasile/mimetype/internal/magic/netpbm.go create mode 100644 vendor/github.com/gabriel-vasile/mimetype/internal/markup/markup.go create mode 100644 vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go create mode 100644 vendor/github.com/getsentry/sentry-go/exception.go create mode 100644 vendor/github.com/getsentry/sentry-go/internal/debuglog/log.go create mode 100644 vendor/github.com/getsentry/sentry-go/internal/http/transport.go create mode 100644 vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go create mode 100644 vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go create mode 100644 vendor/github.com/getsentry/sentry-go/internal/protocol/interfaces.go create mode 100644 vendor/github.com/getsentry/sentry-go/internal/protocol/types.go create mode 100644 vendor/github.com/prometheus/procfs/kernel_hung.go create mode 100644 vendor/github.com/prometheus/procfs/nfnetlink_queue.go create mode 100644 vendor/github.com/vmkteam/appkit/client.go rename vendor/github.com/vmkteam/{zenrpc-middleware => appkit}/handler.go (68%) create mode 100644 vendor/github.com/vmkteam/appkit/middleware.go create mode 100644 vendor/github.com/vmkteam/appkit/xrequestid.go create mode 100644 vendor/github.com/vmkteam/rpcgen/v2/kotlin/kotlin_client.go create mode 100644 vendor/github.com/vmkteam/rpcgen/v2/kotlin/kotlin_template.go create mode 100644 vendor/github.com/vmkteam/zenrpc-middleware/Makefile delete mode 100644 vendor/github.com/vmkteam/zenrpc/v2/MAINTAINERS delete mode 100644 vendor/golang.org/x/net/html/atom/atom.go delete mode 100644 vendor/golang.org/x/net/html/atom/table.go delete mode 100644 vendor/golang.org/x/net/html/const.go delete mode 100644 vendor/golang.org/x/net/html/doc.go delete mode 100644 vendor/golang.org/x/net/html/doctype.go delete mode 100644 vendor/golang.org/x/net/html/entity.go delete mode 100644 vendor/golang.org/x/net/html/escape.go delete mode 100644 vendor/golang.org/x/net/html/foreign.go delete mode 100644 vendor/golang.org/x/net/html/iter.go delete mode 100644 vendor/golang.org/x/net/html/node.go delete mode 100644 vendor/golang.org/x/net/html/parse.go delete mode 100644 vendor/golang.org/x/net/html/render.go delete mode 100644 vendor/golang.org/x/net/html/token.go create mode 100644 vendor/golang.org/x/net/http2/config_go125.go create mode 100644 vendor/golang.org/x/net/http2/config_go126.go rename vendor/golang.org/x/net/http2/{writesched_priority.go => writesched_priority_rfc7540.go} (78%) create mode 100644 vendor/golang.org/x/net/http2/writesched_priority_rfc9128.go create mode 100644 vendor/golang.org/x/tools/go/ast/edge/edge.go create mode 100644 vendor/golang.org/x/tools/go/ast/inspector/cursor.go create mode 100644 vendor/golang.org/x/tools/go/ast/inspector/inspector.go create mode 100644 vendor/golang.org/x/tools/go/ast/inspector/iter.go create mode 100644 vendor/golang.org/x/tools/go/ast/inspector/typeof.go create mode 100644 vendor/golang.org/x/tools/go/ast/inspector/walk.go delete mode 100644 vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go create mode 100644 vendor/golang.org/x/tools/internal/typesinternal/fx.go create mode 100644 vendor/golang.org/x/tools/internal/typesinternal/isnamed.go diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 631b26d..73aea3c 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -23,4 +23,4 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@v7 with: - version: v2.4.0 + version: v2.5.0 diff --git a/Makefile b/Makefile index 99cc306..8c712a9 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ ifeq ($(RACE),1) GOFLAGS+=-race endif -LINT_VERSION := v2.4.0 +LINT_VERSION := v2.5.0 MAIN := ${NAME}/cmd/${NAME} diff --git a/go.mod b/go.mod index f524f66..aa6f99c 100644 --- a/go.mod +++ b/go.mod @@ -4,23 +4,23 @@ go 1.24.5 require ( github.com/BurntSushi/toml v1.5.0 - github.com/getsentry/sentry-go v0.35.3 + github.com/getsentry/sentry-go v0.36.2 github.com/go-pg/pg/v10 v10.15.0 github.com/go-pg/urlstruct v1.0.1 - github.com/go-playground/validator/v10 v10.27.0 + github.com/go-playground/validator/v10 v10.28.0 github.com/hypnoglow/go-pg-monitor v1.2.0 github.com/hypnoglow/go-pg-monitor/gopgv10 v1.2.0 github.com/labstack/echo/v4 v4.13.4 github.com/namsral/flag v1.7.4-pre github.com/prometheus/client_golang v1.23.2 github.com/smartystreets/goconvey v1.8.1 - github.com/vmkteam/appkit v0.0.1 + github.com/vmkteam/appkit v0.1.1 github.com/vmkteam/embedlog v0.1.3 - github.com/vmkteam/rpcgen/v2 v2.4.6 - github.com/vmkteam/vfs v1.4.0 - github.com/vmkteam/zenrpc-middleware v1.3.0 - github.com/vmkteam/zenrpc/v2 v2.2.12 - golang.org/x/crypto v0.42.0 + github.com/vmkteam/rpcgen/v2 v2.5.0 + github.com/vmkteam/vfs v1.4.1 + github.com/vmkteam/zenrpc-middleware v1.3.2 + github.com/vmkteam/zenrpc/v2 v2.3.0 + golang.org/x/crypto v0.43.0 ) require ( @@ -28,8 +28,8 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/codemodus/kace v0.5.1 // indirect - github.com/gabriel-vasile/mimetype v1.4.9 // indirect - github.com/getsentry/sentry-go/echo v0.35.3 // indirect + github.com/gabriel-vasile/mimetype v1.4.10 // indirect + github.com/getsentry/sentry-go/echo v0.36.2 // indirect github.com/go-pg/zerochecker v0.2.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect @@ -46,8 +46,8 @@ require ( github.com/mattn/go-isatty v0.0.20 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.66.1 // indirect - github.com/prometheus/procfs v0.17.0 // indirect + github.com/prometheus/common v0.67.2 // indirect + github.com/prometheus/procfs v0.19.1 // indirect github.com/smarty/assertions v1.16.0 // indirect github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect @@ -60,14 +60,14 @@ require ( github.com/vmkteam/zenrpc v1.1.1 // indirect go.uber.org/atomic v1.11.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect - golang.org/x/mod v0.27.0 // indirect - golang.org/x/net v0.44.0 // indirect + golang.org/x/mod v0.29.0 // indirect + golang.org/x/net v0.46.0 // indirect golang.org/x/sync v0.17.0 // indirect - golang.org/x/sys v0.36.0 // indirect - golang.org/x/text v0.29.0 // indirect - golang.org/x/time v0.11.0 // indirect - golang.org/x/tools v0.36.0 // indirect - google.golang.org/protobuf v1.36.9 // indirect + golang.org/x/sys v0.37.0 // indirect + golang.org/x/text v0.30.0 // indirect + golang.org/x/time v0.14.0 // indirect + golang.org/x/tools v0.38.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect mellium.im/sasl v0.3.2 // indirect ) diff --git a/go.sum b/go.sum index 931ff79..b5cebb7 100644 --- a/go.sum +++ b/go.sum @@ -31,12 +31,12 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7 github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY= -github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok= -github.com/getsentry/sentry-go v0.35.3 h1:u5IJaEqZyPdWqe/hKlBKBBnMTSxB/HenCqF3QLabeds= -github.com/getsentry/sentry-go v0.35.3/go.mod h1:mdL49ixwT2yi57k5eh7mpnDyPybixPzlzEJFu0Z76QA= -github.com/getsentry/sentry-go/echo v0.35.3 h1:aJ0e4kGuH7T1ggAd3LOYwAyQV0bq37AX36vNPr6JYnM= -github.com/getsentry/sentry-go/echo v0.35.3/go.mod h1:zQn5wNGqJUwIlA6z/pi7CFeXiUGrWkzue28C0Mfbz/Q= +github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= +github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/getsentry/sentry-go v0.36.2 h1:uhuxRPTrUy0dnSzTd0LrYXlBYygLkKY0hhlG5LXarzM= +github.com/getsentry/sentry-go v0.36.2/go.mod h1:p5Im24mJBeruET8Q4bbcMfCQ+F+Iadc4L48tB1apo2c= +github.com/getsentry/sentry-go/echo v0.36.2 h1:H7bs/dVFm9vcVDqnkfQcXQvjpf/Sa5dIQ3E5Bv9FVcY= +github.com/getsentry/sentry-go/echo v0.36.2/go.mod h1:Nz4jnPokxo2zh03bOLbVNwewsKNC0OqHWFKjvCjkKx4= 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-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= @@ -59,8 +59,8 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4= -github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo= +github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= +github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= @@ -195,15 +195,15 @@ github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y8 github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= -github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs= -github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA= +github.com/prometheus/common v0.67.2 h1:PcBAckGFTIHt2+L3I33uNRTlKTplNzFctXcWhPyAEN8= +github.com/prometheus/common v0.67.2/go.mod h1:63W3KZb1JOKgcjlIr64WW/LvFGAqKPj0atm+knVGEko= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0= -github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw= +github.com/prometheus/procfs v0.19.1 h1:QVtROpTkphuXuNlnCv3m1ut3JytkXHtQ3xvck/YmzMM= +github.com/prometheus/procfs v0.19.1/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= @@ -239,22 +239,22 @@ github.com/vmihailenco/tagparser v0.1.2 h1:gnjoVuB/kljJ5wICEEOpx98oXMWPLj22G67Vb github.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= -github.com/vmkteam/appkit v0.0.1 h1:s64Y865vFI6i4YTEQQH9D8qaknwG2beVJIRxSAvuMbM= -github.com/vmkteam/appkit v0.0.1/go.mod h1:tPMuTvTqZPf4vAj9E6BMQhBSb7j4R/YyVzqDuBpRpvw= +github.com/vmkteam/appkit v0.1.1 h1:qYPXgGGL7uzseg/LpGFibetEsfCrwxxzXIng+IHTA+8= +github.com/vmkteam/appkit v0.1.1/go.mod h1:A5adBzmHsTQt4qsWccjTaSFv7kmaiiRUZ9El/6CqIfw= github.com/vmkteam/embedlog v0.1.3 h1:A7/ut4SLRipZwfYelkNQfjH+htNvcZ4EO7uf4By+aQk= github.com/vmkteam/embedlog v0.1.3/go.mod h1:U4LGy+iNvADyjTIKgGL8FJbPBGkU2IZOmkvNfUPOam8= github.com/vmkteam/meta-schema/v2 v2.0.1 h1:7eoImKpnCs2wiCcBB8AUCtfVVhGa6L6DDqihutFlE1I= github.com/vmkteam/meta-schema/v2 v2.0.1/go.mod h1:GQzU4Rid0Q9dDIz/OeSDyL/aB/QG7tD0gOUt5nQ4JMk= -github.com/vmkteam/rpcgen/v2 v2.4.6 h1:x4GIjNsAPEVRIoItX8uE/mL/cFuYHonFRoDWoIg8oEo= -github.com/vmkteam/rpcgen/v2 v2.4.6/go.mod h1:GJ8swFJys9AUQxpJPJr1V9T3cG+RfadC7xbAEkn6ZjE= -github.com/vmkteam/vfs v1.4.0 h1:8RQOX8hrluQMw2ahsR+U2QP1PSl6hJcpihovZDunneI= -github.com/vmkteam/vfs v1.4.0/go.mod h1:Ql0fu4D0vAX/Bf4iLGMP4QClJuK+pEyQHK2oj56bS3k= +github.com/vmkteam/rpcgen/v2 v2.5.0 h1:lR2T+rty9FpyKDe+8BH53am0urczFxtEHKKTXek8tJo= +github.com/vmkteam/rpcgen/v2 v2.5.0/go.mod h1:zsYGO2z92FoCHA8pE70765X4EXWzwBtJijs+OmwMIFM= +github.com/vmkteam/vfs v1.4.1 h1:N/AxskypSJV50FD3WWLbIYt5gZA1+8TUJ31E32EPjQc= +github.com/vmkteam/vfs v1.4.1/go.mod h1:v6ZHQ1yTEulSjHNCoLMcqjCVelumHaE2GHHQeDj+nn0= github.com/vmkteam/zenrpc v1.1.1 h1:WmModRVCwgs7XEkeJcVvmDOwEtAQk0TuYV91wdpAaCw= github.com/vmkteam/zenrpc v1.1.1/go.mod h1:x3fCkb9HHOpqwqC7TKXf8pyXWdPxEt2Zrndl50YxexM= -github.com/vmkteam/zenrpc-middleware v1.3.0 h1:cOq7EZm4hfyDRH0FHpycK90pwWH3TCA/9MDw7k92aFA= -github.com/vmkteam/zenrpc-middleware v1.3.0/go.mod h1:ZYSoasDlh0fS7396hArV4d3HtZ5AWW3MGffR+KHpgtA= -github.com/vmkteam/zenrpc/v2 v2.2.12 h1:McYNxjJPqzyxaB+WGj9KlcEto7ldjvfx9NotzSGsv2o= -github.com/vmkteam/zenrpc/v2 v2.2.12/go.mod h1:T/ZQlJbKThBNJtyN0313xEPcxjEyB19uNldTBr0o2KE= +github.com/vmkteam/zenrpc-middleware v1.3.2 h1:LkLb+Uw/42Ug7OtPPm1xSkv/9Sxyvizx5uWHSPjLHzI= +github.com/vmkteam/zenrpc-middleware v1.3.2/go.mod h1:0jcu9ueifVm4hS1S4Mw8tbA+GD/B0UR3CW0o+PQq41U= +github.com/vmkteam/zenrpc/v2 v2.3.0 h1:C3jBi0FkseKmVVh2WTvdMuG0THdL84jOut4Xsqx5NeM= +github.com/vmkteam/zenrpc/v2 v2.3.0/go.mod h1:HSnsZXbtiRDdnga3YjG8x2lQsQha7Jy/pZSFnNN+XeM= go.opentelemetry.io/otel v0.11.0/go.mod h1:G8UCk+KooF2HLkgo8RHX9epABH/aRGYET7gQOqBVdB0= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= @@ -268,8 +268,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= -golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= +golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= +golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20200901203048-c4f52b2c50aa/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= @@ -281,8 +281,8 @@ golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ= -golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc= +golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= +golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -298,8 +298,8 @@ golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= -golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= +golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= +golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -333,22 +333,22 @@ golang.org/x/sys v0.0.0-20200908134130-d2e65c121b96/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= -golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= +golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= -golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= -golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0= -golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= +golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg= -golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s= +golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= +golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= @@ -373,8 +373,8 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2 google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw= -google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/pkg/app/app.go b/pkg/app/app.go index 9d38ad5..b17a9e5 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -41,7 +41,7 @@ type App struct { dbc *pg.DB mon *monitor.Monitor echo *echo.Echo - vtsrv zenrpc.Server + vtsrv *zenrpc.Server } func New(appName string, sl embedlog.Logger, cfg Config, db db.DB, dbc *pg.DB) *App { diff --git a/pkg/app/handlers.go b/pkg/app/handlers.go index 1f7270b..2d49107 100644 --- a/pkg/app/handlers.go +++ b/pkg/app/handlers.go @@ -13,7 +13,6 @@ import ( "github.com/vmkteam/appkit" "github.com/vmkteam/rpcgen/v2" "github.com/vmkteam/rpcgen/v2/typescript" - zm "github.com/vmkteam/zenrpc-middleware" "github.com/vmkteam/zenrpc/v2" ) @@ -64,7 +63,7 @@ func (a *App) registerAPIHandlers() { srv := rpc.New(a.db, a.Logger, a.cfg.Server.IsDevel) gen := rpcgen.FromSMD(srv.SMD()) - a.echo.Any("/v1/rpc/", zm.EchoHandler(zm.XRequestID(srv))) + a.echo.Any("/v1/rpc/", appkit.EchoHandler(appkit.XRequestID(srv))) a.echo.Any("/v1/rpc/doc/", appkit.EchoHandlerFunc(zenrpc.SMDBoxHandler)) a.echo.Any("/v1/rpc/openrpc.json", appkit.EchoHandlerFunc(rpcgen.Handler(gen.OpenRPC("apisrv", "http://localhost:8075/v1/rpc")))) a.echo.Any("/v1/rpc/api.ts", appkit.EchoHandlerFunc(rpcgen.Handler(gen.TSClient(nil)))) @@ -75,7 +74,7 @@ func (a *App) registerVTApiHandlers() { gen := rpcgen.FromSMD(a.vtsrv.SMD()) tsSettings := typescript.Settings{ExcludedNamespace: []string{NSVFS}, WithClasses: true} - a.echo.Any("/v1/vt/", zm.EchoHandler(zm.XRequestID(a.vtsrv))) + a.echo.Any("/v1/vt/", appkit.EchoHandler(appkit.XRequestID(a.vtsrv))) a.echo.Any("/v1/vt/doc/", appkit.EchoHandlerFunc(zenrpc.SMDBoxHandler)) a.echo.Any("/v1/vt/api.ts", appkit.EchoHandlerFunc(rpcgen.Handler(gen.TSCustomClient(tsSettings)))) } diff --git a/pkg/app/vfs.go b/pkg/app/vfs.go index 3870729..3a91e2a 100644 --- a/pkg/app/vfs.go +++ b/pkg/app/vfs.go @@ -7,9 +7,9 @@ import ( "apisrv/pkg/vt" "github.com/labstack/echo/v4" + "github.com/vmkteam/appkit" "github.com/vmkteam/vfs" vfsdb "github.com/vmkteam/vfs/db" - zm "github.com/vmkteam/zenrpc-middleware" ) const NSVFS = "vfs" @@ -23,7 +23,7 @@ func (a *App) RegisterVFS(cfg vfs.Config) error { cr := db.NewCommonRepo(a.db) vfsRepo := vfsdb.NewVfsRepo(a.db) - a.echo.Any("/v1/vfs/upload/file", zm.EchoHandler(vt.HTTPAuthMiddleware(cr, vf.UploadHandler(vfsRepo)))) + a.echo.Any("/v1/vfs/upload/file", appkit.EchoHandler(vt.HTTPAuthMiddleware(cr, vf.UploadHandler(vfsRepo)))) a.echo.Any("/v1/vfs/upload/hash", echo.WrapHandler(vt.HTTPAuthMiddleware(cr, vf.HashUploadHandler(&vfsRepo)))) a.echo.GET(a.cfg.VFS.WebPath, echo.WrapHandler(http.StripPrefix(a.cfg.VFS.WebPath, http.FileServer(http.Dir(a.cfg.VFS.Path))))) vt.WebPath = a.cfg.VFS.WebPath diff --git a/pkg/db/logger.go b/pkg/db/logger.go index 4175030..5efa6ee 100644 --- a/pkg/db/logger.go +++ b/pkg/db/logger.go @@ -7,8 +7,8 @@ import ( "time" "github.com/go-pg/pg/v10" + "github.com/vmkteam/appkit" "github.com/vmkteam/embedlog" - zm "github.com/vmkteam/zenrpc-middleware" "github.com/vmkteam/zenrpc/v2" ) @@ -35,7 +35,7 @@ func (ql QueryLogger) BeforeQuery(ctx context.Context, event *pg.QueryEvent) (co } func (ql QueryLogger) AfterQuery(ctx context.Context, event *pg.QueryEvent) error { - method := fmt.Sprintf("%s.%s", zenrpc.NamespaceFromContext(ctx), zm.MethodFromContext(ctx)) + method := fmt.Sprintf("%s.%s", zenrpc.NamespaceFromContext(ctx), appkit.MethodFromContext(ctx)) query, err := event.FormattedQuery() if err != nil { ql.Error(ctx, string(query), "err", err, "rpc", method) diff --git a/pkg/rpc/server.go b/pkg/rpc/server.go index e22655e..714a2a4 100644 --- a/pkg/rpc/server.go +++ b/pkg/rpc/server.go @@ -24,7 +24,7 @@ var allowDebugFn = func() zm.AllowDebugFunc { //go:generate go tool zenrpc // New returns new zenrpc Server. -func New(dbo db.DB, logger embedlog.Logger, isDevel bool) zenrpc.Server { +func New(dbo db.DB, logger embedlog.Logger, isDevel bool) *zenrpc.Server { rpc := zenrpc.NewServer(zenrpc.Options{ ExposeSMD: true, AllowCORS: true, diff --git a/pkg/vt/server.go b/pkg/vt/server.go index 1d29662..17a136c 100644 --- a/pkg/vt/server.go +++ b/pkg/vt/server.go @@ -40,7 +40,7 @@ func httpAsRPCError(code int) *zenrpc.Error { } // New returns new zenrpc Server. -func New(dbo db.DB, logger embedlog.Logger, isDevel bool) zenrpc.Server { +func New(dbo db.DB, logger embedlog.Logger, isDevel bool) *zenrpc.Server { rpc := zenrpc.NewServer(zenrpc.Options{ ExposeSMD: true, AllowCORS: true, diff --git a/pkg/vt/vt_zenrpc.go b/pkg/vt/vt_zenrpc.go index 9b4c61a..786e6f5 100644 --- a/pkg/vt/vt_zenrpc.go +++ b/pkg/vt/vt_zenrpc.go @@ -1,4 +1,4 @@ -// Code generated by zenrpc v2.2.12; DO NOT EDIT. +// Code generated by zenrpc v2.3.0; DO NOT EDIT. package vt diff --git a/vendor/github.com/gabriel-vasile/mimetype/CODE_OF_CONDUCT.md b/vendor/github.com/gabriel-vasile/mimetype/CODE_OF_CONDUCT.md deleted file mode 100644 index 8479cd8..0000000 --- a/vendor/github.com/gabriel-vasile/mimetype/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,76 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal -appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at vasile.gabriel@email.com. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see -https://www.contributor-covenant.org/faq diff --git a/vendor/github.com/gabriel-vasile/mimetype/CONTRIBUTING.md b/vendor/github.com/gabriel-vasile/mimetype/CONTRIBUTING.md deleted file mode 100644 index 56ae4e5..0000000 --- a/vendor/github.com/gabriel-vasile/mimetype/CONTRIBUTING.md +++ /dev/null @@ -1,12 +0,0 @@ -## Contribute -Contributions to **mimetype** are welcome. If you find an issue and you consider -contributing, you can use the [Github issues tracker](https://github.com/gabriel-vasile/mimetype/issues) -in order to report it, or better yet, open a pull request. - -Code contributions must respect these rules: - - code must be test covered - - code must be formatted using 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/README.md b/vendor/github.com/gabriel-vasile/mimetype/README.md index aa88b4b..f28f56c 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/README.md +++ b/vendor/github.com/gabriel-vasile/mimetype/README.md @@ -27,6 +27,7 @@ - possibility to [extend](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#example-package-Extend) with other file formats - common file formats are prioritized - [text vs. binary files differentiation](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#example-package-TextVsBinary) +- no external dependencies - safe for concurrent usage ## Install @@ -45,8 +46,7 @@ fmt.Println(mtype.String(), mtype.Extension()) ``` See the [runnable Go Playground examples](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#pkg-overview). -## Usage' -Only use libraries like **mimetype** as a last resort. Content type detection +Caution: only use libraries like **mimetype** as a last resort. Content type detection using magic numbers is slow, inaccurate, and non-standard. Most of the times protocols have methods for specifying such metadata; e.g., `Content-Type` header in HTTP and SMTP. @@ -67,6 +67,18 @@ mimetype.DetectFile("file.doc") If increasing the limit does not help, please [open an issue](https://github.com/gabriel-vasile/mimetype/issues/new?assignees=&labels=&template=mismatched-mime-type-detected.md&title=). +## Tests +In addition to unit tests, +[mimetype_tests](https://github.com/gabriel-vasile/mimetype_tests) compares the +library with the [Unix file utility](https://en.wikipedia.org/wiki/File_(command)) +for around 50 000 sample files. Check the latest comparison results +[here](https://github.com/gabriel-vasile/mimetype_tests/actions). + +## Benchmarks +Benchmarks for each file format are performed when a PR is open. The results can +be seen on the [workflows page](https://github.com/gabriel-vasile/mimetype/actions/workflows/benchmark.yml). +Performance improvements are welcome but correctness is prioritized. + ## Structure **mimetype** uses a hierarchical structure to keep the MIME type detection logic. This reduces the number of calls needed for detecting the file type. The reason @@ -84,19 +96,8 @@ or from a [file](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#DetectFil how project is structured -## Performance -Thanks to the hierarchical structure, searching for common formats first, -and limiting itself to file headers, **mimetype** matches the performance of -stdlib `http.DetectContentType` while outperforming the alternative package. - -```bash - mimetype http.DetectContentType filetype -BenchmarkMatchTar-24 250 ns/op 400 ns/op 3778 ns/op -BenchmarkMatchZip-24 524 ns/op 351 ns/op 4884 ns/op -BenchmarkMatchJpeg-24 103 ns/op 228 ns/op 839 ns/op -BenchmarkMatchGif-24 139 ns/op 202 ns/op 751 ns/op -BenchmarkMatchPng-24 165 ns/op 221 ns/op 1176 ns/op -``` - ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md). +Contributions are unexpected but welcome. When submitting a PR for detection of +a new file format, please make sure to add a record to the list of testcases +from [mimetype_test.go](mimetype_test.go). For complex files a record can be added +in the [testdata](testdata) directory. 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 0647f73..8c5a05e 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go @@ -2,11 +2,10 @@ package charset import ( "bytes" - "encoding/xml" - "strings" "unicode/utf8" - "golang.org/x/net/html" + "github.com/gabriel-vasile/mimetype/internal/markup" + "github.com/gabriel-vasile/mimetype/internal/scan" ) const ( @@ -141,20 +140,31 @@ func FromXML(content []byte) string { } return FromPlain(content) } -func fromXML(content []byte) string { - content = trimLWS(content) - dec := xml.NewDecoder(bytes.NewReader(content)) - rawT, err := dec.RawToken() - if err != nil { - return "" - } - - t, ok := rawT.(xml.ProcInst) - if !ok { - return "" +func fromXML(s scan.Bytes) string { + xml := []byte(" 0 && line[n-1] == '\r' { + return line[:n-1], false // drop \r at end of line + } + + // This line is problematic. The logic from CountFields comes from + // encoding/csv.Reader which relies on mutating the input bytes. + // https://github.com/golang/go/blob/b3251514531123d7fd007682389bce7428d159a0/src/encoding/csv/reader.go#L275-L279 + // To avoid mutating the input, we return cutShort. #680 + if n >= 2 && line[n-2] == '\r' && line[n-1] == '\n' { + return line[:n-2], true + } + return line, false +} + +// CountFields reads one CSV line and counts how many records that line contained. +// hasMore reports whether there are more lines in the input. +// collectIndexes makes CountFields return a list of indexes where CSV fields +// start in the line. These indexes are used to test the correctness against the +// encoding/csv parser. +func (r *Parser) CountFields(collectIndexes bool) (fields int, fieldPos []int, hasMore bool) { + finished := false + var line scan.Bytes + cutShort := false + for { + line, cutShort = r.readLine() + if finished { + return 0, nil, false + } + finished = len(r.s) == 0 && len(line) == 0 + if len(line) == lengthNL(line) { + line = nil + continue // Skip empty lines. + } + if len(line) > 0 && line[0] == r.comment { + line = nil + continue + } + break + } + + indexes := []int{} + originalLine := line +parseField: + for { + if len(line) == 0 || line[0] != '"' { // non-quoted string field + fields++ + if collectIndexes { + indexes = append(indexes, len(originalLine)-len(line)) + } + i := bytes.IndexByte(line, r.comma) + if i >= 0 { + line.Advance(i + 1) // 1 to get over ending comma + continue parseField + } + break parseField + } else { // Quoted string field. + if collectIndexes { + indexes = append(indexes, len(originalLine)-len(line)) + } + line.Advance(1) // get over starting quote + for { + i := bytes.IndexByte(line, '"') + if i >= 0 { + line.Advance(i + 1) // 1 for ending quote + switch rn := line.Peek(); { + case rn == '"': + line.Advance(1) + case rn == r.comma: + line.Advance(1) + fields++ + continue parseField + case lengthNL(line) == len(line): + fields++ + break parseField + } + } else if len(line) > 0 || cutShort { + line, cutShort = r.readLine() + originalLine = line + } else { + fields++ + break parseField + } + } + } + } + + return fields, indexes, fields != 0 +} + +// lengthNL reports the number of bytes for the trailing \n. +func lengthNL(b []byte) int { + if len(b) > 0 && b[len(b)-1] == '\n' { + return 1 + } + return 0 +} 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 fd8dd52..4bc8617 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go @@ -258,7 +258,7 @@ out: } func (p *parserState) consumeArray(b []byte, qs []query, lvl int) (n int) { - p.currPath = append(p.currPath, []byte{'['}) + p.appendPath([]byte{'['}, qs) if len(b) == 0 { return 0 } @@ -270,7 +270,7 @@ func (p *parserState) consumeArray(b []byte, qs []query, lvl int) (n int) { } if b[n] == ']' { p.ib++ - p.currPath = p.currPath[:len(p.currPath)-1] + p.popLastPath(qs) return n + 1 } innerParsed := p.consumeAny(b[n:], qs, lvl) @@ -305,6 +305,20 @@ func queryPathMatch(qs []query, path [][]byte) int { return -1 } +// appendPath will append a path fragment if queries is not empty. +// If we don't need query functionality (just checking if a JSON is valid), +// then we can skip keeping track of the path we're currently in. +func (p *parserState) appendPath(path []byte, qs []query) { + if len(qs) != 0 { + p.currPath = append(p.currPath, path) + } +} +func (p *parserState) popLastPath(qs []query) { + if len(qs) != 0 { + p.currPath = p.currPath[:len(p.currPath)-1] + } +} + func (p *parserState) consumeObject(b []byte, qs []query, lvl int) (n int) { for n < len(b) { n += p.consumeSpace(b[n:]) @@ -326,7 +340,7 @@ func (p *parserState) consumeObject(b []byte, qs []query, lvl int) (n int) { if keyLen := p.consumeString(b[n:]); keyLen == 0 { return 0 } else { - p.currPath = append(p.currPath, b[n:n+keyLen-1]) + p.appendPath(b[n:n+keyLen-1], qs) if !p.querySatisfied { queryMatched = queryPathMatch(qs, p.currPath) } @@ -368,12 +382,12 @@ func (p *parserState) consumeObject(b []byte, qs []query, lvl int) (n int) { } switch b[n] { case ',': - p.currPath = p.currPath[:len(p.currPath)-1] + p.popLastPath(qs) n++ p.ib++ continue case '}': - p.currPath = p.currPath[:len(p.currPath)-1] + p.popLastPath(qs) p.ib++ return n + 1 default: @@ -388,6 +402,9 @@ func (p *parserState) consumeAny(b []byte, qs []query, lvl int) (n int) { if p.maxRecursion != 0 && lvl > p.maxRecursion { return 0 } + if len(qs) == 0 { + p.querySatisfied = true + } n += p.consumeSpace(b) if len(b[n:]) == 0 { return 0 @@ -426,9 +443,6 @@ func (p *parserState) consumeAny(b []byte, qs []query, lvl int) (n int) { if lvl == 0 { p.firstToken = t } - if len(qs) == 0 { - p.querySatisfied = true - } if rv <= 0 { return n } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go index b3b26d5..7f9308d 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go @@ -1,18 +1,11 @@ package magic -import "bytes" +import ( + "bytes" + "encoding/binary" +) var ( - // Pdf matches a Portable Document Format file. - // https://github.com/file/file/blob/11010cc805546a3e35597e67e1129a481aed40e8/magic/Magdir/pdf - Pdf = prefix( - // usual pdf signature - []byte("%PDF-"), - // new-line prefixed signature - []byte("\012%PDF-"), - // UTF-8 BOM prefixed signature - []byte("\xef\xbb\xbf%PDF-"), - ) // Fdf matches a Forms Data Format file. Fdf = prefix([]byte("%FDF")) // Mobi matches a Mobi file. @@ -21,8 +14,18 @@ var ( Lit = prefix([]byte("ITOLITLS")) ) +// PDF matches a Portable Document Format file. +// The %PDF- header should be the first thing inside the file but many +// implementations don't follow the rule. The PDF spec at Appendix H says the +// signature can be prepended by anything. +// https://bugs.astron.com/view.php?id=446 +func PDF(raw []byte, _ uint32) bool { + raw = raw[:min(len(raw), 1024)] + return bytes.Contains(raw, []byte("%PDF-")) +} + // DjVu matches a DjVu file. -func DjVu(raw []byte, limit uint32) bool { +func DjVu(raw []byte, _ uint32) bool { if len(raw) < 12 { return false } @@ -36,7 +39,7 @@ func DjVu(raw []byte, limit uint32) bool { } // P7s matches an .p7s signature File (PEM, Base64). -func P7s(raw []byte, limit uint32) bool { +func P7s(raw []byte, _ uint32) bool { // Check for PEM Encoding. if bytes.HasPrefix(raw, []byte("-----BEGIN PKCS7")) { return true @@ -60,3 +63,21 @@ func P7s(raw []byte, limit uint32) bool { return false } + +// Lotus123 matches a Lotus 1-2-3 spreadsheet document. +func Lotus123(raw []byte, _ uint32) bool { + if len(raw) <= 20 { + return false + } + version := binary.BigEndian.Uint32(raw) + if version == 0x00000200 { + return raw[6] != 0 && raw[7] == 0 + } + + return version == 0x00001a00 && raw[20] > 0 && raw[20] < 32 +} + +// CHM matches a Microsoft Compiled HTML Help file. +func CHM(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("ITSF\003\000\000\000\x60\000\000\000")) +} 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 a34c609..5fe435b 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go @@ -4,6 +4,8 @@ package magic import ( "bytes" "fmt" + + "github.com/gabriel-vasile/mimetype/internal/scan" ) type ( @@ -74,12 +76,13 @@ func ciCheck(sig, raw []byte) bool { // matches the raw input. func xml(sigs ...xmlSig) Detector { return func(raw []byte, limit uint32) bool { - raw = trimLWS(raw) - if len(raw) == 0 { + b := scan.Bytes(raw) + b.TrimLWS() + if len(b) == 0 { return false } for _, s := range sigs { - if xmlCheck(s, raw) { + if xmlCheck(s, b) { return true } } @@ -104,19 +107,19 @@ func xmlCheck(sig xmlSig, raw []byte) bool { // matches the raw input. func markup(sigs ...[]byte) Detector { return func(raw []byte, limit uint32) bool { - if bytes.HasPrefix(raw, []byte{0xEF, 0xBB, 0xBF}) { + b := scan.Bytes(raw) + if bytes.HasPrefix(b, []byte{0xEF, 0xBB, 0xBF}) { // We skip the UTF-8 BOM if present to ensure we correctly // process any leading whitespace. The presence of the BOM // is taken into account during charset detection in charset.go. - raw = trimLWS(raw[3:]) - } else { - raw = trimLWS(raw) + b.Advance(3) } - if len(raw) == 0 { + b.TrimLWS() + if len(b) == 0 { return false } for _, s := range sigs { - if markupCheck(s, raw) { + if markupCheck(s, b) { return true } } @@ -139,7 +142,7 @@ func markupCheck(sig, raw []byte) bool { } } // Next byte must be space or right angle bracket. - if db := raw[len(sig)]; db != ' ' && db != '>' { + if db := raw[len(sig)]; !scan.ByteIsWS(db) && db != '>' { return false } @@ -183,8 +186,10 @@ func newXMLSig(localName, xmlns string) xmlSig { // /usr/bin/env is the interpreter, php is the first and only argument. func shebang(sigs ...[]byte) Detector { return func(raw []byte, limit uint32) bool { + b := scan.Bytes(raw) + line := b.Line() for _, s := range sigs { - if shebangCheck(s, firstLine(raw)) { + if shebangCheck(s, line) { return true } } @@ -192,7 +197,7 @@ func shebang(sigs ...[]byte) Detector { } } -func shebangCheck(sig, raw []byte) bool { +func shebangCheck(sig []byte, raw scan.Bytes) bool { if len(raw) < len(sig)+2 { return false } @@ -200,52 +205,8 @@ func shebangCheck(sig, raw []byte) bool { return false } - return bytes.Equal(trimLWS(trimRWS(raw[2:])), sig) -} - -// trimLWS trims whitespace from beginning of the input. -func trimLWS(in []byte) []byte { - firstNonWS := 0 - for ; firstNonWS < len(in) && isWS(in[firstNonWS]); firstNonWS++ { - } - - return in[firstNonWS:] -} - -// trimRWS trims whitespace from the end of the input. -func trimRWS(in []byte) []byte { - lastNonWS := len(in) - 1 - for ; lastNonWS > 0 && isWS(in[lastNonWS]); lastNonWS-- { - } - - return in[:lastNonWS+1] -} - -func firstLine(in []byte) []byte { - lineEnd := 0 - for ; lineEnd < len(in) && in[lineEnd] != '\n'; lineEnd++ { - } - - return in[:lineEnd] -} - -func isWS(b byte) bool { - return b == '\t' || b == '\n' || b == '\x0c' || b == '\r' || b == ' ' -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -type readBuf []byte - -func (b *readBuf) advance(n int) bool { - if n < 0 || len(*b) < n { - return false - } - *b = (*b)[n:] - return true + raw.Advance(2) // skip #! we checked above + raw.TrimLWS() + raw.TrimRWS() + return bytes.Equal(raw, sig) } 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 7d60e22..c912823 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 @@ -7,17 +7,34 @@ import ( // Xlsx matches a Microsoft Excel 2007 file. func Xlsx(raw []byte, limit uint32) bool { - return zipContains(raw, []byte("xl/"), true) + return msoxml(raw, zipEntries{{ + name: []byte("xl/"), + dir: true, + }}, 100) } // Docx matches a Microsoft Word 2007 file. func Docx(raw []byte, limit uint32) bool { - return zipContains(raw, []byte("word/"), true) + return msoxml(raw, zipEntries{{ + name: []byte("word/"), + dir: true, + }}, 100) } // Pptx matches a Microsoft PowerPoint 2007 file. func Pptx(raw []byte, limit uint32) bool { - return zipContains(raw, []byte("ppt/"), true) + return msoxml(raw, zipEntries{{ + name: []byte("ppt/"), + dir: true, + }}, 100) +} + +// Visio matches a Microsoft Visio 2013+ file. +func Visio(raw []byte, limit uint32) bool { + return msoxml(raw, zipEntries{{ + name: []byte("visio/"), + dir: true, + }}, 100) } // Ole matches an Open Linking and Embedding file. @@ -157,6 +174,14 @@ func Msi(raw []byte, limit uint32) bool { }) } +// One matches a Microsoft OneNote file. +func One(raw []byte, limit uint32) bool { + return bytes.HasPrefix(raw, []byte{ + 0xe4, 0x52, 0x5c, 0x7b, 0x8c, 0xd8, 0xa7, 0x4d, + 0xae, 0xb1, 0x53, 0x78, 0xd0, 0x29, 0x96, 0xd3, + }) +} + // Helper to match by a specific CLSID of a compound file. // // http://fileformats.archiveteam.org/wiki/Microsoft_Compound_File diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/netpbm.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/netpbm.go new file mode 100644 index 0000000..4baa257 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/netpbm.go @@ -0,0 +1,111 @@ +package magic + +import ( + "bytes" + "strconv" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +// NetPBM matches a Netpbm Portable BitMap ASCII/Binary file. +// +// See: https://en.wikipedia.org/wiki/Netpbm +func NetPBM(raw []byte, _ uint32) bool { + return netp(raw, "P1\n", "P4\n") +} + +// NetPGM matches a Netpbm Portable GrayMap ASCII/Binary file. +// +// See: https://en.wikipedia.org/wiki/Netpbm +func NetPGM(raw []byte, _ uint32) bool { + return netp(raw, "P2\n", "P5\n") +} + +// NetPPM matches a Netpbm Portable PixMap ASCII/Binary file. +// +// See: https://en.wikipedia.org/wiki/Netpbm +func NetPPM(raw []byte, _ uint32) bool { + return netp(raw, "P3\n", "P6\n") +} + +// NetPAM matches a Netpbm Portable Arbitrary Map file. +// +// See: https://en.wikipedia.org/wiki/Netpbm +func NetPAM(raw []byte, _ uint32) bool { + if !bytes.HasPrefix(raw, []byte("P7\n")) { + return false + } + w, h, d, m, e := false, false, false, false, false + s := scan.Bytes(raw) + var l scan.Bytes + // Read line by line. + for i := 0; i < 128; i++ { + l = s.Line() + // If the line is empty or a comment, skip. + if len(l) == 0 || l.Peek() == '#' { + if len(s) == 0 { + return false + } + continue + } else if bytes.HasPrefix(l, []byte("TUPLTYPE")) { + continue + } else if bytes.HasPrefix(l, []byte("WIDTH ")) { + w = true + } else if bytes.HasPrefix(l, []byte("HEIGHT ")) { + h = true + } else if bytes.HasPrefix(l, []byte("DEPTH ")) { + d = true + } else if bytes.HasPrefix(l, []byte("MAXVAL ")) { + m = true + } else if bytes.HasPrefix(l, []byte("ENDHDR")) { + e = true + } + // When we reached header, return true if we collected all four required headers. + // WIDTH, HEIGHT, DEPTH and MAXVAL. + if e { + return w && h && d && m + } + } + return false +} + +func netp(s scan.Bytes, prefixes ...string) bool { + foundPrefix := "" + for _, p := range prefixes { + if bytes.HasPrefix(s, []byte(p)) { + foundPrefix = p + } + } + if foundPrefix == "" { + return false + } + s.Advance(len(foundPrefix)) // jump over P1, P2, P3, etc. + + var l scan.Bytes + // Read line by line. + for i := 0; i < 128; i++ { + l = s.Line() + // If the line is a comment, skip. + if l.Peek() == '#' { + continue + } + // If line has leading whitespace, then skip over whitespace. + for scan.ByteIsWS(l.Peek()) { + l.Advance(1) + } + if len(s) == 0 || len(l) > 0 { + break + } + } + + // At this point l should be the two integers denoting the size of the matrix. + width := l.PopUntil(scan.ASCIISpaces...) + for scan.ByteIsWS(l.Peek()) { + l.Advance(1) + } + height := l.PopUntil(scan.ASCIISpaces...) + + w, errw := strconv.ParseInt(string(width), 10, 64) + h, errh := strconv.ParseInt(string(height), 10, 64) + return errw == nil && errh == nil && w > 0 && h > 0 +} 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 8178e47..1841ee8 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go @@ -6,6 +6,8 @@ import ( "github.com/gabriel-vasile/mimetype/internal/charset" "github.com/gabriel-vasile/mimetype/internal/json" + mkup "github.com/gabriel-vasile/mimetype/internal/markup" + "github.com/gabriel-vasile/mimetype/internal/scan" ) var ( @@ -27,6 +29,7 @@ var ( []byte(" +// +// +// +func svgWithoutXMLDeclaration(s scan.Bytes) bool { + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + for mkup.SkipAComment(&s) { + } + if !bytes.HasPrefix(s, []byte(" +// +// +// +func svgWithXMLDeclaration(s scan.Bytes) bool { + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + if !bytes.HasPrefix(s, []byte(" 4096 { + s = s[:4096] + } + return hasVersion && bytes.Contains(s, []byte(" 00:02:19,376) limits second line // length to exactly 29 characters. if len(line) != 29 { @@ -266,7 +380,7 @@ func Srt(raw []byte, _ uint32) bool { return false } - line, _ = scanLine(raw) + line = s.Line() // A third line must exist and not be empty. This is the actual subtitle text. return len(line) != 0 } @@ -295,15 +409,3 @@ func Vtt(raw []byte, limit uint32) bool { return bytes.Equal(raw, []byte{0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) || // UTF-8 BOM and "WEBVTT" bytes.Equal(raw, []byte{0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) // "WEBVTT" } - -// dropCR drops a terminal \r from the data. -func dropCR(data []byte) []byte { - if len(data) > 0 && data[len(data)-1] == '\r' { - return data[0 : len(data)-1] - } - return data -} -func scanLine(b []byte) (line, remainder []byte) { - line, remainder, _ = bytes.Cut(b, []byte("\n")) - return dropCR(line), remainder -} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go index 6083ba8..020b5ee 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go @@ -1,77 +1,43 @@ package magic import ( - "bufio" - "bytes" - "encoding/csv" - "errors" - "io" - "sync" + "github.com/gabriel-vasile/mimetype/internal/csv" + "github.com/gabriel-vasile/mimetype/internal/scan" ) -// A bufio.Reader pool to alleviate problems with memory allocations. -var readerPool = sync.Pool{ - New: func() any { - // Initiate with empty source reader. - return bufio.NewReader(nil) - }, -} - -func newReader(r io.Reader) *bufio.Reader { - br := readerPool.Get().(*bufio.Reader) - br.Reset(r) - return br -} - -// Csv matches a comma-separated values file. -func Csv(raw []byte, limit uint32) bool { +// CSV matches a comma-separated values file. +func CSV(raw []byte, limit uint32) bool { return sv(raw, ',', limit) } -// Tsv matches a tab-separated values file. -func Tsv(raw []byte, limit uint32) bool { +// TSV matches a tab-separated values file. +func TSV(raw []byte, limit uint32) bool { return sv(raw, '\t', limit) } -func sv(in []byte, comma rune, limit uint32) bool { - in = dropLastLine(in, limit) - - br := newReader(bytes.NewReader(in)) - defer readerPool.Put(br) - r := csv.NewReader(br) - r.Comma = comma - r.ReuseRecord = true - r.LazyQuotes = true - r.Comment = '#' +func sv(in []byte, comma byte, limit uint32) bool { + s := scan.Bytes(in) + s.DropLastLine(limit) + r := csv.NewParser(comma, '#', s) - lines := 0 + headerFields, _, hasMore := r.CountFields(false) + if headerFields < 2 || !hasMore { + return false + } + csvLines := 1 // 1 for header for { - _, err := r.Read() - if errors.Is(err, io.EOF) { + fields, _, hasMore := r.CountFields(false) + if !hasMore && fields == 0 { break } - if err != nil { + csvLines++ + if fields != headerFields { return false } - lines++ - } - - return r.FieldsPerRecord > 1 && lines > 1 -} - -// 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. -func dropLastLine(b []byte, readLimit uint32) []byte { - if readLimit == 0 || uint32(len(b)) < readLimit { - return b - } - for i := len(b) - 1; i > 0; i-- { - if b[i] == '\n' { - return b[:i] + if csvLines >= 10 { + return true } } - return b + + return csvLines >= 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 f6c6482..17750e6 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go @@ -2,7 +2,8 @@ package magic import ( "bytes" - "encoding/binary" + + "github.com/gabriel-vasile/mimetype/internal/scan" ) var ( @@ -40,92 +41,149 @@ func Zip(raw []byte, limit uint32) bool { (raw[3] == 0x4 || raw[3] == 0x6 || raw[3] == 0x8) } -// Jar matches a Java archive file. +// Jar matches a Java archive file. There are two types of Jar files: +// 1. the ones that can be opened with jexec and have 0xCAFE optional flag +// https://stackoverflow.com/tags/executable-jar/info +// 2. regular jars, same as above, just without the executable flag +// https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=262278#c0 +// There is an argument to only check for manifest, since it's the common nominator +// for both executable and non-executable versions. But the traversing zip entries +// is unreliable because it does linear search for signatures +// (instead of relying on offsets told by the file.) func Jar(raw []byte, limit uint32) bool { - return zipContains(raw, []byte("META-INF/MANIFEST.MF"), false) + return executableJar(raw) || + zipHas(raw, zipEntries{{ + name: []byte("META-INF/MANIFEST.MF"), + }, { + name: []byte("META-INF/"), + }}, 1) } -func zipContains(raw, sig []byte, msoCheck bool) bool { - b := readBuf(raw) - pk := []byte("PK\003\004") - if len(b) < 0x1E { - return false - } +// KMZ matches a zipped KML file, which is "doc.kml" by convention. +func KMZ(raw []byte, _ uint32) bool { + return zipHas(raw, zipEntries{{ + name: []byte("doc.kml"), + }}, 100) +} - if !b.advance(0x1E) { +// An executable Jar has a 0xCAFE flag enabled in the first zip entry. +// The rule from file/file is: +// >(26.s+30) leshort 0xcafe Java archive data (JAR) +func executableJar(b scan.Bytes) bool { + b.Advance(0x1A) + offset, ok := b.Uint16() + if !ok { return false } - if bytes.HasPrefix(b, sig) { - return true - } + b.Advance(int(offset) + 2) - if msoCheck { - skipFiles := [][]byte{ - []byte("[Content_Types].xml"), - []byte("_rels/.rels"), - []byte("docProps"), - []byte("customXml"), - []byte("[trash]"), - } + cafe, ok := b.Uint16() + return ok && cafe == 0xCAFE +} - hasSkipFile := false - for _, sf := range skipFiles { - if bytes.HasPrefix(b, sf) { - hasSkipFile = true - break - } +// zipIterator iterates over a zip file returning the name of the zip entries +// in that file. +type zipIterator struct { + b scan.Bytes +} + +type zipEntries []struct { + name []byte + dir bool // dir means checking just the prefix of the entry, not the whole path +} + +func (z zipEntries) match(file []byte) bool { + for i := range z { + if z[i].dir && bytes.HasPrefix(file, z[i].name) { + return true } - if !hasSkipFile { - return false + if bytes.Equal(file, z[i].name) { + return true } } + return false +} - searchOffset := binary.LittleEndian.Uint32(raw[18:]) + 49 - if !b.advance(int(searchOffset)) { - return false +func zipHas(raw scan.Bytes, searchFor zipEntries, stopAfter int) bool { + iter := zipIterator{raw} + for i := 0; i < stopAfter; i++ { + f := iter.next() + if len(f) == 0 { + break + } + if searchFor.match(f) { + return true + } } - nextHeader := bytes.Index(raw[searchOffset:], pk) - if !b.advance(nextHeader) { - return false - } - if bytes.HasPrefix(b, sig) { - return true - } + return false +} - for i := 0; i < 4; i++ { - if !b.advance(0x1A) { - return false +// msoxml behaves like zipHas, but it puts restrictions on what the first zip +// entry can be. +func msoxml(raw scan.Bytes, searchFor zipEntries, stopAfter int) bool { + iter := zipIterator{raw} + for i := 0; i < stopAfter; i++ { + f := iter.next() + if len(f) == 0 { + break } - nextHeader = bytes.Index(b, pk) - if nextHeader == -1 { - return false - } - if !b.advance(nextHeader + 0x1E) { - return false - } - if bytes.HasPrefix(b, sig) { + if searchFor.match(f) { return true } + // If the first is not one of the next usually expected entries, + // then abort this check. + if i == 0 { + if !bytes.Equal(f, []byte("[Content_Types].xml")) && + !bytes.Equal(f, []byte("_rels/.rels")) && + !bytes.Equal(f, []byte("docProps")) && + !bytes.Equal(f, []byte("customXml")) && + !bytes.Equal(f, []byte("[trash]")) { + return false + } + } } + return false } -// 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 { - apkSignatures := [][]byte{ - []byte("AndroidManifest.xml"), - []byte("META-INF/com/android/build/gradle/app-metadata.properties"), - []byte("classes.dex"), - []byte("resources.arsc"), - []byte("res/drawable"), +// 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) + if n == -1 { + return nil } - for _, sig := range apkSignatures { - if zipContains(raw, sig, false) { - return true - } + i.b.Advance(n) + if !i.b.Advance(0x1A) { + return nil + } + l, ok := i.b.Uint16() + if !ok { + return nil + } + if !i.b.Advance(0x02) { + return nil + } + if len(i.b) < int(l) { + return nil } + return i.b[:l] +} - return false +// 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{{ + name: []byte("AndroidManifest.xml"), + }, { + name: []byte("META-INF/com/android/build/gradle/app-metadata.properties"), + }, { + name: []byte("classes.dex"), + }, { + name: []byte("resources.arsc"), + }, { + name: []byte("res/drawable"), + }}, 100) } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/markup/markup.go b/vendor/github.com/gabriel-vasile/mimetype/internal/markup/markup.go new file mode 100644 index 0000000..937fa1d --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/markup/markup.go @@ -0,0 +1,103 @@ +// Package markup implements functions for extracting info from +// HTML and XML documents. +package markup + +import ( + "bytes" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +func GetAnAttribute(s *scan.Bytes) (name, val string, hasMore bool) { + for scan.ByteIsWS(s.Peek()) || s.Peek() == '/' { + s.Advance(1) + } + if s.Peek() == '>' { + return "", "", false + } + // Allocate 10 to avoid resizes. + // Attribute names and values are continuous slices of bytes in input, + // so we could do without allocating and returning slices of input. + nameB := make([]byte, 0, 10) + // step 4 and 5 + for { + // bap means byte at position in the specification. + bap := s.Pop() + if bap == 0 { + return "", "", false + } + if bap == '=' && len(nameB) > 0 { + val, hasMore := getAValue(s) + return string(nameB), string(val), hasMore + } else if scan.ByteIsWS(bap) { + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + if s.Peek() != '=' { + return string(nameB), "", true + } + s.Advance(1) + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + val, hasMore := getAValue(s) + return string(nameB), string(val), hasMore + } else if bap == '/' || bap == '>' { + return string(nameB), "", false + } else if bap >= 'A' && bap <= 'Z' { + nameB = append(nameB, bap+0x20) + } else { + nameB = append(nameB, bap) + } + } +} + +func getAValue(s *scan.Bytes) (_ []byte, hasMore bool) { + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + origS, end := *s, 0 + bap := s.Pop() + if bap == 0 { + return nil, false + } + end++ + // Step 10 + switch bap { + case '"', '\'': + val := s.PopUntil(bap) + if s.Pop() != bap { + return nil, false + } + return val, s.Peek() != 0 && s.Peek() != '>' + case '>': + return nil, false + } + + // Step 11 + for { + bap = s.Pop() + if bap == 0 { + return nil, false + } + switch { + case scan.ByteIsWS(bap): + return origS[:end], true + case bap == '>': + return origS[:end], false + default: + end++ + } + } +} + +func SkipAComment(s *scan.Bytes) (skipped bool) { + if bytes.HasPrefix(*s, []byte("")); i != -1 { + s.Advance(i + 2 + 3) // 2 comes from len(). + return true + } + } + return false +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go b/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go new file mode 100644 index 0000000..9f09f07 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go @@ -0,0 +1,213 @@ +// Package scan has functions for scanning byte slices. +package scan + +import ( + "bytes" + "encoding/binary" +) + +// Bytes is a byte slice with helper methods for easier scanning. +type Bytes []byte + +func (b *Bytes) Advance(n int) bool { + if n < 0 || len(*b) < n { + return false + } + *b = (*b)[n:] + return true +} + +// TrimLWS trims whitespace from beginning of the bytes. +func (b *Bytes) TrimLWS() { + firstNonWS := 0 + for ; firstNonWS < len(*b) && ByteIsWS((*b)[firstNonWS]); firstNonWS++ { + } + + *b = (*b)[firstNonWS:] +} + +// TrimRWS trims whitespace from the end of the bytes. +func (b *Bytes) TrimRWS() { + lb := len(*b) + for lb > 0 && ByteIsWS((*b)[lb-1]) { + *b = (*b)[:lb-1] + lb-- + } +} + +// Peek one byte from b or 0x00 if b is empty. +func (b *Bytes) Peek() byte { + if len(*b) > 0 { + return (*b)[0] + } + return 0 +} + +// Pop one byte from b or 0x00 if b is empty. +func (b *Bytes) Pop() byte { + if len(*b) > 0 { + ret := (*b)[0] + *b = (*b)[1:] + return ret + } + return 0 +} + +// PopN pops n bytes from b or nil if b is empty. +func (b *Bytes) PopN(n int) []byte { + if len(*b) >= n { + ret := (*b)[:n] + *b = (*b)[n:] + return ret + } + return nil +} + +// PopUntil will advance b until, but not including, the first occurence of stopAt +// character. If no occurence is found, then it will advance until the end of b. +// The returned Bytes is a slice of all the bytes that we're advanced over. +func (b *Bytes) PopUntil(stopAt ...byte) Bytes { + if len(*b) == 0 { + return Bytes{} + } + i := bytes.IndexAny(*b, string(stopAt)) + if i == -1 { + i = len(*b) + } + + prefix := (*b)[:i] + *b = (*b)[i:] + return Bytes(prefix) +} + +// ReadSlice is the same as PopUntil, but the returned value includes stopAt as well. +func (b *Bytes) ReadSlice(stopAt byte) Bytes { + if len(*b) == 0 { + return Bytes{} + } + i := bytes.IndexByte(*b, stopAt) + if i == -1 { + i = len(*b) + } else { + i++ + } + + prefix := (*b)[:i] + *b = (*b)[i:] + return Bytes(prefix) +} + +// Line returns the first line from b and advances b with the length of the +// line. One new line character is trimmed after the line if it exists. +func (b *Bytes) Line() Bytes { + line := b.PopUntil('\n') + lline := len(line) + if lline > 0 && line[lline-1] == '\r' { + line = line[:lline-1] + } + b.Advance(1) + 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 || uint32(len(*b)) < 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 + } + v := binary.LittleEndian.Uint16(*b) + *b = (*b)[2:] + return v, true +} + +const ( + CompactWS = 1 << iota + IgnoreCase +) + +// Search for occurences of pattern p inside b at any index. +func (b Bytes) Search(p []byte, flags int) int { + if flags == 0 { + return bytes.Index(b, p) + } + + lb, lp := len(b), len(p) + for i := range b { + if lb-i < lp { + return -1 + } + if b[i:].Match(p, flags) { + return i + } + } + + return 0 +} + +// Match pattern p at index 0 of b. +func (b Bytes) Match(p []byte, flags int) bool { + for len(b) > 0 { + // If we finished all we we're looking for from p. + if len(p) == 0 { + return true + } + if flags&IgnoreCase > 0 && isUpper(p[0]) { + if upper(b[0]) != p[0] { + return false + } + b, p = b[1:], p[1:] + } else if flags&CompactWS > 0 && ByteIsWS(p[0]) { + p = p[1:] + if !ByteIsWS(b[0]) { + return false + } + b = b[1:] + if !ByteIsWS(p[0]) { + b.TrimLWS() + } + } else { + if b[0] != p[0] { + return false + } + b, p = b[1:], p[1:] + } + } + return true +} + +func isUpper(c byte) bool { + return c >= 'A' && c <= 'Z' +} +func upper(c byte) byte { + if c >= 'a' && c <= 'z' { + return c - ('a' - 'A') + } + return c +} + +func ByteIsWS(b byte) bool { + return b == '\t' || b == '\n' || b == '\x0c' || b == '\r' || b == ' ' +} + +var ( + ASCIISpaces = []byte{' ', '\r', '\n', '\x0c', '\t'} + ASCIIDigits = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} +) diff --git a/vendor/github.com/gabriel-vasile/mimetype/mime.go b/vendor/github.com/gabriel-vasile/mimetype/mime.go index 62cb15f..b82627a 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/mime.go +++ b/vendor/github.com/gabriel-vasile/mimetype/mime.go @@ -103,15 +103,17 @@ func (m *MIME) match(in []byte, readLimit uint32) *MIME { "text/html": charset.FromHTML, "text/xml": charset.FromXML, } - // ps holds optional MIME parameters. - ps := map[string]string{} + charset := "" if f, ok := needsCharset[m.mime]; ok { - if cset := f(in); cset != "" { - ps["charset"] = cset - } + // The charset comes from BOM, from HTML headers, from XML headers. + // Limit the number of bytes searched for to 1024. + charset = f(in[:min(len(in), 1024)]) + } + if m == root { + return m } - return m.cloneHierarchy(ps) + return m.cloneHierarchy(charset) } // flatten transforms an hierarchy of MIMEs into a slice of MIMEs. @@ -125,10 +127,10 @@ func (m *MIME) flatten() []*MIME { } // clone creates a new MIME with the provided optional MIME parameters. -func (m *MIME) clone(ps map[string]string) *MIME { +func (m *MIME) clone(charset string) *MIME { clonedMIME := m.mime - if len(ps) > 0 { - clonedMIME = mime.FormatMediaType(m.mime, ps) + if charset != "" { + clonedMIME = m.mime + "; charset=" + charset } return &MIME{ @@ -140,11 +142,11 @@ func (m *MIME) clone(ps map[string]string) *MIME { // cloneHierarchy creates a clone of m and all its ancestors. The optional MIME // parameters are set on the last child of the hierarchy. -func (m *MIME) cloneHierarchy(ps map[string]string) *MIME { - ret := m.clone(ps) +func (m *MIME) cloneHierarchy(charset string) *MIME { + ret := m.clone(charset) lastChild := ret for p := m.Parent(); p != nil; p = p.Parent() { - pClone := p.clone(nil) + pClone := p.clone("") lastChild.parent = pClone lastChild = pClone } diff --git a/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md b/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md index 6f45bfb..3186a8b 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 @@ -## 179 Supported MIME types +## 191 Supported MIME types This file is automatically generated when running tests. Do not edit manually. Extension | MIME type | Aliases @@ -7,12 +7,12 @@ Extension | MIME type | Aliases **.xpm** | image/x-xpixmap | - **.7z** | application/x-7z-compressed | - **.zip** | application/zip | application/x-zip, application/x-zip-compressed -**.xlsx** | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | - **.docx** | application/vnd.openxmlformats-officedocument.wordprocessingml.document | - **.pptx** | application/vnd.openxmlformats-officedocument.presentationml.presentation | - +**.xlsx** | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | - **.epub** | application/epub+zip | - **.apk** | application/vnd.android.package-archive | - -**.jar** | application/jar | - +**.jar** | application/java-archive | application/jar, application/jar-archive, application/x-java-archive **.odt** | application/vnd.oasis.opendocument.text | application/x-vnd.oasis.opendocument.text **.ott** | application/vnd.oasis.opendocument.text-template | application/x-vnd.oasis.opendocument.text-template **.ods** | application/vnd.oasis.opendocument.spreadsheet | application/x-vnd.oasis.opendocument.spreadsheet @@ -24,6 +24,8 @@ Extension | MIME type | Aliases **.odf** | application/vnd.oasis.opendocument.formula | application/x-vnd.oasis.opendocument.formula **.odc** | application/vnd.oasis.opendocument.chart | application/x-vnd.oasis.opendocument.chart **.sxc** | application/vnd.sun.xml.calc | - +**.kmz** | application/vnd.google-earth.kmz | - +**.vsdx** | application/vnd.ms-visio.drawing.main+xml | - **.pdf** | application/pdf | application/x-pdf **.fdf** | application/vnd.fdf | - **n/a** | application/x-ole-storage | - @@ -61,9 +63,10 @@ Extension | MIME type | Aliases **.tar** | application/x-tar | - **.xar** | application/x-xar | - **.bz2** | application/x-bzip2 | - -**.fits** | application/fits | - +**.fits** | application/fits | image/fits **.tiff** | image/tiff | - **.bmp** | image/bmp | image/x-bmp, image/x-ms-bmp +**.123** | application/vnd.lotus-1-2-3 | - **.ico** | image/x-icon | - **.mp3** | audio/mpeg | audio/x-mpeg, audio/mp3 **.flac** | audio/flac | - @@ -146,9 +149,11 @@ Extension | MIME type | Aliases **.cab** | application/x-installshield | - **.jxr** | image/jxr | image/vnd.ms-photo **.parquet** | application/vnd.apache.parquet | application/x-parquet +**.one** | application/onenote | - +**.chm** | application/vnd.ms-htmlhelp | - **.txt** | text/plain | - -**.html** | text/html | - **.svg** | image/svg+xml | - +**.html** | text/html | - **.xml** | text/xml | application/xml **.rss** | application/rss+xml | text/rss **.atom** | application/atom+xml | - @@ -163,11 +168,13 @@ Extension | MIME type | Aliases **.3mf** | application/vnd.ms-package.3dmanufacturing-3dmodel+xml | - **.xfdf** | application/vnd.adobe.xfdf | - **.owl** | application/owl+xml | - +**.html** | application/xhtml+xml | - **.php** | text/x-php | - **.js** | text/javascript | application/x-javascript, application/javascript **.lua** | text/x-lua | - **.pl** | text/x-perl | - **.py** | text/x-python | text/x-script.python, application/x-python +**.rb** | text/x-ruby | application/x-ruby **.json** | application/json | - **.geojson** | application/geo+json | - **.har** | application/json | - @@ -182,3 +189,8 @@ Extension | MIME type | Aliases **.ics** | text/calendar | - **.warc** | application/warc | - **.vtt** | text/vtt | - +**.sh** | text/x-shellscript | text/x-sh, application/x-shellscript, application/x-sh +**.pbm** | image/x-portable-bitmap | - +**.pgm** | image/x-portable-graymap | - +**.ppm** | image/x-portable-pixmap | - +**.pam** | image/x-portable-arbitrarymap | - diff --git a/vendor/github.com/gabriel-vasile/mimetype/tree.go b/vendor/github.com/gabriel-vasile/mimetype/tree.go index 63a2093..edbde89 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/tree.go +++ b/vendor/github.com/gabriel-vasile/mimetype/tree.go @@ -18,12 +18,13 @@ import ( 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, ico, mp3, - flac, midi, ape, musePack, amr, wav, aiff, au, mpeg, quickTime, mp4, webM, + 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, 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, // Keep text last because it is the slowest check. text, ) @@ -48,22 +49,24 @@ var ( // This means APK should be a child of JAR detector, but in practice, // the decisive signature for JAR might be located at the end of the file // and not reachable because of library readLimit. - zip = newMIME("application/zip", ".zip", magic.Zip, xlsx, docx, pptx, epub, apk, jar, odt, ods, odp, odg, odf, odc, sxc). + zip = newMIME("application/zip", ".zip", magic.Zip, docx, pptx, xlsx, epub, apk, jar, odt, ods, odp, odg, odf, odc, sxc, kmz, visio). alias("application/x-zip", "application/x-zip-compressed") tar = newMIME("application/x-tar", ".tar", magic.Tar) xar = newMIME("application/x-xar", ".xar", magic.Xar) bz2 = newMIME("application/x-bzip2", ".bz2", magic.Bz2) - pdf = newMIME("application/pdf", ".pdf", magic.Pdf). + pdf = newMIME("application/pdf", ".pdf", magic.PDF). alias("application/x-pdf") - fdf = newMIME("application/vnd.fdf", ".fdf", magic.Fdf) - xlsx = newMIME("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx", magic.Xlsx) - docx = newMIME("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx", magic.Docx) - pptx = newMIME("application/vnd.openxmlformats-officedocument.presentationml.presentation", ".pptx", magic.Pptx) - epub = newMIME("application/epub+zip", ".epub", magic.Epub) - jar = newMIME("application/jar", ".jar", magic.Jar) - apk = newMIME("application/vnd.android.package-archive", ".apk", magic.APK) - ole = newMIME("application/x-ole-storage", "", magic.Ole, msi, aaf, msg, xls, pub, ppt, doc) - msi = newMIME("application/x-ms-installer", ".msi", magic.Msi). + fdf = newMIME("application/vnd.fdf", ".fdf", magic.Fdf) + xlsx = newMIME("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx", magic.Xlsx) + docx = newMIME("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx", magic.Docx) + pptx = newMIME("application/vnd.openxmlformats-officedocument.presentationml.presentation", ".pptx", magic.Pptx) + visio = newMIME("application/vnd.ms-visio.drawing.main+xml", ".vsdx", magic.Visio) + epub = newMIME("application/epub+zip", ".epub", magic.Epub) + jar = newMIME("application/java-archive", ".jar", magic.Jar). + alias("application/jar", "application/jar-archive", "application/x-java-archive") + apk = newMIME("application/vnd.android.package-archive", ".apk", magic.APK) + ole = newMIME("application/x-ole-storage", "", magic.Ole, msi, aaf, msg, xls, pub, ppt, doc) + msi = newMIME("application/x-ms-installer", ".msi", magic.Msi). alias("application/x-windows-installer", "application/x-msi") aaf = newMIME("application/octet-stream", ".aaf", magic.Aaf) doc = newMIME("application/msword", ".doc", magic.Doc). @@ -75,18 +78,19 @@ var ( alias("application/msexcel") msg = newMIME("application/vnd.ms-outlook", ".msg", magic.Msg) ps = newMIME("application/postscript", ".ps", magic.Ps) - fits = newMIME("application/fits", ".fits", magic.Fits) + fits = newMIME("application/fits", ".fits", magic.Fits).alias("image/fits") ogg = newMIME("application/ogg", ".ogg", magic.Ogg, oggAudio, oggVideo). 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, html, svg, xml, php, js, lua, perl, python, json, ndJSON, rtf, srt, tcl, csv, tsv, vCard, iCalendar, warc, vtt) - xml = newMIME("text/xml", ".xml", magic.XML, rss, atom, x3d, kml, xliff, collada, gml, gpx, tcx, amf, threemf, xfdf, owl2). + 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) + xml = newMIME("text/xml", ".xml", magic.XML, rss, atom, x3d, kml, xliff, collada, gml, gpx, tcx, amf, threemf, xfdf, owl2, xhtml). alias("application/xml") + xhtml = newMIME("application/xhtml+xml", ".html", magic.XHTML) json = newMIME("application/json", ".json", magic.JSON, geoJSON, har, gltf) har = newMIME("application/json", ".har", magic.HAR) - csv = newMIME("text/csv", ".csv", magic.Csv) - tsv = newMIME("text/tab-separated-values", ".tsv", magic.Tsv) + 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) html = newMIME("text/html", ".html", magic.HTML) @@ -101,6 +105,10 @@ 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") + ruby = newMIME("text/x-ruby", ".rb", magic.Ruby). + alias("application/x-ruby") + shell = newMIME("text/x-shellscript", ".sh", magic.Shell). + alias("text/x-sh", "application/x-shellscript", "application/x-sh") tcl = newMIME("text/x-tcl", ".tcl", magic.Tcl). alias("application/x-tcl") vCard = newMIME("text/vcard", ".vcf", magic.VCard) @@ -112,6 +120,7 @@ var ( atom = newMIME("application/atom+xml", ".atom", magic.Atom) x3d = newMIME("model/x3d+xml", ".x3d", magic.X3d) kml = newMIME("application/vnd.google-earth.kml+xml", ".kml", magic.Kml) + kmz = newMIME("application/vnd.google-earth.kmz", ".kmz", magic.KMZ) xliff = newMIME("application/x-xliff+xml", ".xlf", magic.Xliff) collada = newMIME("model/vnd.collada+xml", ".dae", magic.Collada) gml = newMIME("application/gml+xml", ".gml", magic.Gml) @@ -135,9 +144,12 @@ var ( tiff = newMIME("image/tiff", ".tiff", magic.Tiff) bmp = newMIME("image/bmp", ".bmp", magic.Bmp). alias("image/x-bmp", "image/x-ms-bmp") - ico = newMIME("image/x-icon", ".ico", magic.Ico) - icns = newMIME("image/x-icns", ".icns", magic.Icns) - psd = newMIME("image/vnd.adobe.photoshop", ".psd", magic.Psd). + // lotus check must be done before ico because some ico detection is a bit + // relaxed and some lotus files are wrongfully identified as ico otherwise. + lotus = newMIME("application/vnd.lotus-1-2-3", ".123", magic.Lotus123) + ico = newMIME("image/x-icon", ".ico", magic.Ico) + icns = newMIME("image/x-icns", ".icns", magic.Icns) + psd = newMIME("image/vnd.adobe.photoshop", ".psd", magic.Psd). alias("image/x-psd", "application/photoshop") heic = newMIME("image/heic", ".heic", magic.Heic) heicSeq = newMIME("image/heic-sequence", ".heic", magic.HeicSequence) @@ -267,5 +279,11 @@ var ( jxr = newMIME("image/jxr", ".jxr", magic.Jxr).alias("image/vnd.ms-photo") parquet = newMIME("application/vnd.apache.parquet", ".parquet", magic.Par1). alias("application/x-parquet") - cbor = newMIME("application/cbor", ".cbor", magic.CBOR) + netpbm = newMIME("image/x-portable-bitmap", ".pbm", magic.NetPBM) + netpgm = newMIME("image/x-portable-graymap", ".pgm", magic.NetPGM) + netppm = newMIME("image/x-portable-pixmap", ".ppm", magic.NetPPM) + netpam = newMIME("image/x-portable-arbitrarymap", ".pam", magic.NetPAM) + cbor = newMIME("application/cbor", ".cbor", magic.CBOR) + oneNote = newMIME("application/onenote", ".one", magic.One) + chm = newMIME("application/vnd.ms-htmlhelp", ".chm", magic.CHM) ) diff --git a/vendor/github.com/getsentry/sentry-go/CHANGELOG.md b/vendor/github.com/getsentry/sentry-go/CHANGELOG.md index 1533acc..d8beaa0 100644 --- a/vendor/github.com/getsentry/sentry-go/CHANGELOG.md +++ b/vendor/github.com/getsentry/sentry-go/CHANGELOG.md @@ -1,5 +1,63 @@ # Changelog +## 0.36.2 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.36.2. + +### Bug Fixes + +- Fix context propagation for logs to ensure logger instances correctly inherit span and hub information from their creation context ([#1118](https://github.com/getsentry/sentry-go/pull/1118)) + - Logs now properly propagate trace context from the logger's original context, even when emitted in a different context + - The logger will first check the emission context, then fall back to its creation context, and finally to the current hub + +## 0.36.1 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.36.1. + +### Bug Fixes + +- Prevent panic when converting error chains containing non-comparable error types by using a safe fallback for visited detection in exception conversion ([#1113](https://github.com/getsentry/sentry-go/pull/1113)) + +## 0.36.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.36.0. + +### Breaking Changes + +- Behavioral change for the `MaxBreadcrumbs` client option. Removed the hard limit of 100 breadcrumbs, allowing users to set a larger limit and also changed the default limit from 30 to 100 ([#1106](https://github.com/getsentry/sentry-go/pull/1106))) + +- The changes to error handling ([#1075](https://github.com/getsentry/sentry-go/pull/1075)) will affect issue grouping. It is expected that any wrapped and complex errors will be grouped under a new issue group. + +### Features + +- Add support for improved issue grouping with enhanced error chain handling ([#1075](https://github.com/getsentry/sentry-go/pull/1075)) + + The SDK now provides better handling of complex error scenarios, particularly when dealing with multiple related errors or error chains. This feature automatically detects and properly structures errors created with Go's `errors.Join()` function and other multi-error patterns. + + ```go + // Multiple errors are now properly grouped and displayed in Sentry + err1 := errors.New("err1") + err2 := errors.New("err2") + combinedErr := errors.Join(err1, err2) + + // When captured, these will be shown as related exceptions in Sentry + sentry.CaptureException(combinedErr) + ``` + +- Add `TraceIgnoreStatusCodes` option to allow filtering of HTTP transactions based on status codes ([#1089](https://github.com/getsentry/sentry-go/pull/1089)) + - Configure which HTTP status codes should not be traced by providing single codes or ranges + - Example: `TraceIgnoreStatusCodes: [][]int{{404}, {500, 599}}` ignores 404 and server errors 500-599 + +### Bug Fixes + +- Fix logs being incorrectly filtered by `BeforeSend` callback ([#1109](https://github.com/getsentry/sentry-go/pull/1109)) + - Logs now bypass the `processEvent` method and are sent directly to the transport + - This ensures logs are only filtered by `BeforeSendLog`, not by the error/message `BeforeSend` callback + +### Misc + +- Add support for Go 1.25 and drop support for Go 1.22 ([#1103](https://github.com/getsentry/sentry-go/pull/1103)) + ## 0.35.3 The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.35.3. diff --git a/vendor/github.com/getsentry/sentry-go/Makefile b/vendor/github.com/getsentry/sentry-go/Makefile index 9ef0e9c..26d993e 100644 --- a/vendor/github.com/getsentry/sentry-go/Makefile +++ b/vendor/github.com/getsentry/sentry-go/Makefile @@ -70,7 +70,7 @@ mod-tidy: ## Check go.mod tidiness set -e ; \ for dir in $(ALL_GO_MOD_DIRS); do \ echo ">>> Running 'go mod tidy' for module: $${dir}"; \ - (cd "$${dir}" && go mod tidy -go=1.22 -compat=1.22); \ + (cd "$${dir}" && go mod tidy -go=1.23 -compat=1.23); \ done; \ git diff --exit-code; .PHONY: mod-tidy diff --git a/vendor/github.com/getsentry/sentry-go/batch_logger.go b/vendor/github.com/getsentry/sentry-go/batch_logger.go index d4ebe2f..39487ae 100644 --- a/vendor/github.com/getsentry/sentry-go/batch_logger.go +++ b/vendor/github.com/getsentry/sentry-go/batch_logger.go @@ -125,7 +125,8 @@ func (l *BatchLogger) run(ctx context.Context) { func (l *BatchLogger) processEvent(logs []Log) { event := NewEvent() event.Timestamp = time.Now() + event.EventID = EventID(uuid()) event.Type = logEvent.Type event.Logs = logs - l.client.CaptureEvent(event, nil, nil) + l.client.Transport.SendEvent(event) } diff --git a/vendor/github.com/getsentry/sentry-go/client.go b/vendor/github.com/getsentry/sentry-go/client.go index 3a1b40f..3462302 100644 --- a/vendor/github.com/getsentry/sentry-go/client.go +++ b/vendor/github.com/getsentry/sentry-go/client.go @@ -5,7 +5,6 @@ import ( "crypto/x509" "fmt" "io" - "log" "math/rand" "net/http" "os" @@ -15,24 +14,31 @@ import ( "time" "github.com/getsentry/sentry-go/internal/debug" + "github.com/getsentry/sentry-go/internal/debuglog" ) // The identifier of the SDK. const sdkIdentifier = "sentry.go" -// maxErrorDepth is the maximum number of errors reported in a chain of errors. -// This protects the SDK from an arbitrarily long chain of wrapped errors. -// -// An additional consideration is that arguably reporting a long chain of errors -// is of little use when debugging production errors with Sentry. The Sentry UI -// is not optimized for long chains either. The top-level error together with a -// stack trace is often the most useful information. -const maxErrorDepth = 10 +const ( + // maxErrorDepth is the maximum number of errors reported in a chain of errors. + // This protects the SDK from an arbitrarily long chain of wrapped errors. + // + // An additional consideration is that arguably reporting a long chain of errors + // is of little use when debugging production errors with Sentry. The Sentry UI + // is not optimized for long chains either. The top-level error together with a + // stack trace is often the most useful information. + maxErrorDepth = 100 + + // defaultMaxSpans limits the default number of recorded spans per transaction. The limit is + // meant to bound memory usage and prevent too large transaction events that + // would be rejected by Sentry. + defaultMaxSpans = 1000 -// defaultMaxSpans limits the default number of recorded spans per transaction. The limit is -// meant to bound memory usage and prevent too large transaction events that -// would be rejected by Sentry. -const defaultMaxSpans = 1000 + // defaultMaxBreadcrumbs is the default maximum number of breadcrumbs added to + // an event. Can be overwritten with the MaxBreadcrumbs option. + defaultMaxBreadcrumbs = 100 +) // hostname is the host name reported by the kernel. It is precomputed once to // avoid syscalls when capturing events. @@ -78,8 +84,8 @@ type usageError struct { } // DebugLogger is an instance of log.Logger that is used to provide debug information about running Sentry Client -// can be enabled by either using DebugLogger.SetOutput directly or with Debug client option. -var DebugLogger = log.New(io.Discard, "[Sentry] ", log.LstdFlags) +// can be enabled by either using debuglog.SetOutput directly or with Debug client option. +var DebugLogger = debuglog.GetLogger() // EventProcessor is a function that processes an event. // Event processors are used to change an event before it is sent to Sentry. @@ -228,6 +234,21 @@ type ClientOptions struct { Tags map[string]string // EnableLogs controls when logs should be emitted. EnableLogs bool + // TraceIgnoreStatusCodes is a list of HTTP status codes that should not be traced. + // Each element can be either: + // - A single-element slice [code] for a specific status code + // - A two-element slice [min, max] for a range of status codes (inclusive) + // When an HTTP request results in a status code that matches any of these codes or ranges, + // the transaction will not be sent to Sentry. + // + // Examples: + // [][]int{{404}} // ignore only status code 404 + // [][]int{{400, 405}} // ignore status codes 400-405 + // [][]int{{404}, {500}} // ignore status codes 404 and 500 + // [][]int{{404}, {400, 405}, {500, 599}} // ignore 404, range 400-405, and range 500-599 + // + // By default, this is empty and all status codes are traced. + TraceIgnoreStatusCodes [][]int } // Client is the underlying processor that is used by the main API and Hub @@ -281,7 +302,7 @@ func NewClient(options ClientOptions) (*Client, error) { if debugWriter == nil { debugWriter = os.Stderr } - DebugLogger.SetOutput(debugWriter) + debuglog.SetOutput(debugWriter) } if options.Dsn == "" { @@ -386,12 +407,12 @@ func (client *Client) setupIntegrations() { for _, integration := range integrations { if client.integrationAlreadyInstalled(integration.Name()) { - DebugLogger.Printf("Integration %s is already installed\n", integration.Name()) + debuglog.Printf("Integration %s is already installed\n", integration.Name()) continue } client.integrations = append(client.integrations, integration) integration.SetupOnce(client) - DebugLogger.Printf("Integration installed: %s\n", integration.Name()) + debuglog.Printf("Integration installed: %s\n", integration.Name()) } sort.Slice(client.integrations, func(i, j int) bool { @@ -632,7 +653,7 @@ func (client *Client) processEvent(event *Event, hint *EventHint, scope EventMod // options.TracesSampler when they are started. Other events // (errors, messages) are sampled here. Does not apply to check-ins. if event.Type != transactionType && event.Type != checkInType && !sample(client.options.SampleRate) { - DebugLogger.Println("Event dropped due to SampleRate hit.") + debuglog.Println("Event dropped due to SampleRate hit.") return nil } @@ -648,7 +669,7 @@ func (client *Client) processEvent(event *Event, hint *EventHint, scope EventMod case transactionType: if client.options.BeforeSendTransaction != nil { if event = client.options.BeforeSendTransaction(event, hint); event == nil { - DebugLogger.Println("Transaction dropped due to BeforeSendTransaction callback.") + debuglog.Println("Transaction dropped due to BeforeSendTransaction callback.") return nil } } @@ -656,7 +677,7 @@ func (client *Client) processEvent(event *Event, hint *EventHint, scope EventMod default: if client.options.BeforeSend != nil { if event = client.options.BeforeSend(event, hint); event == nil { - DebugLogger.Println("Event dropped due to BeforeSend callback.") + debuglog.Println("Event dropped due to BeforeSend callback.") return nil } } @@ -723,7 +744,7 @@ func (client *Client) prepareEvent(event *Event, hint *EventHint, scope EventMod id := event.EventID event = processor(event, hint) if event == nil { - DebugLogger.Printf("Event dropped by one of the Client EventProcessors: %s\n", id) + debuglog.Printf("Event dropped by one of the Client EventProcessors: %s\n", id) return nil } } @@ -732,7 +753,7 @@ func (client *Client) prepareEvent(event *Event, hint *EventHint, scope EventMod id := event.EventID event = processor(event, hint) if event == nil { - DebugLogger.Printf("Event dropped by one of the Global EventProcessors: %s\n", id) + debuglog.Printf("Event dropped by one of the Global EventProcessors: %s\n", id) return nil } } diff --git a/vendor/github.com/getsentry/sentry-go/dsn.go b/vendor/github.com/getsentry/sentry-go/dsn.go index 36b9925..64b6f05 100644 --- a/vendor/github.com/getsentry/sentry-go/dsn.go +++ b/vendor/github.com/getsentry/sentry-go/dsn.go @@ -1,233 +1,37 @@ package sentry import ( - "encoding/json" - "fmt" - "net/url" - "strconv" - "strings" - "time" + "github.com/getsentry/sentry-go/internal/protocol" ) -type scheme string +// Re-export protocol types to maintain public API compatibility -const ( - schemeHTTP scheme = "http" - schemeHTTPS scheme = "https" -) - -func (scheme scheme) defaultPort() int { - switch scheme { - case schemeHTTPS: - return 443 - case schemeHTTP: - return 80 - default: - return 80 - } +// Dsn is used as the remote address source to client transport. +type Dsn struct { + protocol.Dsn } // DsnParseError represents an error that occurs if a Sentry // DSN cannot be parsed. -type DsnParseError struct { - Message string -} - -func (e DsnParseError) Error() string { - return "[Sentry] DsnParseError: " + e.Message -} - -// Dsn is used as the remote address source to client transport. -type Dsn struct { - scheme scheme - publicKey string - secretKey string - host string - port int - path string - projectID string -} +type DsnParseError = protocol.DsnParseError // NewDsn creates a Dsn by parsing rawURL. Most users will never call this // function directly. It is provided for use in custom Transport // implementations. func NewDsn(rawURL string) (*Dsn, error) { - // Parse - parsedURL, err := url.Parse(rawURL) + protocolDsn, err := protocol.NewDsn(rawURL) if err != nil { - return nil, &DsnParseError{fmt.Sprintf("invalid url: %v", err)} - } - - // Scheme - var scheme scheme - switch parsedURL.Scheme { - case "http": - scheme = schemeHTTP - case "https": - scheme = schemeHTTPS - default: - return nil, &DsnParseError{"invalid scheme"} - } - - // PublicKey - publicKey := parsedURL.User.Username() - if publicKey == "" { - return nil, &DsnParseError{"empty username"} - } - - // SecretKey - var secretKey string - if parsedSecretKey, ok := parsedURL.User.Password(); ok { - secretKey = parsedSecretKey - } - - // Host - host := parsedURL.Hostname() - if host == "" { - return nil, &DsnParseError{"empty host"} - } - - // Port - var port int - if p := parsedURL.Port(); p != "" { - port, err = strconv.Atoi(p) - if err != nil { - return nil, &DsnParseError{"invalid port"} - } - } else { - port = scheme.defaultPort() - } - - // ProjectID - if parsedURL.Path == "" || parsedURL.Path == "/" { - return nil, &DsnParseError{"empty project id"} - } - pathSegments := strings.Split(parsedURL.Path[1:], "/") - projectID := pathSegments[len(pathSegments)-1] - - if projectID == "" { - return nil, &DsnParseError{"empty project id"} - } - - // Path - var path string - if len(pathSegments) > 1 { - path = "/" + strings.Join(pathSegments[0:len(pathSegments)-1], "/") - } - - return &Dsn{ - scheme: scheme, - publicKey: publicKey, - secretKey: secretKey, - host: host, - port: port, - path: path, - projectID: projectID, - }, nil -} - -// String formats Dsn struct into a valid string url. -func (dsn Dsn) String() string { - var url string - url += fmt.Sprintf("%s://%s", dsn.scheme, dsn.publicKey) - if dsn.secretKey != "" { - url += fmt.Sprintf(":%s", dsn.secretKey) - } - url += fmt.Sprintf("@%s", dsn.host) - if dsn.port != dsn.scheme.defaultPort() { - url += fmt.Sprintf(":%d", dsn.port) + return nil, err } - if dsn.path != "" { - url += dsn.path - } - url += fmt.Sprintf("/%s", dsn.projectID) - return url -} - -// Get the scheme of the DSN. -func (dsn Dsn) GetScheme() string { - return string(dsn.scheme) -} - -// Get the public key of the DSN. -func (dsn Dsn) GetPublicKey() string { - return dsn.publicKey -} - -// Get the secret key of the DSN. -func (dsn Dsn) GetSecretKey() string { - return dsn.secretKey -} - -// Get the host of the DSN. -func (dsn Dsn) GetHost() string { - return dsn.host -} - -// Get the port of the DSN. -func (dsn Dsn) GetPort() int { - return dsn.port -} - -// Get the path of the DSN. -func (dsn Dsn) GetPath() string { - return dsn.path + return &Dsn{Dsn: *protocolDsn}, nil } -// Get the project ID of the DSN. -func (dsn Dsn) GetProjectID() string { - return dsn.projectID -} - -// GetAPIURL returns the URL of the envelope endpoint of the project -// associated with the DSN. -func (dsn Dsn) GetAPIURL() *url.URL { - var rawURL string - rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host) - if dsn.port != dsn.scheme.defaultPort() { - rawURL += fmt.Sprintf(":%d", dsn.port) - } - if dsn.path != "" { - rawURL += dsn.path - } - rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope") - parsedURL, _ := url.Parse(rawURL) - return parsedURL -} - -// RequestHeaders returns all the necessary headers that have to be used in the transport when seinding events +// RequestHeaders returns all the necessary headers that have to be used in the transport when sending events // to the /store endpoint. // // Deprecated: This method shall only be used if you want to implement your own transport that sends events to // the /store endpoint. If you're using the transport provided by the SDK, all necessary headers to authenticate // against the /envelope endpoint are added automatically. func (dsn Dsn) RequestHeaders() map[string]string { - auth := fmt.Sprintf("Sentry sentry_version=%s, sentry_timestamp=%d, "+ - "sentry_client=sentry.go/%s, sentry_key=%s", apiVersion, time.Now().Unix(), SDKVersion, dsn.publicKey) - - if dsn.secretKey != "" { - auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey) - } - - return map[string]string{ - "Content-Type": "application/json", - "X-Sentry-Auth": auth, - } -} - -// MarshalJSON converts the Dsn struct to JSON. -func (dsn Dsn) MarshalJSON() ([]byte, error) { - return json.Marshal(dsn.String()) -} - -// UnmarshalJSON converts JSON data to the Dsn struct. -func (dsn *Dsn) UnmarshalJSON(data []byte) error { - var str string - _ = json.Unmarshal(data, &str) - newDsn, err := NewDsn(str) - if err != nil { - return err - } - *dsn = *newDsn - return nil + return dsn.Dsn.RequestHeaders(SDKVersion) } diff --git a/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go b/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go index 8dae083..5ae3874 100644 --- a/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go +++ b/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go @@ -60,7 +60,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext { } if dsn := client.dsn; dsn != nil { - if publicKey := dsn.publicKey; publicKey != "" { + if publicKey := dsn.GetPublicKey(); publicKey != "" { entries["public_key"] = publicKey } } @@ -136,7 +136,7 @@ func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSampli } if dsn := client.dsn; dsn != nil { - if publicKey := dsn.publicKey; publicKey != "" { + if publicKey := dsn.GetPublicKey(); publicKey != "" { entries["public_key"] = publicKey } } diff --git a/vendor/github.com/getsentry/sentry-go/exception.go b/vendor/github.com/getsentry/sentry-go/exception.go new file mode 100644 index 0000000..9505c99 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/exception.go @@ -0,0 +1,132 @@ +package sentry + +import ( + "fmt" + "reflect" + "slices" +) + +const ( + MechanismTypeGeneric string = "generic" + MechanismTypeChained string = "chained" + MechanismTypeUnwrap string = "unwrap" + MechanismSourceCause string = "cause" +) + +type visited struct { + comparable map[error]struct{} + msgs map[string]struct{} +} + +func (v *visited) seenError(err error) bool { + t := reflect.TypeOf(err) + if t == nil { + return false + } + + if t.Comparable() { + if _, ok := v.comparable[err]; ok { + return true + } + v.comparable[err] = struct{}{} + return false + } + + key := t.String() + err.Error() + if _, ok := v.msgs[key]; ok { + return true + } + v.msgs[key] = struct{}{} + return false +} + +func convertErrorToExceptions(err error, maxErrorDepth int) []Exception { + var exceptions []Exception + vis := &visited{ + make(map[error]struct{}), + make(map[string]struct{}), + } + convertErrorDFS(err, &exceptions, nil, "", vis, maxErrorDepth, 0) + + // mechanism type is used for debugging purposes, but since we can't really distinguish the origin of who invoked + // captureException, we set it to nil if the error is not chained. + if len(exceptions) == 1 { + exceptions[0].Mechanism = nil + } + + slices.Reverse(exceptions) + + // Add a trace of the current stack to the top level(outermost) error in a chain if + // it doesn't have a stack trace yet. + // We only add to the most recent error to avoid duplication and because the + // current stack is most likely unrelated to errors deeper in the chain. + if len(exceptions) > 0 && exceptions[len(exceptions)-1].Stacktrace == nil { + exceptions[len(exceptions)-1].Stacktrace = NewStacktrace() + } + + return exceptions +} + +func convertErrorDFS(err error, exceptions *[]Exception, parentID *int, source string, visited *visited, maxErrorDepth int, currentDepth int) { + if err == nil { + return + } + + if visited.seenError(err) { + return + } + + _, isExceptionGroup := err.(interface{ Unwrap() []error }) + + exception := Exception{ + Value: err.Error(), + Type: reflect.TypeOf(err).String(), + Stacktrace: ExtractStacktrace(err), + } + + currentID := len(*exceptions) + + var mechanismType string + + if parentID == nil { + mechanismType = MechanismTypeGeneric + source = "" + } else { + mechanismType = MechanismTypeChained + } + + exception.Mechanism = &Mechanism{ + Type: mechanismType, + ExceptionID: currentID, + ParentID: parentID, + Source: source, + IsExceptionGroup: isExceptionGroup, + } + + *exceptions = append(*exceptions, exception) + + if maxErrorDepth >= 0 && currentDepth >= maxErrorDepth { + return + } + + switch v := err.(type) { + case interface{ Unwrap() []error }: + unwrapped := v.Unwrap() + for i := range unwrapped { + if unwrapped[i] != nil { + childSource := fmt.Sprintf("errors[%d]", i) + convertErrorDFS(unwrapped[i], exceptions, ¤tID, childSource, visited, maxErrorDepth, currentDepth+1) + } + } + case interface{ Unwrap() error }: + unwrapped := v.Unwrap() + if unwrapped != nil { + convertErrorDFS(unwrapped, exceptions, ¤tID, MechanismTypeUnwrap, visited, maxErrorDepth, currentDepth+1) + } + case interface{ Cause() error }: + cause := v.Cause() + if cause != nil { + convertErrorDFS(cause, exceptions, ¤tID, MechanismSourceCause, visited, maxErrorDepth, currentDepth+1) + } + } +} diff --git a/vendor/github.com/getsentry/sentry-go/hub.go b/vendor/github.com/getsentry/sentry-go/hub.go index 8aea273..30d8c1a 100644 --- a/vendor/github.com/getsentry/sentry-go/hub.go +++ b/vendor/github.com/getsentry/sentry-go/hub.go @@ -5,6 +5,8 @@ import ( "fmt" "sync" "time" + + "github.com/getsentry/sentry-go/internal/debuglog" ) type contextKey int @@ -18,14 +20,6 @@ const ( RequestContextKey = contextKey(2) ) -// defaultMaxBreadcrumbs is the default maximum number of breadcrumbs added to -// an event. Can be overwritten with the maxBreadcrumbs option. -const defaultMaxBreadcrumbs = 30 - -// maxBreadcrumbs is the absolute maximum number of breadcrumbs added to an -// event. The maxBreadcrumbs option cannot be set higher than this value. -const maxBreadcrumbs = 100 - // currentHub is the initial Hub with no Client bound and an empty Scope. var currentHub = NewHub(nil, NewScope()) @@ -289,7 +283,7 @@ func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) { // If there's no client, just store it on the scope straight away if client == nil { - hub.Scope().AddBreadcrumb(breadcrumb, maxBreadcrumbs) + hub.Scope().AddBreadcrumb(breadcrumb, defaultMaxBreadcrumbs) return } @@ -299,8 +293,6 @@ func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) { return case limit == 0: limit = defaultMaxBreadcrumbs - case limit > maxBreadcrumbs: - limit = maxBreadcrumbs } if client.options.BeforeBreadcrumb != nil { @@ -308,7 +300,7 @@ func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) { hint = &BreadcrumbHint{} } if breadcrumb = client.options.BeforeBreadcrumb(breadcrumb, hint); breadcrumb == nil { - DebugLogger.Println("breadcrumb dropped due to BeforeBreadcrumb callback.") + debuglog.Println("breadcrumb dropped due to BeforeBreadcrumb callback.") return } } diff --git a/vendor/github.com/getsentry/sentry-go/integrations.go b/vendor/github.com/getsentry/sentry-go/integrations.go index 70acf91..60cc73d 100644 --- a/vendor/github.com/getsentry/sentry-go/integrations.go +++ b/vendor/github.com/getsentry/sentry-go/integrations.go @@ -8,6 +8,8 @@ import ( "runtime/debug" "strings" "sync" + + "github.com/getsentry/sentry-go/internal/debuglog" ) // ================================ @@ -32,7 +34,7 @@ func (mi *modulesIntegration) processor(event *Event, _ *EventHint) *Event { mi.once.Do(func() { info, ok := debug.ReadBuildInfo() if !ok { - DebugLogger.Print("The Modules integration is not available in binaries built without module support.") + debuglog.Print("The Modules integration is not available in binaries built without module support.") return } mi.modules = extractModules(info) @@ -141,7 +143,7 @@ func (iei *ignoreErrorsIntegration) processor(event *Event, _ *EventHint) *Event for _, suspect := range suspects { for _, pattern := range iei.ignoreErrors { if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) { - DebugLogger.Printf("Event dropped due to being matched by `IgnoreErrors` option."+ + debuglog.Printf("Event dropped due to being matched by `IgnoreErrors` option."+ "| Value matched: %s | Filter used: %s", suspect, pattern) return nil } @@ -203,7 +205,7 @@ func (iei *ignoreTransactionsIntegration) processor(event *Event, _ *EventHint) for _, pattern := range iei.ignoreTransactions { if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) { - DebugLogger.Printf("Transaction dropped due to being matched by `IgnoreTransactions` option."+ + debuglog.Printf("Transaction dropped due to being matched by `IgnoreTransactions` option."+ "| Value matched: %s | Filter used: %s", suspect, pattern) return nil } diff --git a/vendor/github.com/getsentry/sentry-go/interfaces.go b/vendor/github.com/getsentry/sentry-go/interfaces.go index 2cec1cc..ea2f8d8 100644 --- a/vendor/github.com/getsentry/sentry-go/interfaces.go +++ b/vendor/github.com/getsentry/sentry-go/interfaces.go @@ -3,16 +3,14 @@ package sentry import ( "context" "encoding/json" - "errors" "fmt" "net" "net/http" - "reflect" - "slices" "strings" "time" "github.com/getsentry/sentry-go/attribute" + "github.com/getsentry/sentry-go/internal/protocol" "github.com/getsentry/sentry-go/internal/ratelimit" ) @@ -41,18 +39,8 @@ const ( ) // SdkInfo contains all metadata about the SDK. -type SdkInfo struct { - Name string `json:"name,omitempty"` - Version string `json:"version,omitempty"` - Integrations []string `json:"integrations,omitempty"` - Packages []SdkPackage `json:"packages,omitempty"` -} - -// SdkPackage describes a package that was installed. -type SdkPackage struct { - Name string `json:"name,omitempty"` - Version string `json:"version,omitempty"` -} +type SdkInfo = protocol.SdkInfo +type SdkPackage = protocol.SdkPackage // TODO: This type could be more useful, as map of interface{} is too generic // and requires a lot of type assertions in beforeBreadcrumb calls @@ -249,11 +237,11 @@ var sensitiveHeaders = map[string]struct{}{ // NewRequest avoids operations that depend on network access. In particular, it // does not read r.Body. func NewRequest(r *http.Request) *Request { - protocol := schemeHTTP + prot := protocol.SchemeHTTP if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" { - protocol = schemeHTTPS + prot = protocol.SchemeHTTPS } - url := fmt.Sprintf("%s://%s%s", protocol, r.Host, r.URL.Path) + url := fmt.Sprintf("%s://%s%s", prot, r.Host, r.URL.Path) var cookies string var env map[string]string @@ -296,7 +284,7 @@ func NewRequest(r *http.Request) *Request { // Mechanism is the mechanism by which an exception was generated and handled. type Mechanism struct { - Type string `json:"type,omitempty"` + Type string `json:"type"` Description string `json:"description,omitempty"` HelpLink string `json:"help_link,omitempty"` Source string `json:"source,omitempty"` @@ -425,64 +413,84 @@ func (e *Event) SetException(exception error, maxErrorDepth int) { return } - err := exception - - for i := 0; err != nil && (i < maxErrorDepth || maxErrorDepth == -1); i++ { - // Add the current error to the exception slice with its details - e.Exception = append(e.Exception, Exception{ - Value: err.Error(), - Type: reflect.TypeOf(err).String(), - Stacktrace: ExtractStacktrace(err), - }) - - // Attempt to unwrap the error using the standard library's Unwrap method. - // If errors.Unwrap returns nil, it means either there is no error to unwrap, - // or the error does not implement the Unwrap method. - unwrappedErr := errors.Unwrap(err) - - if unwrappedErr != nil { - // The error was successfully unwrapped using the standard library's Unwrap method. - err = unwrappedErr - continue - } + exceptions := convertErrorToExceptions(exception, maxErrorDepth) + if len(exceptions) == 0 { + return + } - cause, ok := err.(interface{ Cause() error }) - if !ok { - // We cannot unwrap the error further. - break - } + e.Exception = exceptions +} + +// ToEnvelope converts the Event to a Sentry envelope. +// This includes the event data and any attachments as separate envelope items. +func (e *Event) ToEnvelope(dsn *protocol.Dsn) (*protocol.Envelope, error) { + return e.ToEnvelopeWithTime(dsn, time.Now()) +} - // The error implements the Cause method, indicating it may have been wrapped - // using the github.com/pkg/errors package. - err = cause.Cause() +// ToEnvelopeWithTime converts the Event to a Sentry envelope with a specific sentAt time. +// This is primarily useful for testing with predictable timestamps. +func (e *Event) ToEnvelopeWithTime(dsn *protocol.Dsn, sentAt time.Time) (*protocol.Envelope, error) { + // Create envelope header with trace context + trace := make(map[string]string) + if dsc := e.sdkMetaData.dsc; dsc.HasEntries() { + for k, v := range dsc.Entries { + trace[k] = v + } } - // Add a trace of the current stack to the most recent error in a chain if - // it doesn't have a stack trace yet. - // We only add to the most recent error to avoid duplication and because the - // current stack is most likely unrelated to errors deeper in the chain. - if e.Exception[0].Stacktrace == nil { - e.Exception[0].Stacktrace = NewStacktrace() + header := &protocol.EnvelopeHeader{ + EventID: string(e.EventID), + SentAt: sentAt, + Trace: trace, } - if len(e.Exception) <= 1 { - return + if dsn != nil { + header.Dsn = dsn.String() } - // event.Exception should be sorted such that the most recent error is last. - slices.Reverse(e.Exception) + header.Sdk = &e.Sdk + + envelope := protocol.NewEnvelope(header) - for i := range e.Exception { - e.Exception[i].Mechanism = &Mechanism{ - IsExceptionGroup: true, - ExceptionID: i, - Type: "generic", + eventBody, err := json.Marshal(e) + if err != nil { + // Try fallback: remove problematic fields and retry + e.Breadcrumbs = nil + e.Contexts = nil + e.Extra = map[string]interface{}{ + "info": fmt.Sprintf("Could not encode original event as JSON. "+ + "Succeeded by removing Breadcrumbs, Contexts and Extra. "+ + "Please verify the data you attach to the scope. "+ + "Error: %s", err), } - if i == 0 { - continue + + eventBody, err = json.Marshal(e) + if err != nil { + return nil, fmt.Errorf("event could not be marshaled even with fallback: %w", err) } - e.Exception[i].Mechanism.ParentID = Pointer(i - 1) + + DebugLogger.Printf("Event marshaling succeeded with fallback after removing problematic fields") } + + var mainItem *protocol.EnvelopeItem + switch e.Type { + case transactionType: + mainItem = protocol.NewEnvelopeItem(protocol.EnvelopeItemTypeTransaction, eventBody) + case checkInType: + mainItem = protocol.NewEnvelopeItem(protocol.EnvelopeItemTypeCheckIn, eventBody) + case logEvent.Type: + mainItem = protocol.NewLogItem(len(e.Logs), eventBody) + default: + mainItem = protocol.NewEnvelopeItem(protocol.EnvelopeItemTypeEvent, eventBody) + } + + envelope.AddItem(mainItem) + for _, attachment := range e.Attachments { + attachmentItem := protocol.NewAttachmentItem(attachment.Filename, attachment.ContentType, attachment.Payload) + envelope.AddItem(attachmentItem) + } + + return envelope, nil } // TODO: Event.Contexts map[string]interface{} => map[string]EventContext, diff --git a/vendor/github.com/getsentry/sentry-go/internal/debuglog/log.go b/vendor/github.com/getsentry/sentry-go/internal/debuglog/log.go new file mode 100644 index 0000000..37fa4d0 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/debuglog/log.go @@ -0,0 +1,35 @@ +package debuglog + +import ( + "io" + "log" +) + +// logger is the global debug logger instance. +var logger = log.New(io.Discard, "[Sentry] ", log.LstdFlags) + +// SetOutput changes the output destination of the logger. +func SetOutput(w io.Writer) { + logger.SetOutput(w) +} + +// GetLogger returns the current logger instance. +// This function is thread-safe and can be called concurrently. +func GetLogger() *log.Logger { + return logger +} + +// Printf calls Printf on the underlying logger. +func Printf(format string, args ...interface{}) { + logger.Printf(format, args...) +} + +// Println calls Println on the underlying logger. +func Println(args ...interface{}) { + logger.Println(args...) +} + +// Print calls Print on the underlying logger. +func Print(args ...interface{}) { + logger.Print(args...) +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/http/transport.go b/vendor/github.com/getsentry/sentry-go/internal/http/transport.go new file mode 100644 index 0000000..52cb32b --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/http/transport.go @@ -0,0 +1,571 @@ +package http + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "sync" + "sync/atomic" + "time" + + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +const ( + apiVersion = 7 + + defaultTimeout = time.Second * 30 + defaultQueueSize = 1000 + + // maxDrainResponseBytes is the maximum number of bytes that transport + // implementations will read from response bodies when draining them. + maxDrainResponseBytes = 16 << 10 +) + +var ( + ErrTransportQueueFull = errors.New("transport queue full") + ErrTransportClosed = errors.New("transport is closed") +) + +type TransportOptions struct { + Dsn string + HTTPClient *http.Client + HTTPTransport http.RoundTripper + HTTPProxy string + HTTPSProxy string + CaCerts *x509.CertPool +} + +func getProxyConfig(options TransportOptions) func(*http.Request) (*url.URL, error) { + if len(options.HTTPSProxy) > 0 { + return func(*http.Request) (*url.URL, error) { + return url.Parse(options.HTTPSProxy) + } + } + + if len(options.HTTPProxy) > 0 { + return func(*http.Request) (*url.URL, error) { + return url.Parse(options.HTTPProxy) + } + } + + return http.ProxyFromEnvironment +} + +func getTLSConfig(options TransportOptions) *tls.Config { + if options.CaCerts != nil { + return &tls.Config{ + RootCAs: options.CaCerts, + MinVersion: tls.VersionTLS12, + } + } + + return nil +} + +func getSentryRequestFromEnvelope(ctx context.Context, dsn *protocol.Dsn, envelope *protocol.Envelope) (r *http.Request, err error) { + defer func() { + if r != nil { + sdkName := envelope.Header.Sdk.Name + sdkVersion := envelope.Header.Sdk.Version + + r.Header.Set("User-Agent", fmt.Sprintf("%s/%s", sdkName, sdkVersion)) + r.Header.Set("Content-Type", "application/x-sentry-envelope") + + auth := fmt.Sprintf("Sentry sentry_version=%d, "+ + "sentry_client=%s/%s, sentry_key=%s", apiVersion, sdkName, sdkVersion, dsn.GetPublicKey()) + + if dsn.GetSecretKey() != "" { + auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.GetSecretKey()) + } + + r.Header.Set("X-Sentry-Auth", auth) + } + }() + + var buf bytes.Buffer + _, err = envelope.WriteTo(&buf) + if err != nil { + return nil, err + } + + return http.NewRequestWithContext( + ctx, + http.MethodPost, + dsn.GetAPIURL().String(), + &buf, + ) +} + +func categoryFromEnvelope(envelope *protocol.Envelope) ratelimit.Category { + if envelope == nil || len(envelope.Items) == 0 { + return ratelimit.CategoryAll + } + + for _, item := range envelope.Items { + if item == nil || item.Header == nil { + continue + } + + switch item.Header.Type { + case protocol.EnvelopeItemTypeEvent: + return ratelimit.CategoryError + case protocol.EnvelopeItemTypeTransaction: + return ratelimit.CategoryTransaction + case protocol.EnvelopeItemTypeCheckIn: + return ratelimit.CategoryMonitor + case protocol.EnvelopeItemTypeLog: + return ratelimit.CategoryLog + case protocol.EnvelopeItemTypeAttachment: + continue + default: + return ratelimit.CategoryAll + } + } + + return ratelimit.CategoryAll +} + +// SyncTransport is a blocking implementation of Transport. +// +// Clients using this transport will send requests to Sentry sequentially and +// block until a response is returned. +// +// The blocking behavior is useful in a limited set of use cases. For example, +// use it when deploying code to a Function as a Service ("Serverless") +// platform, where any work happening in a background goroutine is not +// guaranteed to execute. +// +// For most cases, prefer AsyncTransport. +type SyncTransport struct { + dsn *protocol.Dsn + client *http.Client + transport http.RoundTripper + + mu sync.Mutex + limits ratelimit.Map + + Timeout time.Duration +} + +func NewSyncTransport(options TransportOptions) protocol.TelemetryTransport { + dsn, err := protocol.NewDsn(options.Dsn) + if err != nil || dsn == nil { + debuglog.Printf("Transport is disabled: invalid dsn: %v\n", err) + return NewNoopTransport() + } + + transport := &SyncTransport{ + Timeout: defaultTimeout, + limits: make(ratelimit.Map), + dsn: dsn, + } + + if options.HTTPTransport != nil { + transport.transport = options.HTTPTransport + } else { + transport.transport = &http.Transport{ + Proxy: getProxyConfig(options), + TLSClientConfig: getTLSConfig(options), + } + } + + if options.HTTPClient != nil { + transport.client = options.HTTPClient + } else { + transport.client = &http.Client{ + Transport: transport.transport, + Timeout: transport.Timeout, + } + } + + return transport +} + +func (t *SyncTransport) SendEnvelope(envelope *protocol.Envelope) error { + return t.SendEnvelopeWithContext(context.Background(), envelope) +} + +func (t *SyncTransport) Close() {} + +func (t *SyncTransport) SendEvent(event protocol.EnvelopeConvertible) { + envelope, err := event.ToEnvelope(t.dsn) + if err != nil { + debuglog.Printf("Failed to convert to envelope: %v", err) + return + } + + if envelope == nil { + debuglog.Printf("Error: event with empty envelope") + return + } + + if err := t.SendEnvelope(envelope); err != nil { + debuglog.Printf("Error sending the envelope: %v", err) + } +} + +func (t *SyncTransport) IsRateLimited(category ratelimit.Category) bool { + return t.disabled(category) +} + +func (t *SyncTransport) SendEnvelopeWithContext(ctx context.Context, envelope *protocol.Envelope) error { + if envelope == nil { + debuglog.Printf("Error: provided empty envelope") + return nil + } + + category := categoryFromEnvelope(envelope) + if t.disabled(category) { + return nil + } + + request, err := getSentryRequestFromEnvelope(ctx, t.dsn, envelope) + if err != nil { + debuglog.Printf("There was an issue creating the request: %v", err) + return err + } + response, err := t.client.Do(request) + if err != nil { + debuglog.Printf("There was an issue with sending an event: %v", err) + return err + } + if response.StatusCode >= 400 && response.StatusCode <= 599 { + b, err := io.ReadAll(response.Body) + if err != nil { + debuglog.Printf("Error while reading response body: %v", err) + } + debuglog.Printf("Sending %s failed with the following error: %s", envelope.Header.EventID, string(b)) + } + + t.mu.Lock() + if t.limits == nil { + t.limits = make(ratelimit.Map) + } + + t.limits.Merge(ratelimit.FromResponse(response)) + t.mu.Unlock() + + _, _ = io.CopyN(io.Discard, response.Body, maxDrainResponseBytes) + return response.Body.Close() +} + +func (t *SyncTransport) Flush(_ time.Duration) bool { + return true +} + +func (t *SyncTransport) FlushWithContext(_ context.Context) bool { + return true +} + +func (t *SyncTransport) disabled(c ratelimit.Category) bool { + t.mu.Lock() + defer t.mu.Unlock() + disabled := t.limits.IsRateLimited(c) + if disabled { + debuglog.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) + } + return disabled +} + +// AsyncTransport is the default, non-blocking, implementation of Transport. +// +// Clients using this transport will enqueue requests in a queue and return to +// the caller before any network communication has happened. Requests are sent +// to Sentry sequentially from a background goroutine. +type AsyncTransport struct { + dsn *protocol.Dsn + client *http.Client + transport http.RoundTripper + + queue chan *protocol.Envelope + + mu sync.RWMutex + limits ratelimit.Map + + done chan struct{} + wg sync.WaitGroup + + flushRequest chan chan struct{} + + sentCount int64 + droppedCount int64 + errorCount int64 + + QueueSize int + Timeout time.Duration + + startOnce sync.Once + closeOnce sync.Once +} + +func NewAsyncTransport(options TransportOptions) protocol.TelemetryTransport { + dsn, err := protocol.NewDsn(options.Dsn) + if err != nil || dsn == nil { + debuglog.Printf("Transport is disabled: invalid dsn: %v", err) + return NewNoopTransport() + } + + transport := &AsyncTransport{ + QueueSize: defaultQueueSize, + Timeout: defaultTimeout, + done: make(chan struct{}), + limits: make(ratelimit.Map), + dsn: dsn, + } + + transport.queue = make(chan *protocol.Envelope, transport.QueueSize) + transport.flushRequest = make(chan chan struct{}) + + if options.HTTPTransport != nil { + transport.transport = options.HTTPTransport + } else { + transport.transport = &http.Transport{ + Proxy: getProxyConfig(options), + TLSClientConfig: getTLSConfig(options), + } + } + + if options.HTTPClient != nil { + transport.client = options.HTTPClient + } else { + transport.client = &http.Client{ + Transport: transport.transport, + Timeout: transport.Timeout, + } + } + + transport.start() + return transport +} + +func (t *AsyncTransport) start() { + t.startOnce.Do(func() { + t.wg.Add(1) + go t.worker() + }) +} + +func (t *AsyncTransport) SendEnvelope(envelope *protocol.Envelope) error { + select { + case <-t.done: + return ErrTransportClosed + default: + } + + category := categoryFromEnvelope(envelope) + if t.isRateLimited(category) { + return nil + } + + select { + case t.queue <- envelope: + return nil + default: + atomic.AddInt64(&t.droppedCount, 1) + return ErrTransportQueueFull + } +} + +func (t *AsyncTransport) SendEvent(event protocol.EnvelopeConvertible) { + envelope, err := event.ToEnvelope(t.dsn) + if err != nil { + debuglog.Printf("Failed to convert to envelope: %v", err) + return + } + + if envelope == nil { + debuglog.Printf("Error: event with empty envelope") + return + } + + if err := t.SendEnvelope(envelope); err != nil { + debuglog.Printf("Error sending the envelope: %v", err) + } +} + +func (t *AsyncTransport) Flush(timeout time.Duration) bool { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + return t.FlushWithContext(ctx) +} + +func (t *AsyncTransport) FlushWithContext(ctx context.Context) bool { + flushResponse := make(chan struct{}) + select { + case t.flushRequest <- flushResponse: + select { + case <-flushResponse: + return true + case <-ctx.Done(): + return false + } + case <-ctx.Done(): + return false + } +} + +func (t *AsyncTransport) Close() { + t.closeOnce.Do(func() { + close(t.done) + close(t.queue) + close(t.flushRequest) + t.wg.Wait() + }) +} + +func (t *AsyncTransport) IsRateLimited(category ratelimit.Category) bool { + return t.isRateLimited(category) +} + +func (t *AsyncTransport) worker() { + defer t.wg.Done() + + for { + select { + case <-t.done: + return + case envelope, open := <-t.queue: + if !open { + return + } + t.processEnvelope(envelope) + case flushResponse, open := <-t.flushRequest: + if !open { + return + } + t.drainQueue() + close(flushResponse) + } + } +} + +func (t *AsyncTransport) drainQueue() { + for { + select { + case envelope, open := <-t.queue: + if !open { + return + } + t.processEnvelope(envelope) + default: + return + } + } +} + +func (t *AsyncTransport) processEnvelope(envelope *protocol.Envelope) { + if t.sendEnvelopeHTTP(envelope) { + atomic.AddInt64(&t.sentCount, 1) + } else { + atomic.AddInt64(&t.errorCount, 1) + } +} + +func (t *AsyncTransport) sendEnvelopeHTTP(envelope *protocol.Envelope) bool { + category := categoryFromEnvelope(envelope) + if t.isRateLimited(category) { + return false + } + + ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout) + defer cancel() + + request, err := getSentryRequestFromEnvelope(ctx, t.dsn, envelope) + if err != nil { + debuglog.Printf("Failed to create request from envelope: %v", err) + return false + } + + response, err := t.client.Do(request) + if err != nil { + debuglog.Printf("HTTP request failed: %v", err) + return false + } + defer response.Body.Close() + + success := t.handleResponse(response) + + t.mu.Lock() + if t.limits == nil { + t.limits = make(ratelimit.Map) + } + t.limits.Merge(ratelimit.FromResponse(response)) + t.mu.Unlock() + + _, _ = io.CopyN(io.Discard, response.Body, maxDrainResponseBytes) + return success +} + +func (t *AsyncTransport) handleResponse(response *http.Response) bool { + if response.StatusCode >= 200 && response.StatusCode < 300 { + return true + } + + if response.StatusCode >= 400 && response.StatusCode < 500 { + if body, err := io.ReadAll(io.LimitReader(response.Body, maxDrainResponseBytes)); err == nil { + debuglog.Printf("Client error %d: %s", response.StatusCode, string(body)) + } + return false + } + + if response.StatusCode >= 500 { + debuglog.Printf("Server error %d", response.StatusCode) + return false + } + + debuglog.Printf("Unexpected status code %d", response.StatusCode) + return false +} + +func (t *AsyncTransport) isRateLimited(category ratelimit.Category) bool { + t.mu.RLock() + defer t.mu.RUnlock() + limited := t.limits.IsRateLimited(category) + if limited { + debuglog.Printf("Rate limited for category %q until %v", category, t.limits.Deadline(category)) + } + return limited +} + +// NoopTransport is a transport implementation that drops all events. +// Used internally when an empty or invalid DSN is provided. +type NoopTransport struct{} + +func NewNoopTransport() *NoopTransport { + debuglog.Println("Transport initialized with invalid DSN. Using NoopTransport. No events will be delivered.") + return &NoopTransport{} +} + +func (t *NoopTransport) SendEnvelope(_ *protocol.Envelope) error { + debuglog.Println("Envelope dropped due to NoopTransport usage.") + return nil +} + +func (t *NoopTransport) SendEvent(_ protocol.EnvelopeConvertible) { + debuglog.Println("Event dropped due to NoopTransport usage.") +} + +func (t *NoopTransport) IsRateLimited(_ ratelimit.Category) bool { + return false +} + +func (t *NoopTransport) Flush(_ time.Duration) bool { + return true +} + +func (t *NoopTransport) FlushWithContext(_ context.Context) bool { + return true +} + +func (t *NoopTransport) Close() { + // Nothing to close +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go new file mode 100644 index 0000000..42aff31 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go @@ -0,0 +1,236 @@ +package protocol + +import ( + "encoding/json" + "fmt" + "net/url" + "strconv" + "strings" + "time" +) + +// apiVersion is the version of the Sentry API. +const apiVersion = "7" + +type scheme string + +const ( + SchemeHTTP scheme = "http" + SchemeHTTPS scheme = "https" +) + +func (scheme scheme) defaultPort() int { + switch scheme { + case SchemeHTTPS: + return 443 + case SchemeHTTP: + return 80 + default: + return 80 + } +} + +// DsnParseError represents an error that occurs if a Sentry +// DSN cannot be parsed. +type DsnParseError struct { + Message string +} + +func (e DsnParseError) Error() string { + return "[Sentry] DsnParseError: " + e.Message +} + +// Dsn is used as the remote address source to client transport. +type Dsn struct { + scheme scheme + publicKey string + secretKey string + host string + port int + path string + projectID string +} + +// NewDsn creates a Dsn by parsing rawURL. Most users will never call this +// function directly. It is provided for use in custom Transport +// implementations. +func NewDsn(rawURL string) (*Dsn, error) { + // Parse + parsedURL, err := url.Parse(rawURL) + if err != nil { + return nil, &DsnParseError{fmt.Sprintf("invalid url: %v", err)} + } + + // Scheme + var scheme scheme + switch parsedURL.Scheme { + case "http": + scheme = SchemeHTTP + case "https": + scheme = SchemeHTTPS + default: + return nil, &DsnParseError{"invalid scheme"} + } + + // PublicKey + publicKey := parsedURL.User.Username() + if publicKey == "" { + return nil, &DsnParseError{"empty username"} + } + + // SecretKey + var secretKey string + if parsedSecretKey, ok := parsedURL.User.Password(); ok { + secretKey = parsedSecretKey + } + + // Host + host := parsedURL.Hostname() + if host == "" { + return nil, &DsnParseError{"empty host"} + } + + // Port + var port int + if p := parsedURL.Port(); p != "" { + port, err = strconv.Atoi(p) + if err != nil { + return nil, &DsnParseError{"invalid port"} + } + } else { + port = scheme.defaultPort() + } + + // ProjectID + if parsedURL.Path == "" || parsedURL.Path == "/" { + return nil, &DsnParseError{"empty project id"} + } + pathSegments := strings.Split(parsedURL.Path[1:], "/") + projectID := pathSegments[len(pathSegments)-1] + + if projectID == "" { + return nil, &DsnParseError{"empty project id"} + } + + // Path + var path string + if len(pathSegments) > 1 { + path = "/" + strings.Join(pathSegments[0:len(pathSegments)-1], "/") + } + + return &Dsn{ + scheme: scheme, + publicKey: publicKey, + secretKey: secretKey, + host: host, + port: port, + path: path, + projectID: projectID, + }, nil +} + +// String formats Dsn struct into a valid string url. +func (dsn Dsn) String() string { + var url string + url += fmt.Sprintf("%s://%s", dsn.scheme, dsn.publicKey) + if dsn.secretKey != "" { + url += fmt.Sprintf(":%s", dsn.secretKey) + } + url += fmt.Sprintf("@%s", dsn.host) + if dsn.port != dsn.scheme.defaultPort() { + url += fmt.Sprintf(":%d", dsn.port) + } + if dsn.path != "" { + url += dsn.path + } + url += fmt.Sprintf("/%s", dsn.projectID) + return url +} + +// Get the scheme of the DSN. +func (dsn Dsn) GetScheme() string { + return string(dsn.scheme) +} + +// Get the public key of the DSN. +func (dsn Dsn) GetPublicKey() string { + return dsn.publicKey +} + +// Get the secret key of the DSN. +func (dsn Dsn) GetSecretKey() string { + return dsn.secretKey +} + +// Get the host of the DSN. +func (dsn Dsn) GetHost() string { + return dsn.host +} + +// Get the port of the DSN. +func (dsn Dsn) GetPort() int { + return dsn.port +} + +// Get the path of the DSN. +func (dsn Dsn) GetPath() string { + return dsn.path +} + +// Get the project ID of the DSN. +func (dsn Dsn) GetProjectID() string { + return dsn.projectID +} + +// GetAPIURL returns the URL of the envelope endpoint of the project +// associated with the DSN. +func (dsn Dsn) GetAPIURL() *url.URL { + var rawURL string + rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host) + if dsn.port != dsn.scheme.defaultPort() { + rawURL += fmt.Sprintf(":%d", dsn.port) + } + if dsn.path != "" { + rawURL += dsn.path + } + rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope") + parsedURL, _ := url.Parse(rawURL) + return parsedURL +} + +// RequestHeaders returns all the necessary headers that have to be used in the transport when sending events +// to the /store endpoint. +// +// Deprecated: This method shall only be used if you want to implement your own transport that sends events to +// the /store endpoint. If you're using the transport provided by the SDK, all necessary headers to authenticate +// against the /envelope endpoint are added automatically. +func (dsn Dsn) RequestHeaders(sdkVersion string) map[string]string { + auth := fmt.Sprintf("Sentry sentry_version=%s, sentry_timestamp=%d, "+ + "sentry_client=sentry.go/%s, sentry_key=%s", apiVersion, time.Now().Unix(), sdkVersion, dsn.publicKey) + + if dsn.secretKey != "" { + auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey) + } + + return map[string]string{ + "Content-Type": "application/json", + "X-Sentry-Auth": auth, + } +} + +// MarshalJSON converts the Dsn struct to JSON. +func (dsn Dsn) MarshalJSON() ([]byte, error) { + return json.Marshal(dsn.String()) +} + +// UnmarshalJSON converts JSON data to the Dsn struct. +func (dsn *Dsn) UnmarshalJSON(data []byte) error { + var str string + _ = json.Unmarshal(data, &str) + newDsn, err := NewDsn(str) + if err != nil { + return err + } + *dsn = *newDsn + return nil +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go new file mode 100644 index 0000000..65e305c --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go @@ -0,0 +1,213 @@ +package protocol + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "time" +) + +// Envelope represents a Sentry envelope containing headers and items. +type Envelope struct { + Header *EnvelopeHeader `json:"-"` + Items []*EnvelopeItem `json:"-"` +} + +// EnvelopeHeader represents the header of a Sentry envelope. +type EnvelopeHeader struct { + // EventID is the unique identifier for this event + EventID string `json:"event_id"` + + // 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. + SentAt time.Time `json:"sent_at,omitempty"` + + // Dsn can be used for self-authenticated envelopes. + // This means that the envelope has all the information necessary to be sent to sentry. + // In this case the full DSN must be stored in this key. + Dsn string `json:"dsn,omitempty"` + + // Sdk carries the same payload as the sdk interface in the event payload but can be carried for all events. + // This means that SDK information can be carried for minidumps, session data and other submissions. + Sdk *SdkInfo `json:"sdk,omitempty"` + + // Trace contains the [Dynamic Sampling Context](https://develop.sentry.dev/sdk/telemetry/traces/dynamic-sampling-context/) + Trace map[string]string `json:"trace,omitempty"` +} + +// EnvelopeItemType represents the type of envelope item. +type EnvelopeItemType string + +// Constants for envelope item types as defined in the Sentry documentation. +const ( + EnvelopeItemTypeEvent EnvelopeItemType = "event" + EnvelopeItemTypeTransaction EnvelopeItemType = "transaction" + EnvelopeItemTypeCheckIn EnvelopeItemType = "check_in" + EnvelopeItemTypeAttachment EnvelopeItemType = "attachment" + EnvelopeItemTypeLog EnvelopeItemType = "log" +) + +// EnvelopeItemHeader represents the header of an envelope item. +type EnvelopeItemHeader struct { + // Type specifies the type of this Item and its contents. + // Based on the Item type, more headers may be required. + Type EnvelopeItemType `json:"type"` + + // Length is the length of the payload in bytes. + // If no length is specified, the payload implicitly goes to the next newline. + // For payloads containing newline characters, the length must be specified. + Length *int `json:"length,omitempty"` + + // Filename is the name of the attachment file (used for attachments) + Filename string `json:"filename,omitempty"` + + // ContentType is the MIME type of the item payload (used for attachments and some other item types) + ContentType string `json:"content_type,omitempty"` + + // ItemCount is the number of items in a batch (used for logs) + ItemCount *int `json:"item_count,omitempty"` +} + +// EnvelopeItem represents a single item within an envelope. +type EnvelopeItem struct { + Header *EnvelopeItemHeader `json:"-"` + Payload []byte `json:"-"` +} + +// NewEnvelope creates a new envelope with the given header. +func NewEnvelope(header *EnvelopeHeader) *Envelope { + return &Envelope{ + Header: header, + Items: make([]*EnvelopeItem, 0), + } +} + +// AddItem adds an item to the envelope. +func (e *Envelope) AddItem(item *EnvelopeItem) { + e.Items = append(e.Items, item) +} + +// Serialize serializes the envelope to the Sentry envelope format. +// +// Format: Headers "\n" { Item } [ "\n" ] +// Item: Headers "\n" Payload "\n". +func (e *Envelope) Serialize() ([]byte, error) { + var buf bytes.Buffer + + headerBytes, err := json.Marshal(e.Header) + if err != nil { + return nil, fmt.Errorf("failed to marshal envelope header: %w", err) + } + + if _, err := buf.Write(headerBytes); err != nil { + return nil, fmt.Errorf("failed to write envelope header: %w", err) + } + + if _, err := buf.WriteString("\n"); err != nil { + return nil, fmt.Errorf("failed to write newline after envelope header: %w", err) + } + + for _, item := range e.Items { + if err := e.writeItem(&buf, item); err != nil { + return nil, fmt.Errorf("failed to write envelope item: %w", err) + } + } + + return buf.Bytes(), nil +} + +// WriteTo writes the envelope to the given writer in the Sentry envelope format. +func (e *Envelope) WriteTo(w io.Writer) (int64, error) { + data, err := e.Serialize() + if err != nil { + return 0, err + } + + n, err := w.Write(data) + return int64(n), err +} + +// writeItem writes a single envelope item to the buffer. +func (e *Envelope) writeItem(buf *bytes.Buffer, item *EnvelopeItem) error { + headerBytes, err := json.Marshal(item.Header) + if err != nil { + return fmt.Errorf("failed to marshal item header: %w", err) + } + + if _, err := buf.Write(headerBytes); err != nil { + return fmt.Errorf("failed to write item header: %w", err) + } + + if _, err := buf.WriteString("\n"); err != nil { + return fmt.Errorf("failed to write newline after item header: %w", err) + } + + if len(item.Payload) > 0 { + if _, err := buf.Write(item.Payload); err != nil { + return fmt.Errorf("failed to write item payload: %w", err) + } + } + + if _, err := buf.WriteString("\n"); err != nil { + return fmt.Errorf("failed to write newline after item payload: %w", err) + } + + return nil +} + +// Size returns the total size of the envelope when serialized. +func (e *Envelope) Size() (int, error) { + data, err := e.Serialize() + if err != nil { + return 0, err + } + return len(data), nil +} + +// MarshalJSON converts the EnvelopeHeader to JSON. +func (h *EnvelopeHeader) MarshalJSON() ([]byte, error) { + type header EnvelopeHeader + return json.Marshal((*header)(h)) +} + +// NewEnvelopeItem creates a new envelope item with the specified type and payload. +func NewEnvelopeItem(itemType EnvelopeItemType, payload []byte) *EnvelopeItem { + length := len(payload) + return &EnvelopeItem{ + Header: &EnvelopeItemHeader{ + Type: itemType, + Length: &length, + }, + Payload: payload, + } +} + +// NewAttachmentItem creates a new envelope item for an attachment. +// Parameters: filename, contentType, payload. +func NewAttachmentItem(filename, contentType string, payload []byte) *EnvelopeItem { + length := len(payload) + return &EnvelopeItem{ + Header: &EnvelopeItemHeader{ + Type: EnvelopeItemTypeAttachment, + Length: &length, + ContentType: contentType, + Filename: filename, + }, + Payload: payload, + } +} + +// NewLogItem creates a new envelope item for logs. +func NewLogItem(itemCount int, payload []byte) *EnvelopeItem { + length := len(payload) + return &EnvelopeItem{ + Header: &EnvelopeItemHeader{ + Type: EnvelopeItemTypeLog, + Length: &length, + ItemCount: &itemCount, + ContentType: "application/vnd.sentry.items.log+json", + }, + Payload: payload, + } +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/interfaces.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/interfaces.go new file mode 100644 index 0000000..6f6f29a --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/interfaces.go @@ -0,0 +1,40 @@ +package protocol + +import ( + "context" + "time" + + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +// EnvelopeConvertible represents any type that can be converted to a Sentry envelope. +// This interface allows the telemetry buffers to be generic while still working with +// concrete types like Event. +type EnvelopeConvertible interface { + // ToEnvelope converts the item to a Sentry envelope. + ToEnvelope(dsn *Dsn) (*Envelope, error) +} + +// TelemetryTransport represents the envelope-first transport interface. +// This interface is designed for the telemetry buffer system and provides +// non-blocking sends with backpressure signals. +type TelemetryTransport interface { + // SendEnvelope sends an envelope to Sentry. Returns immediately with + // backpressure error if the queue is full. + SendEnvelope(envelope *Envelope) error + + // SendEvent sends an event to Sentry. + SendEvent(event EnvelopeConvertible) + + // IsRateLimited checks if a specific category is currently rate limited + IsRateLimited(category ratelimit.Category) bool + + // Flush waits for all pending envelopes to be sent, with timeout + Flush(timeout time.Duration) bool + + // FlushWithContext waits for all pending envelopes to be sent + FlushWithContext(ctx context.Context) bool + + // Close shuts down the transport gracefully + Close() +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/types.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/types.go new file mode 100644 index 0000000..5237c9e --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/types.go @@ -0,0 +1,15 @@ +package protocol + +// SdkInfo contains SDK metadata. +type SdkInfo struct { + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` + Integrations []string `json:"integrations,omitempty"` + Packages []SdkPackage `json:"packages,omitempty"` +} + +// SdkPackage describes a package that was installed. +type SdkPackage struct { + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go index 96d9e21..971cba7 100644 --- a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go +++ b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go @@ -57,3 +57,47 @@ func (c Category) String() string { return rv } } + +// Priority represents the importance level of a category for buffer management. +type Priority int + +const ( + PriorityCritical Priority = iota + 1 + PriorityHigh + PriorityMedium + PriorityLow + PriorityLowest +) + +func (p Priority) String() string { + switch p { + case PriorityCritical: + return "critical" + case PriorityHigh: + return "high" + case PriorityMedium: + return "medium" + case PriorityLow: + return "low" + case PriorityLowest: + return "lowest" + default: + return "unknown" + } +} + +// GetPriority returns the priority level for this category. +func (c Category) GetPriority() Priority { + switch c { + case CategoryError: + return PriorityCritical + case CategoryMonitor: + return PriorityHigh + case CategoryLog: + return PriorityMedium + case CategoryTransaction: + return PriorityLow + default: + return PriorityMedium + } +} diff --git a/vendor/github.com/getsentry/sentry-go/log.go b/vendor/github.com/getsentry/sentry-go/log.go index 609ffc8..58e52f7 100644 --- a/vendor/github.com/getsentry/sentry-go/log.go +++ b/vendor/github.com/getsentry/sentry-go/log.go @@ -10,6 +10,7 @@ import ( "time" "github.com/getsentry/sentry-go/attribute" + "github.com/getsentry/sentry-go/internal/debuglog" ) type LogLevel string @@ -74,7 +75,7 @@ func NewLogger(ctx context.Context) Logger { } } - DebugLogger.Println("fallback to noopLogger: enableLogs disabled") + debuglog.Println("fallback to noopLogger: enableLogs disabled") return &noopLogger{} // fallback: does nothing } @@ -89,20 +90,30 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me if message == "" { return } - hub := GetHubFromContext(ctx) - if hub == nil { - hub = CurrentHub() - } - var traceID TraceID var spanID SpanID var span *Span var user User + span = SpanFromContext(ctx) + if span == nil { + span = SpanFromContext(l.ctx) + } + hub := GetHubFromContext(ctx) + if hub == nil { + hub = GetHubFromContext(l.ctx) + } + if hub == nil { + hub = CurrentHub() + } + scope := hub.Scope() if scope != nil { scope.mu.Lock() - span = scope.span + // Use span from hub only as last resort + if span == nil { + span = scope.span + } if span != nil { traceID = span.TraceID spanID = span.SpanID @@ -187,7 +198,7 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me } if l.client.options.Debug { - DebugLogger.Printf(message, args...) + debuglog.Printf(message, args...) } } @@ -198,7 +209,7 @@ func (l *sentryLogger) SetAttributes(attrs ...attribute.Builder) { for _, v := range attrs { t, ok := mapTypesToStr[v.Value.Type()] if !ok || t == "" { - DebugLogger.Printf("invalid attribute type set: %v", t) + debuglog.Printf("invalid attribute type set: %v", t) continue } diff --git a/vendor/github.com/getsentry/sentry-go/log_fallback.go b/vendor/github.com/getsentry/sentry-go/log_fallback.go index 5dc058e..6e93319 100644 --- a/vendor/github.com/getsentry/sentry-go/log_fallback.go +++ b/vendor/github.com/getsentry/sentry-go/log_fallback.go @@ -6,6 +6,7 @@ import ( "os" "github.com/getsentry/sentry-go/attribute" + "github.com/getsentry/sentry-go/internal/debuglog" ) // Fallback, no-op logger if logging is disabled. @@ -46,7 +47,7 @@ func (n *noopLogEntry) Attributes(_ ...attribute.Builder) LogEntry { } func (n *noopLogEntry) Emit(args ...interface{}) { - DebugLogger.Printf("Log with level=[%v] is being dropped. Turn on logging via EnableLogs", n.level) + debuglog.Printf("Log with level=[%v] is being dropped. Turn on logging via EnableLogs", n.level) if n.level == LogLevelFatal { if n.shouldPanic { panic(args) @@ -56,7 +57,7 @@ func (n *noopLogEntry) Emit(args ...interface{}) { } func (n *noopLogEntry) Emitf(message string, args ...interface{}) { - DebugLogger.Printf("Log with level=[%v] is being dropped. Turn on logging via EnableLogs", n.level) + debuglog.Printf("Log with level=[%v] is being dropped. Turn on logging via EnableLogs", n.level) if n.level == LogLevelFatal { if n.shouldPanic { panic(fmt.Sprintf(message, args...)) @@ -96,7 +97,7 @@ func (*noopLogger) Panic() LogEntry { } func (*noopLogger) SetAttributes(...attribute.Builder) { - DebugLogger.Printf("No attributes attached. Turn on logging via EnableLogs") + debuglog.Printf("No attributes attached. Turn on logging via EnableLogs") } func (*noopLogger) Write(_ []byte) (n int, err error) { diff --git a/vendor/github.com/getsentry/sentry-go/scope.go b/vendor/github.com/getsentry/sentry-go/scope.go index 22f7f93..a0bf3f6 100644 --- a/vendor/github.com/getsentry/sentry-go/scope.go +++ b/vendor/github.com/getsentry/sentry-go/scope.go @@ -6,6 +6,8 @@ import ( "net/http" "sync" "time" + + "github.com/getsentry/sentry-go/internal/debuglog" ) // Scope holds contextual data for the current scope. @@ -472,7 +474,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) id := event.EventID event = processor(event, hint) if event == nil { - DebugLogger.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id) + debuglog.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id) return nil } } diff --git a/vendor/github.com/getsentry/sentry-go/sentry.go b/vendor/github.com/getsentry/sentry-go/sentry.go index 55309ed..b349944 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.35.3" +const SDKVersion = "0.36.2" // apiVersion is the minimum version of the Sentry API compatible with the // sentry-go SDK. diff --git a/vendor/github.com/getsentry/sentry-go/span_recorder.go b/vendor/github.com/getsentry/sentry-go/span_recorder.go index a2a7d19..ba04101 100644 --- a/vendor/github.com/getsentry/sentry-go/span_recorder.go +++ b/vendor/github.com/getsentry/sentry-go/span_recorder.go @@ -2,6 +2,8 @@ package sentry import ( "sync" + + "github.com/getsentry/sentry-go/internal/debuglog" ) // A spanRecorder stores a span tree that makes up a transaction. Safe for @@ -24,7 +26,7 @@ func (r *spanRecorder) record(s *Span) { if len(r.spans) >= maxSpans { r.overflowOnce.Do(func() { root := r.spans[0] - DebugLogger.Printf("Too many spans: dropping spans from transaction with TraceID=%s SpanID=%s limit=%d", + debuglog.Printf("Too many spans: dropping spans from transaction with TraceID=%s SpanID=%s limit=%d", root.TraceID, root.SpanID, maxSpans) }) // TODO(tracing): mark the transaction event in some way to diff --git a/vendor/github.com/getsentry/sentry-go/tracing.go b/vendor/github.com/getsentry/sentry-go/tracing.go index 993c207..1ab03d3 100644 --- a/vendor/github.com/getsentry/sentry-go/tracing.go +++ b/vendor/github.com/getsentry/sentry-go/tracing.go @@ -12,6 +12,8 @@ import ( "strings" "sync" "time" + + "github.com/getsentry/sentry-go/internal/debuglog" ) const ( @@ -347,6 +349,58 @@ func (s *Span) SetDynamicSamplingContext(dsc DynamicSamplingContext) { } } +// shouldIgnoreStatusCode checks if the transaction should be ignored based on HTTP status code. +func (s *Span) shouldIgnoreStatusCode() bool { + if !s.IsTransaction() { + return false + } + + ignoreStatusCodes := s.clientOptions().TraceIgnoreStatusCodes + if len(ignoreStatusCodes) == 0 { + return false + } + + s.mu.Lock() + statusCodeData, exists := s.Data["http.response.status_code"] + s.mu.Unlock() + + if !exists { + return false + } + + statusCode, ok := statusCodeData.(int) + if !ok { + return false + } + + for _, ignoredRange := range ignoreStatusCodes { + switch len(ignoredRange) { + case 1: + // Single status code + if statusCode == ignoredRange[0] { + s.mu.Lock() + s.Sampled = SampledFalse + s.mu.Unlock() + debuglog.Printf("dropping transaction with status code %v: found in TraceIgnoreStatusCodes", statusCode) + return true + } + case 2: + // Range of status codes [min, max] + if ignoredRange[0] <= statusCode && statusCode <= ignoredRange[1] { + s.mu.Lock() + s.Sampled = SampledFalse + s.mu.Unlock() + debuglog.Printf("dropping transaction with status code %v: found in TraceIgnoreStatusCodes range [%d, %d]", statusCode, ignoredRange[0], ignoredRange[1]) + return true + } + default: + debuglog.Printf("incorrect TraceIgnoreStatusCodes format: %v", ignoredRange) + } + } + + return false +} + // doFinish runs the actual Span.Finish() logic. func (s *Span) doFinish() { if s.EndTime.IsZero() { @@ -360,6 +414,10 @@ func (s *Span) doFinish() { } } + if s.shouldIgnoreStatusCode() { + return + } + if !s.Sampled.Bool() { return } @@ -449,14 +507,14 @@ func (s *Span) sample() Sampled { // https://develop.sentry.dev/sdk/performance/#sampling // #1 tracing is not enabled. if !clientOptions.EnableTracing { - DebugLogger.Printf("Dropping transaction: EnableTracing is set to %t", clientOptions.EnableTracing) + debuglog.Printf("Dropping transaction: EnableTracing is set to %t", clientOptions.EnableTracing) s.sampleRate = 0.0 return SampledFalse } // #2 explicit sampling decision via StartSpan/StartTransaction options. if s.explicitSampled != SampledUndefined { - DebugLogger.Printf("Using explicit sampling decision from StartSpan/StartTransaction: %v", s.explicitSampled) + debuglog.Printf("Using explicit sampling decision from StartSpan/StartTransaction: %v", s.explicitSampled) switch s.explicitSampled { case SampledTrue: s.sampleRate = 1.0 @@ -489,25 +547,25 @@ func (s *Span) sample() Sampled { s.dynamicSamplingContext.Entries["sample_rate"] = strconv.FormatFloat(tracesSamplerSampleRate, 'f', -1, 64) } if tracesSamplerSampleRate < 0.0 || tracesSamplerSampleRate > 1.0 { - DebugLogger.Printf("Dropping transaction: Returned TracesSampler rate is out of range [0.0, 1.0]: %f", tracesSamplerSampleRate) + debuglog.Printf("Dropping transaction: Returned TracesSampler rate is out of range [0.0, 1.0]: %f", tracesSamplerSampleRate) return SampledFalse } if tracesSamplerSampleRate == 0.0 { - DebugLogger.Printf("Dropping transaction: Returned TracesSampler rate is: %f", tracesSamplerSampleRate) + debuglog.Printf("Dropping transaction: Returned TracesSampler rate is: %f", tracesSamplerSampleRate) return SampledFalse } if rng.Float64() < tracesSamplerSampleRate { return SampledTrue } - DebugLogger.Printf("Dropping transaction: TracesSampler returned rate: %f", tracesSamplerSampleRate) + debuglog.Printf("Dropping transaction: TracesSampler returned rate: %f", tracesSamplerSampleRate) return SampledFalse } // #4 inherit parent decision. if s.Sampled != SampledUndefined { - DebugLogger.Printf("Using sampling decision from parent: %v", s.Sampled) + debuglog.Printf("Using sampling decision from parent: %v", s.Sampled) switch s.Sampled { case SampledTrue: s.sampleRate = 1.0 @@ -525,11 +583,11 @@ func (s *Span) sample() Sampled { s.dynamicSamplingContext.Entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) } if sampleRate < 0.0 || sampleRate > 1.0 { - DebugLogger.Printf("Dropping transaction: TracesSampleRate out of range [0.0, 1.0]: %f", sampleRate) + debuglog.Printf("Dropping transaction: TracesSampleRate out of range [0.0, 1.0]: %f", sampleRate) return SampledFalse } if sampleRate == 0.0 { - DebugLogger.Printf("Dropping transaction: TracesSampleRate rate is: %f", sampleRate) + debuglog.Printf("Dropping transaction: TracesSampleRate rate is: %f", sampleRate) return SampledFalse } @@ -552,7 +610,7 @@ func (s *Span) toEvent() *Event { finished := make([]*Span, 0, len(children)) for _, child := range children { if child.EndTime.IsZero() { - DebugLogger.Printf("Dropped unfinished span: Op=%q TraceID=%s SpanID=%s", child.Op, child.TraceID, child.SpanID) + debuglog.Printf("Dropped unfinished span: Op=%q TraceID=%s SpanID=%s", child.Op, child.TraceID, child.SpanID) continue } finished = append(finished, child) diff --git a/vendor/github.com/getsentry/sentry-go/transport.go b/vendor/github.com/getsentry/sentry-go/transport.go index aae5072..d57e155 100644 --- a/vendor/github.com/getsentry/sentry-go/transport.go +++ b/vendor/github.com/getsentry/sentry-go/transport.go @@ -13,6 +13,9 @@ import ( "sync" "time" + "github.com/getsentry/sentry-go/internal/debuglog" + httpinternal "github.com/getsentry/sentry-go/internal/http" + "github.com/getsentry/sentry-go/internal/protocol" "github.com/getsentry/sentry-go/internal/ratelimit" ) @@ -87,14 +90,14 @@ func getRequestBodyFromEvent(event *Event) []byte { } body, err = json.Marshal(event) if err == nil { - DebugLogger.Println(msg) + debuglog.Println(msg) return body } // This should _only_ happen when Event.Exception[0].Stacktrace.Frames[0].Vars is unserializable // Which won't ever happen, as we don't use it now (although it's the part of public interface accepted by Sentry) // Juuust in case something, somehow goes utterly wrong. - DebugLogger.Println("Event couldn't be marshaled, even with stripped contextual data. Skipping delivery. " + + debuglog.Println("Event couldn't be marshaled, even with stripped contextual data. Skipping delivery. " + "Please notify the SDK owners with possibly broken payload.") return nil } @@ -227,13 +230,13 @@ func getRequestFromEvent(ctx context.Context, event *Event, dsn *Dsn) (r *http.R r.Header.Set("Content-Type", "application/x-sentry-envelope") auth := fmt.Sprintf("Sentry sentry_version=%s, "+ - "sentry_client=%s/%s, sentry_key=%s", apiVersion, event.Sdk.Name, event.Sdk.Version, dsn.publicKey) + "sentry_client=%s/%s, sentry_key=%s", apiVersion, event.Sdk.Name, event.Sdk.Version, dsn.GetPublicKey()) // The key sentry_secret is effectively deprecated and no longer needs to be set. // However, since it was required in older self-hosted versions, // it should still passed through to Sentry if set. - if dsn.secretKey != "" { - auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey) + if dsn.GetSecretKey() != "" { + auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.GetSecretKey()) } r.Header.Set("X-Sentry-Auth", auth) @@ -321,7 +324,7 @@ func NewHTTPTransport() *HTTPTransport { func (t *HTTPTransport) Configure(options ClientOptions) { dsn, err := NewDsn(options.Dsn) if err != nil { - DebugLogger.Printf("%v\n", err) + debuglog.Printf("%v\n", err) return } t.dsn = dsn @@ -403,17 +406,17 @@ func (t *HTTPTransport) SendEventWithContext(ctx context.Context, event *Event) if event.Type == transactionType { eventType = "transaction" } else { - eventType = fmt.Sprintf("%s event", event.Level) + eventType = fmt.Sprintf("%s event", event.Type) } - DebugLogger.Printf( + debuglog.Printf( "Sending %s [%s] to %s project: %s", eventType, event.EventID, - t.dsn.host, - t.dsn.projectID, + t.dsn.GetHost(), + t.dsn.GetProjectID(), ) default: - DebugLogger.Println("Event dropped due to transport buffer being full.") + debuglog.Println("Event dropped due to transport buffer being full.") } t.buffer <- b @@ -477,14 +480,14 @@ started: // Wait until the current batch is done or the timeout. select { case <-b.done: - DebugLogger.Println("Buffer flushed successfully.") + debuglog.Println("Buffer flushed successfully.") return true case <-timeout: goto fail } fail: - DebugLogger.Println("Buffer flushing was canceled or timed out.") + debuglog.Println("Buffer flushing was canceled or timed out.") return false } @@ -524,15 +527,15 @@ func (t *HTTPTransport) worker() { response, err := t.client.Do(item.request) if err != nil { - DebugLogger.Printf("There was an issue with sending an event: %v", err) + debuglog.Printf("There was an issue with sending an event: %v", err) continue } if response.StatusCode >= 400 && response.StatusCode <= 599 { b, err := io.ReadAll(response.Body) if err != nil { - DebugLogger.Printf("Error while reading response code: %v", err) + debuglog.Printf("Error while reading response code: %v", err) } - DebugLogger.Printf("Sending %s failed with the following error: %s", eventType, string(b)) + debuglog.Printf("Sending %s failed with the following error: %s", eventType, string(b)) } t.mu.Lock() @@ -559,7 +562,7 @@ func (t *HTTPTransport) disabled(c ratelimit.Category) bool { defer t.mu.RUnlock() disabled := t.limits.IsRateLimited(c) if disabled { - DebugLogger.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) + debuglog.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) } return disabled } @@ -605,7 +608,7 @@ func NewHTTPSyncTransport() *HTTPSyncTransport { func (t *HTTPSyncTransport) Configure(options ClientOptions) { dsn, err := NewDsn(options.Dsn) if err != nil { - DebugLogger.Printf("%v\n", err) + debuglog.Printf("%v\n", err) return } t.dsn = dsn @@ -660,25 +663,25 @@ func (t *HTTPSyncTransport) SendEventWithContext(ctx context.Context, event *Eve default: eventIdentifier = fmt.Sprintf("%s event", event.Level) } - DebugLogger.Printf( + debuglog.Printf( "Sending %s [%s] to %s project: %s", eventIdentifier, event.EventID, - t.dsn.host, - t.dsn.projectID, + t.dsn.GetHost(), + t.dsn.GetProjectID(), ) response, err := t.client.Do(request) if err != nil { - DebugLogger.Printf("There was an issue with sending an event: %v", err) + debuglog.Printf("There was an issue with sending an event: %v", err) return } if response.StatusCode >= 400 && response.StatusCode <= 599 { b, err := io.ReadAll(response.Body) if err != nil { - DebugLogger.Printf("Error while reading response code: %v", err) + debuglog.Printf("Error while reading response code: %v", err) } - DebugLogger.Printf("Sending %s failed with the following error: %s", eventIdentifier, string(b)) + debuglog.Printf("Sending %s failed with the following error: %s", eventIdentifier, string(b)) } t.mu.Lock() @@ -710,7 +713,7 @@ func (t *HTTPSyncTransport) disabled(c ratelimit.Category) bool { defer t.mu.Unlock() disabled := t.limits.IsRateLimited(c) if disabled { - DebugLogger.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) + debuglog.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) } return disabled } @@ -726,11 +729,11 @@ type noopTransport struct{} var _ Transport = noopTransport{} func (noopTransport) Configure(ClientOptions) { - DebugLogger.Println("Sentry client initialized with an empty DSN. Using noopTransport. No events will be delivered.") + debuglog.Println("Sentry client initialized with an empty DSN. Using noopTransport. No events will be delivered.") } func (noopTransport) SendEvent(*Event) { - DebugLogger.Println("Event dropped due to noopTransport usage.") + debuglog.Println("Event dropped due to noopTransport usage.") } func (noopTransport) Flush(time.Duration) bool { @@ -742,3 +745,60 @@ func (noopTransport) FlushWithContext(context.Context) bool { } func (noopTransport) Close() {} + +// ================================ +// Internal Transport Adapters +// ================================ + +// newInternalAsyncTransport creates a new AsyncTransport from internal/http +// wrapped to satisfy the Transport interface. +// +// This is not yet exposed in the public API and is for internal experimentation. +func newInternalAsyncTransport() Transport { + return &internalAsyncTransportAdapter{} +} + +// internalAsyncTransportAdapter wraps the internal AsyncTransport to implement +// the root-level Transport interface. +type internalAsyncTransportAdapter struct { + transport protocol.TelemetryTransport + dsn *protocol.Dsn +} + +func (a *internalAsyncTransportAdapter) Configure(options ClientOptions) { + transportOptions := httpinternal.TransportOptions{ + Dsn: options.Dsn, + HTTPClient: options.HTTPClient, + HTTPTransport: options.HTTPTransport, + HTTPProxy: options.HTTPProxy, + HTTPSProxy: options.HTTPSProxy, + CaCerts: options.CaCerts, + } + + a.transport = httpinternal.NewAsyncTransport(transportOptions) + + if options.Dsn != "" { + dsn, err := protocol.NewDsn(options.Dsn) + if err != nil { + debuglog.Printf("Failed to parse DSN in adapter: %v\n", err) + } else { + a.dsn = dsn + } + } +} + +func (a *internalAsyncTransportAdapter) SendEvent(event *Event) { + a.transport.SendEvent(event) +} + +func (a *internalAsyncTransportAdapter) Flush(timeout time.Duration) bool { + return a.transport.Flush(timeout) +} + +func (a *internalAsyncTransportAdapter) FlushWithContext(ctx context.Context) bool { + return a.transport.FlushWithContext(ctx) +} + +func (a *internalAsyncTransportAdapter) Close() { + a.transport.Close() +} diff --git a/vendor/github.com/getsentry/sentry-go/util.go b/vendor/github.com/getsentry/sentry-go/util.go index 1dfb091..3a6a33c 100644 --- a/vendor/github.com/getsentry/sentry-go/util.go +++ b/vendor/github.com/getsentry/sentry-go/util.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/getsentry/sentry-go/internal/debuglog" exec "golang.org/x/sys/execabs" ) @@ -62,7 +63,7 @@ func defaultRelease() (release string) { } for _, e := range envs { if release = os.Getenv(e); release != "" { - DebugLogger.Printf("Using release from environment variable %s: %s", e, release) + debuglog.Printf("Using release from environment variable %s: %s", e, release) return release } } @@ -89,23 +90,23 @@ func defaultRelease() (release string) { if err, ok := err.(*exec.ExitError); ok && len(err.Stderr) > 0 { fmt.Fprintf(&s, ": %s", err.Stderr) } - DebugLogger.Print(s.String()) + debuglog.Print(s.String()) } else { release = strings.TrimSpace(string(b)) - DebugLogger.Printf("Using release from Git: %s", release) + debuglog.Printf("Using release from Git: %s", release) return release } } - DebugLogger.Print("Some Sentry features will not be available. See https://docs.sentry.io/product/releases/.") - DebugLogger.Print("To stop seeing this message, pass a Release to sentry.Init or set the SENTRY_RELEASE environment variable.") + debuglog.Print("Some Sentry features will not be available. See https://docs.sentry.io/product/releases/.") + debuglog.Print("To stop seeing this message, pass a Release to sentry.Init or set the SENTRY_RELEASE environment variable.") return "" } func revisionFromBuildInfo(info *debug.BuildInfo) string { for _, setting := range info.Settings { if setting.Key == "vcs.revision" && setting.Value != "" { - DebugLogger.Printf("Using release from debug info: %s", setting.Value) + debuglog.Printf("Using release from debug info: %s", setting.Value) return setting.Value } } diff --git a/vendor/github.com/go-playground/validator/v10/README.md b/vendor/github.com/go-playground/validator/v10/README.md index 28f7e15..cb5d419 100644 --- a/vendor/github.com/go-playground/validator/v10/README.md +++ b/vendor/github.com/go-playground/validator/v10/README.md @@ -106,8 +106,9 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | datauri | Data URL | | fqdn | Full Qualified Domain Name (FQDN) | | hostname | Hostname RFC 952 | -| hostname_port | HostPort | | hostname_rfc1123 | Hostname RFC 1123 | +| hostname_port | HostPort | +| port | Port number | | ip | Internet Protocol Address IP | | ip4_addr | Internet Protocol Address IPv4 | | ip6_addr | Internet Protocol Address IPv6 | @@ -124,7 +125,8 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | unix_addr | Unix domain socket end point Address | | uri | URI String | | url | URL String | -| http_url | HTTP URL String | +| http_url | HTTP(s) URL String | +| https_url | HTTPS-only URL String | | url_encoded | URL Encoded | | urn_rfc2141 | Urn RFC 2141 String | @@ -133,6 +135,7 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | Tag | Description | | - | - | | alpha | Alpha Only | +| alphaspace | Alpha Space | | alphanum | Alphanumeric | | alphanumunicode | Alphanumeric Unicode | | alphaunicode | Alpha Unicode | diff --git a/vendor/github.com/go-playground/validator/v10/baked_in.go b/vendor/github.com/go-playground/validator/v10/baked_in.go index c968ad4..8fd55e7 100644 --- a/vendor/github.com/go-playground/validator/v10/baked_in.go +++ b/vendor/github.com/go-playground/validator/v10/baked_in.go @@ -118,6 +118,7 @@ var ( "fieldcontains": fieldContains, "fieldexcludes": fieldExcludes, "alpha": isAlpha, + "alphaspace": isAlphaSpace, "alphanum": isAlphanum, "alphaunicode": isAlphaUnicode, "alphanumunicode": isAlphanumUnicode, @@ -134,6 +135,7 @@ var ( "email": isEmail, "url": isURL, "http_url": isHttpURL, + "https_url": isHttpsURL, "uri": isURI, "urn_rfc2141": isUrnRFC2141, // RFC 2141 "file": isFile, @@ -1513,6 +1515,29 @@ func isHttpURL(fl FieldLevel) bool { panic(fmt.Sprintf("Bad field type %s", field.Type())) } +// isHttpsURL is the validation function for validating if the current field's value is a valid HTTPS-only URL. +func isHttpsURL(fl FieldLevel) bool { + if !isURL(fl) { + return false + } + + field := fl.Field() + switch field.Kind() { + case reflect.String: + + s := strings.ToLower(field.String()) + + url, err := url.Parse(s) + if err != nil || url.Host == "" { + return false + } + + return url.Scheme == "https" + } + + panic(fmt.Sprintf("Bad field type %s", field.Type())) +} + // isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141. func isUrnRFC2141(fl FieldLevel) bool { field := fl.Field() @@ -1743,6 +1768,11 @@ func isAlphanumUnicode(fl FieldLevel) bool { return alphaUnicodeNumericRegex().MatchString(fl.Field().String()) } +// isAlphaSpace is the validation function for validating if the current field's value is a valid alpha value with spaces. +func isAlphaSpace(fl FieldLevel) bool { + return alphaSpaceRegex().MatchString(fl.Field().String()) +} + // isAlphaUnicode is the validation function for validating if the current field's value is a valid alpha unicode value. func isAlphaUnicode(fl FieldLevel) bool { return alphaUnicodeRegex().MatchString(fl.Field().String()) @@ -1872,6 +1902,15 @@ func requiredIf(fl FieldLevel) bool { if len(params)%2 != 0 { panic(fmt.Sprintf("Bad param number for required_if %s", fl.FieldName())) } + + seen := make(map[string]struct{}) + for i := 0; i < len(params); i += 2 { + if _, ok := seen[params[i]]; ok { + panic(fmt.Sprintf("Duplicate param %s for required_if %s", params[i], fl.FieldName())) + } + seen[params[i]] = struct{}{} + } + for i := 0; i < len(params); i += 2 { if !requireCheckFieldValue(fl, params[i], params[i+1], false) { return true diff --git a/vendor/github.com/go-playground/validator/v10/doc.go b/vendor/github.com/go-playground/validator/v10/doc.go index 23cce99..52918e4 100644 --- a/vendor/github.com/go-playground/validator/v10/doc.go +++ b/vendor/github.com/go-playground/validator/v10/doc.go @@ -264,6 +264,7 @@ The field under validation must be present and not empty only if all the other specified fields are equal to the value following the specified field. For strings ensures value is not "". For slices, maps, pointers, interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value. +Using the same field name multiple times in the parameters will result in a panic at runtime. Usage: required_if @@ -776,6 +777,12 @@ This validates that a string value contains ASCII alpha characters only Usage: alpha +# Alpha Space + +This validates that a string value contains ASCII alpha characters and spaces only + + Usage: alphaspace + # Alphanumeric This validates that a string value contains ASCII alphanumeric characters only @@ -1330,6 +1337,12 @@ can be used to validate fields typically passed to sockets and connections. Usage: hostname_port +# Port + +This validates that the value falls within the valid port number range of 1 to 65,535. + + Usage: port + # Datetime This validates that a string value is a valid datetime based on the supplied datetime format. diff --git a/vendor/github.com/go-playground/validator/v10/regexes.go b/vendor/github.com/go-playground/validator/v10/regexes.go index 93909b2..0b3615f 100644 --- a/vendor/github.com/go-playground/validator/v10/regexes.go +++ b/vendor/github.com/go-playground/validator/v10/regexes.go @@ -7,6 +7,7 @@ import ( const ( alphaRegexString = "^[a-zA-Z]+$" + alphaSpaceRegexString = "^[a-zA-Z ]+$" alphaNumericRegexString = "^[a-zA-Z0-9]+$" alphaUnicodeRegexString = "^[\\p{L}]+$" alphaUnicodeNumericRegexString = "^[\\p{L}\\p{N}]+$" @@ -93,6 +94,7 @@ func lazyRegexCompile(str string) func() *regexp.Regexp { var ( alphaRegex = lazyRegexCompile(alphaRegexString) + alphaSpaceRegex = lazyRegexCompile(alphaSpaceRegexString) alphaNumericRegex = lazyRegexCompile(alphaNumericRegexString) alphaUnicodeRegex = lazyRegexCompile(alphaUnicodeRegexString) alphaUnicodeNumericRegex = lazyRegexCompile(alphaUnicodeNumericRegexString) diff --git a/vendor/github.com/go-playground/validator/v10/validator_instance.go b/vendor/github.com/go-playground/validator/v10/validator_instance.go index 9362cd7..5ba64e5 100644 --- a/vendor/github.com/go-playground/validator/v10/validator_instance.go +++ b/vendor/github.com/go-playground/validator/v10/validator_instance.go @@ -181,7 +181,7 @@ func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{ errs[field] = errors.New("The field: '" + field + "' is not a map to dive") } } else if ruleStr, ok := rule.(string); ok { - err := v.VarCtx(ctx, data[field], ruleStr) + err := v.VarWithKeyCtx(ctx, field, data[field], ruleStr) if err != nil { errs[field] = err } @@ -681,6 +681,64 @@ func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other return } +// VarWithKey validates a single variable with a key to be included in the returned error using tag style validation +// eg. +// var s string +// validate.VarWithKey("email_address", s, "required,email") +// +// WARNING: a struct can be passed for validation eg. time.Time is a struct or +// if you have a custom type and have registered a custom type handler, so must +// allow it; however unforeseen validations will occur if trying to validate a +// struct that is meant to be passed to 'validate.Struct' +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +// validate Array, Slice and maps fields which may contain more than one error +func (v *Validate) VarWithKey(key string, field interface{}, tag string) error { + return v.VarWithKeyCtx(context.Background(), key, field, tag) +} + +// VarWithKeyCtx validates a single variable with a key to be included in the returned error using tag style validation +// and allows passing of contextual validation information via context.Context. +// eg. +// var s string +// validate.VarWithKeyCtx("email_address", s, "required,email") +// +// WARNING: a struct can be passed for validation eg. time.Time is a struct or +// if you have a custom type and have registered a custom type handler, so must +// allow it; however unforeseen validations will occur if trying to validate a +// struct that is meant to be passed to 'validate.Struct' +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +// validate Array, Slice and maps fields which may contain more than one error +func (v *Validate) VarWithKeyCtx(ctx context.Context, key string, field interface{}, tag string) (err error) { + if len(tag) == 0 || tag == skipValidationTag { + return nil + } + + ctag := v.fetchCacheTag(tag) + + cField := &cField{ + name: key, + altName: key, + namesEqual: true, + } + + val := reflect.ValueOf(field) + vd := v.pool.Get().(*validate) + vd.top = val + vd.isPartial = false + vd.traverseField(ctx, val, val, vd.ns[0:0], vd.actualNs[0:0], cField, ctag) + + if len(vd.errs) > 0 { + err = vd.errs + vd.errs = nil + } + v.pool.Put(vd) + return +} + func (v *Validate) registerValidation(tag string, fn FuncCtx, bakedIn bool, nilCheckable bool) error { if len(tag) == 0 { return errors.New("function Key cannot be empty") diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go index 7b76237..8f8dc65 100644 --- a/vendor/github.com/prometheus/common/expfmt/decode.go +++ b/vendor/github.com/prometheus/common/expfmt/decode.go @@ -220,7 +220,7 @@ func extractSamples(f *dto.MetricFamily, o *DecodeOptions) (model.Vector, error) return extractSummary(o, f), nil case dto.MetricType_UNTYPED: return extractUntyped(o, f), nil - case dto.MetricType_HISTOGRAM: + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: return extractHistogram(o, f), nil } return nil, fmt.Errorf("expfmt.extractSamples: unknown metric family type %v", f.GetType()) @@ -403,9 +403,13 @@ func extractHistogram(o *DecodeOptions, f *dto.MetricFamily) model.Vector { infSeen = true } + v := q.GetCumulativeCountFloat() + if v <= 0 { + v = float64(q.GetCumulativeCount()) + } samples = append(samples, &model.Sample{ Metric: model.Metric(lset), - Value: model.SampleValue(q.GetCumulativeCount()), + Value: model.SampleValue(v), Timestamp: timestamp, }) } @@ -428,9 +432,13 @@ func extractHistogram(o *DecodeOptions, f *dto.MetricFamily) model.Vector { } lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_count") + v := m.Histogram.GetSampleCountFloat() + if v <= 0 { + v = float64(m.Histogram.GetSampleCount()) + } count := &model.Sample{ Metric: model.Metric(lset), - Value: model.SampleValue(m.Histogram.GetSampleCount()), + Value: model.SampleValue(v), Timestamp: timestamp, } samples = append(samples, count) diff --git a/vendor/github.com/prometheus/common/expfmt/openmetrics_create.go b/vendor/github.com/prometheus/common/expfmt/openmetrics_create.go index 8dbf6d0..21b93bc 100644 --- a/vendor/github.com/prometheus/common/expfmt/openmetrics_create.go +++ b/vendor/github.com/prometheus/common/expfmt/openmetrics_create.go @@ -160,38 +160,38 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E n, err = w.WriteString("# HELP ") written += n if err != nil { - return + return written, err } n, err = writeName(w, compliantName) written += n if err != nil { - return + return written, err } err = w.WriteByte(' ') written++ if err != nil { - return + return written, err } n, err = writeEscapedString(w, *in.Help, true) written += n if err != nil { - return + return written, err } err = w.WriteByte('\n') written++ if err != nil { - return + return written, err } } n, err = w.WriteString("# TYPE ") written += n if err != nil { - return + return written, err } n, err = writeName(w, compliantName) written += n if err != nil { - return + return written, err } switch metricType { case dto.MetricType_COUNTER: @@ -208,39 +208,41 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E n, err = w.WriteString(" unknown\n") case dto.MetricType_HISTOGRAM: n, err = w.WriteString(" histogram\n") + case dto.MetricType_GAUGE_HISTOGRAM: + n, err = w.WriteString(" gaugehistogram\n") default: return written, fmt.Errorf("unknown metric type %s", metricType.String()) } written += n if err != nil { - return + return written, err } if toOM.withUnit && in.Unit != nil { n, err = w.WriteString("# UNIT ") written += n if err != nil { - return + return written, err } n, err = writeName(w, compliantName) written += n if err != nil { - return + return written, err } err = w.WriteByte(' ') written++ if err != nil { - return + return written, err } n, err = writeEscapedString(w, *in.Unit, true) written += n if err != nil { - return + return written, err } err = w.WriteByte('\n') written++ if err != nil { - return + return written, err } } @@ -304,7 +306,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E ) written += n if err != nil { - return + return written, err } } n, err = writeOpenMetricsSample( @@ -314,7 +316,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E ) written += n if err != nil { - return + return written, err } n, err = writeOpenMetricsSample( w, compliantName, "_count", metric, "", 0, @@ -325,7 +327,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E createdTsBytesWritten, err = writeOpenMetricsCreated(w, compliantName, "", metric, "", 0, metric.Summary.GetCreatedTimestamp()) n += createdTsBytesWritten } - case dto.MetricType_HISTOGRAM: + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: if metric.Histogram == nil { return written, fmt.Errorf( "expected histogram in metric %s %s", compliantName, metric, @@ -333,6 +335,12 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E } infSeen := false for _, b := range metric.Histogram.Bucket { + if b.GetCumulativeCountFloat() > 0 { + return written, fmt.Errorf( + "OpenMetrics v1.0 does not support float histogram %s %s", + compliantName, metric, + ) + } n, err = writeOpenMetricsSample( w, compliantName, "_bucket", metric, model.BucketLabel, b.GetUpperBound(), @@ -341,7 +349,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E ) written += n if err != nil { - return + return written, err } if math.IsInf(b.GetUpperBound(), +1) { infSeen = true @@ -354,9 +362,12 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E 0, metric.Histogram.GetSampleCount(), true, nil, ) + // We do not check for a float sample count here + // because we will check for it below (and error + // out if needed). written += n if err != nil { - return + return written, err } } n, err = writeOpenMetricsSample( @@ -366,7 +377,13 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E ) written += n if err != nil { - return + return written, err + } + if metric.Histogram.GetSampleCountFloat() > 0 { + return written, fmt.Errorf( + "OpenMetrics v1.0 does not support float histogram %s %s", + compliantName, metric, + ) } n, err = writeOpenMetricsSample( w, compliantName, "_count", metric, "", 0, @@ -384,10 +401,10 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E } written += n if err != nil { - return + return written, err } } - return + return written, err } // FinalizeOpenMetrics writes the final `# EOF\n` line required by OpenMetrics. diff --git a/vendor/github.com/prometheus/common/expfmt/text_create.go b/vendor/github.com/prometheus/common/expfmt/text_create.go index c4e9c1b..6b89781 100644 --- a/vendor/github.com/prometheus/common/expfmt/text_create.go +++ b/vendor/github.com/prometheus/common/expfmt/text_create.go @@ -108,38 +108,38 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e n, err = w.WriteString("# HELP ") written += n if err != nil { - return + return written, err } n, err = writeName(w, name) written += n if err != nil { - return + return written, err } err = w.WriteByte(' ') written++ if err != nil { - return + return written, err } n, err = writeEscapedString(w, *in.Help, false) written += n if err != nil { - return + return written, err } err = w.WriteByte('\n') written++ if err != nil { - return + return written, err } } n, err = w.WriteString("# TYPE ") written += n if err != nil { - return + return written, err } n, err = writeName(w, name) written += n if err != nil { - return + return written, err } metricType := in.GetType() switch metricType { @@ -151,14 +151,17 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e n, err = w.WriteString(" summary\n") case dto.MetricType_UNTYPED: n, err = w.WriteString(" untyped\n") - case dto.MetricType_HISTOGRAM: + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: + // The classic Prometheus text format has no notion of a gauge + // histogram. We render a gauge histogram in the same way as a + // regular histogram. n, err = w.WriteString(" histogram\n") default: return written, fmt.Errorf("unknown metric type %s", metricType.String()) } written += n if err != nil { - return + return written, err } // Finally the samples, one line for each. @@ -208,7 +211,7 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e ) written += n if err != nil { - return + return written, err } } n, err = writeSample( @@ -217,13 +220,13 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e ) written += n if err != nil { - return + return written, err } n, err = writeSample( w, name, "_count", metric, "", 0, float64(metric.Summary.GetSampleCount()), ) - case dto.MetricType_HISTOGRAM: + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: if metric.Histogram == nil { return written, fmt.Errorf( "expected histogram in metric %s %s", name, metric, @@ -231,28 +234,36 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e } infSeen := false for _, b := range metric.Histogram.Bucket { + v := b.GetCumulativeCountFloat() + if v == 0 { + v = float64(b.GetCumulativeCount()) + } n, err = writeSample( w, name, "_bucket", metric, model.BucketLabel, b.GetUpperBound(), - float64(b.GetCumulativeCount()), + v, ) written += n if err != nil { - return + return written, err } if math.IsInf(b.GetUpperBound(), +1) { infSeen = true } } if !infSeen { + v := metric.Histogram.GetSampleCountFloat() + if v == 0 { + v = float64(metric.Histogram.GetSampleCount()) + } n, err = writeSample( w, name, "_bucket", metric, model.BucketLabel, math.Inf(+1), - float64(metric.Histogram.GetSampleCount()), + v, ) written += n if err != nil { - return + return written, err } } n, err = writeSample( @@ -261,12 +272,13 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e ) written += n if err != nil { - return + return written, err } - n, err = writeSample( - w, name, "_count", metric, "", 0, - float64(metric.Histogram.GetSampleCount()), - ) + v := metric.Histogram.GetSampleCountFloat() + if v == 0 { + v = float64(metric.Histogram.GetSampleCount()) + } + n, err = writeSample(w, name, "_count", metric, "", 0, v) default: return written, fmt.Errorf( "unexpected type in metric %s %s", name, metric, @@ -274,10 +286,10 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e } written += n if err != nil { - return + return written, err } } - return + return written, err } // writeSample writes a single sample in text format to w, given the metric diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go index 8f2edde..00c8841 100644 --- a/vendor/github.com/prometheus/common/expfmt/text_parse.go +++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go @@ -48,8 +48,10 @@ func (e ParseError) Error() string { return fmt.Sprintf("text format parsing error in line %d: %s", e.Line, e.Msg) } -// TextParser is used to parse the simple and flat text-based exchange format. Its -// zero value is ready to use. +// TextParser is used to parse the simple and flat text-based exchange format. +// +// TextParser instances must be created with NewTextParser, the zero value of +// TextParser is invalid. type TextParser struct { metricFamiliesByName map[string]*dto.MetricFamily buf *bufio.Reader // Where the parsed input is read through. @@ -129,9 +131,44 @@ func (p *TextParser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricF if p.err != nil && errors.Is(p.err, io.EOF) { p.parseError("unexpected end of input stream") } + for _, histogramMetric := range p.histograms { + normalizeHistogram(histogramMetric.GetHistogram()) + } return p.metricFamiliesByName, p.err } +// normalizeHistogram makes sure that all the buckets and the count in each +// histogram is either completely float or completely integer. +func normalizeHistogram(histogram *dto.Histogram) { + if histogram == nil { + return + } + anyFloats := false + if histogram.GetSampleCountFloat() != 0 { + anyFloats = true + } else { + for _, b := range histogram.GetBucket() { + if b.GetCumulativeCountFloat() != 0 { + anyFloats = true + break + } + } + } + if !anyFloats { + return + } + if histogram.GetSampleCountFloat() == 0 { + histogram.SampleCountFloat = proto.Float64(float64(histogram.GetSampleCount())) + histogram.SampleCount = nil + } + for _, b := range histogram.GetBucket() { + if b.GetCumulativeCountFloat() == 0 { + b.CumulativeCountFloat = proto.Float64(float64(b.GetCumulativeCount())) + b.CumulativeCount = nil + } + } +} + func (p *TextParser) reset(in io.Reader) { p.metricFamiliesByName = map[string]*dto.MetricFamily{} p.currentLabelPairs = nil @@ -281,7 +318,9 @@ func (p *TextParser) readingLabels() stateFn { // Summaries/histograms are special. We have to reset the // currentLabels map, currentQuantile and currentBucket before starting to // read labels. - if p.currentMF.GetType() == dto.MetricType_SUMMARY || p.currentMF.GetType() == dto.MetricType_HISTOGRAM { + if p.currentMF.GetType() == dto.MetricType_SUMMARY || + p.currentMF.GetType() == dto.MetricType_HISTOGRAM || + p.currentMF.GetType() == dto.MetricType_GAUGE_HISTOGRAM { p.currentLabels = map[string]string{} p.currentLabels[string(model.MetricNameLabel)] = p.currentMF.GetName() p.currentQuantile = math.NaN() @@ -374,7 +413,9 @@ func (p *TextParser) startLabelName() stateFn { // Special summary/histogram treatment. Don't add 'quantile' and 'le' // labels to 'real' labels. if (p.currentMF.GetType() != dto.MetricType_SUMMARY || p.currentLabelPair.GetName() != model.QuantileLabel) && - (p.currentMF.GetType() != dto.MetricType_HISTOGRAM || p.currentLabelPair.GetName() != model.BucketLabel) { + ((p.currentMF.GetType() != dto.MetricType_HISTOGRAM && + p.currentMF.GetType() != dto.MetricType_GAUGE_HISTOGRAM) || + p.currentLabelPair.GetName() != model.BucketLabel) { p.currentLabelPairs = append(p.currentLabelPairs, p.currentLabelPair) } // Check for duplicate label names. @@ -425,7 +466,7 @@ func (p *TextParser) startLabelValue() stateFn { } } // Similar special treatment of histograms. - if p.currentMF.GetType() == dto.MetricType_HISTOGRAM { + if p.currentMF.GetType() == dto.MetricType_HISTOGRAM || p.currentMF.GetType() == dto.MetricType_GAUGE_HISTOGRAM { if p.currentLabelPair.GetName() == model.BucketLabel { if p.currentBucket, p.err = parseFloat(p.currentLabelPair.GetValue()); p.err != nil { // Create a more helpful error message. @@ -476,7 +517,7 @@ func (p *TextParser) readingValue() stateFn { p.summaries[signature] = p.currentMetric p.currentMF.Metric = append(p.currentMF.Metric, p.currentMetric) } - case dto.MetricType_HISTOGRAM: + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: signature := model.LabelsToSignature(p.currentLabels) if histogram := p.histograms[signature]; histogram != nil { p.currentMetric = histogram @@ -522,24 +563,38 @@ func (p *TextParser) readingValue() stateFn { }, ) } - case dto.MetricType_HISTOGRAM: + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: // *sigh* if p.currentMetric.Histogram == nil { p.currentMetric.Histogram = &dto.Histogram{} } switch { case p.currentIsHistogramCount: - p.currentMetric.Histogram.SampleCount = proto.Uint64(uint64(value)) + if uintValue := uint64(value); value == float64(uintValue) { + p.currentMetric.Histogram.SampleCount = proto.Uint64(uintValue) + } else { + if value < 0 { + p.parseError(fmt.Sprintf("negative count for histogram %q", p.currentMF.GetName())) + return nil + } + p.currentMetric.Histogram.SampleCountFloat = proto.Float64(value) + } case p.currentIsHistogramSum: p.currentMetric.Histogram.SampleSum = proto.Float64(value) case !math.IsNaN(p.currentBucket): - p.currentMetric.Histogram.Bucket = append( - p.currentMetric.Histogram.Bucket, - &dto.Bucket{ - UpperBound: proto.Float64(p.currentBucket), - CumulativeCount: proto.Uint64(uint64(value)), - }, - ) + b := &dto.Bucket{ + UpperBound: proto.Float64(p.currentBucket), + } + if uintValue := uint64(value); value == float64(uintValue) { + b.CumulativeCount = proto.Uint64(uintValue) + } else { + if value < 0 { + p.parseError(fmt.Sprintf("negative bucket population for histogram %q", p.currentMF.GetName())) + return nil + } + b.CumulativeCountFloat = proto.Float64(value) + } + p.currentMetric.Histogram.Bucket = append(p.currentMetric.Histogram.Bucket, b) } default: p.err = fmt.Errorf("unexpected type for metric name %q", p.currentMF.GetName()) @@ -602,10 +657,18 @@ func (p *TextParser) readingType() stateFn { if p.readTokenUntilNewline(false); p.err != nil { return nil // Unexpected end of input. } - metricType, ok := dto.MetricType_value[strings.ToUpper(p.currentToken.String())] + typ := strings.ToUpper(p.currentToken.String()) // Tolerate any combination of upper and lower case. + metricType, ok := dto.MetricType_value[typ] // Tolerate "gauge_histogram" (not originally part of the text format). if !ok { - p.parseError(fmt.Sprintf("unknown metric type %q", p.currentToken.String())) - return nil + // We also want to tolerate "gaugehistogram" to mark a gauge + // histogram, because that string is used in OpenMetrics. Note, + // however, that gauge histograms do not officially exist in the + // classic text format. + if typ != "GAUGEHISTOGRAM" { + p.parseError(fmt.Sprintf("unknown metric type %q", p.currentToken.String())) + return nil + } + metricType = int32(dto.MetricType_GAUGE_HISTOGRAM) } p.currentMF.Type = dto.MetricType(metricType).Enum() return p.startOfLine @@ -855,7 +918,8 @@ func (p *TextParser) setOrCreateCurrentMF() { } histogramName := histogramMetricName(name) if p.currentMF = p.metricFamiliesByName[histogramName]; p.currentMF != nil { - if p.currentMF.GetType() == dto.MetricType_HISTOGRAM { + if p.currentMF.GetType() == dto.MetricType_HISTOGRAM || + p.currentMF.GetType() == dto.MetricType_GAUGE_HISTOGRAM { if isCount(name) { p.currentIsHistogramCount = true } diff --git a/vendor/github.com/prometheus/procfs/.golangci.yml b/vendor/github.com/prometheus/procfs/.golangci.yml index 3c3bf91..23ecd45 100644 --- a/vendor/github.com/prometheus/procfs/.golangci.yml +++ b/vendor/github.com/prometheus/procfs/.golangci.yml @@ -1,7 +1,9 @@ version: "2" linters: enable: + - errorlint - forbidigo + - gocritic - godot - misspell - revive @@ -11,6 +13,20 @@ linters: forbid: - pattern: ^fmt\.Print.*$ msg: Do not commit print statements. + gocritic: + enable-all: true + disabled-checks: + - commentFormatting + - commentedOutCode + - deferInLoop + - filepathJoin + - hugeParam + - importShadow + - paramTypeCombine + - rangeValCopy + - tooManyResultsChecker + - unnamedResult + - whyNoLint godot: exclude: # Ignore "See: URL". @@ -19,16 +35,12 @@ linters: misspell: locale: US exclusions: - generated: lax presets: - comments - common-false-positives - legacy - std-error-handling - paths: - - third_party$ - - builtin$ - - examples$ + warn-unused: true formatters: enable: - gofmt @@ -37,9 +49,3 @@ formatters: goimports: local-prefixes: - github.com/prometheus/procfs - exclusions: - generated: lax - paths: - - third_party$ - - builtin$ - - examples$ diff --git a/vendor/github.com/prometheus/procfs/Makefile b/vendor/github.com/prometheus/procfs/Makefile index 7edfe4d..bce50a1 100644 --- a/vendor/github.com/prometheus/procfs/Makefile +++ b/vendor/github.com/prometheus/procfs/Makefile @@ -1,4 +1,4 @@ -# Copyright 2018 The Prometheus Authors +# Copyright The Prometheus Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/Makefile.common b/vendor/github.com/prometheus/procfs/Makefile.common index 4de2151..6f61bec 100644 --- a/vendor/github.com/prometheus/procfs/Makefile.common +++ b/vendor/github.com/prometheus/procfs/Makefile.common @@ -139,7 +139,7 @@ common-deps: update-go-deps: @echo ">> updating Go dependencies" @for m in $$($(GO) list -mod=readonly -m -f '{{ if and (not .Indirect) (not .Main)}}{{.Path}}{{end}}' all); do \ - $(GO) get -d $$m; \ + $(GO) get $$m; \ done $(GO) mod tidy diff --git a/vendor/github.com/prometheus/procfs/arp.go b/vendor/github.com/prometheus/procfs/arp.go index 2e53344..716bdef 100644 --- a/vendor/github.com/prometheus/procfs/arp.go +++ b/vendor/github.com/prometheus/procfs/arp.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -73,15 +73,16 @@ func parseARPEntries(data []byte) ([]ARPEntry, error) { columns := strings.Fields(line) width := len(columns) - if width == expectedHeaderWidth || width == 0 { + switch width { + case expectedHeaderWidth, 0: continue - } else if width == expectedDataWidth { + case expectedDataWidth: entry, err := parseARPEntry(columns) if err != nil { return []ARPEntry{}, fmt.Errorf("%w: Failed to parse ARP entry: %v: %w", ErrFileParse, entry, err) } entries = append(entries, entry) - } else { + default: return []ARPEntry{}, fmt.Errorf("%w: %d columns found, but expected %d: %w", ErrFileParse, width, expectedDataWidth, err) } diff --git a/vendor/github.com/prometheus/procfs/buddyinfo.go b/vendor/github.com/prometheus/procfs/buddyinfo.go index 8380750..53243e6 100644 --- a/vendor/github.com/prometheus/procfs/buddyinfo.go +++ b/vendor/github.com/prometheus/procfs/buddyinfo.go @@ -1,4 +1,4 @@ -// Copyright 2017 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -64,14 +64,12 @@ func parseBuddyInfo(r io.Reader) ([]BuddyInfo, error) { if bucketCount == -1 { bucketCount = arraySize - } else { - if bucketCount != arraySize { - return nil, fmt.Errorf("%w: mismatch in number of buddyinfo buckets, previous count %d, new count %d", ErrFileParse, bucketCount, arraySize) - } + } else if bucketCount != arraySize { + return nil, fmt.Errorf("%w: mismatch in number of buddyinfo buckets, previous count %d, new count %d", ErrFileParse, bucketCount, arraySize) } sizes := make([]float64, arraySize) - for i := 0; i < arraySize; i++ { + for i := range arraySize { sizes[i], err = strconv.ParseFloat(parts[i+4], 64) if err != nil { return nil, fmt.Errorf("%w: Invalid valid in buddyinfo: %f: %w", ErrFileParse, sizes[i], err) diff --git a/vendor/github.com/prometheus/procfs/cmdline.go b/vendor/github.com/prometheus/procfs/cmdline.go index bf4f3b4..4f1cac1 100644 --- a/vendor/github.com/prometheus/procfs/cmdline.go +++ b/vendor/github.com/prometheus/procfs/cmdline.go @@ -1,4 +1,4 @@ -// Copyright 2021 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/cpuinfo.go b/vendor/github.com/prometheus/procfs/cpuinfo.go index f0950bb..5fe6cec 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_armx.go b/vendor/github.com/prometheus/procfs/cpuinfo_armx.go index 64cfd53..8f15555 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_armx.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_armx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go b/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go index d88442f..e81a5db 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go b/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go index c11207f..4be2b1c 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_others.go b/vendor/github.com/prometheus/procfs/cpuinfo_others.go index a6b2b31..e713bae 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_others.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_others.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go b/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go index 003bc2a..0825aa1 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go b/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go index 1c9b731..496770b 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go b/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go index fa3686b..b3228ce 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_x86.go b/vendor/github.com/prometheus/procfs/cpuinfo_x86.go index a0ef555..575eb02 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_x86.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_x86.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/crypto.go b/vendor/github.com/prometheus/procfs/crypto.go index 5f2a37a..e4a5876 100644 --- a/vendor/github.com/prometheus/procfs/crypto.go +++ b/vendor/github.com/prometheus/procfs/crypto.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/doc.go b/vendor/github.com/prometheus/procfs/doc.go index f9d961e..26bfea0 100644 --- a/vendor/github.com/prometheus/procfs/doc.go +++ b/vendor/github.com/prometheus/procfs/doc.go @@ -1,4 +1,4 @@ -// Copyright 2014 Prometheus Team +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/fs.go b/vendor/github.com/prometheus/procfs/fs.go index 9bdaccc..8f27912 100644 --- a/vendor/github.com/prometheus/procfs/fs.go +++ b/vendor/github.com/prometheus/procfs/fs.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go index 1b5bdbd..3c53023 100644 --- a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go +++ b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_type.go b/vendor/github.com/prometheus/procfs/fs_statfs_type.go index 80df79c..80fce48 100644 --- a/vendor/github.com/prometheus/procfs/fs_statfs_type.go +++ b/vendor/github.com/prometheus/procfs/fs_statfs_type.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/fscache.go b/vendor/github.com/prometheus/procfs/fscache.go index 7db8633..9dde857 100644 --- a/vendor/github.com/prometheus/procfs/fscache.go +++ b/vendor/github.com/prometheus/procfs/fscache.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -388,20 +388,21 @@ func parseFscacheinfo(r io.Reader) (*Fscacheinfo, error) { } } case "CacheOp:": - if strings.Split(fields[1], "=")[0] == "alo" { + switch strings.Split(fields[1], "=")[0] { + case "alo": err := setFSCacheFields(fields[1:], &m.CacheopAllocationsinProgress, &m.CacheopLookupObjectInProgress, &m.CacheopLookupCompleteInPorgress, &m.CacheopGrabObjectInProgress) if err != nil { return &m, err } - } else if strings.Split(fields[1], "=")[0] == "inv" { + case "inv": err := setFSCacheFields(fields[1:], &m.CacheopInvalidations, &m.CacheopUpdateObjectInProgress, &m.CacheopDropObjectInProgress, &m.CacheopPutObjectInProgress, &m.CacheopAttributeChangeInProgress, &m.CacheopSyncCacheInProgress) if err != nil { return &m, err } - } else { + default: err := setFSCacheFields(fields[1:], &m.CacheopReadOrAllocPageInProgress, &m.CacheopReadOrAllocPagesInProgress, &m.CacheopAllocatePageInProgress, &m.CacheopAllocatePagesInProgress, &m.CacheopWritePagesInProgress, &m.CacheopUncachePagesInProgress, &m.CacheopDissociatePagesInProgress) diff --git a/vendor/github.com/prometheus/procfs/internal/fs/fs.go b/vendor/github.com/prometheus/procfs/internal/fs/fs.go index 3a43e83..e7ccad6 100644 --- a/vendor/github.com/prometheus/procfs/internal/fs/fs.go +++ b/vendor/github.com/prometheus/procfs/internal/fs/fs.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/internal/util/parse.go b/vendor/github.com/prometheus/procfs/internal/util/parse.go index 5a7d2df..30c5872 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/parse.go +++ b/vendor/github.com/prometheus/procfs/internal/util/parse.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/internal/util/readfile.go b/vendor/github.com/prometheus/procfs/internal/util/readfile.go index 71b7a70..0e41f71 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/readfile.go +++ b/vendor/github.com/prometheus/procfs/internal/util/readfile.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go index d5404a6..8318d8d 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go +++ b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go index 1d86f5e..15bb096 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go +++ b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go b/vendor/github.com/prometheus/procfs/internal/util/valueparser.go index fe2355d..e0ed671 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go +++ b/vendor/github.com/prometheus/procfs/internal/util/valueparser.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/ipvs.go b/vendor/github.com/prometheus/procfs/ipvs.go index bc3a20c..5374da9 100644 --- a/vendor/github.com/prometheus/procfs/ipvs.go +++ b/vendor/github.com/prometheus/procfs/ipvs.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/kernel_hung.go b/vendor/github.com/prometheus/procfs/kernel_hung.go new file mode 100644 index 0000000..539c111 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/kernel_hung.go @@ -0,0 +1,45 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build !windows +// +build !windows + +package procfs + +import ( + "os" + "strconv" + "strings" +) + +// KernelHung contains information about to the kernel's hung_task_detect_count number. +type KernelHung struct { + // Indicates the total number of tasks that have been detected as hung since the system boot. + // This file shows up if `CONFIG_DETECT_HUNG_TASK` is enabled. + HungTaskDetectCount *uint64 +} + +// KernelHung returns values from /proc/sys/kernel/hung_task_detect_count. +func (fs FS) KernelHung() (KernelHung, error) { + data, err := os.ReadFile(fs.proc.Path("sys", "kernel", "hung_task_detect_count")) + if err != nil { + return KernelHung{}, err + } + val, err := strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64) + if err != nil { + return KernelHung{}, err + } + return KernelHung{ + HungTaskDetectCount: &val, + }, nil +} diff --git a/vendor/github.com/prometheus/procfs/kernel_random.go b/vendor/github.com/prometheus/procfs/kernel_random.go index db88566..b66565a 100644 --- a/vendor/github.com/prometheus/procfs/kernel_random.go +++ b/vendor/github.com/prometheus/procfs/kernel_random.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/loadavg.go b/vendor/github.com/prometheus/procfs/loadavg.go index 332e76c..c8c78a6 100644 --- a/vendor/github.com/prometheus/procfs/loadavg.go +++ b/vendor/github.com/prometheus/procfs/loadavg.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/mdstat.go b/vendor/github.com/prometheus/procfs/mdstat.go index 1fd4381..d66eeda 100644 --- a/vendor/github.com/prometheus/procfs/mdstat.go +++ b/vendor/github.com/prometheus/procfs/mdstat.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -27,13 +27,34 @@ var ( recoveryLinePctRE = regexp.MustCompile(`= (.+)%`) recoveryLineFinishRE = regexp.MustCompile(`finish=(.+)min`) recoveryLineSpeedRE = regexp.MustCompile(`speed=(.+)[A-Z]`) - componentDeviceRE = regexp.MustCompile(`(.*)\[\d+\]`) + componentDeviceRE = regexp.MustCompile(`(.*)\[(\d+)\](\([SF]+\))?`) + personalitiesPrefix = "Personalities : " ) +type MDStatComponent struct { + // Name of the component device. + Name string + // DescriptorIndex number of component device, e.g. the order in the superblock. + DescriptorIndex int32 + // Flags per Linux drivers/md/md.[ch] as of v6.12-rc1 + // Subset that are exposed in mdstat + WriteMostly bool + Journal bool + Faulty bool // "Faulty" is what kernel source uses for "(F)" + Spare bool + Replacement bool + // Some additional flags that are NOT exposed in procfs today; they may + // be available via sysfs. + // In_sync, Bitmap_sync, Blocked, WriteErrorSeen, FaultRecorded, + // BlockedBadBlocks, WantReplacement, Candidate, ... +} + // MDStat holds info parsed from /proc/mdstat. type MDStat struct { // Name of the device. Name string + // raid type of the device. + Type string // activity-state of the device. ActivityState string // Number of active disks. @@ -58,8 +79,8 @@ type MDStat struct { BlocksSyncedFinishTime float64 // current sync speed (in Kilobytes/sec) BlocksSyncedSpeed float64 - // Name of md component devices - Devices []string + // component devices + Devices []MDStatComponent } // MDStat parses an mdstat-file (/proc/mdstat) and returns a slice of @@ -80,28 +101,52 @@ func (fs FS) MDStat() ([]MDStat, error) { // parseMDStat parses data from mdstat file (/proc/mdstat) and returns a slice of // structs containing the relevant info. func parseMDStat(mdStatData []byte) ([]MDStat, error) { + // TODO: + // - parse global hotspares from the "unused devices" line. mdStats := []MDStat{} lines := strings.Split(string(mdStatData), "\n") + knownRaidTypes := make(map[string]bool) for i, line := range lines { if strings.TrimSpace(line) == "" || line[0] == ' ' || - strings.HasPrefix(line, "Personalities") || strings.HasPrefix(line, "unused") { continue } + // Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10] + if len(knownRaidTypes) == 0 && strings.HasPrefix(line, personalitiesPrefix) { + personalities := strings.Fields(line[len(personalitiesPrefix):]) + for _, word := range personalities { + word := word[1 : len(word)-1] + knownRaidTypes[word] = true + } + continue + } deviceFields := strings.Fields(line) if len(deviceFields) < 3 { return nil, fmt.Errorf("%w: Expected 3+ lines, got %q", ErrFileParse, line) } mdName := deviceFields[0] // mdx - state := deviceFields[2] // active or inactive + state := deviceFields[2] // active, inactive, broken + + mdType := "unknown" // raid1, raid5, etc. + var deviceStartIndex int + if len(deviceFields) > 3 { // mdType may be in the 3rd or 4th field + if isRaidType(deviceFields[3], knownRaidTypes) { + mdType = deviceFields[3] + deviceStartIndex = 4 + } else if len(deviceFields) > 4 && isRaidType(deviceFields[4], knownRaidTypes) { + // if the 3rd field is (...), the 4th field is the mdType + mdType = deviceFields[4] + deviceStartIndex = 5 + } + } if len(lines) <= i+3 { return nil, fmt.Errorf("%w: Too few lines for md device: %q", ErrFileParse, mdName) } - // Failed disks have the suffix (F) & Spare disks have the suffix (S). + // Failed (Faulty) disks have the suffix (F) & Spare disks have the suffix (S). fail := int64(strings.Count(line, "(F)")) spare := int64(strings.Count(line, "(S)")) active, total, down, size, err := evalStatusLine(lines[i], lines[i+1]) @@ -129,13 +174,14 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) { // Append recovery and resyncing state info. if recovering || resyncing || checking || reshaping { - if recovering { + switch { + case recovering: state = "recovering" - } else if reshaping { + case reshaping: state = "reshaping" - } else if checking { + case checking: state = "checking" - } else { + default: state = "resyncing" } @@ -151,8 +197,14 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) { } } + devices, err := evalComponentDevices(deviceFields[deviceStartIndex:]) + if err != nil { + return nil, fmt.Errorf("error parsing components in md device %q: %w", mdName, err) + } + mdStats = append(mdStats, MDStat{ Name: mdName, + Type: mdType, ActivityState: state, DisksActive: active, DisksFailed: fail, @@ -165,14 +217,24 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) { BlocksSyncedPct: pct, BlocksSyncedFinishTime: finish, BlocksSyncedSpeed: speed, - Devices: evalComponentDevices(deviceFields), + Devices: devices, }) } return mdStats, nil } +// check if a string's format is like the mdType +// Rule 1: mdType should not be like (...) +// Rule 2: mdType should not be like sda[0] +// . +func isRaidType(mdType string, knownRaidTypes map[string]bool) bool { + _, ok := knownRaidTypes[mdType] + return !strings.ContainsAny(mdType, "([") && ok +} + func evalStatusLine(deviceLine, statusLine string) (active, total, down, size int64, err error) { + // e.g. 523968 blocks super 1.2 [4/4] [UUUU] statusFields := strings.Fields(statusLine) if len(statusFields) < 1 { return 0, 0, 0, 0, fmt.Errorf("%w: Unexpected statusline %q: %w", ErrFileParse, statusLine, err) @@ -263,17 +325,29 @@ func evalRecoveryLine(recoveryLine string) (blocksSynced int64, blocksToBeSynced return blocksSynced, blocksToBeSynced, pct, finish, speed, nil } -func evalComponentDevices(deviceFields []string) []string { - mdComponentDevices := make([]string, 0) - if len(deviceFields) > 3 { - for _, field := range deviceFields[4:] { - match := componentDeviceRE.FindStringSubmatch(field) - if match == nil { - continue - } - mdComponentDevices = append(mdComponentDevices, match[1]) +func evalComponentDevices(deviceFields []string) ([]MDStatComponent, error) { + mdComponentDevices := make([]MDStatComponent, 0) + for _, field := range deviceFields { + match := componentDeviceRE.FindStringSubmatch(field) + if match == nil { + continue + } + descriptorIndex, err := strconv.ParseInt(match[2], 10, 32) + if err != nil { + return mdComponentDevices, fmt.Errorf("error parsing int from device %q: %w", match[2], err) } + mdComponentDevices = append(mdComponentDevices, MDStatComponent{ + Name: match[1], + DescriptorIndex: int32(descriptorIndex), + // match may contain one or more of these + // https://github.com/torvalds/linux/blob/7ec462100ef9142344ddbf86f2c3008b97acddbe/drivers/md/md.c#L8376-L8392 + Faulty: strings.Contains(match[3], "(F)"), + Spare: strings.Contains(match[3], "(S)"), + Journal: strings.Contains(match[3], "(J)"), + Replacement: strings.Contains(match[3], "(R)"), + WriteMostly: strings.Contains(match[3], "(W)"), + }) } - return mdComponentDevices + return mdComponentDevices, nil } diff --git a/vendor/github.com/prometheus/procfs/meminfo.go b/vendor/github.com/prometheus/procfs/meminfo.go index 937e1f9..3420383 100644 --- a/vendor/github.com/prometheus/procfs/meminfo.go +++ b/vendor/github.com/prometheus/procfs/meminfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -307,7 +307,7 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { m.ZswapBytes = &valBytes case "Zswapped:": m.Zswapped = &val - m.ZswapBytes = &valBytes + m.ZswappedBytes = &valBytes case "Dirty:": m.Dirty = &val m.DirtyBytes = &valBytes diff --git a/vendor/github.com/prometheus/procfs/mountinfo.go b/vendor/github.com/prometheus/procfs/mountinfo.go index a704c5e..9414a12 100644 --- a/vendor/github.com/prometheus/procfs/mountinfo.go +++ b/vendor/github.com/prometheus/procfs/mountinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -147,8 +147,7 @@ func mountOptionsParseOptionalFields(o []string) (map[string]string, error) { // mountOptionsParser parses the mount options, superblock options. func mountOptionsParser(mountOptions string) map[string]string { opts := make(map[string]string) - options := strings.Split(mountOptions, ",") - for _, opt := range options { + for opt := range strings.SplitSeq(mountOptions, ",") { splitOption := strings.Split(opt, "=") if len(splitOption) < 2 { key := splitOption[0] @@ -178,3 +177,21 @@ func GetProcMounts(pid int) ([]*MountInfo, error) { } return parseMountInfo(data) } + +// GetMounts retrieves mountinfo information from `/proc/self/mountinfo`. +func (fs FS) GetMounts() ([]*MountInfo, error) { + data, err := util.ReadFileNoStat(fs.proc.Path("self/mountinfo")) + if err != nil { + return nil, err + } + return parseMountInfo(data) +} + +// GetProcMounts retrieves mountinfo information from a processes' `/proc//mountinfo`. +func (fs FS) GetProcMounts(pid int) ([]*MountInfo, error) { + data, err := util.ReadFileNoStat(fs.proc.Path(fmt.Sprintf("%d/mountinfo", pid))) + if err != nil { + return nil, err + } + return parseMountInfo(data) +} diff --git a/vendor/github.com/prometheus/procfs/mountstats.go b/vendor/github.com/prometheus/procfs/mountstats.go index 50caa73..e503cb3 100644 --- a/vendor/github.com/prometheus/procfs/mountstats.go +++ b/vendor/github.com/prometheus/procfs/mountstats.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -383,7 +383,7 @@ func parseMountStatsNFS(s *bufio.Scanner, statVersion string) (*MountStatsNFS, e if stats.Opts == nil { stats.Opts = map[string]string{} } - for _, opt := range strings.Split(ss[1], ",") { + for opt := range strings.SplitSeq(ss[1], ",") { split := strings.Split(opt, "=") if len(split) == 2 { stats.Opts[split[0]] = split[1] diff --git a/vendor/github.com/prometheus/procfs/net_conntrackstat.go b/vendor/github.com/prometheus/procfs/net_conntrackstat.go index 316df5f..e9ca357 100644 --- a/vendor/github.com/prometheus/procfs/net_conntrackstat.go +++ b/vendor/github.com/prometheus/procfs/net_conntrackstat.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_dev.go b/vendor/github.com/prometheus/procfs/net_dev.go index e66208a..7b3e1d6 100644 --- a/vendor/github.com/prometheus/procfs/net_dev.go +++ b/vendor/github.com/prometheus/procfs/net_dev.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_dev_snmp6.go b/vendor/github.com/prometheus/procfs/net_dev_snmp6.go index f50b38e..2a0f60f 100644 --- a/vendor/github.com/prometheus/procfs/net_dev_snmp6.go +++ b/vendor/github.com/prometheus/procfs/net_dev_snmp6.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -18,6 +18,7 @@ import ( "errors" "io" "os" + "path/filepath" "strconv" "strings" ) @@ -56,7 +57,9 @@ func newNetDevSNMP6(dir string) (NetDevSNMP6, error) { } for _, iFaceFile := range ifaceFiles { - f, err := os.Open(dir + "/" + iFaceFile.Name()) + filePath := filepath.Join(dir, iFaceFile.Name()) + + f, err := os.Open(filePath) if err != nil { return netDevSNMP6, err } diff --git a/vendor/github.com/prometheus/procfs/net_ip_socket.go b/vendor/github.com/prometheus/procfs/net_ip_socket.go index 19e3378..9291f8c 100644 --- a/vendor/github.com/prometheus/procfs/net_ip_socket.go +++ b/vendor/github.com/prometheus/procfs/net_ip_socket.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_protocols.go b/vendor/github.com/prometheus/procfs/net_protocols.go index 8d4b1ac..eaa996c 100644 --- a/vendor/github.com/prometheus/procfs/net_protocols.go +++ b/vendor/github.com/prometheus/procfs/net_protocols.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -169,7 +169,7 @@ func (pc *NetProtocolCapabilities) parseCapabilities(capabilities []string) erro &pc.EnterMemoryPressure, } - for i := 0; i < len(capabilities); i++ { + for i := range capabilities { switch capabilities[i] { case "y": *capabilityFields[i] = true diff --git a/vendor/github.com/prometheus/procfs/net_route.go b/vendor/github.com/prometheus/procfs/net_route.go index deb7029..fa3812d 100644 --- a/vendor/github.com/prometheus/procfs/net_route.go +++ b/vendor/github.com/prometheus/procfs/net_route.go @@ -1,4 +1,4 @@ -// Copyright 2023 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_sockstat.go b/vendor/github.com/prometheus/procfs/net_sockstat.go index fae62b1..8b221eb 100644 --- a/vendor/github.com/prometheus/procfs/net_sockstat.go +++ b/vendor/github.com/prometheus/procfs/net_sockstat.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -139,9 +139,6 @@ func parseSockstatKVs(kvs []string) (map[string]int, error) { func parseSockstatProtocol(kvs map[string]int) NetSockstatProtocol { var nsp NetSockstatProtocol for k, v := range kvs { - // Capture the range variable to ensure we get unique pointers for - // each of the optional fields. - v := v switch k { case "inuse": nsp.InUse = v diff --git a/vendor/github.com/prometheus/procfs/net_softnet.go b/vendor/github.com/prometheus/procfs/net_softnet.go index 71c8059..4a2dfa1 100644 --- a/vendor/github.com/prometheus/procfs/net_softnet.go +++ b/vendor/github.com/prometheus/procfs/net_softnet.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_tcp.go b/vendor/github.com/prometheus/procfs/net_tcp.go index 0396d72..610ea78 100644 --- a/vendor/github.com/prometheus/procfs/net_tcp.go +++ b/vendor/github.com/prometheus/procfs/net_tcp.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_tls_stat.go b/vendor/github.com/prometheus/procfs/net_tls_stat.go index 13994c1..b1b3f6a 100644 --- a/vendor/github.com/prometheus/procfs/net_tls_stat.go +++ b/vendor/github.com/prometheus/procfs/net_tls_stat.go @@ -1,4 +1,4 @@ -// Copyright 2023 Prometheus Team +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_udp.go b/vendor/github.com/prometheus/procfs/net_udp.go index 9ac3daf..8a32779 100644 --- a/vendor/github.com/prometheus/procfs/net_udp.go +++ b/vendor/github.com/prometheus/procfs/net_udp.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_unix.go b/vendor/github.com/prometheus/procfs/net_unix.go index d7e0cac..e4d6359 100644 --- a/vendor/github.com/prometheus/procfs/net_unix.go +++ b/vendor/github.com/prometheus/procfs/net_unix.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_wireless.go b/vendor/github.com/prometheus/procfs/net_wireless.go index 7c597bc..69d0794 100644 --- a/vendor/github.com/prometheus/procfs/net_wireless.go +++ b/vendor/github.com/prometheus/procfs/net_wireless.go @@ -1,4 +1,4 @@ -// Copyright 2023 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/net_xfrm.go b/vendor/github.com/prometheus/procfs/net_xfrm.go index 932ef20..5a9f497 100644 --- a/vendor/github.com/prometheus/procfs/net_xfrm.go +++ b/vendor/github.com/prometheus/procfs/net_xfrm.go @@ -1,4 +1,4 @@ -// Copyright 2017 Prometheus Team +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/netstat.go b/vendor/github.com/prometheus/procfs/netstat.go index 742dff4..dbdae47 100644 --- a/vendor/github.com/prometheus/procfs/netstat.go +++ b/vendor/github.com/prometheus/procfs/netstat.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/nfnetlink_queue.go b/vendor/github.com/prometheus/procfs/nfnetlink_queue.go new file mode 100644 index 0000000..7adf17b --- /dev/null +++ b/vendor/github.com/prometheus/procfs/nfnetlink_queue.go @@ -0,0 +1,85 @@ +// Copyright 2024 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package procfs + +import ( + "bufio" + "bytes" + "fmt" + + "github.com/prometheus/procfs/internal/util" +) + +const nfNetLinkQueueFormat = "%d %d %d %d %d %d %d %d %d" + +// NFNetLinkQueue contains general information about netfilter queues found in /proc/net/netfilter/nfnetlink_queue. +type NFNetLinkQueue struct { + // id of the queue + QueueID uint + // pid of process handling the queue + PeerPID uint + // number of packets waiting for a decision + QueueTotal uint + // indicate how userspace receive packets + CopyMode uint + // size of copy + CopyRange uint + // number of items dropped by the kernel because too many packets were waiting a decision. + // It queue_total is superior to queue_max_len (1024 per default) the packets are dropped. + QueueDropped uint + // number of packets dropped by userspace (due to kernel send failure on the netlink socket) + QueueUserDropped uint + // sequence number of packets queued. It gives a correct approximation of the number of queued packets. + SequenceID uint + // internal value (number of entity using the queue) + Use uint +} + +// NFNetLinkQueue returns information about current state of netfilter queues. +func (fs FS) NFNetLinkQueue() ([]NFNetLinkQueue, error) { + data, err := util.ReadFileNoStat(fs.proc.Path("net/netfilter/nfnetlink_queue")) + if err != nil { + return nil, err + } + + queue := []NFNetLinkQueue{} + if len(data) == 0 { + return queue, nil + } + + scanner := bufio.NewScanner(bytes.NewReader(data)) + for scanner.Scan() { + line := scanner.Text() + nFNetLinkQueue, err := parseNFNetLinkQueueLine(line) + if err != nil { + return nil, err + } + queue = append(queue, *nFNetLinkQueue) + } + return queue, nil +} + +// parseNFNetLinkQueueLine parses each line of the /proc/net/netfilter/nfnetlink_queue file. +func parseNFNetLinkQueueLine(line string) (*NFNetLinkQueue, error) { + nFNetLinkQueue := NFNetLinkQueue{} + _, err := fmt.Sscanf( + line, nfNetLinkQueueFormat, + &nFNetLinkQueue.QueueID, &nFNetLinkQueue.PeerPID, &nFNetLinkQueue.QueueTotal, &nFNetLinkQueue.CopyMode, + &nFNetLinkQueue.CopyRange, &nFNetLinkQueue.QueueDropped, &nFNetLinkQueue.QueueUserDropped, &nFNetLinkQueue.SequenceID, &nFNetLinkQueue.Use, + ) + if err != nil { + return nil, err + } + return &nFNetLinkQueue, nil +} diff --git a/vendor/github.com/prometheus/procfs/proc.go b/vendor/github.com/prometheus/procfs/proc.go index 368187f..39c14aa 100644 --- a/vendor/github.com/prometheus/procfs/proc.go +++ b/vendor/github.com/prometheus/procfs/proc.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -49,7 +49,7 @@ func (p Procs) Less(i, j int) bool { return p[i].PID < p[j].PID } // Self returns a process for the current process read via /proc/self. func Self() (Proc, error) { fs, err := NewFS(DefaultMountPoint) - if err != nil || errors.Unwrap(err) == ErrMountPoint { + if err != nil || errors.Is(err, ErrMountPoint) { return Proc{}, err } return fs.Self() diff --git a/vendor/github.com/prometheus/procfs/proc_cgroup.go b/vendor/github.com/prometheus/procfs/proc_cgroup.go index 4a64347..535c08d 100644 --- a/vendor/github.com/prometheus/procfs/proc_cgroup.go +++ b/vendor/github.com/prometheus/procfs/proc_cgroup.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_cgroups.go b/vendor/github.com/prometheus/procfs/proc_cgroups.go index 5dd4938..0b275c3 100644 --- a/vendor/github.com/prometheus/procfs/proc_cgroups.go +++ b/vendor/github.com/prometheus/procfs/proc_cgroups.go @@ -1,4 +1,4 @@ -// Copyright 2021 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -40,13 +40,13 @@ type CgroupSummary struct { // parseCgroupSummary parses each line of the /proc/cgroup file // Line format is `subsys_name hierarchy num_cgroups enabled`. -func parseCgroupSummaryString(CgroupSummaryStr string) (*CgroupSummary, error) { +func parseCgroupSummaryString(cgroupSummaryStr string) (*CgroupSummary, error) { var err error - fields := strings.Fields(CgroupSummaryStr) + fields := strings.Fields(cgroupSummaryStr) // require at least 4 fields if len(fields) < 4 { - return nil, fmt.Errorf("%w: 4+ fields required, found %d fields in cgroup info string: %s", ErrFileParse, len(fields), CgroupSummaryStr) + return nil, fmt.Errorf("%w: 4+ fields required, found %d fields in cgroup info string: %s", ErrFileParse, len(fields), cgroupSummaryStr) } CgroupSummary := &CgroupSummary{ diff --git a/vendor/github.com/prometheus/procfs/proc_environ.go b/vendor/github.com/prometheus/procfs/proc_environ.go index 57a8989..5b941de 100644 --- a/vendor/github.com/prometheus/procfs/proc_environ.go +++ b/vendor/github.com/prometheus/procfs/proc_environ.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_fdinfo.go b/vendor/github.com/prometheus/procfs/proc_fdinfo.go index fa761b3..fa57761 100644 --- a/vendor/github.com/prometheus/procfs/proc_fdinfo.go +++ b/vendor/github.com/prometheus/procfs/proc_fdinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -60,15 +60,16 @@ func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) { scanner := bufio.NewScanner(bytes.NewReader(data)) for scanner.Scan() { text = scanner.Text() - if rPos.MatchString(text) { + switch { + case rPos.MatchString(text): pos = rPos.FindStringSubmatch(text)[1] - } else if rFlags.MatchString(text) { + case rFlags.MatchString(text): flags = rFlags.FindStringSubmatch(text)[1] - } else if rMntID.MatchString(text) { + case rMntID.MatchString(text): mntid = rMntID.FindStringSubmatch(text)[1] - } else if rIno.MatchString(text) { + case rIno.MatchString(text): ino = rIno.FindStringSubmatch(text)[1] - } else if rInotify.MatchString(text) { + case rInotify.MatchString(text): newInotify, err := parseInotifyInfo(text) if err != nil { return nil, err diff --git a/vendor/github.com/prometheus/procfs/proc_interrupts.go b/vendor/github.com/prometheus/procfs/proc_interrupts.go index 86b4b45..b942c50 100644 --- a/vendor/github.com/prometheus/procfs/proc_interrupts.go +++ b/vendor/github.com/prometheus/procfs/proc_interrupts.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_io.go b/vendor/github.com/prometheus/procfs/proc_io.go index d15b66d..dd8086b 100644 --- a/vendor/github.com/prometheus/procfs/proc_io.go +++ b/vendor/github.com/prometheus/procfs/proc_io.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_limits.go b/vendor/github.com/prometheus/procfs/proc_limits.go index 9530b14..4b7d337 100644 --- a/vendor/github.com/prometheus/procfs/proc_limits.go +++ b/vendor/github.com/prometheus/procfs/proc_limits.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -19,6 +19,7 @@ import ( "os" "regexp" "strconv" + "strings" ) // ProcLimits represents the soft limits for each of the process's resource @@ -74,7 +75,7 @@ const ( ) var ( - limitsMatch = regexp.MustCompile(`(Max \w+\s{0,1}?\w*\s{0,1}\w*)\s{2,}(\w+)\s+(\w+)`) + limitsMatch = regexp.MustCompile(`(Max \w+\s??\w*\s?\w*)\s{2,}(\w+)\s+(\w+)`) ) // NewLimits returns the current soft limits of the process. @@ -106,7 +107,7 @@ func (p Proc) Limits() (ProcLimits, error) { return ProcLimits{}, fmt.Errorf("%w: couldn't parse %q line %q", ErrFileParse, f.Name(), s.Text()) } - switch fields[1] { + switch strings.TrimSpace(fields[1]) { case "Max cpu time": l.CPUTime, err = parseUint(fields[2]) case "Max file size": diff --git a/vendor/github.com/prometheus/procfs/proc_maps.go b/vendor/github.com/prometheus/procfs/proc_maps.go index 7e75c28..cc519f9 100644 --- a/vendor/github.com/prometheus/procfs/proc_maps.go +++ b/vendor/github.com/prometheus/procfs/proc_maps.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_netstat.go b/vendor/github.com/prometheus/procfs/proc_netstat.go index 4248c17..7f94cc8 100644 --- a/vendor/github.com/prometheus/procfs/proc_netstat.go +++ b/vendor/github.com/prometheus/procfs/proc_netstat.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_ns.go b/vendor/github.com/prometheus/procfs/proc_ns.go index 0f8f847..5fc0eb9 100644 --- a/vendor/github.com/prometheus/procfs/proc_ns.go +++ b/vendor/github.com/prometheus/procfs/proc_ns.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_psi.go b/vendor/github.com/prometheus/procfs/proc_psi.go index ccd35f1..cc2c5de 100644 --- a/vendor/github.com/prometheus/procfs/proc_psi.go +++ b/vendor/github.com/prometheus/procfs/proc_psi.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_smaps.go b/vendor/github.com/prometheus/procfs/proc_smaps.go index 9a297af..3e48afd 100644 --- a/vendor/github.com/prometheus/procfs/proc_smaps.go +++ b/vendor/github.com/prometheus/procfs/proc_smaps.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_snmp.go b/vendor/github.com/prometheus/procfs/proc_snmp.go index 4bdc90b..8d9a9bc 100644 --- a/vendor/github.com/prometheus/procfs/proc_snmp.go +++ b/vendor/github.com/prometheus/procfs/proc_snmp.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_snmp6.go b/vendor/github.com/prometheus/procfs/proc_snmp6.go index fb7fd39..841fef4 100644 --- a/vendor/github.com/prometheus/procfs/proc_snmp6.go +++ b/vendor/github.com/prometheus/procfs/proc_snmp6.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_stat.go b/vendor/github.com/prometheus/procfs/proc_stat.go index 3328556..02e3f9e 100644 --- a/vendor/github.com/prometheus/procfs/proc_stat.go +++ b/vendor/github.com/prometheus/procfs/proc_stat.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/proc_statm.go b/vendor/github.com/prometheus/procfs/proc_statm.go index ed57984..b0a9360 100644 --- a/vendor/github.com/prometheus/procfs/proc_statm.go +++ b/vendor/github.com/prometheus/procfs/proc_statm.go @@ -1,4 +1,4 @@ -// Copyright 2025 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -80,7 +80,7 @@ func (p Proc) Statm() (ProcStatm, error) { func parseStatm(data []byte) ([]uint64, error) { var statmSlice []uint64 statmItems := strings.Fields(string(data)) - for i := 0; i < len(statmItems); i++ { + for i := range statmItems { statmItem, err := strconv.ParseUint(statmItems[i], 10, 64) if err != nil { return nil, err diff --git a/vendor/github.com/prometheus/procfs/proc_status.go b/vendor/github.com/prometheus/procfs/proc_status.go index dd8aa56..1ed2bce 100644 --- a/vendor/github.com/prometheus/procfs/proc_status.go +++ b/vendor/github.com/prometheus/procfs/proc_status.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -16,7 +16,7 @@ package procfs import ( "bytes" "math/bits" - "sort" + "slices" "strconv" "strings" @@ -94,8 +94,7 @@ func (p Proc) NewStatus() (ProcStatus, error) { s := ProcStatus{PID: p.PID} - lines := strings.Split(string(data), "\n") - for _, line := range lines { + for line := range strings.SplitSeq(string(data), "\n") { if !bytes.Contains([]byte(line), []byte(":")) { continue } @@ -222,7 +221,7 @@ func calcCpusAllowedList(cpuString string) []uint64 { } - sort.Slice(g, func(i, j int) bool { return g[i] < g[j] }) + slices.Sort(g) return g } diff --git a/vendor/github.com/prometheus/procfs/proc_sys.go b/vendor/github.com/prometheus/procfs/proc_sys.go index 3810d1a..52658a4 100644 --- a/vendor/github.com/prometheus/procfs/proc_sys.go +++ b/vendor/github.com/prometheus/procfs/proc_sys.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/schedstat.go b/vendor/github.com/prometheus/procfs/schedstat.go index 5f7f32d..fafd8df 100644 --- a/vendor/github.com/prometheus/procfs/schedstat.go +++ b/vendor/github.com/prometheus/procfs/schedstat.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/slab.go b/vendor/github.com/prometheus/procfs/slab.go index 8611c90..32a0467 100644 --- a/vendor/github.com/prometheus/procfs/slab.go +++ b/vendor/github.com/prometheus/procfs/slab.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/softirqs.go b/vendor/github.com/prometheus/procfs/softirqs.go index 403e6ae..47b73a7 100644 --- a/vendor/github.com/prometheus/procfs/softirqs.go +++ b/vendor/github.com/prometheus/procfs/softirqs.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/stat.go b/vendor/github.com/prometheus/procfs/stat.go index e36b41c..593ad0f 100644 --- a/vendor/github.com/prometheus/procfs/stat.go +++ b/vendor/github.com/prometheus/procfs/stat.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -16,6 +16,7 @@ package procfs import ( "bufio" "bytes" + "errors" "fmt" "io" "strconv" @@ -92,7 +93,7 @@ func parseCPUStat(line string) (CPUStat, int64, error) { &cpuStat.Iowait, &cpuStat.IRQ, &cpuStat.SoftIRQ, &cpuStat.Steal, &cpuStat.Guest, &cpuStat.GuestNice) - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { return CPUStat{}, -1, fmt.Errorf("%w: couldn't parse %q (cpu): %w", ErrFileParse, line, err) } if count == 0 { diff --git a/vendor/github.com/prometheus/procfs/swaps.go b/vendor/github.com/prometheus/procfs/swaps.go index 65fec83..ee17bf4 100644 --- a/vendor/github.com/prometheus/procfs/swaps.go +++ b/vendor/github.com/prometheus/procfs/swaps.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/thread.go b/vendor/github.com/prometheus/procfs/thread.go index 80e0e94..0cfbb54 100644 --- a/vendor/github.com/prometheus/procfs/thread.go +++ b/vendor/github.com/prometheus/procfs/thread.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/vm.go b/vendor/github.com/prometheus/procfs/vm.go index 51c49d8..2a8d763 100644 --- a/vendor/github.com/prometheus/procfs/vm.go +++ b/vendor/github.com/prometheus/procfs/vm.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at diff --git a/vendor/github.com/prometheus/procfs/zoneinfo.go b/vendor/github.com/prometheus/procfs/zoneinfo.go index e54d94b..806e171 100644 --- a/vendor/github.com/prometheus/procfs/zoneinfo.go +++ b/vendor/github.com/prometheus/procfs/zoneinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -88,11 +88,9 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) { zoneinfo := []Zoneinfo{} - zoneinfoBlocks := bytes.Split(zoneinfoData, []byte("\nNode")) - for _, block := range zoneinfoBlocks { + for block := range bytes.SplitSeq(zoneinfoData, []byte("\nNode")) { var zoneinfoElement Zoneinfo - lines := strings.Split(string(block), "\n") - for _, line := range lines { + for line := range strings.SplitSeq(string(block), "\n") { if nodeZone := nodeZoneRE.FindStringSubmatch(line); nodeZone != nil { zoneinfoElement.Node = nodeZone[1] diff --git a/vendor/github.com/vmkteam/appkit/Makefile b/vendor/github.com/vmkteam/appkit/Makefile index 6e72adc..7c211dc 100644 --- a/vendor/github.com/vmkteam/appkit/Makefile +++ b/vendor/github.com/vmkteam/appkit/Makefile @@ -13,4 +13,7 @@ lint: @golangci-lint run run: - @go run example/main.go \ No newline at end of file + @go run example/main.go + +mod: + @go mod tidy diff --git a/vendor/github.com/vmkteam/appkit/README.md b/vendor/github.com/vmkteam/appkit/README.md index 7f4be33..46fe65a 100644 --- a/vendor/github.com/vmkteam/appkit/README.md +++ b/vendor/github.com/vmkteam/appkit/README.md @@ -28,6 +28,21 @@ A comprehensive Go utility package providing common application framework compon - **Database Monitoring**: Connection tracking and replica status - **API Exposure**: Public/private API configuration tracking +### HTTP Client +- **Pre-configured Client**: HTTP client with automatic metrics and internal headers +- **Transport Wrappers**: Composable transport layers for metrics and header injection +- **Caller Tracking**: Context-based caller identification for metrics + +### Request Management +- **X-Request-ID**: Automatic generation, validation, and propagation +- **Context Integration**: Request ID stored in context for easy access +- **Header Management**: CORS and custom header support + +### Context Utilities +- **Metadata Context**: Store and retrieve request metadata (IP, User-Agent, Platform, Version, Country) +- **Debug Support**: Debug ID and SQL group tracking for logging +- **Integration Support**: Sentry Hub and method tracking + ## Usage Examples Please see example/main.go @@ -86,6 +101,22 @@ func callInternalService() { } ``` +### HTTP Client with Metrics + +```go +// Create pre-configured HTTP client for internal service calls +client := appkit.NewHTTPClient("externalsrv", appkit.Version(), 30*time.Second) + +// Set caller name in context for metrics tracking +ctx := appkit.NewCallerNameContext(context.Background(), "externalsrv") + +req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://api-service/endpoint", nil) +resp, _ := client.Do(req) + +// Usage with clients generated by vmkteam/rpcgen +arithsrvClient := arithsrv.NewClient(arithsrvUrl, appkit.NewHTTPClient("arithsrv", appkit.Version(), 5*time.Second)) +``` + ## API Reference ### Core Functions @@ -105,19 +136,65 @@ func callInternalService() { - `HTTPMetrics(serverName string) echo.MiddlewareFunc` - Prometheus HTTP metrics middleware - `MetadataManager` - Service metadata configuration and metrics +### HTTP Client + +- `NewHTTPClient(appName, version string, timeout time.Duration) *http.Client` - Creates HTTP client with metrics and internal headers +- `WithMetricsTransport(base http.RoundTripper) http.RoundTripper` - Wraps transport with Prometheus metrics +- `WithHeadersTransport(base http.RoundTripper, headers http.Header) http.RoundTripper` - Wraps transport to inject headers for each request +- `NewCallerNameContext(ctx context.Context, callerName string) context.Context` - Creates context with caller name for metrics +- `CallerNameFromContext(ctx context.Context) string` - Retrieves caller name from context + +### Request ID & HTTP Handlers + +- `XRequestIDFromContext(ctx context.Context) string` - Retrieves X-Request-ID from context +- `NewXRequestIDContext(ctx context.Context, requestID string) context.Context` - Creates context with X-Request-ID +- `SetXRequestIDFromCtx(ctx context.Context, req *http.Request)` - Adds X-Request-ID from context to request headers +- `CORS(next http.Handler, headers ...string) http.Handler` - CORS middleware for HTTP handlers +- `XRequestID(next http.Handler) http.Handler` - X-Request-ID middleware for HTTP handlers +- `EchoHandler(next http.Handler) echo.HandlerFunc` - Wraps HTTP handler as Echo handler +- `EchoSentryHubContext() echo.MiddlewareFunc` - Echo middleware to apply Sentry hub to context +- `EchoIPContext() echo.MiddlewareFunc` - Echo middleware to apply client IP to context + +### Context Utilities + +- `NewDebugIDContext(ctx context.Context, debugID uint64) context.Context` - Creates context with debug ID +- `DebugIDFromContext(ctx context.Context) uint64` - Retrieves debug ID from context +- `NewSQLGroupContext(ctx context.Context, group string) context.Context` - Creates context with SQL group for debug logging +- `SQLGroupFromContext(ctx context.Context) string` - Retrieves SQL group from context +- `NewIPContext(ctx context.Context, ip string) context.Context` - Creates context with IP address +- `IPFromContext(ctx context.Context) string` - Retrieves IP address from context +- `NewUserAgentContext(ctx context.Context, ua string) context.Context` - Creates context with User-Agent +- `UserAgentFromContext(ctx context.Context) string` - Retrieves User-Agent from context +- `NewNotificationContext(ctx context.Context) context.Context` - Creates context with JSONRPC2 notification flag +- `NotificationFromContext(ctx context.Context) bool` - Retrieves JSONRPC2 notification flag from context +- `NewIsDevelContext(ctx context.Context, isDevel bool) context.Context` - Creates context with isDevel flag +- `IsDevelFromContext(ctx context.Context) bool` - Retrieves isDevel flag from context +- `NewPlatformContext(ctx context.Context, platform string) context.Context` - Creates context with platform +- `PlatformFromContext(ctx context.Context) string` - Retrieves platform from context +- `NewVersionContext(ctx context.Context, version string) context.Context` - Creates context with version +- `VersionFromContext(ctx context.Context) string` - Retrieves version from context +- `NewCountryContext(ctx context.Context, country string) context.Context` - Creates context with country +- `CountryFromContext(ctx context.Context) string` - Retrieves country from context +- `NewMethodContext(ctx context.Context, method string) context.Context` - Creates context with method +- `MethodFromContext(ctx context.Context) string` - Retrieves method from context + ## Dependencies - [Echo](https://echo.labstack.com/) - High performance HTTP framework - [Prometheus](https://prometheus.io/) - Metrics collection and monitoring - [Sentry](https://sentry.io/) - Error tracking and monitoring -- [zenrpc-middleware](https://github.com/vmkteam/zenrpc-middleware) - RPC middleware utilities ## Metrics Exported -### HTTP Metrics +### HTTP Server Metrics - `app_http_requests_total` - Total HTTP requests by method/path/status - `app_http_responses_duration_seconds` - Response time distribution +### HTTP Client Metrics +- `app_http_client_requests_total` - Total client requests by code/method/caller/origin +- `app_http_client_responses_duration_seconds` - Client response time distribution +- `app_http_client_requests_inflight` - Current inflight client requests by caller/origin + ### Service Metadata Metrics - `app_metadata_service` - Service configuration information - `app_metadata_db_connections_total` - Database connection counts diff --git a/vendor/github.com/vmkteam/appkit/appkit.go b/vendor/github.com/vmkteam/appkit/appkit.go index b25b6b7..a630c0b 100644 --- a/vendor/github.com/vmkteam/appkit/appkit.go +++ b/vendor/github.com/vmkteam/appkit/appkit.go @@ -6,6 +6,8 @@ import ( "runtime/debug" ) +type contextKey string + // Version returns app version from VCS info. func Version() string { result := "devel" diff --git a/vendor/github.com/vmkteam/appkit/client.go b/vendor/github.com/vmkteam/appkit/client.go new file mode 100644 index 0000000..80003c6 --- /dev/null +++ b/vendor/github.com/vmkteam/appkit/client.go @@ -0,0 +1,132 @@ +package appkit + +import ( + "context" + "net/http" + "strconv" + "sync" + "time" + + "github.com/prometheus/client_golang/prometheus" +) + +const ( + ctxCallerName contextKey = "callerName" +) + +var ( + clientMetricsOnce sync.Once + clientRequests = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: "app", + Subsystem: "http_client", + Name: "requests_total", + Help: "Requests count by code/method/client/origin.", + }, + []string{"code", "method", "caller", "origin"}, + ) + clientDurations = prometheus.NewSummaryVec( + prometheus.SummaryOpts{ + Namespace: "app", + Subsystem: "http_client", + Name: "responses_duration_seconds", + Help: "Response time by code/method/client/origin.", + }, + []string{"code", "method", "caller", "origin"}, + ) + clientInflights = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "app", + Subsystem: "http_client", + Name: "requests_inflight", + Help: "Gauge for inflight requests.", + }, + []string{"caller", "origin"}, + ) +) + +// NewCallerNameContext creates new context with caller name. +func NewCallerNameContext(ctx context.Context, callerName string) context.Context { + return context.WithValue(ctx, ctxCallerName, callerName) +} + +// CallerNameFromContext returns caller name from context. +func CallerNameFromContext(ctx context.Context) string { + r, _ := ctx.Value(ctxCallerName).(string) + return r +} + +type metricsRoundTripper struct { + base http.RoundTripper +} + +func (m *metricsRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + var origin string + if req.URL != nil { + origin = req.URL.Scheme + "://" + req.URL.Host + } + labels := prometheus.Labels{ + "caller": CallerNameFromContext(req.Context()), + "origin": origin, + } + + start := time.Now() + clientInflights.With(labels).Inc() + resp, err := m.base.RoundTrip(req) + clientInflights.With(labels).Dec() + duration := time.Since(start).Seconds() + + labels["method"] = req.Method + if resp != nil { + labels["code"] = strconv.Itoa(resp.StatusCode) + } + + clientRequests.With(labels).Inc() + clientDurations.With(labels).Observe(duration) + + return resp, err +} + +// WithMetricsTransport wraps http transport, adds client metrics tracking. +func WithMetricsTransport(base http.RoundTripper) http.RoundTripper { + clientMetricsOnce.Do(func() { + prometheus.MustRegister(clientRequests, clientDurations, clientInflights) + }) + return &metricsRoundTripper{base: base} +} + +type headerRoundTripper struct { + base http.RoundTripper + headers http.Header +} + +func (h *headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + reqClone := req.Clone(req.Context()) + + for key, values := range h.headers { + for _, value := range values { + reqClone.Header.Add(key, value) + } + } + + return h.base.RoundTrip(reqClone) +} + +// WithHeadersTransport wraps http transport, adds provided headers for each request. +func WithHeadersTransport(base http.RoundTripper, headers http.Header) http.RoundTripper { + return &headerRoundTripper{ + base: base, + headers: headers, + } +} + +// NewHTTPClient returns http client with metrics and headers for internal service calls. +func NewHTTPClient(appName, version string, timeout time.Duration) *http.Client { + transport := WithHeadersTransport(http.DefaultTransport, NewInternalHeaders(appName, version)) + transport = WithMetricsTransport(transport) + + return &http.Client{ + Timeout: timeout, + Transport: transport, + } +} diff --git a/vendor/github.com/vmkteam/appkit/echo.go b/vendor/github.com/vmkteam/appkit/echo.go index 428337c..37d029f 100644 --- a/vendor/github.com/vmkteam/appkit/echo.go +++ b/vendor/github.com/vmkteam/appkit/echo.go @@ -12,7 +12,6 @@ import ( sentryecho "github.com/getsentry/sentry-go/echo" "github.com/labstack/echo/v4" "github.com/prometheus/client_golang/prometheus" - zm "github.com/vmkteam/zenrpc-middleware" ) const DefaultServerName = "default" @@ -32,7 +31,7 @@ func NewEcho() *echo.Echo { })) // use zenrpc middlewares - e.Use(zm.EchoIPContext(), zm.EchoSentryHubContext()) + e.Use(EchoIPContext(), EchoSentryHubContext()) return e } diff --git a/vendor/github.com/vmkteam/zenrpc-middleware/handler.go b/vendor/github.com/vmkteam/appkit/handler.go similarity index 68% rename from vendor/github.com/vmkteam/zenrpc-middleware/handler.go rename to vendor/github.com/vmkteam/appkit/handler.go index 6dc6d2f..d169435 100644 --- a/vendor/github.com/vmkteam/zenrpc-middleware/handler.go +++ b/vendor/github.com/vmkteam/appkit/handler.go @@ -1,17 +1,28 @@ -package middleware +package appkit import ( + "context" "net/http" + "slices" + "strings" + "github.com/getsentry/sentry-go" sentryecho "github.com/getsentry/sentry-go/echo" "github.com/labstack/echo/v4" ) +var ( + defaultHeaders = []string{ + "Authorization", "Authorization2", "Origin", "X-Requested-With", "Content-Type", + "Accept", "Platform", "Version", "X-Request-ID", + } +) + // CORS allows certain CORS headers. -func CORS(next http.Handler) http.Handler { +func CORS(next http.Handler, headers ...string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Headers", "Authorization, Authorization2, Origin, X-Requested-With, Content-Type, Accept, Platform, Version, X-Request-ID") + w.Header().Set("Access-Control-Allow-Headers", strings.Join(slices.Concat(defaultHeaders, headers), ", ")) if r.Method == http.MethodOptions { return } @@ -20,10 +31,18 @@ func CORS(next http.Handler) http.Handler { }) } +// SetXRequestIDFromCtx adds X-Request-ID to request headers from context. +func SetXRequestIDFromCtx(ctx context.Context, req *http.Request) { + xRequestID := XRequestIDFromContext(ctx) + if xRequestID != "" && req.Header.Get(headerXRequestID) == "" { + req.Header.Add(headerXRequestID, xRequestID) + } +} + // XRequestID add X-Request-ID header if not exists. func XRequestID(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestID := r.Header.Get(echo.HeaderXRequestID) + requestID := r.Header.Get(headerXRequestID) if !isValidXRequestID(requestID) { requestID = generateXRequestID() r.Header.Add(echo.HeaderXRequestID, requestID) @@ -66,7 +85,7 @@ func EchoIPContext() echo.MiddlewareFunc { func applySentryHubToContext(c echo.Context) echo.Context { if hub := sentryecho.GetHubFromContext(c); hub != nil { req := c.Request() - c.SetRequest(req.WithContext(NewSentryHubContext(req.Context(), hub))) + c.SetRequest(req.WithContext(sentry.SetHubOnContext(req.Context(), hub))) } return c } diff --git a/vendor/github.com/vmkteam/appkit/metadata.go b/vendor/github.com/vmkteam/appkit/metadata.go index 3845949..4bfb737 100644 --- a/vendor/github.com/vmkteam/appkit/metadata.go +++ b/vendor/github.com/vmkteam/appkit/metadata.go @@ -32,11 +32,13 @@ type MetadataOpts struct { Services []ServiceMetadata // List of used services } +// ServiceMetadata describes used service. type ServiceMetadata struct { Name string // service name Type MetadataServiceType // sync, async, external } +// DBMetadata describes database configuration. type DBMetadata struct { Name string // database name Connections int // used connections @@ -60,6 +62,7 @@ func (d *MetadataManager) Handler(c echo.Context) error { return c.JSON(http.StatusOK, d.opts) } +// RegisterMetrics tracks metrics based on specified metadata. func (d *MetadataManager) RegisterMetrics() { appInfo := prometheus.NewGaugeVec( prometheus.GaugeOpts{ diff --git a/vendor/github.com/vmkteam/appkit/middleware.go b/vendor/github.com/vmkteam/appkit/middleware.go new file mode 100644 index 0000000..1c235e9 --- /dev/null +++ b/vendor/github.com/vmkteam/appkit/middleware.go @@ -0,0 +1,155 @@ +package appkit + +import ( + "context" +) + +const ( + isDevelCtx contextKey = "isDevel" + ctxPlatformKey contextKey = "platform" + ctxVersionKey contextKey = "version" + ctxMethodKey contextKey = "method" + ctxIPKey contextKey = "ip" + ctxUserAgentKey contextKey = "userAgent" + ctxCountryKey contextKey = "country" + ctxNotificationKey string = "JSONRPC2-Notification" + debugIDCtx contextKey = "debugID" + sqlGroupCtx contextKey = "sqlGroup" + + maxUserAgentLength = 2048 + maxVersionLength = 64 + maxCountryLength = 16 + EmptyDebugID = 0 +) + +// DebugIDFromContext returns debug ID from context. +func DebugIDFromContext(ctx context.Context) uint64 { + if ctx == nil { + return EmptyDebugID + } + + if id, ok := ctx.Value(debugIDCtx).(uint64); ok { + return id + } + + return EmptyDebugID +} + +// NewDebugIDContext creates new context with debug ID. +func NewDebugIDContext(ctx context.Context, debugID uint64) context.Context { + return context.WithValue(ctx, debugIDCtx, debugID) +} + +// NewSQLGroupContext creates new context with SQL Group for debug SQL logging. +func NewSQLGroupContext(ctx context.Context, group string) context.Context { + groups, _ := ctx.Value(sqlGroupCtx).(string) + if groups != "" { + groups += ">" + } + groups += group + return context.WithValue(ctx, sqlGroupCtx, groups) +} + +// SQLGroupFromContext returns sql group from context. +func SQLGroupFromContext(ctx context.Context) string { + r, _ := ctx.Value(sqlGroupCtx).(string) + return r +} + +// NewIPContext creates new context with IP. +func NewIPContext(ctx context.Context, ip string) context.Context { + return context.WithValue(ctx, ctxIPKey, ip) +} + +// IPFromContext returns IP from context. +func IPFromContext(ctx context.Context) string { + r, _ := ctx.Value(ctxIPKey).(string) + return r +} + +// NewUserAgentContext creates new context with User-Agent. +func NewUserAgentContext(ctx context.Context, ua string) context.Context { + return context.WithValue(ctx, ctxUserAgentKey, cutString(ua, maxUserAgentLength)) +} + +// UserAgentFromContext returns userAgent from context. +func UserAgentFromContext(ctx context.Context) string { + r, _ := ctx.Value(ctxUserAgentKey).(string) + return r +} + +// NewNotificationContext creates new context with JSONRPC2 notification flag. +func NewNotificationContext(ctx context.Context) context.Context { + return context.WithValue(ctx, ctxNotificationKey, true) //nolint:staticcheck +} + +// NotificationFromContext returns JSONRPC2 notification flag from context. +func NotificationFromContext(ctx context.Context) bool { + r, _ := ctx.Value(ctxNotificationKey).(bool) + return r +} + +// NewIsDevelContext creates new context with isDevel flag. +func NewIsDevelContext(ctx context.Context, isDevel bool) context.Context { + return context.WithValue(ctx, isDevelCtx, isDevel) +} + +// IsDevelFromContext returns isDevel flag from context. +func IsDevelFromContext(ctx context.Context) bool { + if isDevel, ok := ctx.Value(isDevelCtx).(bool); ok { + return isDevel + } + return false +} + +// NewPlatformContext creates new context with platform. +func NewPlatformContext(ctx context.Context, platform string) context.Context { + return context.WithValue(ctx, ctxPlatformKey, cutString(platform, 64)) +} + +// PlatformFromContext returns platform from context. +func PlatformFromContext(ctx context.Context) string { + r, _ := ctx.Value(ctxPlatformKey).(string) + return r +} + +// NewVersionContext creates new context with version. +func NewVersionContext(ctx context.Context, version string) context.Context { + return context.WithValue(ctx, ctxVersionKey, cutString(version, maxVersionLength)) +} + +// VersionFromContext returns version from context. +func VersionFromContext(ctx context.Context) string { + r, _ := ctx.Value(ctxVersionKey).(string) + return r +} + +// NewCountryContext creates new context with country. +func NewCountryContext(ctx context.Context, country string) context.Context { + return context.WithValue(ctx, ctxCountryKey, cutString(country, maxCountryLength)) +} + +// CountryFromContext returns country from context. +func CountryFromContext(ctx context.Context) string { + r, _ := ctx.Value(ctxCountryKey).(string) + return r +} + +// NewMethodContext creates new context with Method. +func NewMethodContext(ctx context.Context, method string) context.Context { + return context.WithValue(ctx, ctxMethodKey, method) +} + +// MethodFromContext returns Method from context. +func MethodFromContext(ctx context.Context) string { + r, _ := ctx.Value(ctxMethodKey).(string) + return r +} + +// cutString cuts string with given length. +func cutString(s string, length int) string { + if len(s) > length { + return s[:length] + } + return s +} diff --git a/vendor/github.com/vmkteam/appkit/xrequestid.go b/vendor/github.com/vmkteam/appkit/xrequestid.go new file mode 100644 index 0000000..1a48dda --- /dev/null +++ b/vendor/github.com/vmkteam/appkit/xrequestid.go @@ -0,0 +1,38 @@ +package appkit + +import ( + "context" + "crypto/rand" + "encoding/hex" + "regexp" + + "github.com/labstack/echo/v4" +) + +const ( + ctxXRequestIDKey string = echo.HeaderXRequestID + headerXRequestID string = echo.HeaderXRequestID +) + +var xRequestIDre = regexp.MustCompile(`[a-zA-Z0-9-]+`) + +func generateXRequestID() string { + b := make([]byte, 16) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func isValidXRequestID(requestID string) bool { + return requestID != "" && len(requestID) <= 32 && xRequestIDre.MatchString(requestID) +} + +// XRequestIDFromContext returns X-Request-ID from context. +func XRequestIDFromContext(ctx context.Context) string { + r, _ := ctx.Value(ctxXRequestIDKey).(string) + return r +} + +// NewXRequestIDContext creates new context with X-Request-ID. +func NewXRequestIDContext(ctx context.Context, requestID string) context.Context { + return context.WithValue(ctx, ctxXRequestIDKey, requestID) //nolint:staticcheck +} diff --git a/vendor/github.com/vmkteam/rpcgen/v2/README.md b/vendor/github.com/vmkteam/rpcgen/v2/README.md index 488b32b..faede0c 100644 --- a/vendor/github.com/vmkteam/rpcgen/v2/README.md +++ b/vendor/github.com/vmkteam/rpcgen/v2/README.md @@ -8,6 +8,7 @@ - PHP - TypeScript - Swift +- Kotlin - OpenRPC schema ## Examples @@ -157,6 +158,50 @@ func main() { } ``` +### Generate Kotlin networking protocols, rpc models and custom type mapper +Kotlin settings have a lot of properties: +- Class - custom interface name. Default value: `kotlin.BaseClass` +- PackageAPI - custom package name. Default value: `kotlin.BasePackageAPI` +- Imports - optional list of imports in interface. +- IsProtocol - flag controls the output type. Set to `true` to generate a Kotlin interface for the JSON-RPC client, or set to `false` to generate the corresponding data class models. +- TypeMapper - function allows you to implement custom logic for converting schema types into specific Kotlin types. +```go +package main + +import ( + "fmt" + "net/http" + + "github.com/vmkteam/rpcgen/v2" + "github.com/vmkteam/rpcgen/v2/kotlin" + "github.com/vmkteam/zenrpc/v2" + "github.com/vmkteam/zenrpc/v2/smd" +) + +func main() { + rpc := zenrpc.NewServer(zenrpc.Options{}) + + gen := rpcgen.FromSMD(rpc.SMD()) + + kotlinTypeMapper := func(typeName string, in smd.Property, param kotlin.Parameter) kotlin.Parameter { + switch typeName { + case "CustomMapType": + param.Type = "Map" + param.DecodableDefault = kotlin.DefaultMap + case "Group": + if in.Name == "group"{ + param.Type = fmt.Sprintf("Map", param.Type) + param.DecodableDefault = kotlin.DefaultMap + } + } + return param + } + + http.HandleFunc("/networking.generated.kt", rpcgen.Handler(gen.KotlinClient(kotlin.Settings{PackageAPI: "example.api", IsProtocol: true, TypeMapper: kotlinTypeMapper}))) + http.HandleFunc("/rpc.generated.kt", rpcgen.Handler(gen.KotlinClient(kotlin.Settings{Class: "ExampleApi", TypeMapper: kotlinTypeMapper, PackageAPI: "example.api", Imports: []string{"exampleImport"}}))) +} +``` + ### Add custom Dart type mapper ```go diff --git a/vendor/github.com/vmkteam/rpcgen/v2/gen/gen.go b/vendor/github.com/vmkteam/rpcgen/v2/gen/gen.go index cb420e0..bb919e6 100644 --- a/vendor/github.com/vmkteam/rpcgen/v2/gen/gen.go +++ b/vendor/github.com/vmkteam/rpcgen/v2/gen/gen.go @@ -10,7 +10,7 @@ import ( "golang.org/x/text/language" ) -const version = "2.4.6" +const version = "2.5.0" const DefinitionsPrefix = "#/definitions/" diff --git a/vendor/github.com/vmkteam/rpcgen/v2/generator.go b/vendor/github.com/vmkteam/rpcgen/v2/generator.go index 3b594e3..129e8bb 100644 --- a/vendor/github.com/vmkteam/rpcgen/v2/generator.go +++ b/vendor/github.com/vmkteam/rpcgen/v2/generator.go @@ -6,6 +6,7 @@ import ( "github.com/vmkteam/rpcgen/v2/dart" "github.com/vmkteam/rpcgen/v2/golang" + "github.com/vmkteam/rpcgen/v2/kotlin" "github.com/vmkteam/rpcgen/v2/openrpc" "github.com/vmkteam/rpcgen/v2/php" "github.com/vmkteam/rpcgen/v2/swift" @@ -43,6 +44,10 @@ func (g RPCGen) SwiftClient(settings swift.Settings) Generator { return swift.NewClient(g.schema, settings) } +func (g RPCGen) KotlinClient(settings kotlin.Settings) Generator { + return kotlin.NewClient(g.schema, settings) +} + func (g RPCGen) DartClient(settings dart.Settings) Generator { return dart.NewClient(g.schema, settings) } diff --git a/vendor/github.com/vmkteam/rpcgen/v2/golang/go_template.go b/vendor/github.com/vmkteam/rpcgen/v2/golang/go_template.go index 039f128..510ea93 100644 --- a/vendor/github.com/vmkteam/rpcgen/v2/golang/go_template.go +++ b/vendor/github.com/vmkteam/rpcgen/v2/golang/go_template.go @@ -16,9 +16,12 @@ import ( "strconv" "time" + "github.com/vmkteam/appkit" "github.com/vmkteam/zenrpc/v2" ) +const name = "{{ .Package }}" + var ( // Always import time package. Generated models can contain time.Time fields. _ time.Time @@ -30,13 +33,12 @@ type Client struct { {{ range .NamespaceNames }} {{ title . }} *svc{{ title .}}{{ end }}} -func NewDefaultClient(endpoint string) *Client { - return NewClient(endpoint, http.Header{}, &http.Client{}) -} - -func NewClient(endpoint string, header http.Header, httpClient *http.Client) *Client { +func NewClient(endpoint string, httpClient *http.Client) *Client { + if httpClient == nil { + httpClient = &http.Client{Timeout: time.Second * 30} + } c := &Client{ - rpcClient: newRPCClient(endpoint, header, httpClient), + rpcClient: newRPCClient(endpoint, httpClient), } {{ range .NamespaceNames }} c.{{ title . }} = newClient{{ title .}}(c.rpcClient){{ end }} @@ -105,13 +107,11 @@ type rpcClient struct { cl *http.Client requestID uint64 - header http.Header } -func newRPCClient(endpoint string, header http.Header, httpClient *http.Client) *rpcClient { +func newRPCClient(endpoint string, httpClient *http.Client) *rpcClient { return &rpcClient{ endpoint: endpoint, - header: header, cl: httpClient, } } @@ -133,6 +133,8 @@ func (rc *rpcClient) call(ctx context.Context, methodName string, request, resul Params: bts, } + ctx = appkit.NewCallerNameContext(ctx, name) + res, err := rc.Exec(ctx, req) if err != nil { return err @@ -159,7 +161,7 @@ func (rc *rpcClient) call(ctx context.Context, methodName string, request, resul // Exec makes http request to jsonrpc endpoint and returns json rpc response. func (rc *rpcClient) Exec(ctx context.Context, rpcReq zenrpc.Request) (*zenrpc.Response, error) { - if n, ok := ctx.Value("JSONRPC2-Notification").(bool); ok && n { + if appkit.NotificationFromContext(ctx) { rpcReq.ID = nil } @@ -174,12 +176,8 @@ func (rc *rpcClient) Exec(ctx context.Context, rpcReq zenrpc.Request) (*zenrpc.R return nil, fmt.Errorf("create request failed: %w", err) } - req.Header = rc.header.Clone() req.Header.Add("Content-Type", "application/json") - - if xRequestID, ok := ctx.Value("X-Request-Id").(string); ok && req.Header.Get("X-Request-Id") == "" && xRequestID != "" { - req.Header.Add("X-Request-Id", xRequestID) - } + appkit.SetXRequestIDFromCtx(ctx, req) // Do request resp, err := rc.cl.Do(req) diff --git a/vendor/github.com/vmkteam/rpcgen/v2/kotlin/kotlin_client.go b/vendor/github.com/vmkteam/rpcgen/v2/kotlin/kotlin_client.go new file mode 100644 index 0000000..04d7826 --- /dev/null +++ b/vendor/github.com/vmkteam/rpcgen/v2/kotlin/kotlin_client.go @@ -0,0 +1,493 @@ +package kotlin + +import ( + "bytes" + "fmt" + "regexp" + "sort" + "strconv" + "strings" + "text/template" + + "github.com/vmkteam/rpcgen/v2/gen" + "github.com/vmkteam/zenrpc/v2/smd" +) + +const ( + BasePackageAPI = "api" + BaseClass = "Api" + Bool = "Boolean" + Int = "Int" + Double = "Double" + Float = "Float" + String = "String" + Long = "Long" + Timestamp = "ZonedDateTime" + List = "List" + Map = "Map" + + DefaultBoolFalse = "false" + DefaultString = "\"\"" + DefaultInteger = "0" + DefaultDouble = "0.0" + DefaultFloat = "0f" + DefaultTimestamp = "ZonedDateTime.now()" + DefaultList = "emptyList()" + DefaultMap = "emptyMap()" + DefaultLocalTime = "LocalTime.now()" +) + +var ( + id = "id" + linebreakRegex = regexp.MustCompile("[\r\n]+") + kotlinDefaultValues = map[string]string{ + String: DefaultString, + Bool: DefaultBoolFalse, + Float: DefaultFloat, + Double: DefaultDouble, + Timestamp: DefaultTimestamp, + Int: DefaultInteger, + Long: DefaultInteger, + } + doubleSuffixes = map[string]struct{}{ + "Lat": {}, + "Lon": {}, + "Latitude": {}, + "Longitude": {}, + } + reservedKeywords = []string{"as", "as?", "break", "class", "continue", "do", "else", "false", "for", "fun", "if", + "in", "!in", "interface", "is", "!is", "null", "object", "package", "return", "super", "this", "throw", "true", + "try", "typealias", "typeof", "val", "var", "when", "while"} +) + +type templateData struct { + gen.GeneratorData + Methods []Method + Models []Model + PackageAPI string + Class string + Imports []string +} + +type Method struct { + Name string + SafeName string + Description []string + Errors []Parameter + Parameters []Parameter + Returns Parameter +} + +type Model struct { + Name string + Description string + IsInitial bool + Fields []Parameter +} + +type Parameter struct { + Name string + Description string + Type string + BaseType string + ReturnType string + Optional bool + DefaultValue string + IsObject bool + DecodableDefault string + Properties []Parameter +} + +type Settings struct { + Class string + IsProtocol bool + PackageAPI string + Imports []string + TypeMapper TypeMapper +} + +type TypeMapper func(typeName string, in smd.Property, kotlinType Parameter) Parameter + +type Generator struct { + schema smd.Schema + settings Settings +} + +func NewClient(schema smd.Schema, settings Settings) *Generator { + return &Generator{schema: schema, settings: settings} +} + +// Generate return kotlin generated code by template +func (g *Generator) Generate() ([]byte, error) { + data := g.prepareTemplateData() + + return g.executeTemplate(data) +} + +// prepareTemplateData prepare template data +func (g *Generator) prepareTemplateData() templateData { + if g.settings.PackageAPI == "" { + g.settings.PackageAPI = BasePackageAPI + } + + if g.settings.Class == "" { + g.settings.Class = BaseClass + } + + data := templateData{GeneratorData: gen.DefaultGeneratorData(), PackageAPI: g.settings.PackageAPI, Imports: g.settings.Imports, Class: g.settings.Class} + + modelsMap := make(map[string]Model) + servicesMap := make(map[string][]Method) + + for serviceName, service := range g.schema.Services { + var ( + params []Parameter + ) + desc := linebreakRegex.ReplaceAllString(service.Description, "\n") + method := Method{ + Name: serviceName, + Errors: g.prepareErrs(service.Errors), + SafeName: strings.ReplaceAll(serviceName, ".", ""), + Returns: g.prepareParameter(service.Returns), + } + if desc != "" { + method.Description = strings.Split(desc, "\n") + } + if len(service.Returns.Definitions) > 0 { + } + g.defToModelMap(modelsMap, service.Returns.Definitions) + paramToModelMap(modelsMap, method.Returns) + for _, param := range service.Parameters { + p := g.prepareParameter(param) + g.defToModelMap(modelsMap, param.Definitions) + paramToModelMap(modelsMap, p) + params = append(params, p) + } + method.Parameters = params + data.Methods = append(data.Methods, method) + if g.settings.IsProtocol { + parts := strings.SplitN(method.Name, ".", 2) + if len(parts) != 2 { + continue + } + servicesMap[parts[0]] = append(servicesMap[parts[0]], method) + } + } + + for _, v := range modelsMap { + data.Models = append(data.Models, v) + } + + g.fillIsInitial(&data) + g.sortTemplateData(&data) + g.prepareModelFieldName(&data) + + return data +} + +func (g *Generator) fillIsInitial(data *templateData) { + modelByName := make(map[string]*Model, len(data.Models)) + for i := range data.Models { + modelByName[data.Models[i].Name] = &data.Models[i] + } + + initialMap := make(map[string]struct{}) + + // first step - search from all methods and find all model from method params + for _, m := range data.Methods { + for _, p := range m.Parameters { + if p.IsObject { + typ := p.Type + if typ == "" { + typ = p.ReturnType + } + checkModelName(typ, modelByName, initialMap) + } + } + } + + // init loop for initialMap + for loopWithChanged := true; loopWithChanged; { + loopWithChanged = false + for t := range initialMap { + md := modelByName[t] + if md == nil { + continue + } + for _, f := range md.Fields { + if f.IsObject { + if _, ok := initialMap[f.Type]; !ok { + // when find new modelName - use checkModelName and add next cycle + checkModelName(f.Type, modelByName, initialMap) + loopWithChanged = true + } + } + } + } + } + + for name := range initialMap { + if md := modelByName[name]; md != nil { + md.IsInitial = true + } + } +} + +func checkModelName(name string, modelByName map[string]*Model, initialMap map[string]struct{}) { + if name == "" { + return + } + if _, ok := modelByName[name]; !ok { + return + } + initialMap[name] = struct{}{} +} + +func (g *Generator) prepareModelFieldName(data *templateData) { + for i := range data.Models { + for j := range data.Models[i].Fields { + data.Models[i].Fields[j].Name = formattedReservedKey(data.Models[i].Fields[j].Name) + } + } +} + +func (g *Generator) sortTemplateData(data *templateData) { + sort.Slice(data.Methods, func(i, j int) bool { + return data.Methods[i].Name < data.Methods[j].Name + }) + + sort.Slice(data.Models, func(i, j int) bool { + return data.Models[i].Name < data.Models[j].Name + }) + + for idx := range data.Models { + sort.Slice(data.Models[idx].Fields, func(i, j int) bool { + return data.Models[idx].Fields[i].Name < data.Models[idx].Fields[j].Name + }) + } +} + +func (g *Generator) executeTemplate(data templateData) ([]byte, error) { + t := model + if g.settings.IsProtocol { + t = protocolTemplate + } + + gen.TemplateFuncs["hasDescriptions"] = hasDescriptions + + tmpl, err := template.New("kotlin_client").Funcs(gen.TemplateFuncs).Parse(t) + if err != nil { + return nil, err + } + + var buf bytes.Buffer + if err := tmpl.Execute(&buf, data); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +// propertiesToParams convert smd.PropertyList to []Parameter +func (g *Generator) propertiesToParams(typeName string, list smd.PropertyList) []Parameter { + parameters := make([]Parameter, 0, len(list)) + for _, prop := range list { + p := Parameter{ + Name: prop.Name, + Optional: prop.Optional, + Description: prop.Description, + } + + pType := kotlinType(prop.Type, p.Name) + if prop.Type == smd.Object && prop.Ref != "" { + pType = strings.TrimPrefix(prop.Ref, gen.DefinitionsPrefix) + p.IsObject = true + } + + if prop.Type == smd.Array { + prop.Items["name"] = p.Name + pType = arrayType(prop.Items, false) + } + + p.Type = pType + + p.DefaultValue = kotlinDefault(pType) + + if g.settings.TypeMapper != nil { + p = g.settings.TypeMapper(typeName, prop, p) + } + parameters = append(parameters, p) + } + return parameters +} + +// prepareErrs convert errs map to []Parameter +func (g *Generator) prepareErrs(errs map[int]string) []Parameter { + pp := make([]Parameter, 0, len(errs)) + for code, err := range errs { + pp = append(pp, Parameter{ + Name: strconv.Itoa(code), + Description: err, + }) + } + + return pp +} + +// prepareParameter create Parameter from smd.JSONSchema +func (g *Generator) prepareParameter(in smd.JSONSchema) Parameter { + out := Parameter{ + Name: in.Name, + Description: in.Description, + BaseType: kotlinType(in.Type), + Optional: in.Optional, + Properties: g.propertiesToParams(in.TypeName, in.Properties), + } + + pType := out.BaseType + out.ReturnType = pType + if in.Type == smd.Object { + typeName := in.TypeName + if typeName == "" && in.Description != "" && smd.IsSMDTypeName(in.Description, in.Type) { + typeName = in.Description + } + + if typeName != "" { + pType = typeName + out.ReturnType = pType + + } + out.IsObject = true + } + out.Type = pType + + if in.Type == smd.Array { + in.Items["name"] = in.Name + out.Type = arrayType(in.Items, false) + out.ReturnType = arrayType(in.Items, true) + } + + return out +} + +// defToModelMap convert smd.Definition to Model and add to models map +func (g *Generator) defToModelMap(modelMap map[string]Model, definitions map[string]smd.Definition) { + for name, def := range definitions { + modelMap[name] = Model{Name: name, Fields: g.propertiesToParams(name, def.Properties)} + } +} + +// paramToModelMap add Parameter to model map if parameter is object +func paramToModelMap(modelsMap map[string]Model, p Parameter) { + if p.IsObject && p.BaseType != p.Type { + modelsMap[p.Type] = Model{ + Name: p.Type, + Fields: p.Properties, + } + } +} + +// kotlinType convert smd types to kotlin types +func kotlinType(smdType string, propNames ...string) string { + var name string + if len(propNames) > 0 { + name = propNames[0] + } + + switch smdType { + case smd.String: + if kotlinTypeTimestamp(name) { + return Timestamp + } + return String + case smd.Boolean: + return Bool + case smd.Float: + if kotlinTypeDouble(name) { + return Double + } + return Float + case smd.Integer: + if kotlinTypeID(name) { + return Long + } + return Int + } + return smdType +} + +// kotlinDefault convert smd types to kotlin default types +func kotlinDefault(smdType string) string { + if val, ok := kotlinDefaultValues[smdType]; ok { + return val + } + + if strings.HasPrefix(smdType, List) { + return DefaultList + } + + if strings.HasPrefix(smdType, Map) { + return DefaultList + } + + return smdType +} + +// kotlinTypeDouble check if property need set type Double +func kotlinTypeDouble(name string) bool { + if _, ok := doubleSuffixes[name]; ok { + return true + } + + for suffix := range doubleSuffixes { + if strings.HasSuffix(name, suffix) { + return true + } + } + + return false +} + +// kotlinTypeID check if property is ID set type Long +func kotlinTypeID(name string) bool { + return name == id || + strings.HasSuffix(name, strings.ToUpper(id)) || + strings.HasSuffix(name, "Id") || + strings.HasSuffix(name, "Ids") +} + +// kotlinTypeTimestamp check if is time property set Timestamp +func kotlinTypeTimestamp(name string) bool { + return strings.HasSuffix(name, "edAt") +} + +func arrayType(items map[string]string, isReturnType bool) string { + var subType string + if scalar, ok := items["type"]; ok { + subType = kotlinType(scalar, items["name"]) + } + if ref, ok := items["$ref"]; ok { + subType = strings.TrimPrefix(ref, gen.DefinitionsPrefix) + } + + if isReturnType { + return subType + } + + return fmt.Sprintf("List<%s>", subType) +} + +// hasDescriptions check description +func hasDescriptions(m Method) bool { + return m.Returns.Description != "" || len(m.Description) > 0 || len(m.Parameters) > 0 +} + +// formattedReservedKey formatted if key exist in reservedKeywords +func formattedReservedKey(str string) string { + for _, keyword := range reservedKeywords { + if str == keyword { + return fmt.Sprintf("`%s`", str) + } + } + return str +} diff --git a/vendor/github.com/vmkteam/rpcgen/v2/kotlin/kotlin_template.go b/vendor/github.com/vmkteam/rpcgen/v2/kotlin/kotlin_template.go new file mode 100644 index 0000000..bcc5efa --- /dev/null +++ b/vendor/github.com/vmkteam/rpcgen/v2/kotlin/kotlin_template.go @@ -0,0 +1,84 @@ +package kotlin + +const model = `/// Code generated from jsonrpc schema by rpcgen v{{ .Version }}; DO NOT EDIT. +package {{ .PackageAPI }}.model + +import java.time.LocalTime +import java.time.ZonedDateTime + +{{ range $model := .Models }} +{{- if $model.Description }} +/// {{ $model.Description }} +{{- end }} +data class {{ $model.Name }}( + {{- $fieldsLen := len $model.Fields }}{{- range $model.Fields }} + {{- if .Description }} + /** + * {{ .Description }} + */ + {{- end }} + {{- if $model.IsInitial }} + val {{ .Name }}: {{ .Type }}{{ if .Optional }}? = null{{ else }} = {{ .DefaultValue}}{{ if .IsObject}}(){{ else }}{{ end }}{{ end }}, + {{- else }} + val {{ .Name }}: {{ .Type }}{{ if .Optional }}?{{ else }}{{ end }}, + {{- end }} + {{- end }} +) +{{ end }} +` +const protocolTemplate = `/// Code generated from jsonrpc schema by rpcgen v{{ .Version }}; DO NOT EDIT. +package {{ .PackageAPI }} + +import com.google.gson.reflect.TypeToken +import java.time.ZonedDateTime +import java.time.LocalTime +import {{ .PackageAPI }}.model.* +{{- range .Imports }} +import {{.}} +{{- end }} + +interface {{ .Class }} : Transport { +{{- range .Methods }} +{{ if hasDescriptions . }} + /** +{{- range .Description }} + {{- if ne . "" }} + * {{ . }} + {{- end }} +{{- end }} +{{- if (len .Errors) }} + * + * Коды ошибок: + * + {{- range .Errors }} + * "{{.Name}}": "{{.Description}}", + {{- end }} + * + * +{{- end -}} +{{ if (len .Parameters) }} + {{- range .Parameters }} + {{- if ne .Description "" }} + * @param {{ .Name }} + {{- end }} + {{- end }} +{{- end }} + * @return + */ +{{- end }} + fun {{ .SafeName }}( +{{- range .Parameters}} + {{ .Name }}: {{ .Type }}{{ if .Optional }}?{{ end }}, +{{- end}} + vararg transportOptions: TransportOption, + ) = request( + transportOptions, + object : TypeToken>() {}, + "{{ .Name }}", +{{- range .Parameters}} + "{{ .Name }}" to {{ .Name }}, +{{- end}} + ) +{{- end }} +} +` diff --git a/vendor/github.com/vmkteam/rpcgen/v2/typescript/typescript_client.go b/vendor/github.com/vmkteam/rpcgen/v2/typescript/typescript_client.go index 28ace7c..63426e4 100644 --- a/vendor/github.com/vmkteam/rpcgen/v2/typescript/typescript_client.go +++ b/vendor/github.com/vmkteam/rpcgen/v2/typescript/typescript_client.go @@ -30,6 +30,7 @@ type Settings struct { TypeMapper TypeMapper ExcludedNamespace []string WithClasses bool + TypesOnly bool } func NewClient(schema smd.Schema, settings Settings) *Generator { @@ -89,11 +90,13 @@ type tsService struct { HasParams bool Params string Response string + Comment string } type tsModels struct { gen.GeneratorData WithClasses bool + TypesOnly bool Interfaces []tsInterface Namespaces []tsServiceNamespace } @@ -208,6 +211,7 @@ skipNS: HasParams: false, Params: "", Response: respType.Type, + Comment: service.Description, } if len(service.Parameters) > 0 { respService.HasParams = true @@ -238,6 +242,7 @@ skipNS: } models.WithClasses = g.settings.WithClasses + models.TypesOnly = g.settings.TypesOnly return models } diff --git a/vendor/github.com/vmkteam/rpcgen/v2/typescript/typescript_template.go b/vendor/github.com/vmkteam/rpcgen/v2/typescript/typescript_template.go index b667e88..971425e 100644 --- a/vendor/github.com/vmkteam/rpcgen/v2/typescript/typescript_template.go +++ b/vendor/github.com/vmkteam/rpcgen/v2/typescript/typescript_template.go @@ -24,12 +24,35 @@ export class {{ .ModelName }} implements {{ .Name }} { {{ end }} {{- end }} +{{- if .TypesOnly }} +export interface RpcMethods { +{{- $lenN := len .Namespaces }} +{{- range $i,$e := .Namespaces }} + {{ .Name }}: { +{{- $lenS := len .Services }} +{{- range $i, $e := .Services }} +{{- if ne .Comment "" }} + /** + * {{ .Comment }} + */ +{{- end }} + {{ .NameLCF }}({{ if .HasParams }}params: {{ .Params }}{{ end }}): Promise<{{ .Response }}>{{ if ne $i $lenS }},{{ end }} +{{- end }} + }{{ if ne $i $lenN }},{{ end }} +{{- end }} +} +{{- else }} export const factory = (send: any) => ({ {{- $lenN := len .Namespaces }} {{- range $i,$e := .Namespaces }} {{ .Name }}: { {{- $lenS := len .Services }} {{- range $i, $e := .Services }} +{{- if ne .Comment "" }} + /** + * {{ .Comment }} + */ +{{- end }} {{ .NameLCF }}({{ if .HasParams }}params: {{ .Params }}{{ end }}): Promise<{{ .Response }}> { return send('{{ .Namespace }}.{{ .Name }}'{{ if .HasParams }}, params{{ end }}) }{{ if ne $i $lenS }},{{ end }} @@ -37,4 +60,5 @@ export const factory = (send: any) => ({ }{{ if ne $i $lenN }},{{ end }} {{- end }} }) +{{- end }} ` diff --git a/vendor/github.com/vmkteam/vfs/README.md b/vendor/github.com/vmkteam/vfs/README.md index e6e45d1..5c964a3 100644 --- a/vendor/github.com/vmkteam/vfs/README.md +++ b/vendor/github.com/vmkteam/vfs/README.md @@ -39,3 +39,41 @@ HTTP Params: * Default namespace and default extension (jpg): `curl -F 'Filedata=@image.jpg' http://localhost:9999/upload/hash` * Specific namespace (test): `curl -F 'Filedata=@image.jpg' http://localhost:9999/upload/hash?ns=test` * Specific namespace (test) with file extension: `curl -F 'Filedata=@image.gif' http://localhost:9999/upload/hash?ns=test&ext=gif` + +### Default configuration + +* Run service in cli with `init-cfg` argument to generate `config.toml` with default configuration. +* Default configuration example: + +```toml +[Server] + Host = "0.0.0.0" + Port = 9999 + IsDevel = false + JWTHeader = "AuthorizationJWT" + JWTKey = "" + Index = false + IndexBlurhash = true + IndexWorkers = 6 + IndexBatchSize = 64 + +[VFS] + MaxFileSize = 33554432 + Path = "testdata" + WebPath = "/media/" + PreviewPath = "/media/small/" + Namespaces = ["items", "test"] + Extensions = ["jpg", "jpeg", "png", "gif"] + MimeTypes = ["image/jpeg", "image/png", "image/gif"] + UploadFormName = "Filedata" + SaltedFilenames = false + SkipFolderVerify = false + +[Database] + Addr = "localhost:5432" + User = "postgres" + Password = "" + Database = "apisrv" + PoolSize = 10 + ApplicationName = "vfssrv" +``` diff --git a/vendor/github.com/vmkteam/vfs/db/logger.go b/vendor/github.com/vmkteam/vfs/db/logger.go index cdb1e9a..fa68130 100644 --- a/vendor/github.com/vmkteam/vfs/db/logger.go +++ b/vendor/github.com/vmkteam/vfs/db/logger.go @@ -3,6 +3,7 @@ package db import ( "context" "fmt" + "log/slog" "time" "github.com/go-pg/pg/v10" @@ -19,6 +20,11 @@ func NewQueryLogger(logger embedlog.Logger) QueryLogger { return QueryLogger{Logger: logger} } +// Printf used for pg.SetLogger +func (s QueryLogger) Printf(_ context.Context, format string, args ...interface{}) { + s.Logger.With(slog.String("lib", "pg")).Errorf(format, args...) +} + func (ql QueryLogger) BeforeQuery(ctx context.Context, event *pg.QueryEvent) (context.Context, error) { if event.Stash == nil { event.Stash = make(map[interface{}]interface{}) diff --git a/vendor/github.com/vmkteam/zenrpc-middleware/Makefile b/vendor/github.com/vmkteam/zenrpc-middleware/Makefile new file mode 100644 index 0000000..d4c274d --- /dev/null +++ b/vendor/github.com/vmkteam/zenrpc-middleware/Makefile @@ -0,0 +1,20 @@ +LINT_VERSION := v2.5.0 +.PHONY: * + +tools: + @curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${LINT_VERSION} + +fmt: + @golangci-lint fmt + +lint: + @golangci-lint version + @golangci-lint config verify + @golangci-lint run + +run: + @go run example/main.go + +mod: + @go mod tidy + diff --git a/vendor/github.com/vmkteam/zenrpc-middleware/README.md b/vendor/github.com/vmkteam/zenrpc-middleware/README.md index c59e642..c4373ab 100644 --- a/vendor/github.com/vmkteam/zenrpc-middleware/README.md +++ b/vendor/github.com/vmkteam/zenrpc-middleware/README.md @@ -79,30 +79,6 @@ sensitive error data from response. It is good to use pkg/errors for stack trace Same as `WithErrorLogger`, but for slog. -### XRequestID - -Handler for adding `X-Request-ID` header to all requests and responses. - -```go - s := http.NewServer(middleware.XRequestID(http.HandlerFunc(rpc.ServeHTTP))) -``` - -### EchoIPContext - -Echo middleware for adding client IP info to context for zenrpc middleware - -```go - e.Use(middleware.EchoIPContext()) -``` - -### EchoSentryHubContext - -Echo middleware for adding sentry hub info to context for zenrpc middleware - -```go - e.Use(middleware.EchoSentryHubContext()) -``` - ## Examples ### Basic usage @@ -156,29 +132,3 @@ func main() { // rpc.Register and server ``` -### Handler snippets - -```go -// sentry init -sentry.Init(sentry.ClientOptions{ - Dsn: cfg.Sentry.DSN, - Environment: cfg.Sentry.Environment, - Release: version, -} - -// sentry middleware for Echo -e.Use(sentryecho.New(sentryecho.Options{ - Repanic: true, - WaitForDelivery: true, -})) - -// register handler -a.echo.Any("/v1/rpc/", middleware.EchoHandler(rpc)) - ---- OR --- - -e.Use(middleware.EchoIPContext()), middleware.EchoSentryHubContext()) -// register handler -e.Any("/int/rpc/", echo.WrapHandler(XRequestID(rpc))) - -``` diff --git a/vendor/github.com/vmkteam/zenrpc-middleware/logger.go b/vendor/github.com/vmkteam/zenrpc-middleware/logger.go index 0b07201..04f4f1d 100644 --- a/vendor/github.com/vmkteam/zenrpc-middleware/logger.go +++ b/vendor/github.com/vmkteam/zenrpc-middleware/logger.go @@ -6,6 +6,7 @@ import ( "errors" "time" + "github.com/vmkteam/appkit" "github.com/vmkteam/zenrpc/v2" ) @@ -21,15 +22,15 @@ func WithAPILogger(pf Printf, serverName string) zenrpc.MiddlewareFunc { methodName := fullMethodName(serverName, zenrpc.NamespaceFromContext(ctx), method) pf("ip=%s platform=%q version=%q method=%s duration=%v params=%q err=%q userAgent=%q xRequestId=%q", - IPFromContext(ctx), - PlatformFromContext(ctx), - VersionFromContext(ctx), + appkit.IPFromContext(ctx), + appkit.PlatformFromContext(ctx), + appkit.VersionFromContext(ctx), methodName, time.Since(start), params, r.Error, - UserAgentFromContext(ctx), - XRequestIDFromContext(ctx), + appkit.UserAgentFromContext(ctx), + appkit.XRequestIDFromContext(ctx), ) return r @@ -62,8 +63,8 @@ func WithSLog(pf Print, serverName string, fn LogAttrs) zenrpc.MiddlewareFunc { "durationMS", t.Milliseconds(), "params", params, "err", r.Error, - "userAgent", UserAgentFromContext(ctx), - "xRequestId", XRequestIDFromContext(ctx), + "userAgent", appkit.UserAgentFromContext(ctx), + "xRequestId", appkit.XRequestIDFromContext(ctx), }...) pf(ctx, "rpc", append(logArgs, args...)...) @@ -74,16 +75,16 @@ func WithSLog(pf Print, serverName string, fn LogAttrs) zenrpc.MiddlewareFunc { func additionalArgs(ctx context.Context) []any { r := make([]any, 0, 4) - r = append(r, "ip", IPFromContext(ctx)) - if v := CountryFromContext(ctx); v != "" { + r = append(r, "ip", appkit.IPFromContext(ctx)) + if v := appkit.CountryFromContext(ctx); v != "" { r = append(r, "country", v) } - if v := PlatformFromContext(ctx); v != "" { + if v := appkit.PlatformFromContext(ctx); v != "" { r = append(r, "platform", v) } - if v := VersionFromContext(ctx); v != "" { + if v := appkit.VersionFromContext(ctx); v != "" { r = append(r, "version", v) } diff --git a/vendor/github.com/vmkteam/zenrpc-middleware/metrics.go b/vendor/github.com/vmkteam/zenrpc-middleware/metrics.go index 35e928f..fe8a7bb 100644 --- a/vendor/github.com/vmkteam/zenrpc-middleware/metrics.go +++ b/vendor/github.com/vmkteam/zenrpc-middleware/metrics.go @@ -8,6 +8,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "github.com/vmkteam/appkit" "github.com/vmkteam/zenrpc/v2" ) @@ -54,7 +55,7 @@ func WithMetrics(serverName string) zenrpc.MiddlewareFunc { } // set platform & version - platform, version := PlatformFromContext(ctx), VersionFromContext(ctx) + platform, version := appkit.PlatformFromContext(ctx), appkit.VersionFromContext(ctx) if r.Error != nil { if r.Error.Code == zenrpc.MethodNotFound { diff --git a/vendor/github.com/vmkteam/zenrpc-middleware/middleware.go b/vendor/github.com/vmkteam/zenrpc-middleware/middleware.go index 55268ea..9ff1c53 100644 --- a/vendor/github.com/vmkteam/zenrpc-middleware/middleware.go +++ b/vendor/github.com/vmkteam/zenrpc-middleware/middleware.go @@ -5,40 +5,26 @@ import ( "encoding/json" "github.com/labstack/echo/v4" + "github.com/vmkteam/appkit" "github.com/vmkteam/zenrpc/v2" ) const ( - isDevelCtx contextKey = "isDevel" - ctxPlatformKey contextKey = "platform" - ctxVersionKey contextKey = "version" - ctxMethodKey contextKey = "method" - ctxIPKey contextKey = "ip" - ctxUserAgentKey contextKey = "userAgent" - ctxCountryKey contextKey = "country" - - ctxNotificationKey = "JSONRPC2-Notification" - // DefaultServerName is a global default name, mostly used for metrics. DefaultServerName = "" - - maxUserAgentLength = 2048 - maxVersionLength = 64 - maxCountryLength = 16 ) type ( - contextKey string - Printf func(format string, v ...interface{}) - Print func(ctx context.Context, msg string, args ...any) - LogAttrs func(ctx context.Context, r zenrpc.Response) []any + Printf func(format string, v ...interface{}) + Print func(ctx context.Context, msg string, args ...any) + LogAttrs func(ctx context.Context, r zenrpc.Response) []any ) // WithDevel sets bool flag to context for detecting development environment. func WithDevel(isDevel bool) zenrpc.MiddlewareFunc { return func(h zenrpc.InvokeFunc) zenrpc.InvokeFunc { return func(ctx context.Context, method string, params json.RawMessage) zenrpc.Response { - ctx = NewIsDevelContext(ctx, isDevel) + ctx = appkit.NewIsDevelContext(ctx, isDevel) return h(ctx, method, params) } } @@ -58,12 +44,12 @@ func WithHeaders() zenrpc.MiddlewareFunc { return func(h zenrpc.InvokeFunc) zenrpc.InvokeFunc { return func(ctx context.Context, method string, params json.RawMessage) zenrpc.Response { if req, ok := zenrpc.RequestFromContext(ctx); ok && req != nil { - ctx = NewUserAgentContext(ctx, req.UserAgent()) - ctx = NewPlatformContext(ctx, req.Header.Get("Platform")) - ctx = NewVersionContext(ctx, req.Header.Get("Version")) - ctx = NewXRequestIDContext(ctx, req.Header.Get(echo.HeaderXRequestID)) - ctx = NewCountryContext(ctx, req.Header.Get("X-Country")) - ctx = NewMethodContext(ctx, method) + ctx = appkit.NewUserAgentContext(ctx, req.UserAgent()) + ctx = appkit.NewPlatformContext(ctx, req.Header.Get("Platform")) + ctx = appkit.NewVersionContext(ctx, req.Header.Get("Version")) + ctx = appkit.NewXRequestIDContext(ctx, req.Header.Get(echo.HeaderXRequestID)) + ctx = appkit.NewCountryContext(ctx, req.Header.Get("X-Country")) + ctx = appkit.NewMethodContext(ctx, method) } return h(ctx, method, params) } @@ -71,102 +57,99 @@ func WithHeaders() zenrpc.MiddlewareFunc { } // NewIPContext creates new context with IP. +// Deprecated: use appkit.NewIPContext. func NewIPContext(ctx context.Context, ip string) context.Context { - return context.WithValue(ctx, ctxIPKey, ip) + return appkit.NewIPContext(ctx, ip) } // IPFromContext returns IP from context. +// Deprecated: use appkit.IPFromContext. func IPFromContext(ctx context.Context) string { - r, _ := ctx.Value(ctxIPKey).(string) - return r + return appkit.IPFromContext(ctx) } // NewUserAgentContext creates new context with User-Agent. +// Deprecated: use appkit.NewUserAgentContext. func NewUserAgentContext(ctx context.Context, ua string) context.Context { - return context.WithValue(ctx, ctxUserAgentKey, cutString(ua, maxUserAgentLength)) + return appkit.NewUserAgentContext(ctx, ua) } // UserAgentFromContext returns userAgent from context. +// Deprecated: use appkit.UserAgentFromContext. func UserAgentFromContext(ctx context.Context) string { - r, _ := ctx.Value(ctxUserAgentKey).(string) - return r + return appkit.UserAgentFromContext(ctx) } // NewNotificationContext creates new context with JSONRPC2 notification flag. +// Deprecated: use appkit.NewNotificationContext. func NewNotificationContext(ctx context.Context) context.Context { - //nolint:staticcheck // must be global - return context.WithValue(ctx, ctxNotificationKey, true) + return appkit.NewNotificationContext(ctx) } // NotificationFromContext returns JSONRPC2 notification flag from context. +// Deprecated: use appkit.NotificationFromContext. func NotificationFromContext(ctx context.Context) bool { - r, _ := ctx.Value(ctxNotificationKey).(bool) - return r + return appkit.NotificationFromContext(ctx) } // NewIsDevelContext creates new context with isDevel flag. +// Deprecated: use appkit.NewIsDevelContext. func NewIsDevelContext(ctx context.Context, isDevel bool) context.Context { - return context.WithValue(ctx, isDevelCtx, isDevel) + return appkit.NewIsDevelContext(ctx, isDevel) } // IsDevelFromContext returns isDevel flag from context. +// Deprecated: use appkit.IsDevelFromContext. func IsDevelFromContext(ctx context.Context) bool { - if isDevel, ok := ctx.Value(isDevelCtx).(bool); ok { - return isDevel - } - return false + return appkit.IsDevelFromContext(ctx) } // NewPlatformContext creates new context with platform. +// Deprecated: use appkit.NewPlatformContext. func NewPlatformContext(ctx context.Context, platform string) context.Context { - return context.WithValue(ctx, ctxPlatformKey, cutString(platform, 64)) + return appkit.NewPlatformContext(ctx, platform) } // PlatformFromContext returns platform from context. +// Deprecated: use appkit.PlatformFromContext. func PlatformFromContext(ctx context.Context) string { - r, _ := ctx.Value(ctxPlatformKey).(string) - return r + return appkit.PlatformFromContext(ctx) } // NewVersionContext creates new context with version. +// Deprecated: use appkit.NewVersionContext. func NewVersionContext(ctx context.Context, version string) context.Context { - return context.WithValue(ctx, ctxVersionKey, cutString(version, maxVersionLength)) + return appkit.NewVersionContext(ctx, version) } // VersionFromContext returns version from context. +// Deprecated: use appkit.VersionFromContext. func VersionFromContext(ctx context.Context) string { - r, _ := ctx.Value(ctxVersionKey).(string) - return r + return appkit.VersionFromContext(ctx) } // NewCountryContext creates new context with country. +// Deprecated: use appkit.NewCountryContext. func NewCountryContext(ctx context.Context, country string) context.Context { - return context.WithValue(ctx, ctxCountryKey, cutString(country, maxCountryLength)) + return appkit.NewCountryContext(ctx, country) } // CountryFromContext returns country from context. +// Deprecated: use appkit.CountryFromContext. func CountryFromContext(ctx context.Context) string { - r, _ := ctx.Value(ctxCountryKey).(string) - return r + return appkit.CountryFromContext(ctx) } // NewMethodContext creates new context with Method. +// Deprecated: use appkit.NewMethodContext. func NewMethodContext(ctx context.Context, method string) context.Context { - return context.WithValue(ctx, ctxMethodKey, method) + return appkit.NewMethodContext(ctx, method) } // MethodFromContext returns Method from context. +// Deprecated: use appkit.MethodFromContext. func MethodFromContext(ctx context.Context) string { - r, _ := ctx.Value(ctxMethodKey).(string) - return r -} - -// cutString cuts string with given length. -func cutString(s string, length int) string { - if len(s) > length { - return s[:length] - } - return s + return appkit.MethodFromContext(ctx) } // fullMethodName returns namespace.method or serverName.namespace.method. diff --git a/vendor/github.com/vmkteam/zenrpc-middleware/sentry.go b/vendor/github.com/vmkteam/zenrpc-middleware/sentry.go index 348e5d4..b8db4db 100644 --- a/vendor/github.com/vmkteam/zenrpc-middleware/sentry.go +++ b/vendor/github.com/vmkteam/zenrpc-middleware/sentry.go @@ -9,25 +9,10 @@ import ( "time" "github.com/getsentry/sentry-go" + "github.com/vmkteam/appkit" "github.com/vmkteam/zenrpc/v2" ) -const ctxSentryHubKey contextKey = "sentryHub" - -// NewSentryHubContext creates new context with Sentry Hub. -func NewSentryHubContext(ctx context.Context, sentryHub *sentry.Hub) context.Context { - if sentryHub == nil { - return ctx - } - return context.WithValue(ctx, ctxSentryHubKey, sentryHub) -} - -// sentryHubFromContext returns Sentry Hub from context. -func sentryHubFromContext(ctx context.Context) (*sentry.Hub, bool) { - r, ok := ctx.Value(ctxSentryHubKey).(*sentry.Hub) - return r, ok -} - // WithSentry sets additional parameters for current Sentry scope. Extras: params, duration, ip. Tags: platform, // version, method. It's also handles panic. func WithSentry(serverName string) zenrpc.MiddlewareFunc { @@ -45,8 +30,8 @@ func WithSentry(serverName string) zenrpc.MiddlewareFunc { } } - if hub, ok := sentryHubFromContext(ctx); ok { - start, platform, version, ip, xRequestID := time.Now(), PlatformFromContext(ctx), VersionFromContext(ctx), IPFromContext(ctx), XRequestIDFromContext(ctx) + if hub := sentry.GetHubFromContext(ctx); hub != nil { + start, platform, version, ip, xRequestID := time.Now(), appkit.PlatformFromContext(ctx), appkit.VersionFromContext(ctx), appkit.IPFromContext(ctx), appkit.XRequestIDFromContext(ctx) methodName := fullMethodName(serverName, zenrpc.NamespaceFromContext(ctx), method) @@ -79,7 +64,7 @@ func WithSentry(serverName string) zenrpc.MiddlewareFunc { func WithErrorLogger(pf Printf, serverName string) zenrpc.MiddlewareFunc { return func(h zenrpc.InvokeFunc) zenrpc.InvokeFunc { return func(ctx context.Context, method string, params json.RawMessage) zenrpc.Response { - start, platform, version, ip, xRequestID := time.Now(), PlatformFromContext(ctx), VersionFromContext(ctx), IPFromContext(ctx), XRequestIDFromContext(ctx) + start, platform, version, ip, xRequestID := time.Now(), appkit.PlatformFromContext(ctx), appkit.VersionFromContext(ctx), appkit.IPFromContext(ctx), appkit.XRequestIDFromContext(ctx) namespace := zenrpc.NamespaceFromContext(ctx) r := h(ctx, method, params) @@ -89,22 +74,29 @@ func WithErrorLogger(pf Printf, serverName string) zenrpc.MiddlewareFunc { pf("ip=%s platform=%q version=%q method=%s duration=%v params=%s xRequestId=%q err=%q", ip, platform, version, methodName, duration, params, xRequestID, r.Error) - sentry.WithScope(func(scope *sentry.Scope) { - scope.SetExtras(map[string]interface{}{ - "params": params, - "duration": duration.String(), - "ip": ip, - "error.data": r.Error.Data, - "error.code": r.Error.Code, - }) - scope.SetTags(map[string]string{ - "platform": platform, - "version": version, - "method": methodName, - "xRequestId": xRequestID, - }) - sentry.CaptureException(r.Error) + // initialize hub and scope + currentHub, scope := sentry.CurrentHub(), sentry.NewScope() + + // set hub and scope from context, if present + if hub := sentry.GetHubFromContext(ctx); hub != nil { + scope = hub.Scope() + currentHub = hub + } + + scope.SetExtras(map[string]interface{}{ + "params": params, + "duration": duration.String(), + "ip": ip, + "error.data": r.Error.Data, + "error.code": r.Error.Code, }) + scope.SetTags(map[string]string{ + "platform": platform, + "version": version, + "method": methodName, + "xRequestId": xRequestID, + }) + currentHub.CaptureException(r.Error) // remove sensitive error data from response r.Error.Err = nil @@ -135,7 +127,7 @@ func WithErrorSLog(pf Print, serverName string, fn LogAttrs) zenrpc.MiddlewareFu } if r.Error != nil && (r.Error.Code == http.StatusInternalServerError || r.Error.Code < 0) { - start, platform, version, ip, xRequestID := time.Now(), PlatformFromContext(ctx), VersionFromContext(ctx), IPFromContext(ctx), XRequestIDFromContext(ctx) + start, platform, version, ip, xRequestID := time.Now(), appkit.PlatformFromContext(ctx), appkit.VersionFromContext(ctx), appkit.IPFromContext(ctx), appkit.XRequestIDFromContext(ctx) namespace := zenrpc.NamespaceFromContext(ctx) duration := time.Since(start) @@ -148,28 +140,35 @@ func WithErrorSLog(pf Print, serverName string, fn LogAttrs) zenrpc.MiddlewareFu "durationMS", t.Milliseconds(), "params", params, "err", r.Error, - "userAgent", UserAgentFromContext(ctx), - "xRequestId", XRequestIDFromContext(ctx), + "userAgent", appkit.UserAgentFromContext(ctx), + "xRequestId", appkit.XRequestIDFromContext(ctx), }...) pf(ctx, "rpc error", append(logArgs, args...)...) - sentry.WithScope(func(scope *sentry.Scope) { - scope.SetExtras(map[string]interface{}{ - "params": params, - "duration": duration.String(), - "ip": ip, - "error.data": r.Error.Data, - "error.code": r.Error.Code, - }) - scope.SetTags(map[string]string{ - "platform": platform, - "version": version, - "method": methodName, - "xRequestId": xRequestID, - }) - sentry.CaptureException(r.Error) + // initialize hub and scope + currentHub, scope := sentry.CurrentHub(), sentry.NewScope() + + // set hub and scope from context, if present + if hub := sentry.GetHubFromContext(ctx); hub != nil { + scope = hub.Scope() + currentHub = hub + } + + scope.SetExtras(map[string]interface{}{ + "params": params, + "duration": duration.String(), + "ip": ip, + "error.data": r.Error.Data, + "error.code": r.Error.Code, + }) + scope.SetTags(map[string]string{ + "platform": platform, + "version": version, + "method": methodName, + "xRequestId": xRequestID, }) + currentHub.CaptureException(r.Error) // remove sensitive error data from response r.Error.Err = nil diff --git a/vendor/github.com/vmkteam/zenrpc-middleware/sql_logger.go b/vendor/github.com/vmkteam/zenrpc-middleware/sql_logger.go index dafb7a3..fca2e64 100644 --- a/vendor/github.com/vmkteam/zenrpc-middleware/sql_logger.go +++ b/vendor/github.com/vmkteam/zenrpc-middleware/sql_logger.go @@ -11,50 +11,38 @@ import ( "time" "github.com/go-pg/pg/v10" + "github.com/vmkteam/appkit" "github.com/vmkteam/zenrpc/v2" ) const ( - debugIDCtx contextKey = "debugID" - sqlGroupCtx contextKey = "sqlGroup" - - emptyDebugID = 0 eventStartedAt = "queryStartedAt" ) type AllowDebugFunc func(*http.Request) bool +// DebugIDFromContext returns debug id from context. +// Deprecated: use appkit.DebugIDFromContext. func DebugIDFromContext(ctx context.Context) uint64 { - if ctx == nil { - return emptyDebugID - } - - if id, ok := ctx.Value(debugIDCtx).(uint64); ok { - return id - } - - return emptyDebugID + return appkit.DebugIDFromContext(ctx) } // NewDebugIDContext creates new context with debug ID. +// Deprecated: use appkit.NewDebugIDContext. func NewDebugIDContext(ctx context.Context, debugID uint64) context.Context { - return context.WithValue(ctx, debugIDCtx, debugID) + return appkit.NewDebugIDContext(ctx, debugID) } // NewSQLGroupContext creates new context with SQL Group for debug SQL logging. +// Deprecated: use appkit.NewSQLGroupContext. func NewSQLGroupContext(ctx context.Context, group string) context.Context { - groups, _ := ctx.Value(sqlGroupCtx).(string) - if groups != "" { - groups += ">" - } - groups += group - return context.WithValue(ctx, sqlGroupCtx, groups) + return appkit.NewSQLGroupContext(ctx, group) } // SQLGroupFromContext returns sql group from context. +// Deprecated: use appkit.SQLGroupFromContext. func SQLGroupFromContext(ctx context.Context) string { - r, _ := ctx.Value(sqlGroupCtx).(string) - return r + return appkit.SQLGroupFromContext(ctx) } // WithTiming adds timings in JSON-RPC 2.0 Response via `extensions` field (not in spec). @@ -132,7 +120,7 @@ func WithSQLLogger(db *pg.DB, isDevel bool, allowDebugFunc, allowSQLDebugFunc Al } debugID := ql.NextID() - ctx = NewDebugIDContext(ctx, debugID) + ctx = appkit.NewDebugIDContext(ctx, debugID) ql.Push(debugID) resp := h(ctx, method, params) @@ -192,7 +180,7 @@ func (ql *sqlQueryLogger) BeforeQuery(ctx context.Context, event *pg.QueryEvent) event.Stash = make(map[interface{}]interface{}) } - if DebugIDFromContext(ctx) != emptyDebugID { + if appkit.DebugIDFromContext(ctx) != appkit.EmptyDebugID { event.Stash[eventStartedAt] = time.Now() } @@ -200,8 +188,8 @@ func (ql *sqlQueryLogger) BeforeQuery(ctx context.Context, event *pg.QueryEvent) } func (ql *sqlQueryLogger) AfterQuery(ctx context.Context, event *pg.QueryEvent) error { - debugID := DebugIDFromContext(ctx) - if debugID == emptyDebugID { + debugID := appkit.DebugIDFromContext(ctx) + if debugID == appkit.EmptyDebugID { return nil } @@ -221,7 +209,7 @@ func (ql *sqlQueryLogger) AfterQuery(ctx context.Context, event *pg.QueryEvent) } } - sq.Group = strings.Trim(SQLGroupFromContext(ctx), ">") + sq.Group = strings.Trim(appkit.SQLGroupFromContext(ctx), ">") ql.Store(debugID, sq) diff --git a/vendor/github.com/vmkteam/zenrpc-middleware/xrequestid.go b/vendor/github.com/vmkteam/zenrpc-middleware/xrequestid.go index 4542c18..d3c67e5 100644 --- a/vendor/github.com/vmkteam/zenrpc-middleware/xrequestid.go +++ b/vendor/github.com/vmkteam/zenrpc-middleware/xrequestid.go @@ -2,35 +2,18 @@ package middleware import ( "context" - "crypto/rand" - "encoding/hex" - "regexp" - "github.com/labstack/echo/v4" + "github.com/vmkteam/appkit" ) -const ctxXRequestIDKey = echo.HeaderXRequestID - -var xRequestIDre = regexp.MustCompile(`[a-zA-Z0-9-]+`) - -func generateXRequestID() string { - b := make([]byte, 16) - _, _ = rand.Read(b) - return hex.EncodeToString(b) -} - -func isValidXRequestID(requestID string) bool { - return requestID != "" && len(requestID) <= 32 && xRequestIDre.MatchString(requestID) -} - // XRequestIDFromContext returns X-Request-ID from context. +// Deprecated: use appkit.XRequestIDFromContext. func XRequestIDFromContext(ctx context.Context) string { - r, _ := ctx.Value(ctxXRequestIDKey).(string) - return r + return appkit.XRequestIDFromContext(ctx) } // NewXRequestIDContext creates new context with X-Request-ID. +// Deprecated: use appkit.NewXRequestIDContext. func NewXRequestIDContext(ctx context.Context, requestID string) context.Context { - //nolint:staticcheck // must be global - return context.WithValue(ctx, ctxXRequestIDKey, requestID) + return appkit.NewXRequestIDContext(ctx, requestID) } diff --git a/vendor/github.com/vmkteam/zenrpc/v2/.golangci.yml b/vendor/github.com/vmkteam/zenrpc/v2/.golangci.yml index 3be6dec..ae6e342 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/.golangci.yml +++ b/vendor/github.com/vmkteam/zenrpc/v2/.golangci.yml @@ -1,82 +1,411 @@ -run: - # default concurrency is a available CPU number - concurrency: 4 - - # timeout for analysis, e.g. 30s, 5m, default is 1m - deadline: 30m - - # exit code when at least one issue was found, default is 1 - issues-exit-code: 1 - - # include test files or not, default is true - tests: true - - # skip files - skip-files: - - ".*\\_gen\\.go$" - -output: - # colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number" - format: colored-line-number - - # print lines of code with issue, default is true - print-issued-lines: true - - # print linter name in the end of issue text, default is true - print-linter-name: true - -linters-settings: - goimports: - # put imports beginning with prefix after 3rd-party packages; - # it's a comma-separated list of prefixes - local-prefixes: github.com/vmkteam/zenrpc - gocritic: - # Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint` run to see all tags and checks. - # Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags". - enabled-checks: - - appendAssign - - appendCombine - - assignOp - - badCond - - boolExprSimplify - - captLocal - - caseOrder - - defaultCaseOrder - - dupArg - - dupBranchBody - - dupCase - - dupSubExpr - - elseif - - emptyFallthrough - - emptyStringTest - - equalFold - - exitAfterDefer - - flagName - - hexLiteral - - indexAlloc - - nilValReturn - - offBy1 - - regexpMust - - sloppyLen - - switchTrue - - wrapperFunc - - yodaStyleExpr +version: "2" linters: - enable-all: false - disable-all: true enable: - - bodyclose - - dogsled - - dupl - - goconst - - gofmt - - goimports - - gosimple - - gocritic - - govet - - ineffassign - - staticcheck - - typecheck - - unconvert - - unused + - asasalint # checks for pass []any as any in variadic func(...any) + - asciicheck # checks that your code does not contain non-ASCII identifiers + - bidichk # checks for dangerous unicode character sequences + - bodyclose # checks whether HTTP response body is closed successfully + - canonicalheader # checks whether net/http.Header uses canonical header + - copyloopvar # detects places where loop variables are copied (Go 1.22+) + - cyclop # checks function and package cyclomatic complexity + # - depguard # checks if package imports are in a list of acceptable packages + - dupl # tool for code clone detection + - durationcheck # checks for two durations multiplied together + - errcheck # checking for unchecked errors, these unchecked errors can be critical bugs in some cases + - errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error + - errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13 + - exhaustive # checks exhaustiveness of enum switch statements + - exptostd # detects functions from golang.org/x/exp/ that can be replaced by std functions + - fatcontext # detects nested contexts in loops + # - forbidigo # forbids identifiers + - funcorder # checks the order of functions, methods, and constructors + - funlen # tool for detection of long functions + - gocheckcompilerdirectives # validates go compiler directive comments (//go:) + # - gochecknoglobals # checks that no global variables exist + - gochecknoinits # checks that no init functions are present in Go code + - gochecksumtype # checks exhaustiveness on Go "sum types" + - gocognit # computes and checks the cognitive complexity of functions + - goconst # finds repeated strings that could be replaced by a constant + - gocritic # provides diagnostics that check for bugs, performance and style issues + - gocyclo # computes and checks the cyclomatic complexity of functions + # - godot # checks if comments end in a period + - gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod + - goprintffuncname # checks that printf-like functions are named with f at the end + # - gosec # inspects source code for security problems + - govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string + - iface # checks the incorrect use of interfaces, helping developers avoid interface pollution + - ineffassign # detects when assignments to existing variables are not used + - intrange # finds places where for loops could make use of an integer range + - loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap) + - makezero # finds slice declarations with non-zero initial length + - mirror # reports wrong mirror patterns of bytes/strings usage + # - mnd # detects magic numbers + # - musttag # enforces field tags in (un)marshaled structs + # - nakedret # finds naked returns in functions greater than a specified function length + # - nestif # reports deeply nested if statements + - nilerr # finds the code that returns nil even if it checks that the error is not nil + - nilnesserr # reports that it checks for err != nil, but it returns a different nil value error (powered by nilness and nilerr) + # - nilnil # checks that there is no simultaneous return of nil error and an invalid value + - noctx # finds sending http request without context.Context + # - nolintlint # reports ill-formed or insufficient nolint directives + # - nonamedreturns # reports all named returns + - nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL + - perfsprint # checks that fmt.Sprintf can be replaced with a faster alternative + - predeclared # finds code that shadows one of Go's predeclared identifiers + - promlinter # checks Prometheus metrics naming via promlint + - protogetter # reports direct reads from proto message fields when getters should be used + # - reassign # checks that package variables are not reassigned + - recvcheck # checks for receiver type consistency + # - revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint + - rowserrcheck # checks whether Err of rows is checked successfully + - sloglint # ensure consistent code style when using log/slog + - spancheck # checks for mistakes with OpenTelemetry/Census spans + - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed + - staticcheck # is a go vet on steroids, applying a ton of static analysis checks + - testableexamples # checks if examples are testable (have an expected output) + - testifylint # checks usage of github.com/stretchr/testify + # - testpackage # makes you use a separate _test package + - tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes + - unconvert # removes unnecessary type conversions + - unparam # reports unused function parameters + - unused # checks for unused constants, variables, functions and types + - usestdlibvars # detects the possibility to use variables/constants from the Go standard library + - usetesting # reports uses of functions with replacement inside the testing package + - wastedassign # finds wasted assignment statements + - whitespace # detects leading and trailing whitespace + + ## you may want to enable + - decorder # checks declaration order and count of types, constants, variables and functions + # - exhaustruct # [highly recommend to enable] checks if all structure fields are initialized + - ginkgolinter # [if you use ginkgo/gomega] enforces standards of using ginkgo and gomega + # - godox # detects usage of FIXME, TODO and other keywords inside comments + - goheader # checks is file header matches to pattern + - inamedparam # [great idea, but too strict, need to ignore a lot of cases by default] reports interfaces with unnamed method parameters + - interfacebloat # checks the number of methods inside an interface + # - ireturn # accept interfaces, return concrete types + - prealloc # [premature optimization, but can be used in some cases] finds slice declarations that could potentially be preallocated + # - tagalign # checks that struct tags are well aligned + # - varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope + # - wrapcheck # checks that errors returned from external packages are wrapped + - zerologlint # detects the wrong usage of zerolog that a user forgets to dispatch zerolog.Event + + ## disabled + #- containedctx # detects struct contained context.Context field + #- contextcheck # [too many false positives] checks the function whether use a non-inherited context + #- dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) + #- dupword # [useless without config] checks for duplicate words in the source code + #- err113 # [too strict] checks the errors handling expressions + #- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted + #- forcetypeassert # [replaced by errcheck] finds forced type assertions + #- gomodguard # [use more powerful depguard] allow and block lists linter for direct Go module dependencies + #- gosmopolitan # reports certain i18n/l10n anti-patterns in your Go codebase + #- grouper # analyzes expression groups + #- importas # enforces consistent import aliases + #- lll # [replaced by golines] reports long lines + #- maintidx # measures the maintainability index of each function + #- misspell # [useless] finds commonly misspelled English words in comments + #- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity + #- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test + #- tagliatelle # checks the struct tags + #- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers + #- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines + settings: + cyclop: + # The maximal code complexity to report. + # Default: 10 + max-complexity: 31 + # The maximal average package complexity. + # If it's higher than 0.0 (float) the check is enabled. + # Default: 0.0 + package-average: 10.0 + + depguard: + # Rules to apply. + # + # Variables: + # - File Variables + # Use an exclamation mark `!` to negate a variable. + # Example: `!$test` matches any file that is not a go test file. + # + # `$all` - matches all go files + # `$test` - matches all go test files + # + # - Package Variables + # + # `$gostd` - matches all of go's standard library (Pulled from `GOROOT`) + # + # Default (applies if no custom rules are defined): Only allow $gostd in all files. + rules: + "deprecated": + # List of file globs that will match this list of settings to compare against. + # By default, if a path is relative, it is relative to the directory where the golangci-lint command is executed. + # The placeholder '${base-path}' is substituted with a path relative to the mode defined with `run.relative-path-mode`. + # The placeholder '${config-path}' is substituted with a path relative to the configuration file. + # Default: $all + files: + - "$all" + # List of packages that are not allowed. + # Entries can be a variable (starting with $), a string prefix, or an exact match (if ending with $). + # Default: [] + deny: + - pkg: github.com/golang/protobuf + desc: Use google.golang.org/protobuf instead, see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules + - pkg: github.com/satori/go.uuid + desc: Use github.com/google/uuid instead, satori's package is not maintained + - pkg: github.com/gofrs/uuid$ + desc: Use github.com/gofrs/uuid/v5 or later, it was not a go module before v5 + "non-test files": + files: + - "!$test" + deny: + - pkg: math/rand$ + desc: Use math/rand/v2 instead, see https://go.dev/blog/randv2 + "non-main files": + files: + - "!**/main.go" + deny: + - pkg: log$ + desc: Use log/slog instead, see https://go.dev/blog/slog + + errcheck: + # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. + # Such cases aren't reported by default. + # Default: false + check-type-assertions: true + + exhaustive: + # Program elements to check for exhaustiveness. + # Default: [ switch ] + check: + - switch + - map + + exhaustruct: + # List of regular expressions to exclude struct packages and their names from checks. + # Regular expressions must match complete canonical struct package/name/structname. + # Default: [] + exclude: + # std libs + - ^net/http.Client$ + - ^net/http.Cookie$ + - ^net/http.Request$ + - ^net/http.Response$ + - ^net/http.Server$ + - ^net/http.Transport$ + - ^net/url.URL$ + - ^os/exec.Cmd$ + - ^reflect.StructField$ + # public libs + - ^github.com/Shopify/sarama.Config$ + - ^github.com/Shopify/sarama.ProducerMessage$ + - ^github.com/mitchellh/mapstructure.DecoderConfig$ + - ^github.com/prometheus/client_golang/.+Opts$ + - ^github.com/spf13/cobra.Command$ + - ^github.com/spf13/cobra.CompletionOptions$ + - ^github.com/stretchr/testify/mock.Mock$ + - ^github.com/testcontainers/testcontainers-go.+Request$ + - ^github.com/testcontainers/testcontainers-go.FromDockerfile$ + - ^golang.org/x/tools/go/analysis.Analyzer$ + - ^google.golang.org/protobuf/.+Options$ + - ^gopkg.in/yaml.v3.Node$ + + funcorder: + # Checks if the exported methods of a structure are placed before the non-exported ones. + # Default: true + struct-method: false + + funlen: + # Checks the number of lines in a function. + # If lower than 0, disable the check. + # Default: 60 + lines: 110 + # Checks the number of statements in a function. + # If lower than 0, disable the check. + # Default: 40 + statements: 55 + + gochecksumtype: + # Presence of `default` case in switch statements satisfies exhaustiveness, if all members are not listed. + # Default: true + default-signifies-exhaustive: false + + gocognit: + # Minimal code complexity to report. + # Default: 30 (but we recommend 10-20) + min-complexity: 32 + + gocritic: + # Settings passed to gocritic. + # The settings key is the name of a supported gocritic checker. + # The list of supported checkers can be found at https://go-critic.com/overview. + settings: + captLocal: + # Whether to restrict checker to params only. + # Default: true + paramsOnly: false + underef: + # Whether to skip (*x).method() calls where x is a pointer receiver. + # Default: true + skipRecvDeref: false + + govet: + # Enable all analyzers. + # Default: false + enable-all: true + # Disable analyzers by name. + # Run `GL_DEBUG=govet golangci-lint run --enable=govet` to see default, all available analyzers, and enabled analyzers. + # Default: [] + disable: + - fieldalignment # too strict + # Settings per analyzer. + settings: + shadow: + # Whether to be strict about shadowing; can be noisy. + # Default: false + strict: false + + inamedparam: + # Skips check for interface methods with only a single parameter. + # Default: false + skip-single-param: true + + mnd: + # List of function patterns to exclude from analysis. + # Values always ignored: `time.Date`, + # `strconv.FormatInt`, `strconv.FormatUint`, `strconv.FormatFloat`, + # `strconv.ParseInt`, `strconv.ParseUint`, `strconv.ParseFloat`. + # Default: [] + ignored-functions: + - args.Error + - flag.Arg + - flag.Duration.* + - flag.Float.* + - flag.Int.* + - flag.Uint.* + - os.Chmod + - os.Mkdir.* + - os.OpenFile + - os.WriteFile + - prometheus.ExponentialBuckets.* + - prometheus.LinearBuckets + + nakedret: + # Make an issue if func has more lines of code than this setting, and it has naked returns. + # Default: 30 + max-func-lines: 0 + + nolintlint: + # Exclude following linters from requiring an explanation. + # Default: [] + allow-no-explanation: [ funlen, gocognit, golines, unparam, dupl, unused ] + # Enable to require an explanation of nonzero length after each nolint directive. + # Default: false + require-explanation: true + # Enable to require nolint directives to mention the specific linter being suppressed. + # Default: false + require-specific: true + + perfsprint: + # Optimizes into strings concatenation. + # Default: true + strconcat: false + + reassign: + # Patterns for global variable names that are checked for reassignment. + # See https://github.com/curioswitch/go-reassign#usage + # Default: ["EOF", "Err.*"] + patterns: + - ".*" + + rowserrcheck: + # database/sql is always checked. + # Default: [] + packages: + - github.com/jmoiron/sqlx + + sloglint: + # Enforce not using global loggers. + # Values: + # - "": disabled + # - "all": report all global loggers + # - "default": report only the default slog logger + # https://github.com/go-simpler/sloglint?tab=readme-ov-file#no-global + # Default: "" + no-global: all + # Enforce using methods that accept a context. + # Values: + # - "": disabled + # - "all": report all contextless calls + # - "scope": report only if a context exists in the scope of the outermost function + # https://github.com/go-simpler/sloglint?tab=readme-ov-file#context-only + # Default: "" + context: scope + + staticcheck: + # SAxxxx checks in https://staticcheck.dev/docs/configuration/options/#checks + # Example (to disable some checks): [ "all", "-SA1000", "-SA1001"] + # Default: ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022"] + checks: + - all + # Incorrect or missing package comment. + # https://staticcheck.dev/docs/checks/#ST1000 + - -ST1000 + # Use consistent method receiver names. + # https://staticcheck.dev/docs/checks/#ST1016 + - -ST1016 + # Omit embedded fields from selector expression. + # https://staticcheck.dev/docs/checks/#QF1008 + - -QF1008 + + usetesting: + # Enable/disable `os.TempDir()` detections. + # Default: false + os-temp-dir: true + + exclusions: + # Log a warning if an exclusion rule is unused. + # Default: false + warn-unused: false + # Predefined exclusion rules. + # Default: [] + presets: + - std-error-handling + - common-false-positives + # Excluding configuration per-path, per-linter, per-text and per-source. + rules: + - source: 'TODO' + linters: [ godot ] + - text: 'should have a package comment' + linters: [ revive ] + - text: 'exported \S+ \S+ should have comment( \(or a comment on this block\))? or be unexported' + linters: [ revive ] + - text: 'package comment should be of the form ".+"' + source: '// ?(nolint|TODO)' + linters: [ revive ] + - text: 'comment on exported \S+ \S+ should be of the form ".+"' + source: '// ?(nolint|TODO)' + linters: [ revive, staticcheck ] + - path: '_test\.go' + linters: + - bodyclose + - dupl + - errcheck + - funlen + - goconst + - gosec + - noctx + - wrapcheck +formatters: + enable: + - gci + settings: + gci: + sections: + - standard + - localmodule + - default + no-inline-comments: true + no-prefix-comments: true + custom-order: true + no-lex-order: true diff --git a/vendor/github.com/vmkteam/zenrpc/v2/MAINTAINERS b/vendor/github.com/vmkteam/zenrpc/v2/MAINTAINERS deleted file mode 100644 index c549504..0000000 --- a/vendor/github.com/vmkteam/zenrpc/v2/MAINTAINERS +++ /dev/null @@ -1,4 +0,0 @@ -Sergey Bykov -Vladimir Tereschenko -Andrei Simonov -Mikhail Eremin \ No newline at end of file diff --git a/vendor/github.com/vmkteam/zenrpc/v2/Makefile b/vendor/github.com/vmkteam/zenrpc/v2/Makefile index cff8ab8..098675c 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/Makefile +++ b/vendor/github.com/vmkteam/zenrpc/v2/Makefile @@ -1,13 +1,18 @@ PKG := `go list -f {{.Dir}} ./...` fmt: - @goimports -local "github.com/vmkteam/zenrpc" -l -w $(PKG) + @golangci-lint fmt lint: - @golangci-lint run -c .golangci.yml + @golangci-lint version + @golangci-lint config verify + @golangci-lint run test: @go test -v ./... mod: @go mod tidy + +build: + @go build -o zenrpc/zenrpc zenrpc/*.go \ No newline at end of file diff --git a/vendor/github.com/vmkteam/zenrpc/v2/README.md b/vendor/github.com/vmkteam/zenrpc/v2/README.md index b9c120d..0a3eb91 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/README.md +++ b/vendor/github.com/vmkteam/zenrpc/v2/README.md @@ -141,7 +141,6 @@ All comments are optional. * [x] Input * [x] Output * [x] Codes - * [ ] Scopes for OAuth # Server Library Features diff --git a/vendor/github.com/vmkteam/zenrpc/v2/handlers.go b/vendor/github.com/vmkteam/zenrpc/v2/handlers.go index 793ba9a..7723a00 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/handlers.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/handlers.go @@ -11,12 +11,25 @@ import ( ) type Printer interface { - Printf(string, ...interface{}) + Printf(msg string, args ...any) } -// ServeHTTP process JSON-RPC 2.0 requests via HTTP. -// http://www.simple-is-better.org/json-rpc/transport_http.html -func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { +// printErr prints error if not nil. +func (s *Server) printErr(msg string, err error) { + if err != nil { + s.printf("%s: %v", msg, err) + } +} + +// httpError writes http header with status text. +func (s *Server) httpError(w http.ResponseWriter, code int) { + http.Error(w, http.StatusText(code), code) +} + +// ServeHTTP processes JSON-RPC 2.0 requests via HTTP. +// It handles CORS, SMD schema requests, and standard JSON-RPC calls. +// Implements http.Handler interface for the Server type. +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // check for CORS GET & POST requests if s.options.AllowCORS { w.Header().Set("Access-Control-Allow-Origin", "*") @@ -24,8 +37,11 @@ func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // check for smd parameter and server settings and write schema if all conditions met, if _, ok := r.URL.Query()["smd"]; ok && s.options.ExposeSMD && r.Method == http.MethodGet { - b, _ := json.Marshal(s.SMD()) - w.Write(b) + b, err := json.Marshal(s.SMD()) + s.printErr("json marshal", err) + + _, err = w.Write(b) + s.printErr("response write", err) return } @@ -41,22 +57,22 @@ func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // check for content-type and POST method. if !s.options.DisableTransportChecks { - if !strings.HasPrefix(r.Header.Get("Content-Type"), contentTypeJSON) { - w.WriteHeader(http.StatusUnsupportedMediaType) + switch { + case !strings.HasPrefix(r.Header.Get("Content-Type"), contentTypeJSON): + s.httpError(w, http.StatusUnsupportedMediaType) return - } else if r.Method == http.MethodGet { - w.WriteHeader(http.StatusMethodNotAllowed) + case r.Method == http.MethodGet: + s.httpError(w, http.StatusMethodNotAllowed) return - } else if r.Method != http.MethodPost { + case r.Method != http.MethodPost: // skip rpc calls return } } // ok, method is POST and content-type is application/json, process body + var data any b, err := io.ReadAll(r.Body) - var data interface{} - if err != nil { s.printf("read request body failed with err=%v", err) data = NewResponseError(nil, ParseError, "", nil) @@ -69,28 +85,32 @@ func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - // set headers - w.Header().Set("Content-Type", contentTypeJSON) - // marshals data and write it to client. - if resp, err := json.Marshal(data); err != nil { - s.printf("marshal json response failed with err=%v", err) - w.WriteHeader(http.StatusInternalServerError) - } else if _, err := w.Write(resp); err != nil { - s.printf("write response failed with err=%v", err) - w.WriteHeader(http.StatusInternalServerError) + resp, err := json.Marshal(data) + s.printErr("json marshal", err) + if err != nil { + s.httpError(w, http.StatusInternalServerError) + } + + // write response + w.Header().Set("Content-Type", contentTypeJSON) + if _, err = w.Write(resp); err != nil { + s.printErr("response write", err) + s.httpError(w, http.StatusInternalServerError) } } -// ServeWS processes JSON-RPC 2.0 requests via Gorilla WebSocket. -// https://github.com/gorilla/websocket/blob/master/examples/echo/ -func (s Server) ServeWS(w http.ResponseWriter, r *http.Request) { +// ServeWS processes JSON-RPC 2.0 requests via WebSocket using Gorilla WebSocket. +// It maintains a persistent connection and handles bidirectional JSON-RPC communication. +func (s *Server) ServeWS(w http.ResponseWriter, r *http.Request) { c, err := s.options.Upgrader.Upgrade(w, r, nil) if err != nil { s.printf("upgrade connection failed with err=%v", err) return } - defer c.Close() + defer func(c *websocket.Conn) { + s.printErr("close websocket", c.Close()) + }(c) for { mt, message, err := c.ReadMessage() @@ -106,23 +126,26 @@ func (s Server) ServeWS(w http.ResponseWriter, r *http.Request) { } data, err := s.Do(NewRequestContext(r.Context(), r), message) + s.printErr("marshal json", err) if err != nil { - s.printf("marshal json response failed with err=%v", err) - c.WriteControl(websocket.CloseInternalServerErr, nil, time.Time{}) + e := c.WriteControl(websocket.CloseInternalServerErr, nil, time.Time{}) + s.printErr("write control", e) break } if err = c.WriteMessage(mt, data); err != nil { s.printf("write response failed with err=%v", err) - c.WriteControl(websocket.CloseInternalServerErr, nil, time.Time{}) + e := c.WriteControl(websocket.CloseInternalServerErr, nil, time.Time{}) + s.printErr("write control", e) break } } } -// SMDBoxHandler is a handler for SMDBox web app. -func SMDBoxHandler(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(` +// SMDBoxHandler serves the SMDBox web application interface. +// This provides a web-based interface for exploring and testing the JSON-RPC API. +func SMDBoxHandler(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(` diff --git a/vendor/github.com/vmkteam/zenrpc/v2/jsonrpc2.go b/vendor/github.com/vmkteam/zenrpc/v2/jsonrpc2.go index 2e62efa..f5dc995 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/jsonrpc2.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/jsonrpc2.go @@ -2,6 +2,7 @@ package zenrpc import ( "encoding/json" + "errors" ) const ( @@ -48,7 +49,7 @@ func ErrorMsg(code int) string { return errorMessages[code] } -// Request is a json structure for json-rpc request to server. See: +// Request is a json structure for JSON-RPC request to server. See: // http://www.jsonrpc.org/specification#request_object // //easyjson:json @@ -74,7 +75,7 @@ type Request struct { Namespace string `json:"-"` } -// Response is json structure for json-rpc response from server. See: +// Response is json structure for JSON-RPC response from server. See: // http://www.jsonrpc.org/specification#response_object // //easyjson:json @@ -97,12 +98,29 @@ type Response struct { // The value for this member MUST be an Object as defined in section 5.1. Error *Error `json:"error,omitempty"` - // Extensions is additional field for extending standard response. It could be useful for tracing, method execution, etc... - Extensions map[string]interface{} `json:"extensions,omitempty"` + // Extensions are additional field for extending standard response. It could be useful for tracing, method execution, etc... + Extensions map[string]any `json:"extensions,omitempty"` +} + +// NewResponseError returns new Response with Error object. +func NewResponseError(id *json.RawMessage, code int, message string, data any) Response { + if message == "" { + message = ErrorMsg(code) + } + + return Response{ + Version: Version, + ID: id, + Error: &Error{ + Code: code, + Message: message, + Data: data, + }, + } } // JSON is temporary method that silences error during json marshalling. -func (r Response) JSON() []byte { +func (r *Response) JSON() []byte { // TODO process error b, _ := json.Marshal(r) return b @@ -124,7 +142,7 @@ type Error struct { // A Primitive or Structured value that contains additional information about the error. // This may be omitted. // The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.). - Data interface{} `json:"data,omitempty"` + Data any `json:"data,omitempty"` // Err is inner error. Err error `json:"-"` @@ -143,7 +161,7 @@ func NewError(code int, err error) *Error { } // Error returns first filled value from Err, Message or default text for JSON-RPC error. -func (e Error) Error() string { +func (e *Error) Error() string { if e.Err != nil { return e.Err.Error() } @@ -156,29 +174,12 @@ func (e Error) Error() string { } // Unwrap returns unwrapped inner error if exists -func (e Error) Unwrap() error { +func (e *Error) Unwrap() error { return e.Err } -// NewResponseError returns new Response with Error object. -func NewResponseError(id *json.RawMessage, code int, message string, data interface{}) Response { - if message == "" { - message = ErrorMsg(code) - } - - return Response{ - Version: Version, - ID: id, - Error: &Error{ - Code: code, - Message: message, - Data: data, - }, - } -} - // Set sets result and error if needed. -func (r *Response) Set(v interface{}, er ...error) { +func (r *Response) Set(v any, er ...error) { r.Version = Version var err error @@ -187,17 +188,19 @@ func (r *Response) Set(v interface{}, er ...error) { v = nil } // check for nil *zenrpc.Error - // TODO(sergeyfast): add ability to return other error types if len(er) > 0 && er[0] != nil { err = er[0] - if e, ok := err.(*Error); ok && e == nil { + + var e *Error + if errors.As(err, &e) && e == nil { err = nil } } // set first error if occurred if err != nil { - if e, ok := err.(*Error); ok { + var e *Error + if errors.As(err, &e) { r.Error = e } else { r.Error = NewError(InternalError, err) diff --git a/vendor/github.com/vmkteam/zenrpc/v2/middleware.go b/vendor/github.com/vmkteam/zenrpc/v2/middleware.go index 6dec100..bb2971c 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/middleware.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/middleware.go @@ -28,26 +28,26 @@ func Logger(l *log.Logger) MiddlewareFunc { } } -// Metrics is a middleware for logging duration of RPC requests via Prometheus. Default AppName is zenrpc. -// It exposes two metrics: appName_rpc_error_requests_count and appName_rpc_responses_duration_seconds. -func Metrics(appName string) MiddlewareFunc { - if appName == "" { - appName = "zenrpc" +// Metrics is a middleware for logging duration of RPC requests via Prometheus. +// It exposes two metrics: app_rpc_error_requests_total and app_rpc_responses_duration_seconds. +func Metrics(serverName string) MiddlewareFunc { + if serverName == "" { + serverName = "rpc" } rpcErrors := prometheus.NewCounterVec(prometheus.CounterOpts{ - Namespace: appName, + Namespace: "app", Subsystem: "rpc", - Name: "error_requests_count", + Name: "error_requests_total", Help: "Error requests count by method and error code.", - }, []string{"method", "code"}) + }, []string{"server", "method", "code"}) rpcDurations := prometheus.NewSummaryVec(prometheus.SummaryOpts{ - Namespace: appName, + Namespace: "app", Subsystem: "rpc", Name: "responses_duration_seconds", Help: "Response time by method and error code.", - }, []string{"method", "code"}) + }, []string{"server", "method", "code"}) prometheus.MustRegister(rpcErrors, rpcDurations) @@ -63,10 +63,10 @@ func Metrics(appName string) MiddlewareFunc { if r.Error != nil { code = strconv.Itoa(r.Error.Code) - rpcErrors.WithLabelValues(method, code).Inc() + rpcErrors.WithLabelValues(serverName, method, code).Inc() } - rpcDurations.WithLabelValues(method, code).Observe(time.Since(start).Seconds()) + rpcDurations.WithLabelValues(serverName, method, code).Observe(time.Since(start).Seconds()) return r } diff --git a/vendor/github.com/vmkteam/zenrpc/v2/parser/helpers.go b/vendor/github.com/vmkteam/zenrpc/v2/parser/helpers.go index 740b595..a9947a1 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/parser/helpers.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/parser/helpers.go @@ -1,7 +1,7 @@ package parser import ( - "fmt" + "errors" "go/ast" "path" @@ -60,7 +60,7 @@ func EntryPointPackageName(filename string) (string, string, error) { for _, pack := range pkgs { return pack.Name, pack.PkgPath, nil } - return "", "", fmt.Errorf("package not found for entry point") + return "", "", errors.New("package not found for entry point") } func loadPackage(path string) ([]*packages.Package, error) { diff --git a/vendor/github.com/vmkteam/zenrpc/v2/parser/parser.go b/vendor/github.com/vmkteam/zenrpc/v2/parser/parser.go index a4999be..88a87ba 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/parser/parser.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/parser/parser.go @@ -10,10 +10,10 @@ import ( "unicode" "unicode/utf8" + "github.com/vmkteam/zenrpc/v2/smd" + "golang.org/x/text/cases" "golang.org/x/text/language" - - "github.com/vmkteam/zenrpc/v2/smd" ) const ( @@ -49,6 +49,7 @@ type PackageInfo struct { Services []*Service + //nolint:staticcheck Scopes map[string][]*ast.Scope // key - import name, value - array of scopes from each package file Structs map[string]*Struct Imports []*ast.ImportSpec @@ -90,7 +91,7 @@ type Arg struct { Name string Type string CapitalName string - JsonName string + JSONName string HasStar bool HasDefaultValue bool Description string // from magic comment @@ -156,6 +157,7 @@ func NewPackageInfo(filename string) (*PackageInfo, error) { GeneratorVersion: GeneratorVersion, Services: []*Service{}, + //nolint:staticcheck Scopes: make(map[string][]*ast.Scope), Structs: make(map[string]*Struct), Imports: []*ast.ImportSpec{}, @@ -165,7 +167,7 @@ func NewPackageInfo(filename string) (*PackageInfo, error) { }, nil } -// ParseFiles parse all files associated with package from original file +// Parse parses all files associated with package from original file func (pi *PackageInfo) Parse(filename string) error { pfs, err := GetDependenciesAstFiles(filename) if err != nil { @@ -294,7 +296,7 @@ func (pi *PackageInfo) parseMethods(f *ast.File, packagePath string) error { return nil } -func (pi PackageInfo) String() string { +func (pi *PackageInfo) String() string { result := fmt.Sprintf("Generated services for package %s:\n", pi.PackageName) for _, s := range pi.Services { result += fmt.Sprintf("- %s\n", s.Name) @@ -344,7 +346,7 @@ func (pi PackageInfo) String() string { return result } -func (pi PackageInfo) OutputFilename() string { +func (pi *PackageInfo) OutputFilename() string { return filepath.Join(pi.Dir, pi.PackageName+GenerateFileSuffix) } @@ -415,7 +417,7 @@ func (m *Method) parseArguments(pi *PackageInfo, fdecl *ast.FuncDecl, serviceNam for _, s := range serviceNames { methods = append(methods, s+"."+m.Name) } - return fmt.Errorf("Can't parse type of argument %s in %s", strings.Join(fields, ", "), strings.Join(methods, ", ")) + return fmt.Errorf("can't parse type of argument %s in %s", strings.Join(fields, ", "), strings.Join(methods, ", ")) } if typeName == contextTypeName { @@ -450,7 +452,7 @@ func (m *Method) parseArguments(pi *PackageInfo, fdecl *ast.FuncDecl, serviceNam Name: name.Name, Type: typeName, CapitalName: c.String(name.Name), - JsonName: lowerFirst(name.Name), + JSONName: lowerFirst(name.Name), HasStar: hasStar, SMDType: SMDType{ Type: smdType, @@ -488,7 +490,7 @@ func (m *Method) parseReturns(pi *PackageInfo, fdecl *ast.FuncDecl, serviceNames // parse type typeName := parseType(field.Type) if typeName == "" { - return fmt.Errorf("Can't parse type of return value in %s on position %d", methods(), len(m.Returns)+1) + return fmt.Errorf("can't parse type of return value in %s on position %d", methods(), len(m.Returns)+1) } var fieldName string @@ -545,7 +547,7 @@ func (m *Method) parseReturns(pi *PackageInfo, fdecl *ast.FuncDecl, serviceNames // parseComments parse method comments and // fill default values, description for params and user errors map -func (m *Method) parseComments(doc *ast.CommentGroup, pi *PackageInfo) { +func (m *Method) parseComments(doc *ast.CommentGroup, _ *PackageInfo) { if doc == nil { return } @@ -687,7 +689,8 @@ func parseSMDType(expr ast.Expr) (string, string) { case *ast.StarExpr: return parseSMDType(v.X) case *ast.SelectorExpr: - //save time.Time as string type in SMD + // save time.Time as string type in SMD + //nolint:errcheck if v.X.(*ast.Ident).Name == "time" && v.Sel.Name == "Time" { return SmdString, "" } @@ -726,13 +729,16 @@ func parseSMDType(expr ast.Expr) (string, string) { } // parseStruct find struct in type for display in SMD +// +//nolint:gocognit func parseStruct(expr ast.Expr) *Struct { switch v := expr.(type) { case *ast.StarExpr: return parseStruct(v.X) case *ast.SelectorExpr: + //nolint:errcheck namespace := v.X.(*ast.Ident).Name - //skip time.Time struct parsing + // skip time.Time struct parsing if namespace == "time" && v.Sel.Name == "Time" { return nil } @@ -824,5 +830,5 @@ func lowerFirst(s string) string { } func hasStar(s string) bool { - return s[:1] == "*" + return len(s) > 0 && s[:1] == "*" } diff --git a/vendor/github.com/vmkteam/zenrpc/v2/parser/struct.go b/vendor/github.com/vmkteam/zenrpc/v2/parser/struct.go index f06c49e..917d360 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/parser/struct.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/parser/struct.go @@ -2,13 +2,16 @@ package parser import ( "go/ast" + "log" "reflect" "strings" ) func (pi *PackageInfo) parseStructs() { for _, s := range pi.Structs { - s.parse(pi, []string{}) + if err := s.parse(pi, []string{}); err != nil { + log.Printf("Error parsing struct %s: %v", s.Name, err) + } } } @@ -31,6 +34,9 @@ func (s *Struct) findTypeSpec(pi *PackageInfo) bool { return false } +// parse parses package +// +//nolint:gocyclo,gocognit func (s *Struct) parse(pi *PackageInfo, parsed []string) error { if !s.findTypeSpec(pi) || s.Properties != nil { // can't find struct implementation @@ -41,7 +47,7 @@ func (s *Struct) parse(pi *PackageInfo, parsed []string) error { s.Properties = []Property{} parsed = append(parsed, s.Name) for _, field := range s.StructType.Fields.List { - tag := parseJsonTag(field.Tag) + tag := parseJSONTag(field.Tag) // do not parse tags that ignored in json if tag == "-" { @@ -65,7 +71,7 @@ func (s *Struct) parse(pi *PackageInfo, parsed []string) error { return err } - if embeddedS.Properties != nil && len(embeddedS.Properties) > 0 { + if len(embeddedS.Properties) > 0 { s.Properties = append(s.Properties, embeddedS.Properties...) } } @@ -156,7 +162,7 @@ func (s *Struct) parse(pi *PackageInfo, parsed []string) error { return nil } -func parseJsonTag(bl *ast.BasicLit) string { +func parseJSONTag(bl *ast.BasicLit) string { if bl == nil { return "" } diff --git a/vendor/github.com/vmkteam/zenrpc/v2/server.go b/vendor/github.com/vmkteam/zenrpc/v2/server.go index ba867df..50a6e7a 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/server.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/server.go @@ -10,15 +10,15 @@ import ( "sync" "unicode" - "github.com/gorilla/websocket" - "github.com/vmkteam/zenrpc/v2/smd" + + "github.com/gorilla/websocket" ) type contextKey string const ( - // defaultBatchMaxLen is default value of BatchMaxLen option in rpc Server options. + // defaultBatchMaxLen is default value of BatchMaxLen option in RPC Server options. defaultBatchMaxLen = 10 // defaultTargetURL is default value for SMD target url. @@ -30,7 +30,10 @@ const ( // context key for namespace. namespaceKey contextKey = "namespace" - // context key for ID. + // batchMethods key for all batch methods in request. + batchMethodsKey contextKey = "batchMethods" + + // IDKey context key for ID. IDKey contextKey = "id" // contentTypeJSON is default content type for HTTP transport. @@ -85,8 +88,8 @@ type Server struct { } // NewServer returns new JSON-RPC 2.0 Server. -func NewServer(opts Options) Server { - // For safety reasons we do not allowing to much requests in batch +func NewServer(opts Options) *Server { + // For safety reasons we do not allowing too much requests in batch if opts.BatchMaxLen == 0 { opts.BatchMaxLen = defaultBatchMaxLen } @@ -101,7 +104,7 @@ func NewServer(opts Options) Server { } } - return Server{ + return &Server{ services: make(map[string]Invoker), options: opts, } @@ -129,7 +132,7 @@ func (s *Server) SetLogger(printer Printer) { s.logger = printer } -// process process JSON-RPC 2.0 message, invokes correct method for namespace and returns JSON-RPC 2.0 Response. +// process processes JSON-RPC 2.0 message, invokes correct method for namespace and returns JSON-RPC 2.0 Response. func (s *Server) process(ctx context.Context, message json.RawMessage) interface{} { var requests []Request // parsing batch requests @@ -145,13 +148,18 @@ func (s *Server) process(ctx context.Context, message json.RawMessage) interface return NewResponseError(nil, ParseError, "", nil) } - // if there no requests to process + // if there are no requests to process if len(requests) == 0 { return NewResponseError(nil, InvalidRequest, "", nil) } else if len(requests) > s.options.BatchMaxLen { return NewResponseError(nil, InvalidRequest, "", "max requests length in batch exceeded") } + // set batch methods in request + if batch { + ctx = newBatchMethodsContext(ctx, methodsFromRequests(requests)) + } + // process single request: if request single and not notification - just run it and return result if !batch && requests[0].ID != nil { return s.processRequest(ctx, requests[0]) @@ -166,7 +174,7 @@ func (s *Server) process(ctx context.Context, message json.RawMessage) interface } // processBatch process batch requests with context. -func (s Server) processBatch(ctx context.Context, requests []Request) []Response { +func (s *Server) processBatch(ctx context.Context, requests []Request) []Response { reqLen := len(requests) // running requests in batch asynchronously @@ -207,8 +215,8 @@ func (s Server) processBatch(ctx context.Context, requests []Request) []Response } // processRequest processes a single request in service invoker. -func (s Server) processRequest(ctx context.Context, req Request) Response { - // checks for json-rpc version and method +func (s *Server) processRequest(ctx context.Context, req Request) Response { + // checks for JSON-RPC version and method if req.Version != Version || req.Method == "" { return NewResponseError(req.ID, InvalidRequest, "", nil) } @@ -249,18 +257,27 @@ func (s Server) processRequest(ctx context.Context, req Request) Response { } // Do process JSON-RPC 2.0 request, invokes correct method for namespace and returns JSON-RPC 2.0 Response or marshaller error. -func (s Server) Do(ctx context.Context, req []byte) ([]byte, error) { +func (s *Server) Do(ctx context.Context, req []byte) ([]byte, error) { return json.Marshal(s.process(ctx, req)) } -func (s Server) printf(format string, v ...interface{}) { +func (s *Server) printf(format string, v ...any) { if s.logger != nil { s.logger.Printf(format, v...) } } +func methodsFromRequests(reqs []Request) []string { + result := make([]string, 0, len(reqs)) + for i := range reqs { + result = append(result, strings.ToLower(reqs[i].Method)) + } + + return result +} + // SMD returns Service Mapping Description object with all registered methods. -func (s Server) SMD() smd.Schema { +func (s *Server) SMD() smd.Schema { sch := smd.Schema{ Transport: "POST", Envelope: "JSON-RPC-2.0", @@ -286,7 +303,7 @@ func (s Server) SMD() smd.Schema { return sch } -// IsArray checks json message if it array or object. +// IsArray checks json message if it arrays or object. func IsArray(message json.RawMessage) bool { for _, b := range message { if unicode.IsSpace(rune(b)) { @@ -338,8 +355,8 @@ func ConvertToObject(keys []string, params json.RawMessage) (json.RawMessage, er return nil, err } } - } + if _, err := buf.WriteString(`}`); err != nil { return nil, err } @@ -385,3 +402,17 @@ func IDFromContext(ctx context.Context) *json.RawMessage { return nil } + +// newBatchMethodsContext creates new context with current batch methods. +func newBatchMethodsContext(ctx context.Context, methods []string) context.Context { + return context.WithValue(ctx, batchMethodsKey, methods) +} + +// BatchMethodsFromContext returns batch method's from context. +func BatchMethodsFromContext(ctx context.Context) []string { + if r, ok := ctx.Value(batchMethodsKey).([]string); ok { + return r + } + + return nil +} diff --git a/vendor/github.com/vmkteam/zenrpc/v2/smd/model.go b/vendor/github.com/vmkteam/zenrpc/v2/smd/model.go index 9c7e783..1ac050e 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/smd/model.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/smd/model.go @@ -145,7 +145,7 @@ func (pl *PropertyList) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &v); err != nil { return err } - var plist PropertyList + plist := make(PropertyList, 0, len(v)) for k, vl := range v { p := vl p.Name = k diff --git a/vendor/github.com/vmkteam/zenrpc/v2/zenrpc/main.go b/vendor/github.com/vmkteam/zenrpc/v2/zenrpc/main.go index 162dee2..4f77558 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/zenrpc/main.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/zenrpc/main.go @@ -2,8 +2,10 @@ package main import ( "bytes" + "errors" "fmt" "go/format" + "log" "os" "runtime/debug" "time" @@ -17,9 +19,11 @@ const ( ) func main() { + log.SetFlags(log.Lshortfile) + start := time.Now() - appVersion() + parser.GeneratorVersion = appVersion() fmt.Printf("Generator version: %s\n", parser.GeneratorVersion) var filename string @@ -30,52 +34,47 @@ func main() { } if filename == "" { - fmt.Fprintln(os.Stderr, "File path is empty") - os.Exit(1) + exitOnErr(errors.New("no filename specified")) } fmt.Printf("Entrypoint: %s\n", filename) // create package info pi, err := parser.NewPackageInfo(filename) - if err != nil { - printError(err) - os.Exit(1) - } - - outputFileName := pi.OutputFilename() + exitWithErr(err) // remove output file if it already exists - if _, err := os.Stat(outputFileName); err == nil { - if err := os.Remove(outputFileName); err != nil { - printError(err) - os.Exit(1) - } + outputFileName := pi.OutputFilename() + if _, err = os.Stat(outputFileName); err == nil { + err = os.Remove(outputFileName) + exitWithErr(err) } - if err := pi.Parse(filename); err != nil { - printError(err) - os.Exit(1) - } + // parse file + err = pi.Parse(filename) + exitWithErr(err) if len(pi.Services) == 0 { - fmt.Fprintln(os.Stderr, "Services not found") - os.Exit(1) + exitOnErr(fmt.Errorf("no services found in %s", filename)) } - if err := generateFile(outputFileName, pi); err != nil { - printError(err) - os.Exit(1) - } + // generate file + err = generateFile(outputFileName, pi) + exitWithErr(err) fmt.Printf("Generated: %s\n", outputFileName) - fmt.Printf("Duration: %dms\n", int64(time.Since(start)/time.Millisecond)) + fmt.Printf("Duration: %dms\n", time.Since(start).Milliseconds()) fmt.Println() fmt.Print(pi) fmt.Println() } -func printError(err error) { +// exitWithErr logs the error and exits the program if error is not nil with additional information. +func exitWithErr(err error) { + if err == nil { + return + } + // print error to stderr fmt.Fprintf(os.Stderr, "Error: %s\n", err) @@ -84,6 +83,8 @@ func printError(err error) { fmt.Printf("\t%s\n", openIssueURL) fmt.Println("For more information, see:") fmt.Printf("\t%s\n\n", githubURL) + + os.Exit(1) } func generateFile(outputFileName string, pi *parser.PackageInfo) error { @@ -91,10 +92,13 @@ func generateFile(outputFileName string, pi *parser.PackageInfo) error { if err != nil { return err } - defer file.Close() + defer func(file *os.File) { + e := file.Close() + exitOnErr(e) + }(file) - output := new(bytes.Buffer) - if err := serviceTemplate.Execute(output, pi); err != nil { + var output bytes.Buffer + if err = serviceTemplate.Execute(&output, pi); err != nil { return err } @@ -103,18 +107,37 @@ func generateFile(outputFileName string, pi *parser.PackageInfo) error { return err } - if _, err = file.Write(source); err != nil { - return err - } - - return nil + _, err = file.Write(source) + return err } -func appVersion() { +func appVersion() string { + result := "devel" info, ok := debug.ReadBuildInfo() if !ok { - return + return result + } + + if info.Main.Version != "" { + return info.Main.Version + } + + for _, v := range info.Settings { + if v.Key == "vcs.revision" { + result = v.Value + } + } + + if len(result) > 8 { + result = result[:8] } - parser.GeneratorVersion = info.Main.Version + return result +} + +// exitOnErr logs the error and exits the program if error is not nil. +func exitOnErr(err error) { + if err != nil { + log.Fatal("generation failed: ", err) + } } diff --git a/vendor/github.com/vmkteam/zenrpc/v2/zenrpc/template.go b/vendor/github.com/vmkteam/zenrpc/v2/zenrpc/template.go index 7ca2a9e..6ff78bf 100644 --- a/vendor/github.com/vmkteam/zenrpc/v2/zenrpc/template.go +++ b/vendor/github.com/vmkteam/zenrpc/v2/zenrpc/template.go @@ -159,13 +159,13 @@ var RPC = struct { case RPC.{{$s.Name}}.{{.Name}}: {{ if .Args }} var args = struct { {{ range .Args }} - {{.CapitalName}} {{if and (not .HasStar) .HasDefaultValue}}*{{end}}{{.Type}} ` + "`json:\"{{.JsonName}}\"`" + ` + {{.CapitalName}} {{if and (not .HasStar) .HasDefaultValue}}*{{end}}{{.Type}} ` + "`json:\"{{.JSONName}}\"`" + ` {{- end }} }{} if zenrpc.IsArray(params) { if params, err = zenrpc.ConvertToObject([]string{ - {{- range .Args }}"{{.JsonName}}",{{ end -}} + {{- range .Args }}"{{.JSONName}}",{{ end -}} }, params); err != nil { return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) } diff --git a/vendor/golang.org/x/net/html/atom/atom.go b/vendor/golang.org/x/net/html/atom/atom.go deleted file mode 100644 index cd0a8ac..0000000 --- a/vendor/golang.org/x/net/html/atom/atom.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package atom provides integer codes (also known as atoms) for a fixed set of -// frequently occurring HTML strings: tag names and attribute keys such as "p" -// and "id". -// -// Sharing an atom's name between all elements with the same tag can result in -// fewer string allocations when tokenizing and parsing HTML. Integer -// comparisons are also generally faster than string comparisons. -// -// The value of an atom's particular code is not guaranteed to stay the same -// between versions of this package. Neither is any ordering guaranteed: -// whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to -// be dense. The only guarantees are that e.g. looking up "div" will yield -// atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. -package atom // import "golang.org/x/net/html/atom" - -// Atom is an integer code for a string. The zero value maps to "". -type Atom uint32 - -// String returns the atom's name. -func (a Atom) String() string { - start := uint32(a >> 8) - n := uint32(a & 0xff) - if start+n > uint32(len(atomText)) { - return "" - } - return atomText[start : start+n] -} - -func (a Atom) string() string { - return atomText[a>>8 : a>>8+a&0xff] -} - -// fnv computes the FNV hash with an arbitrary starting value h. -func fnv(h uint32, s []byte) uint32 { - for i := range s { - h ^= uint32(s[i]) - h *= 16777619 - } - return h -} - -func match(s string, t []byte) bool { - for i, c := range t { - if s[i] != c { - return false - } - } - return true -} - -// Lookup returns the atom whose name is s. It returns zero if there is no -// such atom. The lookup is case sensitive. -func Lookup(s []byte) Atom { - if len(s) == 0 || len(s) > maxAtomLen { - return 0 - } - h := fnv(hash0, s) - if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { - return a - } - if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { - return a - } - return 0 -} - -// String returns a string whose contents are equal to s. In that sense, it is -// equivalent to string(s) but may be more efficient. -func String(s []byte) string { - if a := Lookup(s); a != 0 { - return a.String() - } - return string(s) -} diff --git a/vendor/golang.org/x/net/html/atom/table.go b/vendor/golang.org/x/net/html/atom/table.go deleted file mode 100644 index b460e6f..0000000 --- a/vendor/golang.org/x/net/html/atom/table.go +++ /dev/null @@ -1,785 +0,0 @@ -// Code generated by go generate gen.go; DO NOT EDIT. - -//go:generate go run gen.go - -package atom - -const ( - A Atom = 0x1 - Abbr Atom = 0x4 - Accept Atom = 0x1a06 - AcceptCharset Atom = 0x1a0e - Accesskey Atom = 0x2c09 - Acronym Atom = 0xaa07 - Action Atom = 0x26506 - Address Atom = 0x6f107 - Align Atom = 0xb105 - Allowfullscreen Atom = 0x3280f - Allowpaymentrequest Atom = 0xc113 - Allowusermedia Atom = 0xdd0e - Alt Atom = 0xf303 - Annotation Atom = 0x1c90a - AnnotationXml Atom = 0x1c90e - Applet Atom = 0x30806 - Area Atom = 0x35004 - Article Atom = 0x3f607 - As Atom = 0x3c02 - Aside Atom = 0x10705 - Async Atom = 0xff05 - Audio Atom = 0x11505 - Autocomplete Atom = 0x26b0c - Autofocus Atom = 0x12109 - Autoplay Atom = 0x13c08 - B Atom = 0x101 - Base Atom = 0x3b04 - Basefont Atom = 0x3b08 - Bdi Atom = 0xba03 - Bdo Atom = 0x14b03 - Bgsound Atom = 0x15e07 - Big Atom = 0x17003 - Blink Atom = 0x17305 - Blockquote Atom = 0x1870a - Body Atom = 0x2804 - Br Atom = 0x202 - Button Atom = 0x19106 - Canvas Atom = 0x10306 - Caption Atom = 0x22407 - Center Atom = 0x21306 - Challenge Atom = 0x28e09 - Charset Atom = 0x2107 - Checked Atom = 0x5b507 - Cite Atom = 0x19c04 - Class Atom = 0x55805 - Code Atom = 0x5ee04 - Col Atom = 0x1ab03 - Colgroup Atom = 0x1ab08 - Color Atom = 0x1bf05 - Cols Atom = 0x1c404 - Colspan Atom = 0x1c407 - Command Atom = 0x1d707 - Content Atom = 0x57b07 - Contenteditable Atom = 0x57b0f - Contextmenu Atom = 0x37a0b - Controls Atom = 0x1de08 - Coords Atom = 0x1f006 - Crossorigin Atom = 0x1fa0b - Data Atom = 0x49904 - Datalist Atom = 0x49908 - Datetime Atom = 0x2ab08 - Dd Atom = 0x2bf02 - Default Atom = 0x10a07 - Defer Atom = 0x5f005 - Del Atom = 0x44c03 - Desc Atom = 0x55504 - Details Atom = 0x7207 - Dfn Atom = 0x8703 - Dialog Atom = 0xbb06 - Dir Atom = 0x9303 - Dirname Atom = 0x9307 - Disabled Atom = 0x16408 - Div Atom = 0x16b03 - Dl Atom = 0x5d602 - Download Atom = 0x45d08 - Draggable Atom = 0x17a09 - Dropzone Atom = 0x3ff08 - Dt Atom = 0x64002 - Em Atom = 0x6e02 - Embed Atom = 0x6e05 - Enctype Atom = 0x28007 - Face Atom = 0x21104 - Fieldset Atom = 0x21908 - Figcaption Atom = 0x2210a - Figure Atom = 0x23b06 - Font Atom = 0x3f04 - Footer Atom = 0xf606 - For Atom = 0x24703 - ForeignObject Atom = 0x2470d - Foreignobject Atom = 0x2540d - Form Atom = 0x26104 - Formaction Atom = 0x2610a - Formenctype Atom = 0x27c0b - Formmethod Atom = 0x2970a - Formnovalidate Atom = 0x2a10e - Formtarget Atom = 0x2b30a - Frame Atom = 0x8b05 - Frameset Atom = 0x8b08 - H1 Atom = 0x15c02 - H2 Atom = 0x56102 - H3 Atom = 0x2cd02 - H4 Atom = 0x2fc02 - H5 Atom = 0x33f02 - H6 Atom = 0x34902 - Head Atom = 0x32004 - Header Atom = 0x32006 - Headers Atom = 0x32007 - Height Atom = 0x5206 - Hgroup Atom = 0x64206 - Hidden Atom = 0x2bd06 - High Atom = 0x2ca04 - Hr Atom = 0x15702 - Href Atom = 0x2cf04 - Hreflang Atom = 0x2cf08 - Html Atom = 0x5604 - HttpEquiv Atom = 0x2d70a - I Atom = 0x601 - Icon Atom = 0x57a04 - Id Atom = 0x10902 - Iframe Atom = 0x2eb06 - Image Atom = 0x2f105 - Img Atom = 0x2f603 - Input Atom = 0x44505 - Inputmode Atom = 0x44509 - Ins Atom = 0x20303 - Integrity Atom = 0x23209 - Is Atom = 0x16502 - Isindex Atom = 0x2fe07 - Ismap Atom = 0x30505 - Itemid Atom = 0x38506 - Itemprop Atom = 0x19d08 - Itemref Atom = 0x3c707 - Itemscope Atom = 0x66f09 - Itemtype Atom = 0x30e08 - Kbd Atom = 0xb903 - Keygen Atom = 0x3206 - Keytype Atom = 0xd607 - Kind Atom = 0x17704 - Label Atom = 0x5905 - Lang Atom = 0x2d304 - Legend Atom = 0x18106 - Li Atom = 0xb202 - Link Atom = 0x17404 - List Atom = 0x49d04 - Listing Atom = 0x49d07 - Loop Atom = 0x5d04 - Low Atom = 0xc303 - Main Atom = 0x1004 - Malignmark Atom = 0xb00a - Manifest Atom = 0x6d508 - Map Atom = 0x30703 - Mark Atom = 0xb604 - Marquee Atom = 0x31607 - Math Atom = 0x31d04 - Max Atom = 0x33703 - Maxlength Atom = 0x33709 - Media Atom = 0xe605 - Mediagroup Atom = 0xe60a - Menu Atom = 0x38104 - Menuitem Atom = 0x38108 - Meta Atom = 0x4ac04 - Meter Atom = 0x9805 - Method Atom = 0x29b06 - Mglyph Atom = 0x2f706 - Mi Atom = 0x34102 - Min Atom = 0x34103 - Minlength Atom = 0x34109 - Mn Atom = 0x2a402 - Mo Atom = 0xa402 - Ms Atom = 0x67202 - Mtext Atom = 0x34b05 - Multiple Atom = 0x35908 - Muted Atom = 0x36105 - Name Atom = 0x9604 - Nav Atom = 0x1303 - Nobr Atom = 0x3704 - Noembed Atom = 0x6c07 - Noframes Atom = 0x8908 - Nomodule Atom = 0xa208 - Nonce Atom = 0x1a605 - Noscript Atom = 0x2c208 - Novalidate Atom = 0x2a50a - Object Atom = 0x25b06 - Ol Atom = 0x13702 - Onabort Atom = 0x19507 - Onafterprint Atom = 0x2290c - Onautocomplete Atom = 0x2690e - Onautocompleteerror Atom = 0x26913 - Onauxclick Atom = 0x6140a - Onbeforeprint Atom = 0x69c0d - Onbeforeunload Atom = 0x6e50e - Onblur Atom = 0x1ea06 - Oncancel Atom = 0x11908 - Oncanplay Atom = 0x14d09 - Oncanplaythrough Atom = 0x14d10 - Onchange Atom = 0x41508 - Onclick Atom = 0x2e407 - Onclose Atom = 0x36607 - Oncontextmenu Atom = 0x3780d - Oncopy Atom = 0x38b06 - Oncuechange Atom = 0x3910b - Oncut Atom = 0x39c05 - Ondblclick Atom = 0x3a10a - Ondrag Atom = 0x3ab06 - Ondragend Atom = 0x3ab09 - Ondragenter Atom = 0x3b40b - Ondragexit Atom = 0x3bf0a - Ondragleave Atom = 0x3d90b - Ondragover Atom = 0x3e40a - Ondragstart Atom = 0x3ee0b - Ondrop Atom = 0x3fd06 - Ondurationchange Atom = 0x40d10 - Onemptied Atom = 0x40409 - Onended Atom = 0x41d07 - Onerror Atom = 0x42407 - Onfocus Atom = 0x42b07 - Onhashchange Atom = 0x4370c - Oninput Atom = 0x44307 - Oninvalid Atom = 0x44f09 - Onkeydown Atom = 0x45809 - Onkeypress Atom = 0x4650a - Onkeyup Atom = 0x47407 - Onlanguagechange Atom = 0x48110 - Onload Atom = 0x49106 - Onloadeddata Atom = 0x4910c - Onloadedmetadata Atom = 0x4a410 - Onloadend Atom = 0x4ba09 - Onloadstart Atom = 0x4c30b - Onmessage Atom = 0x4ce09 - Onmessageerror Atom = 0x4ce0e - Onmousedown Atom = 0x4dc0b - Onmouseenter Atom = 0x4e70c - Onmouseleave Atom = 0x4f30c - Onmousemove Atom = 0x4ff0b - Onmouseout Atom = 0x50a0a - Onmouseover Atom = 0x5170b - Onmouseup Atom = 0x52209 - Onmousewheel Atom = 0x5300c - Onoffline Atom = 0x53c09 - Ononline Atom = 0x54508 - Onpagehide Atom = 0x54d0a - Onpageshow Atom = 0x5630a - Onpaste Atom = 0x56f07 - Onpause Atom = 0x58a07 - Onplay Atom = 0x59406 - Onplaying Atom = 0x59409 - Onpopstate Atom = 0x59d0a - Onprogress Atom = 0x5a70a - Onratechange Atom = 0x5bc0c - Onrejectionhandled Atom = 0x5c812 - Onreset Atom = 0x5da07 - Onresize Atom = 0x5e108 - Onscroll Atom = 0x5f508 - Onsecuritypolicyviolation Atom = 0x5fd19 - Onseeked Atom = 0x61e08 - Onseeking Atom = 0x62609 - Onselect Atom = 0x62f08 - Onshow Atom = 0x63906 - Onsort Atom = 0x64d06 - Onstalled Atom = 0x65709 - Onstorage Atom = 0x66009 - Onsubmit Atom = 0x66908 - Onsuspend Atom = 0x67909 - Ontimeupdate Atom = 0x400c - Ontoggle Atom = 0x68208 - Onunhandledrejection Atom = 0x68a14 - Onunload Atom = 0x6a908 - Onvolumechange Atom = 0x6b10e - Onwaiting Atom = 0x6bf09 - Onwheel Atom = 0x6c807 - Open Atom = 0x1a304 - Optgroup Atom = 0x5f08 - Optimum Atom = 0x6cf07 - Option Atom = 0x6e106 - Output Atom = 0x51106 - P Atom = 0xc01 - Param Atom = 0xc05 - Pattern Atom = 0x6607 - Picture Atom = 0x7b07 - Ping Atom = 0xef04 - Placeholder Atom = 0x1310b - Plaintext Atom = 0x1b209 - Playsinline Atom = 0x1400b - Poster Atom = 0x64706 - Pre Atom = 0x46a03 - Preload Atom = 0x47a07 - Progress Atom = 0x5a908 - Prompt Atom = 0x52a06 - Public Atom = 0x57606 - Q Atom = 0xcf01 - Radiogroup Atom = 0x30a - Rb Atom = 0x3a02 - Readonly Atom = 0x35108 - Referrerpolicy Atom = 0x3cb0e - Rel Atom = 0x47b03 - Required Atom = 0x23f08 - Reversed Atom = 0x8008 - Rows Atom = 0x9c04 - Rowspan Atom = 0x9c07 - Rp Atom = 0x22f02 - Rt Atom = 0x19a02 - Rtc Atom = 0x19a03 - Ruby Atom = 0xfb04 - S Atom = 0x2501 - Samp Atom = 0x7804 - Sandbox Atom = 0x12907 - Scope Atom = 0x67305 - Scoped Atom = 0x67306 - Script Atom = 0x2c406 - Seamless Atom = 0x36b08 - Search Atom = 0x55c06 - Section Atom = 0x1e507 - Select Atom = 0x63106 - Selected Atom = 0x63108 - Shape Atom = 0x1f505 - Size Atom = 0x5e504 - Sizes Atom = 0x5e505 - Slot Atom = 0x20504 - Small Atom = 0x32605 - Sortable Atom = 0x64f08 - Sorted Atom = 0x37206 - Source Atom = 0x43106 - Spacer Atom = 0x46e06 - Span Atom = 0x9f04 - Spellcheck Atom = 0x5b00a - Src Atom = 0x5e903 - Srcdoc Atom = 0x5e906 - Srclang Atom = 0x6f707 - Srcset Atom = 0x6fe06 - Start Atom = 0x3f405 - Step Atom = 0x57304 - Strike Atom = 0xd206 - Strong Atom = 0x6db06 - Style Atom = 0x70405 - Sub Atom = 0x66b03 - Summary Atom = 0x70907 - Sup Atom = 0x71003 - Svg Atom = 0x71303 - System Atom = 0x71606 - Tabindex Atom = 0x4b208 - Table Atom = 0x58505 - Target Atom = 0x2b706 - Tbody Atom = 0x2705 - Td Atom = 0x9202 - Template Atom = 0x71908 - Textarea Atom = 0x34c08 - Tfoot Atom = 0xf505 - Th Atom = 0x15602 - Thead Atom = 0x31f05 - Time Atom = 0x4204 - Title Atom = 0x11005 - Tr Atom = 0xcc02 - Track Atom = 0x1ba05 - Translate Atom = 0x20809 - Tt Atom = 0x6802 - Type Atom = 0xd904 - Typemustmatch Atom = 0x2830d - U Atom = 0xb01 - Ul Atom = 0xa702 - Updateviacache Atom = 0x460e - Usemap Atom = 0x58e06 - Value Atom = 0x1505 - Var Atom = 0x16d03 - Video Atom = 0x2e005 - Wbr Atom = 0x56c03 - Width Atom = 0x63e05 - Workertype Atom = 0x7210a - Wrap Atom = 0x72b04 - Xmp Atom = 0x12f03 -) - -const hash0 = 0x84f70e16 - -const maxAtomLen = 25 - -var table = [1 << 9]Atom{ - 0x1: 0x3ff08, // dropzone - 0x2: 0x3b08, // basefont - 0x3: 0x23209, // integrity - 0x4: 0x43106, // source - 0x5: 0x2c09, // accesskey - 0x6: 0x1a06, // accept - 0x7: 0x6c807, // onwheel - 0xb: 0x47407, // onkeyup - 0xc: 0x32007, // headers - 0xd: 0x67306, // scoped - 0xe: 0x67909, // onsuspend - 0xf: 0x8908, // noframes - 0x10: 0x1fa0b, // crossorigin - 0x11: 0x2e407, // onclick - 0x12: 0x3f405, // start - 0x13: 0x37a0b, // contextmenu - 0x14: 0x5e903, // src - 0x15: 0x1c404, // cols - 0x16: 0xbb06, // dialog - 0x17: 0x47a07, // preload - 0x18: 0x3c707, // itemref - 0x1b: 0x2f105, // image - 0x1d: 0x4ba09, // onloadend - 0x1e: 0x45d08, // download - 0x1f: 0x46a03, // pre - 0x23: 0x2970a, // formmethod - 0x24: 0x71303, // svg - 0x25: 0xcf01, // q - 0x26: 0x64002, // dt - 0x27: 0x1de08, // controls - 0x2a: 0x2804, // body - 0x2b: 0xd206, // strike - 0x2c: 0x3910b, // oncuechange - 0x2d: 0x4c30b, // onloadstart - 0x2e: 0x2fe07, // isindex - 0x2f: 0xb202, // li - 0x30: 0x1400b, // playsinline - 0x31: 0x34102, // mi - 0x32: 0x30806, // applet - 0x33: 0x4ce09, // onmessage - 0x35: 0x13702, // ol - 0x36: 0x1a304, // open - 0x39: 0x14d09, // oncanplay - 0x3a: 0x6bf09, // onwaiting - 0x3b: 0x11908, // oncancel - 0x3c: 0x6a908, // onunload - 0x3e: 0x53c09, // onoffline - 0x3f: 0x1a0e, // accept-charset - 0x40: 0x32004, // head - 0x42: 0x3ab09, // ondragend - 0x43: 0x1310b, // placeholder - 0x44: 0x2b30a, // formtarget - 0x45: 0x2540d, // foreignobject - 0x47: 0x400c, // ontimeupdate - 0x48: 0xdd0e, // allowusermedia - 0x4a: 0x69c0d, // onbeforeprint - 0x4b: 0x5604, // html - 0x4c: 0x9f04, // span - 0x4d: 0x64206, // hgroup - 0x4e: 0x16408, // disabled - 0x4f: 0x4204, // time - 0x51: 0x42b07, // onfocus - 0x53: 0xb00a, // malignmark - 0x55: 0x4650a, // onkeypress - 0x56: 0x55805, // class - 0x57: 0x1ab08, // colgroup - 0x58: 0x33709, // maxlength - 0x59: 0x5a908, // progress - 0x5b: 0x70405, // style - 0x5c: 0x2a10e, // formnovalidate - 0x5e: 0x38b06, // oncopy - 0x60: 0x26104, // form - 0x61: 0xf606, // footer - 0x64: 0x30a, // radiogroup - 0x66: 0xfb04, // ruby - 0x67: 0x4ff0b, // onmousemove - 0x68: 0x19d08, // itemprop - 0x69: 0x2d70a, // http-equiv - 0x6a: 0x15602, // th - 0x6c: 0x6e02, // em - 0x6d: 0x38108, // menuitem - 0x6e: 0x63106, // select - 0x6f: 0x48110, // onlanguagechange - 0x70: 0x31f05, // thead - 0x71: 0x15c02, // h1 - 0x72: 0x5e906, // srcdoc - 0x75: 0x9604, // name - 0x76: 0x19106, // button - 0x77: 0x55504, // desc - 0x78: 0x17704, // kind - 0x79: 0x1bf05, // color - 0x7c: 0x58e06, // usemap - 0x7d: 0x30e08, // itemtype - 0x7f: 0x6d508, // manifest - 0x81: 0x5300c, // onmousewheel - 0x82: 0x4dc0b, // onmousedown - 0x84: 0xc05, // param - 0x85: 0x2e005, // video - 0x86: 0x4910c, // onloadeddata - 0x87: 0x6f107, // address - 0x8c: 0xef04, // ping - 0x8d: 0x24703, // for - 0x8f: 0x62f08, // onselect - 0x90: 0x30703, // map - 0x92: 0xc01, // p - 0x93: 0x8008, // reversed - 0x94: 0x54d0a, // onpagehide - 0x95: 0x3206, // keygen - 0x96: 0x34109, // minlength - 0x97: 0x3e40a, // ondragover - 0x98: 0x42407, // onerror - 0x9a: 0x2107, // charset - 0x9b: 0x29b06, // method - 0x9c: 0x101, // b - 0x9d: 0x68208, // ontoggle - 0x9e: 0x2bd06, // hidden - 0xa0: 0x3f607, // article - 0xa2: 0x63906, // onshow - 0xa3: 0x64d06, // onsort - 0xa5: 0x57b0f, // contenteditable - 0xa6: 0x66908, // onsubmit - 0xa8: 0x44f09, // oninvalid - 0xaa: 0x202, // br - 0xab: 0x10902, // id - 0xac: 0x5d04, // loop - 0xad: 0x5630a, // onpageshow - 0xb0: 0x2cf04, // href - 0xb2: 0x2210a, // figcaption - 0xb3: 0x2690e, // onautocomplete - 0xb4: 0x49106, // onload - 0xb6: 0x9c04, // rows - 0xb7: 0x1a605, // nonce - 0xb8: 0x68a14, // onunhandledrejection - 0xbb: 0x21306, // center - 0xbc: 0x59406, // onplay - 0xbd: 0x33f02, // h5 - 0xbe: 0x49d07, // listing - 0xbf: 0x57606, // public - 0xc2: 0x23b06, // figure - 0xc3: 0x57a04, // icon - 0xc4: 0x1ab03, // col - 0xc5: 0x47b03, // rel - 0xc6: 0xe605, // media - 0xc7: 0x12109, // autofocus - 0xc8: 0x19a02, // rt - 0xca: 0x2d304, // lang - 0xcc: 0x49908, // datalist - 0xce: 0x2eb06, // iframe - 0xcf: 0x36105, // muted - 0xd0: 0x6140a, // onauxclick - 0xd2: 0x3c02, // as - 0xd6: 0x3fd06, // ondrop - 0xd7: 0x1c90a, // annotation - 0xd8: 0x21908, // fieldset - 0xdb: 0x2cf08, // hreflang - 0xdc: 0x4e70c, // onmouseenter - 0xdd: 0x2a402, // mn - 0xde: 0xe60a, // mediagroup - 0xdf: 0x9805, // meter - 0xe0: 0x56c03, // wbr - 0xe2: 0x63e05, // width - 0xe3: 0x2290c, // onafterprint - 0xe4: 0x30505, // ismap - 0xe5: 0x1505, // value - 0xe7: 0x1303, // nav - 0xe8: 0x54508, // ononline - 0xe9: 0xb604, // mark - 0xea: 0xc303, // low - 0xeb: 0x3ee0b, // ondragstart - 0xef: 0x12f03, // xmp - 0xf0: 0x22407, // caption - 0xf1: 0xd904, // type - 0xf2: 0x70907, // summary - 0xf3: 0x6802, // tt - 0xf4: 0x20809, // translate - 0xf5: 0x1870a, // blockquote - 0xf8: 0x15702, // hr - 0xfa: 0x2705, // tbody - 0xfc: 0x7b07, // picture - 0xfd: 0x5206, // height - 0xfe: 0x19c04, // cite - 0xff: 0x2501, // s - 0x101: 0xff05, // async - 0x102: 0x56f07, // onpaste - 0x103: 0x19507, // onabort - 0x104: 0x2b706, // target - 0x105: 0x14b03, // bdo - 0x106: 0x1f006, // coords - 0x107: 0x5e108, // onresize - 0x108: 0x71908, // template - 0x10a: 0x3a02, // rb - 0x10b: 0x2a50a, // novalidate - 0x10c: 0x460e, // updateviacache - 0x10d: 0x71003, // sup - 0x10e: 0x6c07, // noembed - 0x10f: 0x16b03, // div - 0x110: 0x6f707, // srclang - 0x111: 0x17a09, // draggable - 0x112: 0x67305, // scope - 0x113: 0x5905, // label - 0x114: 0x22f02, // rp - 0x115: 0x23f08, // required - 0x116: 0x3780d, // oncontextmenu - 0x117: 0x5e504, // size - 0x118: 0x5b00a, // spellcheck - 0x119: 0x3f04, // font - 0x11a: 0x9c07, // rowspan - 0x11b: 0x10a07, // default - 0x11d: 0x44307, // oninput - 0x11e: 0x38506, // itemid - 0x11f: 0x5ee04, // code - 0x120: 0xaa07, // acronym - 0x121: 0x3b04, // base - 0x125: 0x2470d, // foreignObject - 0x126: 0x2ca04, // high - 0x127: 0x3cb0e, // referrerpolicy - 0x128: 0x33703, // max - 0x129: 0x59d0a, // onpopstate - 0x12a: 0x2fc02, // h4 - 0x12b: 0x4ac04, // meta - 0x12c: 0x17305, // blink - 0x12e: 0x5f508, // onscroll - 0x12f: 0x59409, // onplaying - 0x130: 0xc113, // allowpaymentrequest - 0x131: 0x19a03, // rtc - 0x132: 0x72b04, // wrap - 0x134: 0x8b08, // frameset - 0x135: 0x32605, // small - 0x137: 0x32006, // header - 0x138: 0x40409, // onemptied - 0x139: 0x34902, // h6 - 0x13a: 0x35908, // multiple - 0x13c: 0x52a06, // prompt - 0x13f: 0x28e09, // challenge - 0x141: 0x4370c, // onhashchange - 0x142: 0x57b07, // content - 0x143: 0x1c90e, // annotation-xml - 0x144: 0x36607, // onclose - 0x145: 0x14d10, // oncanplaythrough - 0x148: 0x5170b, // onmouseover - 0x149: 0x64f08, // sortable - 0x14a: 0xa402, // mo - 0x14b: 0x2cd02, // h3 - 0x14c: 0x2c406, // script - 0x14d: 0x41d07, // onended - 0x14f: 0x64706, // poster - 0x150: 0x7210a, // workertype - 0x153: 0x1f505, // shape - 0x154: 0x4, // abbr - 0x155: 0x1, // a - 0x156: 0x2bf02, // dd - 0x157: 0x71606, // system - 0x158: 0x4ce0e, // onmessageerror - 0x159: 0x36b08, // seamless - 0x15a: 0x2610a, // formaction - 0x15b: 0x6e106, // option - 0x15c: 0x31d04, // math - 0x15d: 0x62609, // onseeking - 0x15e: 0x39c05, // oncut - 0x15f: 0x44c03, // del - 0x160: 0x11005, // title - 0x161: 0x11505, // audio - 0x162: 0x63108, // selected - 0x165: 0x3b40b, // ondragenter - 0x166: 0x46e06, // spacer - 0x167: 0x4a410, // onloadedmetadata - 0x168: 0x44505, // input - 0x16a: 0x58505, // table - 0x16b: 0x41508, // onchange - 0x16e: 0x5f005, // defer - 0x171: 0x50a0a, // onmouseout - 0x172: 0x20504, // slot - 0x175: 0x3704, // nobr - 0x177: 0x1d707, // command - 0x17a: 0x7207, // details - 0x17b: 0x38104, // menu - 0x17c: 0xb903, // kbd - 0x17d: 0x57304, // step - 0x17e: 0x20303, // ins - 0x17f: 0x13c08, // autoplay - 0x182: 0x34103, // min - 0x183: 0x17404, // link - 0x185: 0x40d10, // ondurationchange - 0x186: 0x9202, // td - 0x187: 0x8b05, // frame - 0x18a: 0x2ab08, // datetime - 0x18b: 0x44509, // inputmode - 0x18c: 0x35108, // readonly - 0x18d: 0x21104, // face - 0x18f: 0x5e505, // sizes - 0x191: 0x4b208, // tabindex - 0x192: 0x6db06, // strong - 0x193: 0xba03, // bdi - 0x194: 0x6fe06, // srcset - 0x196: 0x67202, // ms - 0x197: 0x5b507, // checked - 0x198: 0xb105, // align - 0x199: 0x1e507, // section - 0x19b: 0x6e05, // embed - 0x19d: 0x15e07, // bgsound - 0x1a2: 0x49d04, // list - 0x1a3: 0x61e08, // onseeked - 0x1a4: 0x66009, // onstorage - 0x1a5: 0x2f603, // img - 0x1a6: 0xf505, // tfoot - 0x1a9: 0x26913, // onautocompleteerror - 0x1aa: 0x5fd19, // onsecuritypolicyviolation - 0x1ad: 0x9303, // dir - 0x1ae: 0x9307, // dirname - 0x1b0: 0x5a70a, // onprogress - 0x1b2: 0x65709, // onstalled - 0x1b5: 0x66f09, // itemscope - 0x1b6: 0x49904, // data - 0x1b7: 0x3d90b, // ondragleave - 0x1b8: 0x56102, // h2 - 0x1b9: 0x2f706, // mglyph - 0x1ba: 0x16502, // is - 0x1bb: 0x6e50e, // onbeforeunload - 0x1bc: 0x2830d, // typemustmatch - 0x1bd: 0x3ab06, // ondrag - 0x1be: 0x5da07, // onreset - 0x1c0: 0x51106, // output - 0x1c1: 0x12907, // sandbox - 0x1c2: 0x1b209, // plaintext - 0x1c4: 0x34c08, // textarea - 0x1c7: 0xd607, // keytype - 0x1c8: 0x34b05, // mtext - 0x1c9: 0x6b10e, // onvolumechange - 0x1ca: 0x1ea06, // onblur - 0x1cb: 0x58a07, // onpause - 0x1cd: 0x5bc0c, // onratechange - 0x1ce: 0x10705, // aside - 0x1cf: 0x6cf07, // optimum - 0x1d1: 0x45809, // onkeydown - 0x1d2: 0x1c407, // colspan - 0x1d3: 0x1004, // main - 0x1d4: 0x66b03, // sub - 0x1d5: 0x25b06, // object - 0x1d6: 0x55c06, // search - 0x1d7: 0x37206, // sorted - 0x1d8: 0x17003, // big - 0x1d9: 0xb01, // u - 0x1db: 0x26b0c, // autocomplete - 0x1dc: 0xcc02, // tr - 0x1dd: 0xf303, // alt - 0x1df: 0x7804, // samp - 0x1e0: 0x5c812, // onrejectionhandled - 0x1e1: 0x4f30c, // onmouseleave - 0x1e2: 0x28007, // enctype - 0x1e3: 0xa208, // nomodule - 0x1e5: 0x3280f, // allowfullscreen - 0x1e6: 0x5f08, // optgroup - 0x1e8: 0x27c0b, // formenctype - 0x1e9: 0x18106, // legend - 0x1ea: 0x10306, // canvas - 0x1eb: 0x6607, // pattern - 0x1ec: 0x2c208, // noscript - 0x1ed: 0x601, // i - 0x1ee: 0x5d602, // dl - 0x1ef: 0xa702, // ul - 0x1f2: 0x52209, // onmouseup - 0x1f4: 0x1ba05, // track - 0x1f7: 0x3a10a, // ondblclick - 0x1f8: 0x3bf0a, // ondragexit - 0x1fa: 0x8703, // dfn - 0x1fc: 0x26506, // action - 0x1fd: 0x35004, // area - 0x1fe: 0x31607, // marquee - 0x1ff: 0x16d03, // var -} - -const atomText = "abbradiogrouparamainavalueaccept-charsetbodyaccesskeygenobrb" + - "asefontimeupdateviacacheightmlabelooptgroupatternoembedetail" + - "sampictureversedfnoframesetdirnameterowspanomoduleacronymali" + - "gnmarkbdialogallowpaymentrequestrikeytypeallowusermediagroup" + - "ingaltfooterubyasyncanvasidefaultitleaudioncancelautofocusan" + - "dboxmplaceholderautoplaysinlinebdoncanplaythrough1bgsoundisa" + - "bledivarbigblinkindraggablegendblockquotebuttonabortcitempro" + - "penoncecolgrouplaintextrackcolorcolspannotation-xmlcommandco" + - "ntrolsectionblurcoordshapecrossoriginslotranslatefacenterfie" + - "ldsetfigcaptionafterprintegrityfigurequiredforeignObjectfore" + - "ignobjectformactionautocompleteerrorformenctypemustmatchalle" + - "ngeformmethodformnovalidatetimeformtargethiddenoscripthigh3h" + - "reflanghttp-equivideonclickiframeimageimglyph4isindexismappl" + - "etitemtypemarqueematheadersmallowfullscreenmaxlength5minleng" + - "th6mtextareadonlymultiplemutedoncloseamlessortedoncontextmen" + - "uitemidoncopyoncuechangeoncutondblclickondragendondragentero" + - "ndragexitemreferrerpolicyondragleaveondragoverondragstarticl" + - "eondropzonemptiedondurationchangeonendedonerroronfocusourceo" + - "nhashchangeoninputmodeloninvalidonkeydownloadonkeypresspacer" + - "onkeyupreloadonlanguagechangeonloadeddatalistingonloadedmeta" + - "databindexonloadendonloadstartonmessageerroronmousedownonmou" + - "seenteronmouseleaveonmousemoveonmouseoutputonmouseoveronmous" + - "eupromptonmousewheelonofflineononlineonpagehidesclassearch2o" + - "npageshowbronpastepublicontenteditableonpausemaponplayingonp" + - "opstateonprogresspellcheckedonratechangeonrejectionhandledon" + - "resetonresizesrcdocodeferonscrollonsecuritypolicyviolationau" + - "xclickonseekedonseekingonselectedonshowidthgrouposteronsorta" + - "bleonstalledonstorageonsubmitemscopedonsuspendontoggleonunha" + - "ndledrejectionbeforeprintonunloadonvolumechangeonwaitingonwh" + - "eeloptimumanifestrongoptionbeforeunloaddressrclangsrcsetstyl" + - "esummarysupsvgsystemplateworkertypewrap" diff --git a/vendor/golang.org/x/net/html/const.go b/vendor/golang.org/x/net/html/const.go deleted file mode 100644 index ff7acf2..0000000 --- a/vendor/golang.org/x/net/html/const.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -// Section 12.2.4.2 of the HTML5 specification says "The following elements -// have varying levels of special parsing rules". -// https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements -var isSpecialElementMap = map[string]bool{ - "address": true, - "applet": true, - "area": true, - "article": true, - "aside": true, - "base": true, - "basefont": true, - "bgsound": true, - "blockquote": true, - "body": true, - "br": true, - "button": true, - "caption": true, - "center": true, - "col": true, - "colgroup": true, - "dd": true, - "details": true, - "dir": true, - "div": true, - "dl": true, - "dt": true, - "embed": true, - "fieldset": true, - "figcaption": true, - "figure": true, - "footer": true, - "form": true, - "frame": true, - "frameset": true, - "h1": true, - "h2": true, - "h3": true, - "h4": true, - "h5": true, - "h6": true, - "head": true, - "header": true, - "hgroup": true, - "hr": true, - "html": true, - "iframe": true, - "img": true, - "input": true, - "keygen": true, // "keygen" has been removed from the spec, but are kept here for backwards compatibility. - "li": true, - "link": true, - "listing": true, - "main": true, - "marquee": true, - "menu": true, - "meta": true, - "nav": true, - "noembed": true, - "noframes": true, - "noscript": true, - "object": true, - "ol": true, - "p": true, - "param": true, - "plaintext": true, - "pre": true, - "script": true, - "section": true, - "select": true, - "source": true, - "style": true, - "summary": true, - "table": true, - "tbody": true, - "td": true, - "template": true, - "textarea": true, - "tfoot": true, - "th": true, - "thead": true, - "title": true, - "tr": true, - "track": true, - "ul": true, - "wbr": true, - "xmp": true, -} - -func isSpecialElement(element *Node) bool { - switch element.Namespace { - case "", "html": - return isSpecialElementMap[element.Data] - case "math": - switch element.Data { - case "mi", "mo", "mn", "ms", "mtext", "annotation-xml": - return true - } - case "svg": - switch element.Data { - case "foreignObject", "desc", "title": - return true - } - } - return false -} diff --git a/vendor/golang.org/x/net/html/doc.go b/vendor/golang.org/x/net/html/doc.go deleted file mode 100644 index 885c4c5..0000000 --- a/vendor/golang.org/x/net/html/doc.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package html implements an HTML5-compliant tokenizer and parser. - -Tokenization is done by creating a Tokenizer for an io.Reader r. It is the -caller's responsibility to ensure that r provides UTF-8 encoded HTML. - - z := html.NewTokenizer(r) - -Given a Tokenizer z, the HTML is tokenized by repeatedly calling z.Next(), -which parses the next token and returns its type, or an error: - - for { - tt := z.Next() - if tt == html.ErrorToken { - // ... - return ... - } - // Process the current token. - } - -There are two APIs for retrieving the current token. The high-level API is to -call Token; the low-level API is to call Text or TagName / TagAttr. Both APIs -allow optionally calling Raw after Next but before Token, Text, TagName, or -TagAttr. In EBNF notation, the valid call sequence per token is: - - Next {Raw} [ Token | Text | TagName {TagAttr} ] - -Token returns an independent data structure that completely describes a token. -Entities (such as "<") are unescaped, tag names and attribute keys are -lower-cased, and attributes are collected into a []Attribute. For example: - - for { - if z.Next() == html.ErrorToken { - // Returning io.EOF indicates success. - return z.Err() - } - emitToken(z.Token()) - } - -The low-level API performs fewer allocations and copies, but the contents of -the []byte values returned by Text, TagName and TagAttr may change on the next -call to Next. For example, to extract an HTML page's anchor text: - - depth := 0 - for { - tt := z.Next() - switch tt { - case html.ErrorToken: - return z.Err() - case html.TextToken: - if depth > 0 { - // emitBytes should copy the []byte it receives, - // if it doesn't process it immediately. - emitBytes(z.Text()) - } - case html.StartTagToken, html.EndTagToken: - tn, _ := z.TagName() - if len(tn) == 1 && tn[0] == 'a' { - if tt == html.StartTagToken { - depth++ - } else { - depth-- - } - } - } - } - -Parsing is done by calling Parse with an io.Reader, which returns the root of -the parse tree (the document element) as a *Node. It is the caller's -responsibility to ensure that the Reader provides UTF-8 encoded HTML. For -example, to process each anchor node in depth-first order: - - doc, err := html.Parse(r) - if err != nil { - // ... - } - for n := range doc.Descendants() { - if n.Type == html.ElementNode && n.Data == "a" { - // Do something with n... - } - } - -The relevant specifications include: -https://html.spec.whatwg.org/multipage/syntax.html and -https://html.spec.whatwg.org/multipage/syntax.html#tokenization - -# Security Considerations - -Care should be taken when parsing and interpreting HTML, whether full documents -or fragments, within the framework of the HTML specification, especially with -regard to untrusted inputs. - -This package provides both a tokenizer and a parser, which implement the -tokenization, and tokenization and tree construction stages of the WHATWG HTML -parsing specification respectively. While the tokenizer parses and normalizes -individual HTML tokens, only the parser constructs the DOM tree from the -tokenized HTML, as described in the tree construction stage of the -specification, dynamically modifying or extending the document's DOM tree. - -If your use case requires semantically well-formed HTML documents, as defined by -the WHATWG specification, the parser should be used rather than the tokenizer. - -In security contexts, if trust decisions are being made using the tokenized or -parsed content, the input must be re-serialized (for instance by using Render or -Token.String) in order for those trust decisions to hold, as the process of -tokenization or parsing may alter the content. -*/ -package html // import "golang.org/x/net/html" - -// The tokenization algorithm implemented by this package is not a line-by-line -// transliteration of the relatively verbose state-machine in the WHATWG -// specification. A more direct approach is used instead, where the program -// counter implies the state, such as whether it is tokenizing a tag or a text -// node. Specification compliance is verified by checking expected and actual -// outputs over a test suite rather than aiming for algorithmic fidelity. - -// TODO(nigeltao): Does a DOM API belong in this package or a separate one? -// TODO(nigeltao): How does parsing interact with a JavaScript engine? diff --git a/vendor/golang.org/x/net/html/doctype.go b/vendor/golang.org/x/net/html/doctype.go deleted file mode 100644 index bca3ae9..0000000 --- a/vendor/golang.org/x/net/html/doctype.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -import ( - "strings" -) - -// parseDoctype parses the data from a DoctypeToken into a name, -// public identifier, and system identifier. It returns a Node whose Type -// is DoctypeNode, whose Data is the name, and which has attributes -// named "system" and "public" for the two identifiers if they were present. -// quirks is whether the document should be parsed in "quirks mode". -func parseDoctype(s string) (n *Node, quirks bool) { - n = &Node{Type: DoctypeNode} - - // Find the name. - space := strings.IndexAny(s, whitespace) - if space == -1 { - space = len(s) - } - n.Data = s[:space] - // The comparison to "html" is case-sensitive. - if n.Data != "html" { - quirks = true - } - n.Data = strings.ToLower(n.Data) - s = strings.TrimLeft(s[space:], whitespace) - - if len(s) < 6 { - // It can't start with "PUBLIC" or "SYSTEM". - // Ignore the rest of the string. - return n, quirks || s != "" - } - - key := strings.ToLower(s[:6]) - s = s[6:] - for key == "public" || key == "system" { - s = strings.TrimLeft(s, whitespace) - if s == "" { - break - } - quote := s[0] - if quote != '"' && quote != '\'' { - break - } - s = s[1:] - q := strings.IndexRune(s, rune(quote)) - var id string - if q == -1 { - id = s - s = "" - } else { - id = s[:q] - s = s[q+1:] - } - n.Attr = append(n.Attr, Attribute{Key: key, Val: id}) - if key == "public" { - key = "system" - } else { - key = "" - } - } - - if key != "" || s != "" { - quirks = true - } else if len(n.Attr) > 0 { - if n.Attr[0].Key == "public" { - public := strings.ToLower(n.Attr[0].Val) - switch public { - case "-//w3o//dtd w3 html strict 3.0//en//", "-/w3d/dtd html 4.0 transitional/en", "html": - quirks = true - default: - for _, q := range quirkyIDs { - if strings.HasPrefix(public, q) { - quirks = true - break - } - } - } - // The following two public IDs only cause quirks mode if there is no system ID. - if len(n.Attr) == 1 && (strings.HasPrefix(public, "-//w3c//dtd html 4.01 frameset//") || - strings.HasPrefix(public, "-//w3c//dtd html 4.01 transitional//")) { - quirks = true - } - } - if lastAttr := n.Attr[len(n.Attr)-1]; lastAttr.Key == "system" && - strings.EqualFold(lastAttr.Val, "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd") { - quirks = true - } - } - - return n, quirks -} - -// quirkyIDs is a list of public doctype identifiers that cause a document -// to be interpreted in quirks mode. The identifiers should be in lower case. -var quirkyIDs = []string{ - "+//silmaril//dtd html pro v0r11 19970101//", - "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", - "-//as//dtd html 3.0 aswedit + extensions//", - "-//ietf//dtd html 2.0 level 1//", - "-//ietf//dtd html 2.0 level 2//", - "-//ietf//dtd html 2.0 strict level 1//", - "-//ietf//dtd html 2.0 strict level 2//", - "-//ietf//dtd html 2.0 strict//", - "-//ietf//dtd html 2.0//", - "-//ietf//dtd html 2.1e//", - "-//ietf//dtd html 3.0//", - "-//ietf//dtd html 3.2 final//", - "-//ietf//dtd html 3.2//", - "-//ietf//dtd html 3//", - "-//ietf//dtd html level 0//", - "-//ietf//dtd html level 1//", - "-//ietf//dtd html level 2//", - "-//ietf//dtd html level 3//", - "-//ietf//dtd html strict level 0//", - "-//ietf//dtd html strict level 1//", - "-//ietf//dtd html strict level 2//", - "-//ietf//dtd html strict level 3//", - "-//ietf//dtd html strict//", - "-//ietf//dtd html//", - "-//metrius//dtd metrius presentational//", - "-//microsoft//dtd internet explorer 2.0 html strict//", - "-//microsoft//dtd internet explorer 2.0 html//", - "-//microsoft//dtd internet explorer 2.0 tables//", - "-//microsoft//dtd internet explorer 3.0 html strict//", - "-//microsoft//dtd internet explorer 3.0 html//", - "-//microsoft//dtd internet explorer 3.0 tables//", - "-//netscape comm. corp.//dtd html//", - "-//netscape comm. corp.//dtd strict html//", - "-//o'reilly and associates//dtd html 2.0//", - "-//o'reilly and associates//dtd html extended 1.0//", - "-//o'reilly and associates//dtd html extended relaxed 1.0//", - "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", - "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", - "-//spyglass//dtd html 2.0 extended//", - "-//sq//dtd html 2.0 hotmetal + extensions//", - "-//sun microsystems corp.//dtd hotjava html//", - "-//sun microsystems corp.//dtd hotjava strict html//", - "-//w3c//dtd html 3 1995-03-24//", - "-//w3c//dtd html 3.2 draft//", - "-//w3c//dtd html 3.2 final//", - "-//w3c//dtd html 3.2//", - "-//w3c//dtd html 3.2s draft//", - "-//w3c//dtd html 4.0 frameset//", - "-//w3c//dtd html 4.0 transitional//", - "-//w3c//dtd html experimental 19960712//", - "-//w3c//dtd html experimental 970421//", - "-//w3c//dtd w3 html//", - "-//w3o//dtd w3 html 3.0//", - "-//webtechs//dtd mozilla html 2.0//", - "-//webtechs//dtd mozilla html//", -} diff --git a/vendor/golang.org/x/net/html/entity.go b/vendor/golang.org/x/net/html/entity.go deleted file mode 100644 index b628880..0000000 --- a/vendor/golang.org/x/net/html/entity.go +++ /dev/null @@ -1,2253 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -// All entities that do not end with ';' are 6 or fewer bytes long. -const longestEntityWithoutSemicolon = 6 - -// entity is a map from HTML entity names to their values. The semicolon matters: -// https://html.spec.whatwg.org/multipage/syntax.html#named-character-references -// lists both "amp" and "amp;" as two separate entries. -// -// Note that the HTML5 list is larger than the HTML4 list at -// http://www.w3.org/TR/html4/sgml/entities.html -var entity = map[string]rune{ - "AElig;": '\U000000C6', - "AMP;": '\U00000026', - "Aacute;": '\U000000C1', - "Abreve;": '\U00000102', - "Acirc;": '\U000000C2', - "Acy;": '\U00000410', - "Afr;": '\U0001D504', - "Agrave;": '\U000000C0', - "Alpha;": '\U00000391', - "Amacr;": '\U00000100', - "And;": '\U00002A53', - "Aogon;": '\U00000104', - "Aopf;": '\U0001D538', - "ApplyFunction;": '\U00002061', - "Aring;": '\U000000C5', - "Ascr;": '\U0001D49C', - "Assign;": '\U00002254', - "Atilde;": '\U000000C3', - "Auml;": '\U000000C4', - "Backslash;": '\U00002216', - "Barv;": '\U00002AE7', - "Barwed;": '\U00002306', - "Bcy;": '\U00000411', - "Because;": '\U00002235', - "Bernoullis;": '\U0000212C', - "Beta;": '\U00000392', - "Bfr;": '\U0001D505', - "Bopf;": '\U0001D539', - "Breve;": '\U000002D8', - "Bscr;": '\U0000212C', - "Bumpeq;": '\U0000224E', - "CHcy;": '\U00000427', - "COPY;": '\U000000A9', - "Cacute;": '\U00000106', - "Cap;": '\U000022D2', - "CapitalDifferentialD;": '\U00002145', - "Cayleys;": '\U0000212D', - "Ccaron;": '\U0000010C', - "Ccedil;": '\U000000C7', - "Ccirc;": '\U00000108', - "Cconint;": '\U00002230', - "Cdot;": '\U0000010A', - "Cedilla;": '\U000000B8', - "CenterDot;": '\U000000B7', - "Cfr;": '\U0000212D', - "Chi;": '\U000003A7', - "CircleDot;": '\U00002299', - "CircleMinus;": '\U00002296', - "CirclePlus;": '\U00002295', - "CircleTimes;": '\U00002297', - "ClockwiseContourIntegral;": '\U00002232', - "CloseCurlyDoubleQuote;": '\U0000201D', - "CloseCurlyQuote;": '\U00002019', - "Colon;": '\U00002237', - "Colone;": '\U00002A74', - "Congruent;": '\U00002261', - "Conint;": '\U0000222F', - "ContourIntegral;": '\U0000222E', - "Copf;": '\U00002102', - "Coproduct;": '\U00002210', - "CounterClockwiseContourIntegral;": '\U00002233', - "Cross;": '\U00002A2F', - "Cscr;": '\U0001D49E', - "Cup;": '\U000022D3', - "CupCap;": '\U0000224D', - "DD;": '\U00002145', - "DDotrahd;": '\U00002911', - "DJcy;": '\U00000402', - "DScy;": '\U00000405', - "DZcy;": '\U0000040F', - "Dagger;": '\U00002021', - "Darr;": '\U000021A1', - "Dashv;": '\U00002AE4', - "Dcaron;": '\U0000010E', - "Dcy;": '\U00000414', - "Del;": '\U00002207', - "Delta;": '\U00000394', - "Dfr;": '\U0001D507', - "DiacriticalAcute;": '\U000000B4', - "DiacriticalDot;": '\U000002D9', - "DiacriticalDoubleAcute;": '\U000002DD', - "DiacriticalGrave;": '\U00000060', - "DiacriticalTilde;": '\U000002DC', - "Diamond;": '\U000022C4', - "DifferentialD;": '\U00002146', - "Dopf;": '\U0001D53B', - "Dot;": '\U000000A8', - "DotDot;": '\U000020DC', - "DotEqual;": '\U00002250', - "DoubleContourIntegral;": '\U0000222F', - "DoubleDot;": '\U000000A8', - "DoubleDownArrow;": '\U000021D3', - "DoubleLeftArrow;": '\U000021D0', - "DoubleLeftRightArrow;": '\U000021D4', - "DoubleLeftTee;": '\U00002AE4', - "DoubleLongLeftArrow;": '\U000027F8', - "DoubleLongLeftRightArrow;": '\U000027FA', - "DoubleLongRightArrow;": '\U000027F9', - "DoubleRightArrow;": '\U000021D2', - "DoubleRightTee;": '\U000022A8', - "DoubleUpArrow;": '\U000021D1', - "DoubleUpDownArrow;": '\U000021D5', - "DoubleVerticalBar;": '\U00002225', - "DownArrow;": '\U00002193', - "DownArrowBar;": '\U00002913', - "DownArrowUpArrow;": '\U000021F5', - "DownBreve;": '\U00000311', - "DownLeftRightVector;": '\U00002950', - "DownLeftTeeVector;": '\U0000295E', - "DownLeftVector;": '\U000021BD', - "DownLeftVectorBar;": '\U00002956', - "DownRightTeeVector;": '\U0000295F', - "DownRightVector;": '\U000021C1', - "DownRightVectorBar;": '\U00002957', - "DownTee;": '\U000022A4', - "DownTeeArrow;": '\U000021A7', - "Downarrow;": '\U000021D3', - "Dscr;": '\U0001D49F', - "Dstrok;": '\U00000110', - "ENG;": '\U0000014A', - "ETH;": '\U000000D0', - "Eacute;": '\U000000C9', - "Ecaron;": '\U0000011A', - "Ecirc;": '\U000000CA', - "Ecy;": '\U0000042D', - "Edot;": '\U00000116', - "Efr;": '\U0001D508', - "Egrave;": '\U000000C8', - "Element;": '\U00002208', - "Emacr;": '\U00000112', - "EmptySmallSquare;": '\U000025FB', - "EmptyVerySmallSquare;": '\U000025AB', - "Eogon;": '\U00000118', - "Eopf;": '\U0001D53C', - "Epsilon;": '\U00000395', - "Equal;": '\U00002A75', - "EqualTilde;": '\U00002242', - "Equilibrium;": '\U000021CC', - "Escr;": '\U00002130', - "Esim;": '\U00002A73', - "Eta;": '\U00000397', - "Euml;": '\U000000CB', - "Exists;": '\U00002203', - "ExponentialE;": '\U00002147', - "Fcy;": '\U00000424', - "Ffr;": '\U0001D509', - "FilledSmallSquare;": '\U000025FC', - "FilledVerySmallSquare;": '\U000025AA', - "Fopf;": '\U0001D53D', - "ForAll;": '\U00002200', - "Fouriertrf;": '\U00002131', - "Fscr;": '\U00002131', - "GJcy;": '\U00000403', - "GT;": '\U0000003E', - "Gamma;": '\U00000393', - "Gammad;": '\U000003DC', - "Gbreve;": '\U0000011E', - "Gcedil;": '\U00000122', - "Gcirc;": '\U0000011C', - "Gcy;": '\U00000413', - "Gdot;": '\U00000120', - "Gfr;": '\U0001D50A', - "Gg;": '\U000022D9', - "Gopf;": '\U0001D53E', - "GreaterEqual;": '\U00002265', - "GreaterEqualLess;": '\U000022DB', - "GreaterFullEqual;": '\U00002267', - "GreaterGreater;": '\U00002AA2', - "GreaterLess;": '\U00002277', - "GreaterSlantEqual;": '\U00002A7E', - "GreaterTilde;": '\U00002273', - "Gscr;": '\U0001D4A2', - "Gt;": '\U0000226B', - "HARDcy;": '\U0000042A', - "Hacek;": '\U000002C7', - "Hat;": '\U0000005E', - "Hcirc;": '\U00000124', - "Hfr;": '\U0000210C', - "HilbertSpace;": '\U0000210B', - "Hopf;": '\U0000210D', - "HorizontalLine;": '\U00002500', - "Hscr;": '\U0000210B', - "Hstrok;": '\U00000126', - "HumpDownHump;": '\U0000224E', - "HumpEqual;": '\U0000224F', - "IEcy;": '\U00000415', - "IJlig;": '\U00000132', - "IOcy;": '\U00000401', - "Iacute;": '\U000000CD', - "Icirc;": '\U000000CE', - "Icy;": '\U00000418', - "Idot;": '\U00000130', - "Ifr;": '\U00002111', - "Igrave;": '\U000000CC', - "Im;": '\U00002111', - "Imacr;": '\U0000012A', - "ImaginaryI;": '\U00002148', - "Implies;": '\U000021D2', - "Int;": '\U0000222C', - "Integral;": '\U0000222B', - "Intersection;": '\U000022C2', - "InvisibleComma;": '\U00002063', - "InvisibleTimes;": '\U00002062', - "Iogon;": '\U0000012E', - "Iopf;": '\U0001D540', - "Iota;": '\U00000399', - "Iscr;": '\U00002110', - "Itilde;": '\U00000128', - "Iukcy;": '\U00000406', - "Iuml;": '\U000000CF', - "Jcirc;": '\U00000134', - "Jcy;": '\U00000419', - "Jfr;": '\U0001D50D', - "Jopf;": '\U0001D541', - "Jscr;": '\U0001D4A5', - "Jsercy;": '\U00000408', - "Jukcy;": '\U00000404', - "KHcy;": '\U00000425', - "KJcy;": '\U0000040C', - "Kappa;": '\U0000039A', - "Kcedil;": '\U00000136', - "Kcy;": '\U0000041A', - "Kfr;": '\U0001D50E', - "Kopf;": '\U0001D542', - "Kscr;": '\U0001D4A6', - "LJcy;": '\U00000409', - "LT;": '\U0000003C', - "Lacute;": '\U00000139', - "Lambda;": '\U0000039B', - "Lang;": '\U000027EA', - "Laplacetrf;": '\U00002112', - "Larr;": '\U0000219E', - "Lcaron;": '\U0000013D', - "Lcedil;": '\U0000013B', - "Lcy;": '\U0000041B', - "LeftAngleBracket;": '\U000027E8', - "LeftArrow;": '\U00002190', - "LeftArrowBar;": '\U000021E4', - "LeftArrowRightArrow;": '\U000021C6', - "LeftCeiling;": '\U00002308', - "LeftDoubleBracket;": '\U000027E6', - "LeftDownTeeVector;": '\U00002961', - "LeftDownVector;": '\U000021C3', - "LeftDownVectorBar;": '\U00002959', - "LeftFloor;": '\U0000230A', - "LeftRightArrow;": '\U00002194', - "LeftRightVector;": '\U0000294E', - "LeftTee;": '\U000022A3', - "LeftTeeArrow;": '\U000021A4', - "LeftTeeVector;": '\U0000295A', - "LeftTriangle;": '\U000022B2', - "LeftTriangleBar;": '\U000029CF', - "LeftTriangleEqual;": '\U000022B4', - "LeftUpDownVector;": '\U00002951', - "LeftUpTeeVector;": '\U00002960', - "LeftUpVector;": '\U000021BF', - "LeftUpVectorBar;": '\U00002958', - "LeftVector;": '\U000021BC', - "LeftVectorBar;": '\U00002952', - "Leftarrow;": '\U000021D0', - "Leftrightarrow;": '\U000021D4', - "LessEqualGreater;": '\U000022DA', - "LessFullEqual;": '\U00002266', - "LessGreater;": '\U00002276', - "LessLess;": '\U00002AA1', - "LessSlantEqual;": '\U00002A7D', - "LessTilde;": '\U00002272', - "Lfr;": '\U0001D50F', - "Ll;": '\U000022D8', - "Lleftarrow;": '\U000021DA', - "Lmidot;": '\U0000013F', - "LongLeftArrow;": '\U000027F5', - "LongLeftRightArrow;": '\U000027F7', - "LongRightArrow;": '\U000027F6', - "Longleftarrow;": '\U000027F8', - "Longleftrightarrow;": '\U000027FA', - "Longrightarrow;": '\U000027F9', - "Lopf;": '\U0001D543', - "LowerLeftArrow;": '\U00002199', - "LowerRightArrow;": '\U00002198', - "Lscr;": '\U00002112', - "Lsh;": '\U000021B0', - "Lstrok;": '\U00000141', - "Lt;": '\U0000226A', - "Map;": '\U00002905', - "Mcy;": '\U0000041C', - "MediumSpace;": '\U0000205F', - "Mellintrf;": '\U00002133', - "Mfr;": '\U0001D510', - "MinusPlus;": '\U00002213', - "Mopf;": '\U0001D544', - "Mscr;": '\U00002133', - "Mu;": '\U0000039C', - "NJcy;": '\U0000040A', - "Nacute;": '\U00000143', - "Ncaron;": '\U00000147', - "Ncedil;": '\U00000145', - "Ncy;": '\U0000041D', - "NegativeMediumSpace;": '\U0000200B', - "NegativeThickSpace;": '\U0000200B', - "NegativeThinSpace;": '\U0000200B', - "NegativeVeryThinSpace;": '\U0000200B', - "NestedGreaterGreater;": '\U0000226B', - "NestedLessLess;": '\U0000226A', - "NewLine;": '\U0000000A', - "Nfr;": '\U0001D511', - "NoBreak;": '\U00002060', - "NonBreakingSpace;": '\U000000A0', - "Nopf;": '\U00002115', - "Not;": '\U00002AEC', - "NotCongruent;": '\U00002262', - "NotCupCap;": '\U0000226D', - "NotDoubleVerticalBar;": '\U00002226', - "NotElement;": '\U00002209', - "NotEqual;": '\U00002260', - "NotExists;": '\U00002204', - "NotGreater;": '\U0000226F', - "NotGreaterEqual;": '\U00002271', - "NotGreaterLess;": '\U00002279', - "NotGreaterTilde;": '\U00002275', - "NotLeftTriangle;": '\U000022EA', - "NotLeftTriangleEqual;": '\U000022EC', - "NotLess;": '\U0000226E', - "NotLessEqual;": '\U00002270', - "NotLessGreater;": '\U00002278', - "NotLessTilde;": '\U00002274', - "NotPrecedes;": '\U00002280', - "NotPrecedesSlantEqual;": '\U000022E0', - "NotReverseElement;": '\U0000220C', - "NotRightTriangle;": '\U000022EB', - "NotRightTriangleEqual;": '\U000022ED', - "NotSquareSubsetEqual;": '\U000022E2', - "NotSquareSupersetEqual;": '\U000022E3', - "NotSubsetEqual;": '\U00002288', - "NotSucceeds;": '\U00002281', - "NotSucceedsSlantEqual;": '\U000022E1', - "NotSupersetEqual;": '\U00002289', - "NotTilde;": '\U00002241', - "NotTildeEqual;": '\U00002244', - "NotTildeFullEqual;": '\U00002247', - "NotTildeTilde;": '\U00002249', - "NotVerticalBar;": '\U00002224', - "Nscr;": '\U0001D4A9', - "Ntilde;": '\U000000D1', - "Nu;": '\U0000039D', - "OElig;": '\U00000152', - "Oacute;": '\U000000D3', - "Ocirc;": '\U000000D4', - "Ocy;": '\U0000041E', - "Odblac;": '\U00000150', - "Ofr;": '\U0001D512', - "Ograve;": '\U000000D2', - "Omacr;": '\U0000014C', - "Omega;": '\U000003A9', - "Omicron;": '\U0000039F', - "Oopf;": '\U0001D546', - "OpenCurlyDoubleQuote;": '\U0000201C', - "OpenCurlyQuote;": '\U00002018', - "Or;": '\U00002A54', - "Oscr;": '\U0001D4AA', - "Oslash;": '\U000000D8', - "Otilde;": '\U000000D5', - "Otimes;": '\U00002A37', - "Ouml;": '\U000000D6', - "OverBar;": '\U0000203E', - "OverBrace;": '\U000023DE', - "OverBracket;": '\U000023B4', - "OverParenthesis;": '\U000023DC', - "PartialD;": '\U00002202', - "Pcy;": '\U0000041F', - "Pfr;": '\U0001D513', - "Phi;": '\U000003A6', - "Pi;": '\U000003A0', - "PlusMinus;": '\U000000B1', - "Poincareplane;": '\U0000210C', - "Popf;": '\U00002119', - "Pr;": '\U00002ABB', - "Precedes;": '\U0000227A', - "PrecedesEqual;": '\U00002AAF', - "PrecedesSlantEqual;": '\U0000227C', - "PrecedesTilde;": '\U0000227E', - "Prime;": '\U00002033', - "Product;": '\U0000220F', - "Proportion;": '\U00002237', - "Proportional;": '\U0000221D', - "Pscr;": '\U0001D4AB', - "Psi;": '\U000003A8', - "QUOT;": '\U00000022', - "Qfr;": '\U0001D514', - "Qopf;": '\U0000211A', - "Qscr;": '\U0001D4AC', - "RBarr;": '\U00002910', - "REG;": '\U000000AE', - "Racute;": '\U00000154', - "Rang;": '\U000027EB', - "Rarr;": '\U000021A0', - "Rarrtl;": '\U00002916', - "Rcaron;": '\U00000158', - "Rcedil;": '\U00000156', - "Rcy;": '\U00000420', - "Re;": '\U0000211C', - "ReverseElement;": '\U0000220B', - "ReverseEquilibrium;": '\U000021CB', - "ReverseUpEquilibrium;": '\U0000296F', - "Rfr;": '\U0000211C', - "Rho;": '\U000003A1', - "RightAngleBracket;": '\U000027E9', - "RightArrow;": '\U00002192', - "RightArrowBar;": '\U000021E5', - "RightArrowLeftArrow;": '\U000021C4', - "RightCeiling;": '\U00002309', - "RightDoubleBracket;": '\U000027E7', - "RightDownTeeVector;": '\U0000295D', - "RightDownVector;": '\U000021C2', - "RightDownVectorBar;": '\U00002955', - "RightFloor;": '\U0000230B', - "RightTee;": '\U000022A2', - "RightTeeArrow;": '\U000021A6', - "RightTeeVector;": '\U0000295B', - "RightTriangle;": '\U000022B3', - "RightTriangleBar;": '\U000029D0', - "RightTriangleEqual;": '\U000022B5', - "RightUpDownVector;": '\U0000294F', - "RightUpTeeVector;": '\U0000295C', - "RightUpVector;": '\U000021BE', - "RightUpVectorBar;": '\U00002954', - "RightVector;": '\U000021C0', - "RightVectorBar;": '\U00002953', - "Rightarrow;": '\U000021D2', - "Ropf;": '\U0000211D', - "RoundImplies;": '\U00002970', - "Rrightarrow;": '\U000021DB', - "Rscr;": '\U0000211B', - "Rsh;": '\U000021B1', - "RuleDelayed;": '\U000029F4', - "SHCHcy;": '\U00000429', - "SHcy;": '\U00000428', - "SOFTcy;": '\U0000042C', - "Sacute;": '\U0000015A', - "Sc;": '\U00002ABC', - "Scaron;": '\U00000160', - "Scedil;": '\U0000015E', - "Scirc;": '\U0000015C', - "Scy;": '\U00000421', - "Sfr;": '\U0001D516', - "ShortDownArrow;": '\U00002193', - "ShortLeftArrow;": '\U00002190', - "ShortRightArrow;": '\U00002192', - "ShortUpArrow;": '\U00002191', - "Sigma;": '\U000003A3', - "SmallCircle;": '\U00002218', - "Sopf;": '\U0001D54A', - "Sqrt;": '\U0000221A', - "Square;": '\U000025A1', - "SquareIntersection;": '\U00002293', - "SquareSubset;": '\U0000228F', - "SquareSubsetEqual;": '\U00002291', - "SquareSuperset;": '\U00002290', - "SquareSupersetEqual;": '\U00002292', - "SquareUnion;": '\U00002294', - "Sscr;": '\U0001D4AE', - "Star;": '\U000022C6', - "Sub;": '\U000022D0', - "Subset;": '\U000022D0', - "SubsetEqual;": '\U00002286', - "Succeeds;": '\U0000227B', - "SucceedsEqual;": '\U00002AB0', - "SucceedsSlantEqual;": '\U0000227D', - "SucceedsTilde;": '\U0000227F', - "SuchThat;": '\U0000220B', - "Sum;": '\U00002211', - "Sup;": '\U000022D1', - "Superset;": '\U00002283', - "SupersetEqual;": '\U00002287', - "Supset;": '\U000022D1', - "THORN;": '\U000000DE', - "TRADE;": '\U00002122', - "TSHcy;": '\U0000040B', - "TScy;": '\U00000426', - "Tab;": '\U00000009', - "Tau;": '\U000003A4', - "Tcaron;": '\U00000164', - "Tcedil;": '\U00000162', - "Tcy;": '\U00000422', - "Tfr;": '\U0001D517', - "Therefore;": '\U00002234', - "Theta;": '\U00000398', - "ThinSpace;": '\U00002009', - "Tilde;": '\U0000223C', - "TildeEqual;": '\U00002243', - "TildeFullEqual;": '\U00002245', - "TildeTilde;": '\U00002248', - "Topf;": '\U0001D54B', - "TripleDot;": '\U000020DB', - "Tscr;": '\U0001D4AF', - "Tstrok;": '\U00000166', - "Uacute;": '\U000000DA', - "Uarr;": '\U0000219F', - "Uarrocir;": '\U00002949', - "Ubrcy;": '\U0000040E', - "Ubreve;": '\U0000016C', - "Ucirc;": '\U000000DB', - "Ucy;": '\U00000423', - "Udblac;": '\U00000170', - "Ufr;": '\U0001D518', - "Ugrave;": '\U000000D9', - "Umacr;": '\U0000016A', - "UnderBar;": '\U0000005F', - "UnderBrace;": '\U000023DF', - "UnderBracket;": '\U000023B5', - "UnderParenthesis;": '\U000023DD', - "Union;": '\U000022C3', - "UnionPlus;": '\U0000228E', - "Uogon;": '\U00000172', - "Uopf;": '\U0001D54C', - "UpArrow;": '\U00002191', - "UpArrowBar;": '\U00002912', - "UpArrowDownArrow;": '\U000021C5', - "UpDownArrow;": '\U00002195', - "UpEquilibrium;": '\U0000296E', - "UpTee;": '\U000022A5', - "UpTeeArrow;": '\U000021A5', - "Uparrow;": '\U000021D1', - "Updownarrow;": '\U000021D5', - "UpperLeftArrow;": '\U00002196', - "UpperRightArrow;": '\U00002197', - "Upsi;": '\U000003D2', - "Upsilon;": '\U000003A5', - "Uring;": '\U0000016E', - "Uscr;": '\U0001D4B0', - "Utilde;": '\U00000168', - "Uuml;": '\U000000DC', - "VDash;": '\U000022AB', - "Vbar;": '\U00002AEB', - "Vcy;": '\U00000412', - "Vdash;": '\U000022A9', - "Vdashl;": '\U00002AE6', - "Vee;": '\U000022C1', - "Verbar;": '\U00002016', - "Vert;": '\U00002016', - "VerticalBar;": '\U00002223', - "VerticalLine;": '\U0000007C', - "VerticalSeparator;": '\U00002758', - "VerticalTilde;": '\U00002240', - "VeryThinSpace;": '\U0000200A', - "Vfr;": '\U0001D519', - "Vopf;": '\U0001D54D', - "Vscr;": '\U0001D4B1', - "Vvdash;": '\U000022AA', - "Wcirc;": '\U00000174', - "Wedge;": '\U000022C0', - "Wfr;": '\U0001D51A', - "Wopf;": '\U0001D54E', - "Wscr;": '\U0001D4B2', - "Xfr;": '\U0001D51B', - "Xi;": '\U0000039E', - "Xopf;": '\U0001D54F', - "Xscr;": '\U0001D4B3', - "YAcy;": '\U0000042F', - "YIcy;": '\U00000407', - "YUcy;": '\U0000042E', - "Yacute;": '\U000000DD', - "Ycirc;": '\U00000176', - "Ycy;": '\U0000042B', - "Yfr;": '\U0001D51C', - "Yopf;": '\U0001D550', - "Yscr;": '\U0001D4B4', - "Yuml;": '\U00000178', - "ZHcy;": '\U00000416', - "Zacute;": '\U00000179', - "Zcaron;": '\U0000017D', - "Zcy;": '\U00000417', - "Zdot;": '\U0000017B', - "ZeroWidthSpace;": '\U0000200B', - "Zeta;": '\U00000396', - "Zfr;": '\U00002128', - "Zopf;": '\U00002124', - "Zscr;": '\U0001D4B5', - "aacute;": '\U000000E1', - "abreve;": '\U00000103', - "ac;": '\U0000223E', - "acd;": '\U0000223F', - "acirc;": '\U000000E2', - "acute;": '\U000000B4', - "acy;": '\U00000430', - "aelig;": '\U000000E6', - "af;": '\U00002061', - "afr;": '\U0001D51E', - "agrave;": '\U000000E0', - "alefsym;": '\U00002135', - "aleph;": '\U00002135', - "alpha;": '\U000003B1', - "amacr;": '\U00000101', - "amalg;": '\U00002A3F', - "amp;": '\U00000026', - "and;": '\U00002227', - "andand;": '\U00002A55', - "andd;": '\U00002A5C', - "andslope;": '\U00002A58', - "andv;": '\U00002A5A', - "ang;": '\U00002220', - "ange;": '\U000029A4', - "angle;": '\U00002220', - "angmsd;": '\U00002221', - "angmsdaa;": '\U000029A8', - "angmsdab;": '\U000029A9', - "angmsdac;": '\U000029AA', - "angmsdad;": '\U000029AB', - "angmsdae;": '\U000029AC', - "angmsdaf;": '\U000029AD', - "angmsdag;": '\U000029AE', - "angmsdah;": '\U000029AF', - "angrt;": '\U0000221F', - "angrtvb;": '\U000022BE', - "angrtvbd;": '\U0000299D', - "angsph;": '\U00002222', - "angst;": '\U000000C5', - "angzarr;": '\U0000237C', - "aogon;": '\U00000105', - "aopf;": '\U0001D552', - "ap;": '\U00002248', - "apE;": '\U00002A70', - "apacir;": '\U00002A6F', - "ape;": '\U0000224A', - "apid;": '\U0000224B', - "apos;": '\U00000027', - "approx;": '\U00002248', - "approxeq;": '\U0000224A', - "aring;": '\U000000E5', - "ascr;": '\U0001D4B6', - "ast;": '\U0000002A', - "asymp;": '\U00002248', - "asympeq;": '\U0000224D', - "atilde;": '\U000000E3', - "auml;": '\U000000E4', - "awconint;": '\U00002233', - "awint;": '\U00002A11', - "bNot;": '\U00002AED', - "backcong;": '\U0000224C', - "backepsilon;": '\U000003F6', - "backprime;": '\U00002035', - "backsim;": '\U0000223D', - "backsimeq;": '\U000022CD', - "barvee;": '\U000022BD', - "barwed;": '\U00002305', - "barwedge;": '\U00002305', - "bbrk;": '\U000023B5', - "bbrktbrk;": '\U000023B6', - "bcong;": '\U0000224C', - "bcy;": '\U00000431', - "bdquo;": '\U0000201E', - "becaus;": '\U00002235', - "because;": '\U00002235', - "bemptyv;": '\U000029B0', - "bepsi;": '\U000003F6', - "bernou;": '\U0000212C', - "beta;": '\U000003B2', - "beth;": '\U00002136', - "between;": '\U0000226C', - "bfr;": '\U0001D51F', - "bigcap;": '\U000022C2', - "bigcirc;": '\U000025EF', - "bigcup;": '\U000022C3', - "bigodot;": '\U00002A00', - "bigoplus;": '\U00002A01', - "bigotimes;": '\U00002A02', - "bigsqcup;": '\U00002A06', - "bigstar;": '\U00002605', - "bigtriangledown;": '\U000025BD', - "bigtriangleup;": '\U000025B3', - "biguplus;": '\U00002A04', - "bigvee;": '\U000022C1', - "bigwedge;": '\U000022C0', - "bkarow;": '\U0000290D', - "blacklozenge;": '\U000029EB', - "blacksquare;": '\U000025AA', - "blacktriangle;": '\U000025B4', - "blacktriangledown;": '\U000025BE', - "blacktriangleleft;": '\U000025C2', - "blacktriangleright;": '\U000025B8', - "blank;": '\U00002423', - "blk12;": '\U00002592', - "blk14;": '\U00002591', - "blk34;": '\U00002593', - "block;": '\U00002588', - "bnot;": '\U00002310', - "bopf;": '\U0001D553', - "bot;": '\U000022A5', - "bottom;": '\U000022A5', - "bowtie;": '\U000022C8', - "boxDL;": '\U00002557', - "boxDR;": '\U00002554', - "boxDl;": '\U00002556', - "boxDr;": '\U00002553', - "boxH;": '\U00002550', - "boxHD;": '\U00002566', - "boxHU;": '\U00002569', - "boxHd;": '\U00002564', - "boxHu;": '\U00002567', - "boxUL;": '\U0000255D', - "boxUR;": '\U0000255A', - "boxUl;": '\U0000255C', - "boxUr;": '\U00002559', - "boxV;": '\U00002551', - "boxVH;": '\U0000256C', - "boxVL;": '\U00002563', - "boxVR;": '\U00002560', - "boxVh;": '\U0000256B', - "boxVl;": '\U00002562', - "boxVr;": '\U0000255F', - "boxbox;": '\U000029C9', - "boxdL;": '\U00002555', - "boxdR;": '\U00002552', - "boxdl;": '\U00002510', - "boxdr;": '\U0000250C', - "boxh;": '\U00002500', - "boxhD;": '\U00002565', - "boxhU;": '\U00002568', - "boxhd;": '\U0000252C', - "boxhu;": '\U00002534', - "boxminus;": '\U0000229F', - "boxplus;": '\U0000229E', - "boxtimes;": '\U000022A0', - "boxuL;": '\U0000255B', - "boxuR;": '\U00002558', - "boxul;": '\U00002518', - "boxur;": '\U00002514', - "boxv;": '\U00002502', - "boxvH;": '\U0000256A', - "boxvL;": '\U00002561', - "boxvR;": '\U0000255E', - "boxvh;": '\U0000253C', - "boxvl;": '\U00002524', - "boxvr;": '\U0000251C', - "bprime;": '\U00002035', - "breve;": '\U000002D8', - "brvbar;": '\U000000A6', - "bscr;": '\U0001D4B7', - "bsemi;": '\U0000204F', - "bsim;": '\U0000223D', - "bsime;": '\U000022CD', - "bsol;": '\U0000005C', - "bsolb;": '\U000029C5', - "bsolhsub;": '\U000027C8', - "bull;": '\U00002022', - "bullet;": '\U00002022', - "bump;": '\U0000224E', - "bumpE;": '\U00002AAE', - "bumpe;": '\U0000224F', - "bumpeq;": '\U0000224F', - "cacute;": '\U00000107', - "cap;": '\U00002229', - "capand;": '\U00002A44', - "capbrcup;": '\U00002A49', - "capcap;": '\U00002A4B', - "capcup;": '\U00002A47', - "capdot;": '\U00002A40', - "caret;": '\U00002041', - "caron;": '\U000002C7', - "ccaps;": '\U00002A4D', - "ccaron;": '\U0000010D', - "ccedil;": '\U000000E7', - "ccirc;": '\U00000109', - "ccups;": '\U00002A4C', - "ccupssm;": '\U00002A50', - "cdot;": '\U0000010B', - "cedil;": '\U000000B8', - "cemptyv;": '\U000029B2', - "cent;": '\U000000A2', - "centerdot;": '\U000000B7', - "cfr;": '\U0001D520', - "chcy;": '\U00000447', - "check;": '\U00002713', - "checkmark;": '\U00002713', - "chi;": '\U000003C7', - "cir;": '\U000025CB', - "cirE;": '\U000029C3', - "circ;": '\U000002C6', - "circeq;": '\U00002257', - "circlearrowleft;": '\U000021BA', - "circlearrowright;": '\U000021BB', - "circledR;": '\U000000AE', - "circledS;": '\U000024C8', - "circledast;": '\U0000229B', - "circledcirc;": '\U0000229A', - "circleddash;": '\U0000229D', - "cire;": '\U00002257', - "cirfnint;": '\U00002A10', - "cirmid;": '\U00002AEF', - "cirscir;": '\U000029C2', - "clubs;": '\U00002663', - "clubsuit;": '\U00002663', - "colon;": '\U0000003A', - "colone;": '\U00002254', - "coloneq;": '\U00002254', - "comma;": '\U0000002C', - "commat;": '\U00000040', - "comp;": '\U00002201', - "compfn;": '\U00002218', - "complement;": '\U00002201', - "complexes;": '\U00002102', - "cong;": '\U00002245', - "congdot;": '\U00002A6D', - "conint;": '\U0000222E', - "copf;": '\U0001D554', - "coprod;": '\U00002210', - "copy;": '\U000000A9', - "copysr;": '\U00002117', - "crarr;": '\U000021B5', - "cross;": '\U00002717', - "cscr;": '\U0001D4B8', - "csub;": '\U00002ACF', - "csube;": '\U00002AD1', - "csup;": '\U00002AD0', - "csupe;": '\U00002AD2', - "ctdot;": '\U000022EF', - "cudarrl;": '\U00002938', - "cudarrr;": '\U00002935', - "cuepr;": '\U000022DE', - "cuesc;": '\U000022DF', - "cularr;": '\U000021B6', - "cularrp;": '\U0000293D', - "cup;": '\U0000222A', - "cupbrcap;": '\U00002A48', - "cupcap;": '\U00002A46', - "cupcup;": '\U00002A4A', - "cupdot;": '\U0000228D', - "cupor;": '\U00002A45', - "curarr;": '\U000021B7', - "curarrm;": '\U0000293C', - "curlyeqprec;": '\U000022DE', - "curlyeqsucc;": '\U000022DF', - "curlyvee;": '\U000022CE', - "curlywedge;": '\U000022CF', - "curren;": '\U000000A4', - "curvearrowleft;": '\U000021B6', - "curvearrowright;": '\U000021B7', - "cuvee;": '\U000022CE', - "cuwed;": '\U000022CF', - "cwconint;": '\U00002232', - "cwint;": '\U00002231', - "cylcty;": '\U0000232D', - "dArr;": '\U000021D3', - "dHar;": '\U00002965', - "dagger;": '\U00002020', - "daleth;": '\U00002138', - "darr;": '\U00002193', - "dash;": '\U00002010', - "dashv;": '\U000022A3', - "dbkarow;": '\U0000290F', - "dblac;": '\U000002DD', - "dcaron;": '\U0000010F', - "dcy;": '\U00000434', - "dd;": '\U00002146', - "ddagger;": '\U00002021', - "ddarr;": '\U000021CA', - "ddotseq;": '\U00002A77', - "deg;": '\U000000B0', - "delta;": '\U000003B4', - "demptyv;": '\U000029B1', - "dfisht;": '\U0000297F', - "dfr;": '\U0001D521', - "dharl;": '\U000021C3', - "dharr;": '\U000021C2', - "diam;": '\U000022C4', - "diamond;": '\U000022C4', - "diamondsuit;": '\U00002666', - "diams;": '\U00002666', - "die;": '\U000000A8', - "digamma;": '\U000003DD', - "disin;": '\U000022F2', - "div;": '\U000000F7', - "divide;": '\U000000F7', - "divideontimes;": '\U000022C7', - "divonx;": '\U000022C7', - "djcy;": '\U00000452', - "dlcorn;": '\U0000231E', - "dlcrop;": '\U0000230D', - "dollar;": '\U00000024', - "dopf;": '\U0001D555', - "dot;": '\U000002D9', - "doteq;": '\U00002250', - "doteqdot;": '\U00002251', - "dotminus;": '\U00002238', - "dotplus;": '\U00002214', - "dotsquare;": '\U000022A1', - "doublebarwedge;": '\U00002306', - "downarrow;": '\U00002193', - "downdownarrows;": '\U000021CA', - "downharpoonleft;": '\U000021C3', - "downharpoonright;": '\U000021C2', - "drbkarow;": '\U00002910', - "drcorn;": '\U0000231F', - "drcrop;": '\U0000230C', - "dscr;": '\U0001D4B9', - "dscy;": '\U00000455', - "dsol;": '\U000029F6', - "dstrok;": '\U00000111', - "dtdot;": '\U000022F1', - "dtri;": '\U000025BF', - "dtrif;": '\U000025BE', - "duarr;": '\U000021F5', - "duhar;": '\U0000296F', - "dwangle;": '\U000029A6', - "dzcy;": '\U0000045F', - "dzigrarr;": '\U000027FF', - "eDDot;": '\U00002A77', - "eDot;": '\U00002251', - "eacute;": '\U000000E9', - "easter;": '\U00002A6E', - "ecaron;": '\U0000011B', - "ecir;": '\U00002256', - "ecirc;": '\U000000EA', - "ecolon;": '\U00002255', - "ecy;": '\U0000044D', - "edot;": '\U00000117', - "ee;": '\U00002147', - "efDot;": '\U00002252', - "efr;": '\U0001D522', - "eg;": '\U00002A9A', - "egrave;": '\U000000E8', - "egs;": '\U00002A96', - "egsdot;": '\U00002A98', - "el;": '\U00002A99', - "elinters;": '\U000023E7', - "ell;": '\U00002113', - "els;": '\U00002A95', - "elsdot;": '\U00002A97', - "emacr;": '\U00000113', - "empty;": '\U00002205', - "emptyset;": '\U00002205', - "emptyv;": '\U00002205', - "emsp;": '\U00002003', - "emsp13;": '\U00002004', - "emsp14;": '\U00002005', - "eng;": '\U0000014B', - "ensp;": '\U00002002', - "eogon;": '\U00000119', - "eopf;": '\U0001D556', - "epar;": '\U000022D5', - "eparsl;": '\U000029E3', - "eplus;": '\U00002A71', - "epsi;": '\U000003B5', - "epsilon;": '\U000003B5', - "epsiv;": '\U000003F5', - "eqcirc;": '\U00002256', - "eqcolon;": '\U00002255', - "eqsim;": '\U00002242', - "eqslantgtr;": '\U00002A96', - "eqslantless;": '\U00002A95', - "equals;": '\U0000003D', - "equest;": '\U0000225F', - "equiv;": '\U00002261', - "equivDD;": '\U00002A78', - "eqvparsl;": '\U000029E5', - "erDot;": '\U00002253', - "erarr;": '\U00002971', - "escr;": '\U0000212F', - "esdot;": '\U00002250', - "esim;": '\U00002242', - "eta;": '\U000003B7', - "eth;": '\U000000F0', - "euml;": '\U000000EB', - "euro;": '\U000020AC', - "excl;": '\U00000021', - "exist;": '\U00002203', - "expectation;": '\U00002130', - "exponentiale;": '\U00002147', - "fallingdotseq;": '\U00002252', - "fcy;": '\U00000444', - "female;": '\U00002640', - "ffilig;": '\U0000FB03', - "fflig;": '\U0000FB00', - "ffllig;": '\U0000FB04', - "ffr;": '\U0001D523', - "filig;": '\U0000FB01', - "flat;": '\U0000266D', - "fllig;": '\U0000FB02', - "fltns;": '\U000025B1', - "fnof;": '\U00000192', - "fopf;": '\U0001D557', - "forall;": '\U00002200', - "fork;": '\U000022D4', - "forkv;": '\U00002AD9', - "fpartint;": '\U00002A0D', - "frac12;": '\U000000BD', - "frac13;": '\U00002153', - "frac14;": '\U000000BC', - "frac15;": '\U00002155', - "frac16;": '\U00002159', - "frac18;": '\U0000215B', - "frac23;": '\U00002154', - "frac25;": '\U00002156', - "frac34;": '\U000000BE', - "frac35;": '\U00002157', - "frac38;": '\U0000215C', - "frac45;": '\U00002158', - "frac56;": '\U0000215A', - "frac58;": '\U0000215D', - "frac78;": '\U0000215E', - "frasl;": '\U00002044', - "frown;": '\U00002322', - "fscr;": '\U0001D4BB', - "gE;": '\U00002267', - "gEl;": '\U00002A8C', - "gacute;": '\U000001F5', - "gamma;": '\U000003B3', - "gammad;": '\U000003DD', - "gap;": '\U00002A86', - "gbreve;": '\U0000011F', - "gcirc;": '\U0000011D', - "gcy;": '\U00000433', - "gdot;": '\U00000121', - "ge;": '\U00002265', - "gel;": '\U000022DB', - "geq;": '\U00002265', - "geqq;": '\U00002267', - "geqslant;": '\U00002A7E', - "ges;": '\U00002A7E', - "gescc;": '\U00002AA9', - "gesdot;": '\U00002A80', - "gesdoto;": '\U00002A82', - "gesdotol;": '\U00002A84', - "gesles;": '\U00002A94', - "gfr;": '\U0001D524', - "gg;": '\U0000226B', - "ggg;": '\U000022D9', - "gimel;": '\U00002137', - "gjcy;": '\U00000453', - "gl;": '\U00002277', - "glE;": '\U00002A92', - "gla;": '\U00002AA5', - "glj;": '\U00002AA4', - "gnE;": '\U00002269', - "gnap;": '\U00002A8A', - "gnapprox;": '\U00002A8A', - "gne;": '\U00002A88', - "gneq;": '\U00002A88', - "gneqq;": '\U00002269', - "gnsim;": '\U000022E7', - "gopf;": '\U0001D558', - "grave;": '\U00000060', - "gscr;": '\U0000210A', - "gsim;": '\U00002273', - "gsime;": '\U00002A8E', - "gsiml;": '\U00002A90', - "gt;": '\U0000003E', - "gtcc;": '\U00002AA7', - "gtcir;": '\U00002A7A', - "gtdot;": '\U000022D7', - "gtlPar;": '\U00002995', - "gtquest;": '\U00002A7C', - "gtrapprox;": '\U00002A86', - "gtrarr;": '\U00002978', - "gtrdot;": '\U000022D7', - "gtreqless;": '\U000022DB', - "gtreqqless;": '\U00002A8C', - "gtrless;": '\U00002277', - "gtrsim;": '\U00002273', - "hArr;": '\U000021D4', - "hairsp;": '\U0000200A', - "half;": '\U000000BD', - "hamilt;": '\U0000210B', - "hardcy;": '\U0000044A', - "harr;": '\U00002194', - "harrcir;": '\U00002948', - "harrw;": '\U000021AD', - "hbar;": '\U0000210F', - "hcirc;": '\U00000125', - "hearts;": '\U00002665', - "heartsuit;": '\U00002665', - "hellip;": '\U00002026', - "hercon;": '\U000022B9', - "hfr;": '\U0001D525', - "hksearow;": '\U00002925', - "hkswarow;": '\U00002926', - "hoarr;": '\U000021FF', - "homtht;": '\U0000223B', - "hookleftarrow;": '\U000021A9', - "hookrightarrow;": '\U000021AA', - "hopf;": '\U0001D559', - "horbar;": '\U00002015', - "hscr;": '\U0001D4BD', - "hslash;": '\U0000210F', - "hstrok;": '\U00000127', - "hybull;": '\U00002043', - "hyphen;": '\U00002010', - "iacute;": '\U000000ED', - "ic;": '\U00002063', - "icirc;": '\U000000EE', - "icy;": '\U00000438', - "iecy;": '\U00000435', - "iexcl;": '\U000000A1', - "iff;": '\U000021D4', - "ifr;": '\U0001D526', - "igrave;": '\U000000EC', - "ii;": '\U00002148', - "iiiint;": '\U00002A0C', - "iiint;": '\U0000222D', - "iinfin;": '\U000029DC', - "iiota;": '\U00002129', - "ijlig;": '\U00000133', - "imacr;": '\U0000012B', - "image;": '\U00002111', - "imagline;": '\U00002110', - "imagpart;": '\U00002111', - "imath;": '\U00000131', - "imof;": '\U000022B7', - "imped;": '\U000001B5', - "in;": '\U00002208', - "incare;": '\U00002105', - "infin;": '\U0000221E', - "infintie;": '\U000029DD', - "inodot;": '\U00000131', - "int;": '\U0000222B', - "intcal;": '\U000022BA', - "integers;": '\U00002124', - "intercal;": '\U000022BA', - "intlarhk;": '\U00002A17', - "intprod;": '\U00002A3C', - "iocy;": '\U00000451', - "iogon;": '\U0000012F', - "iopf;": '\U0001D55A', - "iota;": '\U000003B9', - "iprod;": '\U00002A3C', - "iquest;": '\U000000BF', - "iscr;": '\U0001D4BE', - "isin;": '\U00002208', - "isinE;": '\U000022F9', - "isindot;": '\U000022F5', - "isins;": '\U000022F4', - "isinsv;": '\U000022F3', - "isinv;": '\U00002208', - "it;": '\U00002062', - "itilde;": '\U00000129', - "iukcy;": '\U00000456', - "iuml;": '\U000000EF', - "jcirc;": '\U00000135', - "jcy;": '\U00000439', - "jfr;": '\U0001D527', - "jmath;": '\U00000237', - "jopf;": '\U0001D55B', - "jscr;": '\U0001D4BF', - "jsercy;": '\U00000458', - "jukcy;": '\U00000454', - "kappa;": '\U000003BA', - "kappav;": '\U000003F0', - "kcedil;": '\U00000137', - "kcy;": '\U0000043A', - "kfr;": '\U0001D528', - "kgreen;": '\U00000138', - "khcy;": '\U00000445', - "kjcy;": '\U0000045C', - "kopf;": '\U0001D55C', - "kscr;": '\U0001D4C0', - "lAarr;": '\U000021DA', - "lArr;": '\U000021D0', - "lAtail;": '\U0000291B', - "lBarr;": '\U0000290E', - "lE;": '\U00002266', - "lEg;": '\U00002A8B', - "lHar;": '\U00002962', - "lacute;": '\U0000013A', - "laemptyv;": '\U000029B4', - "lagran;": '\U00002112', - "lambda;": '\U000003BB', - "lang;": '\U000027E8', - "langd;": '\U00002991', - "langle;": '\U000027E8', - "lap;": '\U00002A85', - "laquo;": '\U000000AB', - "larr;": '\U00002190', - "larrb;": '\U000021E4', - "larrbfs;": '\U0000291F', - "larrfs;": '\U0000291D', - "larrhk;": '\U000021A9', - "larrlp;": '\U000021AB', - "larrpl;": '\U00002939', - "larrsim;": '\U00002973', - "larrtl;": '\U000021A2', - "lat;": '\U00002AAB', - "latail;": '\U00002919', - "late;": '\U00002AAD', - "lbarr;": '\U0000290C', - "lbbrk;": '\U00002772', - "lbrace;": '\U0000007B', - "lbrack;": '\U0000005B', - "lbrke;": '\U0000298B', - "lbrksld;": '\U0000298F', - "lbrkslu;": '\U0000298D', - "lcaron;": '\U0000013E', - "lcedil;": '\U0000013C', - "lceil;": '\U00002308', - "lcub;": '\U0000007B', - "lcy;": '\U0000043B', - "ldca;": '\U00002936', - "ldquo;": '\U0000201C', - "ldquor;": '\U0000201E', - "ldrdhar;": '\U00002967', - "ldrushar;": '\U0000294B', - "ldsh;": '\U000021B2', - "le;": '\U00002264', - "leftarrow;": '\U00002190', - "leftarrowtail;": '\U000021A2', - "leftharpoondown;": '\U000021BD', - "leftharpoonup;": '\U000021BC', - "leftleftarrows;": '\U000021C7', - "leftrightarrow;": '\U00002194', - "leftrightarrows;": '\U000021C6', - "leftrightharpoons;": '\U000021CB', - "leftrightsquigarrow;": '\U000021AD', - "leftthreetimes;": '\U000022CB', - "leg;": '\U000022DA', - "leq;": '\U00002264', - "leqq;": '\U00002266', - "leqslant;": '\U00002A7D', - "les;": '\U00002A7D', - "lescc;": '\U00002AA8', - "lesdot;": '\U00002A7F', - "lesdoto;": '\U00002A81', - "lesdotor;": '\U00002A83', - "lesges;": '\U00002A93', - "lessapprox;": '\U00002A85', - "lessdot;": '\U000022D6', - "lesseqgtr;": '\U000022DA', - "lesseqqgtr;": '\U00002A8B', - "lessgtr;": '\U00002276', - "lesssim;": '\U00002272', - "lfisht;": '\U0000297C', - "lfloor;": '\U0000230A', - "lfr;": '\U0001D529', - "lg;": '\U00002276', - "lgE;": '\U00002A91', - "lhard;": '\U000021BD', - "lharu;": '\U000021BC', - "lharul;": '\U0000296A', - "lhblk;": '\U00002584', - "ljcy;": '\U00000459', - "ll;": '\U0000226A', - "llarr;": '\U000021C7', - "llcorner;": '\U0000231E', - "llhard;": '\U0000296B', - "lltri;": '\U000025FA', - "lmidot;": '\U00000140', - "lmoust;": '\U000023B0', - "lmoustache;": '\U000023B0', - "lnE;": '\U00002268', - "lnap;": '\U00002A89', - "lnapprox;": '\U00002A89', - "lne;": '\U00002A87', - "lneq;": '\U00002A87', - "lneqq;": '\U00002268', - "lnsim;": '\U000022E6', - "loang;": '\U000027EC', - "loarr;": '\U000021FD', - "lobrk;": '\U000027E6', - "longleftarrow;": '\U000027F5', - "longleftrightarrow;": '\U000027F7', - "longmapsto;": '\U000027FC', - "longrightarrow;": '\U000027F6', - "looparrowleft;": '\U000021AB', - "looparrowright;": '\U000021AC', - "lopar;": '\U00002985', - "lopf;": '\U0001D55D', - "loplus;": '\U00002A2D', - "lotimes;": '\U00002A34', - "lowast;": '\U00002217', - "lowbar;": '\U0000005F', - "loz;": '\U000025CA', - "lozenge;": '\U000025CA', - "lozf;": '\U000029EB', - "lpar;": '\U00000028', - "lparlt;": '\U00002993', - "lrarr;": '\U000021C6', - "lrcorner;": '\U0000231F', - "lrhar;": '\U000021CB', - "lrhard;": '\U0000296D', - "lrm;": '\U0000200E', - "lrtri;": '\U000022BF', - "lsaquo;": '\U00002039', - "lscr;": '\U0001D4C1', - "lsh;": '\U000021B0', - "lsim;": '\U00002272', - "lsime;": '\U00002A8D', - "lsimg;": '\U00002A8F', - "lsqb;": '\U0000005B', - "lsquo;": '\U00002018', - "lsquor;": '\U0000201A', - "lstrok;": '\U00000142', - "lt;": '\U0000003C', - "ltcc;": '\U00002AA6', - "ltcir;": '\U00002A79', - "ltdot;": '\U000022D6', - "lthree;": '\U000022CB', - "ltimes;": '\U000022C9', - "ltlarr;": '\U00002976', - "ltquest;": '\U00002A7B', - "ltrPar;": '\U00002996', - "ltri;": '\U000025C3', - "ltrie;": '\U000022B4', - "ltrif;": '\U000025C2', - "lurdshar;": '\U0000294A', - "luruhar;": '\U00002966', - "mDDot;": '\U0000223A', - "macr;": '\U000000AF', - "male;": '\U00002642', - "malt;": '\U00002720', - "maltese;": '\U00002720', - "map;": '\U000021A6', - "mapsto;": '\U000021A6', - "mapstodown;": '\U000021A7', - "mapstoleft;": '\U000021A4', - "mapstoup;": '\U000021A5', - "marker;": '\U000025AE', - "mcomma;": '\U00002A29', - "mcy;": '\U0000043C', - "mdash;": '\U00002014', - "measuredangle;": '\U00002221', - "mfr;": '\U0001D52A', - "mho;": '\U00002127', - "micro;": '\U000000B5', - "mid;": '\U00002223', - "midast;": '\U0000002A', - "midcir;": '\U00002AF0', - "middot;": '\U000000B7', - "minus;": '\U00002212', - "minusb;": '\U0000229F', - "minusd;": '\U00002238', - "minusdu;": '\U00002A2A', - "mlcp;": '\U00002ADB', - "mldr;": '\U00002026', - "mnplus;": '\U00002213', - "models;": '\U000022A7', - "mopf;": '\U0001D55E', - "mp;": '\U00002213', - "mscr;": '\U0001D4C2', - "mstpos;": '\U0000223E', - "mu;": '\U000003BC', - "multimap;": '\U000022B8', - "mumap;": '\U000022B8', - "nLeftarrow;": '\U000021CD', - "nLeftrightarrow;": '\U000021CE', - "nRightarrow;": '\U000021CF', - "nVDash;": '\U000022AF', - "nVdash;": '\U000022AE', - "nabla;": '\U00002207', - "nacute;": '\U00000144', - "nap;": '\U00002249', - "napos;": '\U00000149', - "napprox;": '\U00002249', - "natur;": '\U0000266E', - "natural;": '\U0000266E', - "naturals;": '\U00002115', - "nbsp;": '\U000000A0', - "ncap;": '\U00002A43', - "ncaron;": '\U00000148', - "ncedil;": '\U00000146', - "ncong;": '\U00002247', - "ncup;": '\U00002A42', - "ncy;": '\U0000043D', - "ndash;": '\U00002013', - "ne;": '\U00002260', - "neArr;": '\U000021D7', - "nearhk;": '\U00002924', - "nearr;": '\U00002197', - "nearrow;": '\U00002197', - "nequiv;": '\U00002262', - "nesear;": '\U00002928', - "nexist;": '\U00002204', - "nexists;": '\U00002204', - "nfr;": '\U0001D52B', - "nge;": '\U00002271', - "ngeq;": '\U00002271', - "ngsim;": '\U00002275', - "ngt;": '\U0000226F', - "ngtr;": '\U0000226F', - "nhArr;": '\U000021CE', - "nharr;": '\U000021AE', - "nhpar;": '\U00002AF2', - "ni;": '\U0000220B', - "nis;": '\U000022FC', - "nisd;": '\U000022FA', - "niv;": '\U0000220B', - "njcy;": '\U0000045A', - "nlArr;": '\U000021CD', - "nlarr;": '\U0000219A', - "nldr;": '\U00002025', - "nle;": '\U00002270', - "nleftarrow;": '\U0000219A', - "nleftrightarrow;": '\U000021AE', - "nleq;": '\U00002270', - "nless;": '\U0000226E', - "nlsim;": '\U00002274', - "nlt;": '\U0000226E', - "nltri;": '\U000022EA', - "nltrie;": '\U000022EC', - "nmid;": '\U00002224', - "nopf;": '\U0001D55F', - "not;": '\U000000AC', - "notin;": '\U00002209', - "notinva;": '\U00002209', - "notinvb;": '\U000022F7', - "notinvc;": '\U000022F6', - "notni;": '\U0000220C', - "notniva;": '\U0000220C', - "notnivb;": '\U000022FE', - "notnivc;": '\U000022FD', - "npar;": '\U00002226', - "nparallel;": '\U00002226', - "npolint;": '\U00002A14', - "npr;": '\U00002280', - "nprcue;": '\U000022E0', - "nprec;": '\U00002280', - "nrArr;": '\U000021CF', - "nrarr;": '\U0000219B', - "nrightarrow;": '\U0000219B', - "nrtri;": '\U000022EB', - "nrtrie;": '\U000022ED', - "nsc;": '\U00002281', - "nsccue;": '\U000022E1', - "nscr;": '\U0001D4C3', - "nshortmid;": '\U00002224', - "nshortparallel;": '\U00002226', - "nsim;": '\U00002241', - "nsime;": '\U00002244', - "nsimeq;": '\U00002244', - "nsmid;": '\U00002224', - "nspar;": '\U00002226', - "nsqsube;": '\U000022E2', - "nsqsupe;": '\U000022E3', - "nsub;": '\U00002284', - "nsube;": '\U00002288', - "nsubseteq;": '\U00002288', - "nsucc;": '\U00002281', - "nsup;": '\U00002285', - "nsupe;": '\U00002289', - "nsupseteq;": '\U00002289', - "ntgl;": '\U00002279', - "ntilde;": '\U000000F1', - "ntlg;": '\U00002278', - "ntriangleleft;": '\U000022EA', - "ntrianglelefteq;": '\U000022EC', - "ntriangleright;": '\U000022EB', - "ntrianglerighteq;": '\U000022ED', - "nu;": '\U000003BD', - "num;": '\U00000023', - "numero;": '\U00002116', - "numsp;": '\U00002007', - "nvDash;": '\U000022AD', - "nvHarr;": '\U00002904', - "nvdash;": '\U000022AC', - "nvinfin;": '\U000029DE', - "nvlArr;": '\U00002902', - "nvrArr;": '\U00002903', - "nwArr;": '\U000021D6', - "nwarhk;": '\U00002923', - "nwarr;": '\U00002196', - "nwarrow;": '\U00002196', - "nwnear;": '\U00002927', - "oS;": '\U000024C8', - "oacute;": '\U000000F3', - "oast;": '\U0000229B', - "ocir;": '\U0000229A', - "ocirc;": '\U000000F4', - "ocy;": '\U0000043E', - "odash;": '\U0000229D', - "odblac;": '\U00000151', - "odiv;": '\U00002A38', - "odot;": '\U00002299', - "odsold;": '\U000029BC', - "oelig;": '\U00000153', - "ofcir;": '\U000029BF', - "ofr;": '\U0001D52C', - "ogon;": '\U000002DB', - "ograve;": '\U000000F2', - "ogt;": '\U000029C1', - "ohbar;": '\U000029B5', - "ohm;": '\U000003A9', - "oint;": '\U0000222E', - "olarr;": '\U000021BA', - "olcir;": '\U000029BE', - "olcross;": '\U000029BB', - "oline;": '\U0000203E', - "olt;": '\U000029C0', - "omacr;": '\U0000014D', - "omega;": '\U000003C9', - "omicron;": '\U000003BF', - "omid;": '\U000029B6', - "ominus;": '\U00002296', - "oopf;": '\U0001D560', - "opar;": '\U000029B7', - "operp;": '\U000029B9', - "oplus;": '\U00002295', - "or;": '\U00002228', - "orarr;": '\U000021BB', - "ord;": '\U00002A5D', - "order;": '\U00002134', - "orderof;": '\U00002134', - "ordf;": '\U000000AA', - "ordm;": '\U000000BA', - "origof;": '\U000022B6', - "oror;": '\U00002A56', - "orslope;": '\U00002A57', - "orv;": '\U00002A5B', - "oscr;": '\U00002134', - "oslash;": '\U000000F8', - "osol;": '\U00002298', - "otilde;": '\U000000F5', - "otimes;": '\U00002297', - "otimesas;": '\U00002A36', - "ouml;": '\U000000F6', - "ovbar;": '\U0000233D', - "par;": '\U00002225', - "para;": '\U000000B6', - "parallel;": '\U00002225', - "parsim;": '\U00002AF3', - "parsl;": '\U00002AFD', - "part;": '\U00002202', - "pcy;": '\U0000043F', - "percnt;": '\U00000025', - "period;": '\U0000002E', - "permil;": '\U00002030', - "perp;": '\U000022A5', - "pertenk;": '\U00002031', - "pfr;": '\U0001D52D', - "phi;": '\U000003C6', - "phiv;": '\U000003D5', - "phmmat;": '\U00002133', - "phone;": '\U0000260E', - "pi;": '\U000003C0', - "pitchfork;": '\U000022D4', - "piv;": '\U000003D6', - "planck;": '\U0000210F', - "planckh;": '\U0000210E', - "plankv;": '\U0000210F', - "plus;": '\U0000002B', - "plusacir;": '\U00002A23', - "plusb;": '\U0000229E', - "pluscir;": '\U00002A22', - "plusdo;": '\U00002214', - "plusdu;": '\U00002A25', - "pluse;": '\U00002A72', - "plusmn;": '\U000000B1', - "plussim;": '\U00002A26', - "plustwo;": '\U00002A27', - "pm;": '\U000000B1', - "pointint;": '\U00002A15', - "popf;": '\U0001D561', - "pound;": '\U000000A3', - "pr;": '\U0000227A', - "prE;": '\U00002AB3', - "prap;": '\U00002AB7', - "prcue;": '\U0000227C', - "pre;": '\U00002AAF', - "prec;": '\U0000227A', - "precapprox;": '\U00002AB7', - "preccurlyeq;": '\U0000227C', - "preceq;": '\U00002AAF', - "precnapprox;": '\U00002AB9', - "precneqq;": '\U00002AB5', - "precnsim;": '\U000022E8', - "precsim;": '\U0000227E', - "prime;": '\U00002032', - "primes;": '\U00002119', - "prnE;": '\U00002AB5', - "prnap;": '\U00002AB9', - "prnsim;": '\U000022E8', - "prod;": '\U0000220F', - "profalar;": '\U0000232E', - "profline;": '\U00002312', - "profsurf;": '\U00002313', - "prop;": '\U0000221D', - "propto;": '\U0000221D', - "prsim;": '\U0000227E', - "prurel;": '\U000022B0', - "pscr;": '\U0001D4C5', - "psi;": '\U000003C8', - "puncsp;": '\U00002008', - "qfr;": '\U0001D52E', - "qint;": '\U00002A0C', - "qopf;": '\U0001D562', - "qprime;": '\U00002057', - "qscr;": '\U0001D4C6', - "quaternions;": '\U0000210D', - "quatint;": '\U00002A16', - "quest;": '\U0000003F', - "questeq;": '\U0000225F', - "quot;": '\U00000022', - "rAarr;": '\U000021DB', - "rArr;": '\U000021D2', - "rAtail;": '\U0000291C', - "rBarr;": '\U0000290F', - "rHar;": '\U00002964', - "racute;": '\U00000155', - "radic;": '\U0000221A', - "raemptyv;": '\U000029B3', - "rang;": '\U000027E9', - "rangd;": '\U00002992', - "range;": '\U000029A5', - "rangle;": '\U000027E9', - "raquo;": '\U000000BB', - "rarr;": '\U00002192', - "rarrap;": '\U00002975', - "rarrb;": '\U000021E5', - "rarrbfs;": '\U00002920', - "rarrc;": '\U00002933', - "rarrfs;": '\U0000291E', - "rarrhk;": '\U000021AA', - "rarrlp;": '\U000021AC', - "rarrpl;": '\U00002945', - "rarrsim;": '\U00002974', - "rarrtl;": '\U000021A3', - "rarrw;": '\U0000219D', - "ratail;": '\U0000291A', - "ratio;": '\U00002236', - "rationals;": '\U0000211A', - "rbarr;": '\U0000290D', - "rbbrk;": '\U00002773', - "rbrace;": '\U0000007D', - "rbrack;": '\U0000005D', - "rbrke;": '\U0000298C', - "rbrksld;": '\U0000298E', - "rbrkslu;": '\U00002990', - "rcaron;": '\U00000159', - "rcedil;": '\U00000157', - "rceil;": '\U00002309', - "rcub;": '\U0000007D', - "rcy;": '\U00000440', - "rdca;": '\U00002937', - "rdldhar;": '\U00002969', - "rdquo;": '\U0000201D', - "rdquor;": '\U0000201D', - "rdsh;": '\U000021B3', - "real;": '\U0000211C', - "realine;": '\U0000211B', - "realpart;": '\U0000211C', - "reals;": '\U0000211D', - "rect;": '\U000025AD', - "reg;": '\U000000AE', - "rfisht;": '\U0000297D', - "rfloor;": '\U0000230B', - "rfr;": '\U0001D52F', - "rhard;": '\U000021C1', - "rharu;": '\U000021C0', - "rharul;": '\U0000296C', - "rho;": '\U000003C1', - "rhov;": '\U000003F1', - "rightarrow;": '\U00002192', - "rightarrowtail;": '\U000021A3', - "rightharpoondown;": '\U000021C1', - "rightharpoonup;": '\U000021C0', - "rightleftarrows;": '\U000021C4', - "rightleftharpoons;": '\U000021CC', - "rightrightarrows;": '\U000021C9', - "rightsquigarrow;": '\U0000219D', - "rightthreetimes;": '\U000022CC', - "ring;": '\U000002DA', - "risingdotseq;": '\U00002253', - "rlarr;": '\U000021C4', - "rlhar;": '\U000021CC', - "rlm;": '\U0000200F', - "rmoust;": '\U000023B1', - "rmoustache;": '\U000023B1', - "rnmid;": '\U00002AEE', - "roang;": '\U000027ED', - "roarr;": '\U000021FE', - "robrk;": '\U000027E7', - "ropar;": '\U00002986', - "ropf;": '\U0001D563', - "roplus;": '\U00002A2E', - "rotimes;": '\U00002A35', - "rpar;": '\U00000029', - "rpargt;": '\U00002994', - "rppolint;": '\U00002A12', - "rrarr;": '\U000021C9', - "rsaquo;": '\U0000203A', - "rscr;": '\U0001D4C7', - "rsh;": '\U000021B1', - "rsqb;": '\U0000005D', - "rsquo;": '\U00002019', - "rsquor;": '\U00002019', - "rthree;": '\U000022CC', - "rtimes;": '\U000022CA', - "rtri;": '\U000025B9', - "rtrie;": '\U000022B5', - "rtrif;": '\U000025B8', - "rtriltri;": '\U000029CE', - "ruluhar;": '\U00002968', - "rx;": '\U0000211E', - "sacute;": '\U0000015B', - "sbquo;": '\U0000201A', - "sc;": '\U0000227B', - "scE;": '\U00002AB4', - "scap;": '\U00002AB8', - "scaron;": '\U00000161', - "sccue;": '\U0000227D', - "sce;": '\U00002AB0', - "scedil;": '\U0000015F', - "scirc;": '\U0000015D', - "scnE;": '\U00002AB6', - "scnap;": '\U00002ABA', - "scnsim;": '\U000022E9', - "scpolint;": '\U00002A13', - "scsim;": '\U0000227F', - "scy;": '\U00000441', - "sdot;": '\U000022C5', - "sdotb;": '\U000022A1', - "sdote;": '\U00002A66', - "seArr;": '\U000021D8', - "searhk;": '\U00002925', - "searr;": '\U00002198', - "searrow;": '\U00002198', - "sect;": '\U000000A7', - "semi;": '\U0000003B', - "seswar;": '\U00002929', - "setminus;": '\U00002216', - "setmn;": '\U00002216', - "sext;": '\U00002736', - "sfr;": '\U0001D530', - "sfrown;": '\U00002322', - "sharp;": '\U0000266F', - "shchcy;": '\U00000449', - "shcy;": '\U00000448', - "shortmid;": '\U00002223', - "shortparallel;": '\U00002225', - "shy;": '\U000000AD', - "sigma;": '\U000003C3', - "sigmaf;": '\U000003C2', - "sigmav;": '\U000003C2', - "sim;": '\U0000223C', - "simdot;": '\U00002A6A', - "sime;": '\U00002243', - "simeq;": '\U00002243', - "simg;": '\U00002A9E', - "simgE;": '\U00002AA0', - "siml;": '\U00002A9D', - "simlE;": '\U00002A9F', - "simne;": '\U00002246', - "simplus;": '\U00002A24', - "simrarr;": '\U00002972', - "slarr;": '\U00002190', - "smallsetminus;": '\U00002216', - "smashp;": '\U00002A33', - "smeparsl;": '\U000029E4', - "smid;": '\U00002223', - "smile;": '\U00002323', - "smt;": '\U00002AAA', - "smte;": '\U00002AAC', - "softcy;": '\U0000044C', - "sol;": '\U0000002F', - "solb;": '\U000029C4', - "solbar;": '\U0000233F', - "sopf;": '\U0001D564', - "spades;": '\U00002660', - "spadesuit;": '\U00002660', - "spar;": '\U00002225', - "sqcap;": '\U00002293', - "sqcup;": '\U00002294', - "sqsub;": '\U0000228F', - "sqsube;": '\U00002291', - "sqsubset;": '\U0000228F', - "sqsubseteq;": '\U00002291', - "sqsup;": '\U00002290', - "sqsupe;": '\U00002292', - "sqsupset;": '\U00002290', - "sqsupseteq;": '\U00002292', - "squ;": '\U000025A1', - "square;": '\U000025A1', - "squarf;": '\U000025AA', - "squf;": '\U000025AA', - "srarr;": '\U00002192', - "sscr;": '\U0001D4C8', - "ssetmn;": '\U00002216', - "ssmile;": '\U00002323', - "sstarf;": '\U000022C6', - "star;": '\U00002606', - "starf;": '\U00002605', - "straightepsilon;": '\U000003F5', - "straightphi;": '\U000003D5', - "strns;": '\U000000AF', - "sub;": '\U00002282', - "subE;": '\U00002AC5', - "subdot;": '\U00002ABD', - "sube;": '\U00002286', - "subedot;": '\U00002AC3', - "submult;": '\U00002AC1', - "subnE;": '\U00002ACB', - "subne;": '\U0000228A', - "subplus;": '\U00002ABF', - "subrarr;": '\U00002979', - "subset;": '\U00002282', - "subseteq;": '\U00002286', - "subseteqq;": '\U00002AC5', - "subsetneq;": '\U0000228A', - "subsetneqq;": '\U00002ACB', - "subsim;": '\U00002AC7', - "subsub;": '\U00002AD5', - "subsup;": '\U00002AD3', - "succ;": '\U0000227B', - "succapprox;": '\U00002AB8', - "succcurlyeq;": '\U0000227D', - "succeq;": '\U00002AB0', - "succnapprox;": '\U00002ABA', - "succneqq;": '\U00002AB6', - "succnsim;": '\U000022E9', - "succsim;": '\U0000227F', - "sum;": '\U00002211', - "sung;": '\U0000266A', - "sup;": '\U00002283', - "sup1;": '\U000000B9', - "sup2;": '\U000000B2', - "sup3;": '\U000000B3', - "supE;": '\U00002AC6', - "supdot;": '\U00002ABE', - "supdsub;": '\U00002AD8', - "supe;": '\U00002287', - "supedot;": '\U00002AC4', - "suphsol;": '\U000027C9', - "suphsub;": '\U00002AD7', - "suplarr;": '\U0000297B', - "supmult;": '\U00002AC2', - "supnE;": '\U00002ACC', - "supne;": '\U0000228B', - "supplus;": '\U00002AC0', - "supset;": '\U00002283', - "supseteq;": '\U00002287', - "supseteqq;": '\U00002AC6', - "supsetneq;": '\U0000228B', - "supsetneqq;": '\U00002ACC', - "supsim;": '\U00002AC8', - "supsub;": '\U00002AD4', - "supsup;": '\U00002AD6', - "swArr;": '\U000021D9', - "swarhk;": '\U00002926', - "swarr;": '\U00002199', - "swarrow;": '\U00002199', - "swnwar;": '\U0000292A', - "szlig;": '\U000000DF', - "target;": '\U00002316', - "tau;": '\U000003C4', - "tbrk;": '\U000023B4', - "tcaron;": '\U00000165', - "tcedil;": '\U00000163', - "tcy;": '\U00000442', - "tdot;": '\U000020DB', - "telrec;": '\U00002315', - "tfr;": '\U0001D531', - "there4;": '\U00002234', - "therefore;": '\U00002234', - "theta;": '\U000003B8', - "thetasym;": '\U000003D1', - "thetav;": '\U000003D1', - "thickapprox;": '\U00002248', - "thicksim;": '\U0000223C', - "thinsp;": '\U00002009', - "thkap;": '\U00002248', - "thksim;": '\U0000223C', - "thorn;": '\U000000FE', - "tilde;": '\U000002DC', - "times;": '\U000000D7', - "timesb;": '\U000022A0', - "timesbar;": '\U00002A31', - "timesd;": '\U00002A30', - "tint;": '\U0000222D', - "toea;": '\U00002928', - "top;": '\U000022A4', - "topbot;": '\U00002336', - "topcir;": '\U00002AF1', - "topf;": '\U0001D565', - "topfork;": '\U00002ADA', - "tosa;": '\U00002929', - "tprime;": '\U00002034', - "trade;": '\U00002122', - "triangle;": '\U000025B5', - "triangledown;": '\U000025BF', - "triangleleft;": '\U000025C3', - "trianglelefteq;": '\U000022B4', - "triangleq;": '\U0000225C', - "triangleright;": '\U000025B9', - "trianglerighteq;": '\U000022B5', - "tridot;": '\U000025EC', - "trie;": '\U0000225C', - "triminus;": '\U00002A3A', - "triplus;": '\U00002A39', - "trisb;": '\U000029CD', - "tritime;": '\U00002A3B', - "trpezium;": '\U000023E2', - "tscr;": '\U0001D4C9', - "tscy;": '\U00000446', - "tshcy;": '\U0000045B', - "tstrok;": '\U00000167', - "twixt;": '\U0000226C', - "twoheadleftarrow;": '\U0000219E', - "twoheadrightarrow;": '\U000021A0', - "uArr;": '\U000021D1', - "uHar;": '\U00002963', - "uacute;": '\U000000FA', - "uarr;": '\U00002191', - "ubrcy;": '\U0000045E', - "ubreve;": '\U0000016D', - "ucirc;": '\U000000FB', - "ucy;": '\U00000443', - "udarr;": '\U000021C5', - "udblac;": '\U00000171', - "udhar;": '\U0000296E', - "ufisht;": '\U0000297E', - "ufr;": '\U0001D532', - "ugrave;": '\U000000F9', - "uharl;": '\U000021BF', - "uharr;": '\U000021BE', - "uhblk;": '\U00002580', - "ulcorn;": '\U0000231C', - "ulcorner;": '\U0000231C', - "ulcrop;": '\U0000230F', - "ultri;": '\U000025F8', - "umacr;": '\U0000016B', - "uml;": '\U000000A8', - "uogon;": '\U00000173', - "uopf;": '\U0001D566', - "uparrow;": '\U00002191', - "updownarrow;": '\U00002195', - "upharpoonleft;": '\U000021BF', - "upharpoonright;": '\U000021BE', - "uplus;": '\U0000228E', - "upsi;": '\U000003C5', - "upsih;": '\U000003D2', - "upsilon;": '\U000003C5', - "upuparrows;": '\U000021C8', - "urcorn;": '\U0000231D', - "urcorner;": '\U0000231D', - "urcrop;": '\U0000230E', - "uring;": '\U0000016F', - "urtri;": '\U000025F9', - "uscr;": '\U0001D4CA', - "utdot;": '\U000022F0', - "utilde;": '\U00000169', - "utri;": '\U000025B5', - "utrif;": '\U000025B4', - "uuarr;": '\U000021C8', - "uuml;": '\U000000FC', - "uwangle;": '\U000029A7', - "vArr;": '\U000021D5', - "vBar;": '\U00002AE8', - "vBarv;": '\U00002AE9', - "vDash;": '\U000022A8', - "vangrt;": '\U0000299C', - "varepsilon;": '\U000003F5', - "varkappa;": '\U000003F0', - "varnothing;": '\U00002205', - "varphi;": '\U000003D5', - "varpi;": '\U000003D6', - "varpropto;": '\U0000221D', - "varr;": '\U00002195', - "varrho;": '\U000003F1', - "varsigma;": '\U000003C2', - "vartheta;": '\U000003D1', - "vartriangleleft;": '\U000022B2', - "vartriangleright;": '\U000022B3', - "vcy;": '\U00000432', - "vdash;": '\U000022A2', - "vee;": '\U00002228', - "veebar;": '\U000022BB', - "veeeq;": '\U0000225A', - "vellip;": '\U000022EE', - "verbar;": '\U0000007C', - "vert;": '\U0000007C', - "vfr;": '\U0001D533', - "vltri;": '\U000022B2', - "vopf;": '\U0001D567', - "vprop;": '\U0000221D', - "vrtri;": '\U000022B3', - "vscr;": '\U0001D4CB', - "vzigzag;": '\U0000299A', - "wcirc;": '\U00000175', - "wedbar;": '\U00002A5F', - "wedge;": '\U00002227', - "wedgeq;": '\U00002259', - "weierp;": '\U00002118', - "wfr;": '\U0001D534', - "wopf;": '\U0001D568', - "wp;": '\U00002118', - "wr;": '\U00002240', - "wreath;": '\U00002240', - "wscr;": '\U0001D4CC', - "xcap;": '\U000022C2', - "xcirc;": '\U000025EF', - "xcup;": '\U000022C3', - "xdtri;": '\U000025BD', - "xfr;": '\U0001D535', - "xhArr;": '\U000027FA', - "xharr;": '\U000027F7', - "xi;": '\U000003BE', - "xlArr;": '\U000027F8', - "xlarr;": '\U000027F5', - "xmap;": '\U000027FC', - "xnis;": '\U000022FB', - "xodot;": '\U00002A00', - "xopf;": '\U0001D569', - "xoplus;": '\U00002A01', - "xotime;": '\U00002A02', - "xrArr;": '\U000027F9', - "xrarr;": '\U000027F6', - "xscr;": '\U0001D4CD', - "xsqcup;": '\U00002A06', - "xuplus;": '\U00002A04', - "xutri;": '\U000025B3', - "xvee;": '\U000022C1', - "xwedge;": '\U000022C0', - "yacute;": '\U000000FD', - "yacy;": '\U0000044F', - "ycirc;": '\U00000177', - "ycy;": '\U0000044B', - "yen;": '\U000000A5', - "yfr;": '\U0001D536', - "yicy;": '\U00000457', - "yopf;": '\U0001D56A', - "yscr;": '\U0001D4CE', - "yucy;": '\U0000044E', - "yuml;": '\U000000FF', - "zacute;": '\U0000017A', - "zcaron;": '\U0000017E', - "zcy;": '\U00000437', - "zdot;": '\U0000017C', - "zeetrf;": '\U00002128', - "zeta;": '\U000003B6', - "zfr;": '\U0001D537', - "zhcy;": '\U00000436', - "zigrarr;": '\U000021DD', - "zopf;": '\U0001D56B', - "zscr;": '\U0001D4CF', - "zwj;": '\U0000200D', - "zwnj;": '\U0000200C', - "AElig": '\U000000C6', - "AMP": '\U00000026', - "Aacute": '\U000000C1', - "Acirc": '\U000000C2', - "Agrave": '\U000000C0', - "Aring": '\U000000C5', - "Atilde": '\U000000C3', - "Auml": '\U000000C4', - "COPY": '\U000000A9', - "Ccedil": '\U000000C7', - "ETH": '\U000000D0', - "Eacute": '\U000000C9', - "Ecirc": '\U000000CA', - "Egrave": '\U000000C8', - "Euml": '\U000000CB', - "GT": '\U0000003E', - "Iacute": '\U000000CD', - "Icirc": '\U000000CE', - "Igrave": '\U000000CC', - "Iuml": '\U000000CF', - "LT": '\U0000003C', - "Ntilde": '\U000000D1', - "Oacute": '\U000000D3', - "Ocirc": '\U000000D4', - "Ograve": '\U000000D2', - "Oslash": '\U000000D8', - "Otilde": '\U000000D5', - "Ouml": '\U000000D6', - "QUOT": '\U00000022', - "REG": '\U000000AE', - "THORN": '\U000000DE', - "Uacute": '\U000000DA', - "Ucirc": '\U000000DB', - "Ugrave": '\U000000D9', - "Uuml": '\U000000DC', - "Yacute": '\U000000DD', - "aacute": '\U000000E1', - "acirc": '\U000000E2', - "acute": '\U000000B4', - "aelig": '\U000000E6', - "agrave": '\U000000E0', - "amp": '\U00000026', - "aring": '\U000000E5', - "atilde": '\U000000E3', - "auml": '\U000000E4', - "brvbar": '\U000000A6', - "ccedil": '\U000000E7', - "cedil": '\U000000B8', - "cent": '\U000000A2', - "copy": '\U000000A9', - "curren": '\U000000A4', - "deg": '\U000000B0', - "divide": '\U000000F7', - "eacute": '\U000000E9', - "ecirc": '\U000000EA', - "egrave": '\U000000E8', - "eth": '\U000000F0', - "euml": '\U000000EB', - "frac12": '\U000000BD', - "frac14": '\U000000BC', - "frac34": '\U000000BE', - "gt": '\U0000003E', - "iacute": '\U000000ED', - "icirc": '\U000000EE', - "iexcl": '\U000000A1', - "igrave": '\U000000EC', - "iquest": '\U000000BF', - "iuml": '\U000000EF', - "laquo": '\U000000AB', - "lt": '\U0000003C', - "macr": '\U000000AF', - "micro": '\U000000B5', - "middot": '\U000000B7', - "nbsp": '\U000000A0', - "not": '\U000000AC', - "ntilde": '\U000000F1', - "oacute": '\U000000F3', - "ocirc": '\U000000F4', - "ograve": '\U000000F2', - "ordf": '\U000000AA', - "ordm": '\U000000BA', - "oslash": '\U000000F8', - "otilde": '\U000000F5', - "ouml": '\U000000F6', - "para": '\U000000B6', - "plusmn": '\U000000B1', - "pound": '\U000000A3', - "quot": '\U00000022', - "raquo": '\U000000BB', - "reg": '\U000000AE', - "sect": '\U000000A7', - "shy": '\U000000AD', - "sup1": '\U000000B9', - "sup2": '\U000000B2', - "sup3": '\U000000B3', - "szlig": '\U000000DF', - "thorn": '\U000000FE', - "times": '\U000000D7', - "uacute": '\U000000FA', - "ucirc": '\U000000FB', - "ugrave": '\U000000F9', - "uml": '\U000000A8', - "uuml": '\U000000FC', - "yacute": '\U000000FD', - "yen": '\U000000A5', - "yuml": '\U000000FF', -} - -// HTML entities that are two unicode codepoints. -var entity2 = map[string][2]rune{ - // TODO(nigeltao): Handle replacements that are wider than their names. - // "nLt;": {'\u226A', '\u20D2'}, - // "nGt;": {'\u226B', '\u20D2'}, - "NotEqualTilde;": {'\u2242', '\u0338'}, - "NotGreaterFullEqual;": {'\u2267', '\u0338'}, - "NotGreaterGreater;": {'\u226B', '\u0338'}, - "NotGreaterSlantEqual;": {'\u2A7E', '\u0338'}, - "NotHumpDownHump;": {'\u224E', '\u0338'}, - "NotHumpEqual;": {'\u224F', '\u0338'}, - "NotLeftTriangleBar;": {'\u29CF', '\u0338'}, - "NotLessLess;": {'\u226A', '\u0338'}, - "NotLessSlantEqual;": {'\u2A7D', '\u0338'}, - "NotNestedGreaterGreater;": {'\u2AA2', '\u0338'}, - "NotNestedLessLess;": {'\u2AA1', '\u0338'}, - "NotPrecedesEqual;": {'\u2AAF', '\u0338'}, - "NotRightTriangleBar;": {'\u29D0', '\u0338'}, - "NotSquareSubset;": {'\u228F', '\u0338'}, - "NotSquareSuperset;": {'\u2290', '\u0338'}, - "NotSubset;": {'\u2282', '\u20D2'}, - "NotSucceedsEqual;": {'\u2AB0', '\u0338'}, - "NotSucceedsTilde;": {'\u227F', '\u0338'}, - "NotSuperset;": {'\u2283', '\u20D2'}, - "ThickSpace;": {'\u205F', '\u200A'}, - "acE;": {'\u223E', '\u0333'}, - "bne;": {'\u003D', '\u20E5'}, - "bnequiv;": {'\u2261', '\u20E5'}, - "caps;": {'\u2229', '\uFE00'}, - "cups;": {'\u222A', '\uFE00'}, - "fjlig;": {'\u0066', '\u006A'}, - "gesl;": {'\u22DB', '\uFE00'}, - "gvertneqq;": {'\u2269', '\uFE00'}, - "gvnE;": {'\u2269', '\uFE00'}, - "lates;": {'\u2AAD', '\uFE00'}, - "lesg;": {'\u22DA', '\uFE00'}, - "lvertneqq;": {'\u2268', '\uFE00'}, - "lvnE;": {'\u2268', '\uFE00'}, - "nGg;": {'\u22D9', '\u0338'}, - "nGtv;": {'\u226B', '\u0338'}, - "nLl;": {'\u22D8', '\u0338'}, - "nLtv;": {'\u226A', '\u0338'}, - "nang;": {'\u2220', '\u20D2'}, - "napE;": {'\u2A70', '\u0338'}, - "napid;": {'\u224B', '\u0338'}, - "nbump;": {'\u224E', '\u0338'}, - "nbumpe;": {'\u224F', '\u0338'}, - "ncongdot;": {'\u2A6D', '\u0338'}, - "nedot;": {'\u2250', '\u0338'}, - "nesim;": {'\u2242', '\u0338'}, - "ngE;": {'\u2267', '\u0338'}, - "ngeqq;": {'\u2267', '\u0338'}, - "ngeqslant;": {'\u2A7E', '\u0338'}, - "nges;": {'\u2A7E', '\u0338'}, - "nlE;": {'\u2266', '\u0338'}, - "nleqq;": {'\u2266', '\u0338'}, - "nleqslant;": {'\u2A7D', '\u0338'}, - "nles;": {'\u2A7D', '\u0338'}, - "notinE;": {'\u22F9', '\u0338'}, - "notindot;": {'\u22F5', '\u0338'}, - "nparsl;": {'\u2AFD', '\u20E5'}, - "npart;": {'\u2202', '\u0338'}, - "npre;": {'\u2AAF', '\u0338'}, - "npreceq;": {'\u2AAF', '\u0338'}, - "nrarrc;": {'\u2933', '\u0338'}, - "nrarrw;": {'\u219D', '\u0338'}, - "nsce;": {'\u2AB0', '\u0338'}, - "nsubE;": {'\u2AC5', '\u0338'}, - "nsubset;": {'\u2282', '\u20D2'}, - "nsubseteqq;": {'\u2AC5', '\u0338'}, - "nsucceq;": {'\u2AB0', '\u0338'}, - "nsupE;": {'\u2AC6', '\u0338'}, - "nsupset;": {'\u2283', '\u20D2'}, - "nsupseteqq;": {'\u2AC6', '\u0338'}, - "nvap;": {'\u224D', '\u20D2'}, - "nvge;": {'\u2265', '\u20D2'}, - "nvgt;": {'\u003E', '\u20D2'}, - "nvle;": {'\u2264', '\u20D2'}, - "nvlt;": {'\u003C', '\u20D2'}, - "nvltrie;": {'\u22B4', '\u20D2'}, - "nvrtrie;": {'\u22B5', '\u20D2'}, - "nvsim;": {'\u223C', '\u20D2'}, - "race;": {'\u223D', '\u0331'}, - "smtes;": {'\u2AAC', '\uFE00'}, - "sqcaps;": {'\u2293', '\uFE00'}, - "sqcups;": {'\u2294', '\uFE00'}, - "varsubsetneq;": {'\u228A', '\uFE00'}, - "varsubsetneqq;": {'\u2ACB', '\uFE00'}, - "varsupsetneq;": {'\u228B', '\uFE00'}, - "varsupsetneqq;": {'\u2ACC', '\uFE00'}, - "vnsub;": {'\u2282', '\u20D2'}, - "vnsup;": {'\u2283', '\u20D2'}, - "vsubnE;": {'\u2ACB', '\uFE00'}, - "vsubne;": {'\u228A', '\uFE00'}, - "vsupnE;": {'\u2ACC', '\uFE00'}, - "vsupne;": {'\u228B', '\uFE00'}, -} diff --git a/vendor/golang.org/x/net/html/escape.go b/vendor/golang.org/x/net/html/escape.go deleted file mode 100644 index 04c6bec..0000000 --- a/vendor/golang.org/x/net/html/escape.go +++ /dev/null @@ -1,339 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -import ( - "bytes" - "strings" - "unicode/utf8" -) - -// These replacements permit compatibility with old numeric entities that -// assumed Windows-1252 encoding. -// https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference -var replacementTable = [...]rune{ - '\u20AC', // First entry is what 0x80 should be replaced with. - '\u0081', - '\u201A', - '\u0192', - '\u201E', - '\u2026', - '\u2020', - '\u2021', - '\u02C6', - '\u2030', - '\u0160', - '\u2039', - '\u0152', - '\u008D', - '\u017D', - '\u008F', - '\u0090', - '\u2018', - '\u2019', - '\u201C', - '\u201D', - '\u2022', - '\u2013', - '\u2014', - '\u02DC', - '\u2122', - '\u0161', - '\u203A', - '\u0153', - '\u009D', - '\u017E', - '\u0178', // Last entry is 0x9F. - // 0x00->'\uFFFD' is handled programmatically. - // 0x0D->'\u000D' is a no-op. -} - -// unescapeEntity reads an entity like "<" from b[src:] and writes the -// corresponding "<" to b[dst:], returning the incremented dst and src cursors. -// Precondition: b[src] == '&' && dst <= src. -// attribute should be true if parsing an attribute value. -func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { - // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference - - // i starts at 1 because we already know that s[0] == '&'. - i, s := 1, b[src:] - - if len(s) <= 1 { - b[dst] = b[src] - return dst + 1, src + 1 - } - - if s[i] == '#' { - if len(s) <= 3 { // We need to have at least "&#.". - b[dst] = b[src] - return dst + 1, src + 1 - } - i++ - c := s[i] - hex := false - if c == 'x' || c == 'X' { - hex = true - i++ - } - - x := '\x00' - for i < len(s) { - c = s[i] - i++ - if hex { - if '0' <= c && c <= '9' { - x = 16*x + rune(c) - '0' - continue - } else if 'a' <= c && c <= 'f' { - x = 16*x + rune(c) - 'a' + 10 - continue - } else if 'A' <= c && c <= 'F' { - x = 16*x + rune(c) - 'A' + 10 - continue - } - } else if '0' <= c && c <= '9' { - x = 10*x + rune(c) - '0' - continue - } - if c != ';' { - i-- - } - break - } - - if i <= 3 { // No characters matched. - b[dst] = b[src] - return dst + 1, src + 1 - } - - if 0x80 <= x && x <= 0x9F { - // Replace characters from Windows-1252 with UTF-8 equivalents. - x = replacementTable[x-0x80] - } else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF { - // Replace invalid characters with the replacement character. - x = '\uFFFD' - } - - return dst + utf8.EncodeRune(b[dst:], x), src + i - } - - // Consume the maximum number of characters possible, with the - // consumed characters matching one of the named references. - - for i < len(s) { - c := s[i] - i++ - // Lower-cased characters are more common in entities, so we check for them first. - if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { - continue - } - if c != ';' { - i-- - } - break - } - - entityName := string(s[1:i]) - if entityName == "" { - // No-op. - } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' { - // No-op. - } else if x := entity[entityName]; x != 0 { - return dst + utf8.EncodeRune(b[dst:], x), src + i - } else if x := entity2[entityName]; x[0] != 0 { - dst1 := dst + utf8.EncodeRune(b[dst:], x[0]) - return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i - } else if !attribute { - maxLen := len(entityName) - 1 - if maxLen > longestEntityWithoutSemicolon { - maxLen = longestEntityWithoutSemicolon - } - for j := maxLen; j > 1; j-- { - if x := entity[entityName[:j]]; x != 0 { - return dst + utf8.EncodeRune(b[dst:], x), src + j + 1 - } - } - } - - dst1, src1 = dst+i, src+i - copy(b[dst:dst1], b[src:src1]) - return dst1, src1 -} - -// unescape unescapes b's entities in-place, so that "a<b" becomes "a' byte that, per above, we'd like to avoid escaping unless we have to. -// -// Studying the summary table (and T actions in its '>' column) closely, we -// only need to escape in states 43, 44, 49, 51 and 52. State 43 is at the -// start of the comment data. State 52 is after a '!'. The other three states -// are after a '-'. -// -// Our algorithm is thus to escape every '&' and to escape '>' if and only if: -// - The '>' is after a '!' or '-' (in the unescaped data) or -// - The '>' is at the start of the comment data (after the opening ""); err != nil { - return err - } - return nil - case DoctypeNode: - if _, err := w.WriteString("') - case RawNode: - _, err := w.WriteString(n.Data) - return err - default: - return errors.New("html: unknown node type") - } - - // Render the opening tag. - if err := w.WriteByte('<'); err != nil { - return err - } - if _, err := w.WriteString(n.Data); err != nil { - return err - } - for _, a := range n.Attr { - if err := w.WriteByte(' '); err != nil { - return err - } - if a.Namespace != "" { - if _, err := w.WriteString(a.Namespace); err != nil { - return err - } - if err := w.WriteByte(':'); err != nil { - return err - } - } - if _, err := w.WriteString(a.Key); err != nil { - return err - } - if _, err := w.WriteString(`="`); err != nil { - return err - } - if err := escape(w, a.Val); err != nil { - return err - } - if err := w.WriteByte('"'); err != nil { - return err - } - } - if voidElements[n.Data] { - if n.FirstChild != nil { - return fmt.Errorf("html: void element <%s> has child nodes", n.Data) - } - _, err := w.WriteString("/>") - return err - } - if err := w.WriteByte('>'); err != nil { - return err - } - - // Add initial newline where there is danger of a newline beging ignored. - if c := n.FirstChild; c != nil && c.Type == TextNode && strings.HasPrefix(c.Data, "\n") { - switch n.Data { - case "pre", "listing", "textarea": - if err := w.WriteByte('\n'); err != nil { - return err - } - } - } - - // Render any child nodes - if childTextNodesAreLiteral(n) { - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == TextNode { - if _, err := w.WriteString(c.Data); err != nil { - return err - } - } else { - if err := render1(w, c); err != nil { - return err - } - } - } - if n.Data == "plaintext" { - // Don't render anything else. must be the - // last element in the file, with no closing tag. - return plaintextAbort - } - } else { - for c := n.FirstChild; c != nil; c = c.NextSibling { - if err := render1(w, c); err != nil { - return err - } - } - } - - // Render the </xxx> closing tag. - if _, err := w.WriteString("</"); err != nil { - return err - } - if _, err := w.WriteString(n.Data); err != nil { - return err - } - return w.WriteByte('>') -} - -func childTextNodesAreLiteral(n *Node) bool { - // Per WHATWG HTML 13.3, if the parent of the current node is a style, - // script, xmp, iframe, noembed, noframes, or plaintext element, and the - // current node is a text node, append the value of the node's data - // literally. The specification is not explicit about it, but we only - // enforce this if we are in the HTML namespace (i.e. when the namespace is - // ""). - // NOTE: we also always include noscript elements, although the - // specification states that they should only be rendered as such if - // scripting is enabled for the node (which is not something we track). - if n.Namespace != "" { - return false - } - switch n.Data { - case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "xmp": - return true - default: - return false - } -} - -// writeQuoted writes s to w surrounded by quotes. Normally it will use double -// quotes, but if s contains a double quote, it will use single quotes. -// It is used for writing the identifiers in a doctype declaration. -// In valid HTML, they can't contain both types of quotes. -func writeQuoted(w writer, s string) error { - var q byte = '"' - if strings.Contains(s, `"`) { - q = '\'' - } - if err := w.WriteByte(q); err != nil { - return err - } - if _, err := w.WriteString(s); err != nil { - return err - } - if err := w.WriteByte(q); err != nil { - return err - } - return nil -} - -// Section 12.1.2, "Elements", gives this list of void elements. Void elements -// are those that can't have any contents. -var voidElements = map[string]bool{ - "area": true, - "base": true, - "br": true, - "col": true, - "embed": true, - "hr": true, - "img": true, - "input": true, - "keygen": true, // "keygen" has been removed from the spec, but are kept here for backwards compatibility. - "link": true, - "meta": true, - "param": true, - "source": true, - "track": true, - "wbr": true, -} diff --git a/vendor/golang.org/x/net/html/token.go b/vendor/golang.org/x/net/html/token.go deleted file mode 100644 index 6598c1f..0000000 --- a/vendor/golang.org/x/net/html/token.go +++ /dev/null @@ -1,1286 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -import ( - "bytes" - "errors" - "io" - "strconv" - "strings" - - "golang.org/x/net/html/atom" -) - -// A TokenType is the type of a Token. -type TokenType uint32 - -const ( - // ErrorToken means that an error occurred during tokenization. - ErrorToken TokenType = iota - // TextToken means a text node. - TextToken - // A StartTagToken looks like <a>. - StartTagToken - // An EndTagToken looks like </a>. - EndTagToken - // A SelfClosingTagToken tag looks like <br/>. - SelfClosingTagToken - // A CommentToken looks like <!--x-->. - CommentToken - // A DoctypeToken looks like <!DOCTYPE x> - DoctypeToken -) - -// ErrBufferExceeded means that the buffering limit was exceeded. -var ErrBufferExceeded = errors.New("max buffer exceeded") - -// String returns a string representation of the TokenType. -func (t TokenType) String() string { - switch t { - case ErrorToken: - return "Error" - case TextToken: - return "Text" - case StartTagToken: - return "StartTag" - case EndTagToken: - return "EndTag" - case SelfClosingTagToken: - return "SelfClosingTag" - case CommentToken: - return "Comment" - case DoctypeToken: - return "Doctype" - } - return "Invalid(" + strconv.Itoa(int(t)) + ")" -} - -// An Attribute is an attribute namespace-key-value triple. Namespace is -// non-empty for foreign attributes like xlink, Key is alphabetic (and hence -// does not contain escapable characters like '&', '<' or '>'), and Val is -// unescaped (it looks like "a<b" rather than "a&lt;b"). -// -// Namespace is only used by the parser, not the tokenizer. -type Attribute struct { - Namespace, Key, Val string -} - -// A Token consists of a TokenType and some Data (tag name for start and end -// tags, content for text, comments and doctypes). A tag Token may also contain -// a slice of Attributes. Data is unescaped for all Tokens (it looks like "a<b" -// rather than "a&lt;b"). For tag Tokens, DataAtom is the atom for Data, or -// zero if Data is not a known tag name. -type Token struct { - Type TokenType - DataAtom atom.Atom - Data string - Attr []Attribute -} - -// tagString returns a string representation of a tag Token's Data and Attr. -func (t Token) tagString() string { - if len(t.Attr) == 0 { - return t.Data - } - buf := bytes.NewBufferString(t.Data) - for _, a := range t.Attr { - buf.WriteByte(' ') - buf.WriteString(a.Key) - buf.WriteString(`="`) - escape(buf, a.Val) - buf.WriteByte('"') - } - return buf.String() -} - -// String returns a string representation of the Token. -func (t Token) String() string { - switch t.Type { - case ErrorToken: - return "" - case TextToken: - return EscapeString(t.Data) - case StartTagToken: - return "<" + t.tagString() + ">" - case EndTagToken: - return "</" + t.tagString() + ">" - case SelfClosingTagToken: - return "<" + t.tagString() + "/>" - case CommentToken: - return "<!--" + escapeCommentString(t.Data) + "-->" - case DoctypeToken: - return "<!DOCTYPE " + EscapeString(t.Data) + ">" - } - return "Invalid(" + strconv.Itoa(int(t.Type)) + ")" -} - -// span is a range of bytes in a Tokenizer's buffer. The start is inclusive, -// the end is exclusive. -type span struct { - start, end int -} - -// A Tokenizer returns a stream of HTML Tokens. -type Tokenizer struct { - // r is the source of the HTML text. - r io.Reader - // tt is the TokenType of the current token. - tt TokenType - // err is the first error encountered during tokenization. It is possible - // for tt != Error && err != nil to hold: this means that Next returned a - // valid token but the subsequent Next call will return an error token. - // For example, if the HTML text input was just "plain", then the first - // Next call would set z.err to io.EOF but return a TextToken, and all - // subsequent Next calls would return an ErrorToken. - // err is never reset. Once it becomes non-nil, it stays non-nil. - err error - // readErr is the error returned by the io.Reader r. It is separate from - // err because it is valid for an io.Reader to return (n int, err1 error) - // such that n > 0 && err1 != nil, and callers should always process the - // n > 0 bytes before considering the error err1. - readErr error - // buf[raw.start:raw.end] holds the raw bytes of the current token. - // buf[raw.end:] is buffered input that will yield future tokens. - raw span - buf []byte - // maxBuf limits the data buffered in buf. A value of 0 means unlimited. - maxBuf int - // buf[data.start:data.end] holds the raw bytes of the current token's data: - // a text token's text, a tag token's tag name, etc. - data span - // pendingAttr is the attribute key and value currently being tokenized. - // When complete, pendingAttr is pushed onto attr. nAttrReturned is - // incremented on each call to TagAttr. - pendingAttr [2]span - attr [][2]span - nAttrReturned int - // rawTag is the "script" in "</script>" that closes the next token. If - // non-empty, the subsequent call to Next will return a raw or RCDATA text - // token: one that treats "<p>" as text instead of an element. - // rawTag's contents are lower-cased. - rawTag string - // textIsRaw is whether the current text token's data is not escaped. - textIsRaw bool - // convertNUL is whether NUL bytes in the current token's data should - // be converted into \ufffd replacement characters. - convertNUL bool - // allowCDATA is whether CDATA sections are allowed in the current context. - allowCDATA bool -} - -// AllowCDATA sets whether or not the tokenizer recognizes <![CDATA[foo]]> as -// the text "foo". The default value is false, which means to recognize it as -// a bogus comment "<!-- [CDATA[foo]] -->" instead. -// -// Strictly speaking, an HTML5 compliant tokenizer should allow CDATA if and -// only if tokenizing foreign content, such as MathML and SVG. However, -// tracking foreign-contentness is difficult to do purely in the tokenizer, -// as opposed to the parser, due to HTML integration points: an <svg> element -// can contain a <foreignObject> that is foreign-to-SVG but not foreign-to- -// HTML. For strict compliance with the HTML5 tokenization algorithm, it is the -// responsibility of the user of a tokenizer to call AllowCDATA as appropriate. -// In practice, if using the tokenizer without caring whether MathML or SVG -// CDATA is text or comments, such as tokenizing HTML to find all the anchor -// text, it is acceptable to ignore this responsibility. -func (z *Tokenizer) AllowCDATA(allowCDATA bool) { - z.allowCDATA = allowCDATA -} - -// NextIsNotRawText instructs the tokenizer that the next token should not be -// considered as 'raw text'. Some elements, such as script and title elements, -// normally require the next token after the opening tag to be 'raw text' that -// has no child elements. For example, tokenizing "<title>a<b>c</b>d</title>" -// yields a start tag token for "<title>", a text token for "a<b>c</b>d", and -// an end tag token for "</title>". There are no distinct start tag or end tag -// tokens for the "<b>" and "</b>". -// -// This tokenizer implementation will generally look for raw text at the right -// times. Strictly speaking, an HTML5 compliant tokenizer should not look for -// raw text if in foreign content: <title> generally needs raw text, but a -// <title> inside an <svg> does not. Another example is that a <textarea> -// generally needs raw text, but a <textarea> is not allowed as an immediate -// child of a <select>; in normal parsing, a <textarea> implies </select>, but -// one cannot close the implicit element when parsing a <select>'s InnerHTML. -// Similarly to AllowCDATA, tracking the correct moment to override raw-text- -// ness is difficult to do purely in the tokenizer, as opposed to the parser. -// For strict compliance with the HTML5 tokenization algorithm, it is the -// responsibility of the user of a tokenizer to call NextIsNotRawText as -// appropriate. In practice, like AllowCDATA, it is acceptable to ignore this -// responsibility for basic usage. -// -// Note that this 'raw text' concept is different from the one offered by the -// Tokenizer.Raw method. -func (z *Tokenizer) NextIsNotRawText() { - z.rawTag = "" -} - -// Err returns the error associated with the most recent ErrorToken token. -// This is typically io.EOF, meaning the end of tokenization. -func (z *Tokenizer) Err() error { - if z.tt != ErrorToken { - return nil - } - return z.err -} - -// readByte returns the next byte from the input stream, doing a buffered read -// from z.r into z.buf if necessary. z.buf[z.raw.start:z.raw.end] remains a contiguous byte -// slice that holds all the bytes read so far for the current token. -// It sets z.err if the underlying reader returns an error. -// Pre-condition: z.err == nil. -func (z *Tokenizer) readByte() byte { - if z.raw.end >= len(z.buf) { - // Our buffer is exhausted and we have to read from z.r. Check if the - // previous read resulted in an error. - if z.readErr != nil { - z.err = z.readErr - return 0 - } - // We copy z.buf[z.raw.start:z.raw.end] to the beginning of z.buf. If the length - // z.raw.end - z.raw.start is more than half the capacity of z.buf, then we - // allocate a new buffer before the copy. - c := cap(z.buf) - d := z.raw.end - z.raw.start - var buf1 []byte - if 2*d > c { - buf1 = make([]byte, d, 2*c) - } else { - buf1 = z.buf[:d] - } - copy(buf1, z.buf[z.raw.start:z.raw.end]) - if x := z.raw.start; x != 0 { - // Adjust the data/attr spans to refer to the same contents after the copy. - z.data.start -= x - z.data.end -= x - z.pendingAttr[0].start -= x - z.pendingAttr[0].end -= x - z.pendingAttr[1].start -= x - z.pendingAttr[1].end -= x - for i := range z.attr { - z.attr[i][0].start -= x - z.attr[i][0].end -= x - z.attr[i][1].start -= x - z.attr[i][1].end -= x - } - } - z.raw.start, z.raw.end, z.buf = 0, d, buf1[:d] - // Now that we have copied the live bytes to the start of the buffer, - // we read from z.r into the remainder. - var n int - n, z.readErr = readAtLeastOneByte(z.r, buf1[d:cap(buf1)]) - if n == 0 { - z.err = z.readErr - return 0 - } - z.buf = buf1[:d+n] - } - x := z.buf[z.raw.end] - z.raw.end++ - if z.maxBuf > 0 && z.raw.end-z.raw.start >= z.maxBuf { - z.err = ErrBufferExceeded - return 0 - } - return x -} - -// Buffered returns a slice containing data buffered but not yet tokenized. -func (z *Tokenizer) Buffered() []byte { - return z.buf[z.raw.end:] -} - -// readAtLeastOneByte wraps an io.Reader so that reading cannot return (0, nil). -// It returns io.ErrNoProgress if the underlying r.Read method returns (0, nil) -// too many times in succession. -func readAtLeastOneByte(r io.Reader, b []byte) (int, error) { - for i := 0; i < 100; i++ { - if n, err := r.Read(b); n != 0 || err != nil { - return n, err - } - } - return 0, io.ErrNoProgress -} - -// skipWhiteSpace skips past any white space. -func (z *Tokenizer) skipWhiteSpace() { - if z.err != nil { - return - } - for { - c := z.readByte() - if z.err != nil { - return - } - switch c { - case ' ', '\n', '\r', '\t', '\f': - // No-op. - default: - z.raw.end-- - return - } - } -} - -// readRawOrRCDATA reads until the next "</foo>", where "foo" is z.rawTag and -// is typically something like "script" or "textarea". -func (z *Tokenizer) readRawOrRCDATA() { - if z.rawTag == "script" { - z.readScript() - z.textIsRaw = true - z.rawTag = "" - return - } -loop: - for { - c := z.readByte() - if z.err != nil { - break loop - } - if c != '<' { - continue loop - } - c = z.readByte() - if z.err != nil { - break loop - } - if c != '/' { - z.raw.end-- - continue loop - } - if z.readRawEndTag() || z.err != nil { - break loop - } - } - z.data.end = z.raw.end - // A textarea's or title's RCDATA can contain escaped entities. - z.textIsRaw = z.rawTag != "textarea" && z.rawTag != "title" - z.rawTag = "" -} - -// readRawEndTag attempts to read a tag like "</foo>", where "foo" is z.rawTag. -// If it succeeds, it backs up the input position to reconsume the tag and -// returns true. Otherwise it returns false. The opening "</" has already been -// consumed. -func (z *Tokenizer) readRawEndTag() bool { - for i := 0; i < len(z.rawTag); i++ { - c := z.readByte() - if z.err != nil { - return false - } - if c != z.rawTag[i] && c != z.rawTag[i]-('a'-'A') { - z.raw.end-- - return false - } - } - c := z.readByte() - if z.err != nil { - return false - } - switch c { - case ' ', '\n', '\r', '\t', '\f', '/', '>': - // The 3 is 2 for the leading "</" plus 1 for the trailing character c. - z.raw.end -= 3 + len(z.rawTag) - return true - } - z.raw.end-- - return false -} - -// readScript reads until the next </script> tag, following the byzantine -// rules for escaping/hiding the closing tag. -func (z *Tokenizer) readScript() { - defer func() { - z.data.end = z.raw.end - }() - var c byte - -scriptData: - c = z.readByte() - if z.err != nil { - return - } - if c == '<' { - goto scriptDataLessThanSign - } - goto scriptData - -scriptDataLessThanSign: - c = z.readByte() - if z.err != nil { - return - } - switch c { - case '/': - goto scriptDataEndTagOpen - case '!': - goto scriptDataEscapeStart - } - z.raw.end-- - goto scriptData - -scriptDataEndTagOpen: - if z.readRawEndTag() || z.err != nil { - return - } - goto scriptData - -scriptDataEscapeStart: - c = z.readByte() - if z.err != nil { - return - } - if c == '-' { - goto scriptDataEscapeStartDash - } - z.raw.end-- - goto scriptData - -scriptDataEscapeStartDash: - c = z.readByte() - if z.err != nil { - return - } - if c == '-' { - goto scriptDataEscapedDashDash - } - z.raw.end-- - goto scriptData - -scriptDataEscaped: - c = z.readByte() - if z.err != nil { - return - } - switch c { - case '-': - goto scriptDataEscapedDash - case '<': - goto scriptDataEscapedLessThanSign - } - goto scriptDataEscaped - -scriptDataEscapedDash: - c = z.readByte() - if z.err != nil { - return - } - switch c { - case '-': - goto scriptDataEscapedDashDash - case '<': - goto scriptDataEscapedLessThanSign - } - goto scriptDataEscaped - -scriptDataEscapedDashDash: - c = z.readByte() - if z.err != nil { - return - } - switch c { - case '-': - goto scriptDataEscapedDashDash - case '<': - goto scriptDataEscapedLessThanSign - case '>': - goto scriptData - } - goto scriptDataEscaped - -scriptDataEscapedLessThanSign: - c = z.readByte() - if z.err != nil { - return - } - if c == '/' { - goto scriptDataEscapedEndTagOpen - } - if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' { - goto scriptDataDoubleEscapeStart - } - z.raw.end-- - goto scriptData - -scriptDataEscapedEndTagOpen: - if z.readRawEndTag() || z.err != nil { - return - } - goto scriptDataEscaped - -scriptDataDoubleEscapeStart: - z.raw.end-- - for i := 0; i < len("script"); i++ { - c = z.readByte() - if z.err != nil { - return - } - if c != "script"[i] && c != "SCRIPT"[i] { - z.raw.end-- - goto scriptDataEscaped - } - } - c = z.readByte() - if z.err != nil { - return - } - switch c { - case ' ', '\n', '\r', '\t', '\f', '/', '>': - goto scriptDataDoubleEscaped - } - z.raw.end-- - goto scriptDataEscaped - -scriptDataDoubleEscaped: - c = z.readByte() - if z.err != nil { - return - } - switch c { - case '-': - goto scriptDataDoubleEscapedDash - case '<': - goto scriptDataDoubleEscapedLessThanSign - } - goto scriptDataDoubleEscaped - -scriptDataDoubleEscapedDash: - c = z.readByte() - if z.err != nil { - return - } - switch c { - case '-': - goto scriptDataDoubleEscapedDashDash - case '<': - goto scriptDataDoubleEscapedLessThanSign - } - goto scriptDataDoubleEscaped - -scriptDataDoubleEscapedDashDash: - c = z.readByte() - if z.err != nil { - return - } - switch c { - case '-': - goto scriptDataDoubleEscapedDashDash - case '<': - goto scriptDataDoubleEscapedLessThanSign - case '>': - goto scriptData - } - goto scriptDataDoubleEscaped - -scriptDataDoubleEscapedLessThanSign: - c = z.readByte() - if z.err != nil { - return - } - if c == '/' { - goto scriptDataDoubleEscapeEnd - } - z.raw.end-- - goto scriptDataDoubleEscaped - -scriptDataDoubleEscapeEnd: - if z.readRawEndTag() { - z.raw.end += len("</script>") - goto scriptDataEscaped - } - if z.err != nil { - return - } - goto scriptDataDoubleEscaped -} - -// readComment reads the next comment token starting with "<!--". The opening -// "<!--" has already been consumed. -func (z *Tokenizer) readComment() { - // When modifying this function, consider manually increasing the - // maxSuffixLen constant in func TestComments, from 6 to e.g. 9 or more. - // That increase should only be temporary, not committed, as it - // exponentially affects the test running time. - - z.data.start = z.raw.end - defer func() { - if z.data.end < z.data.start { - // It's a comment with no data, like <!-->. - z.data.end = z.data.start - } - }() - - var dashCount int - beginning := true - for { - c := z.readByte() - if z.err != nil { - z.data.end = z.calculateAbruptCommentDataEnd() - return - } - switch c { - case '-': - dashCount++ - continue - case '>': - if dashCount >= 2 || beginning { - z.data.end = z.raw.end - len("-->") - return - } - case '!': - if dashCount >= 2 { - c = z.readByte() - if z.err != nil { - z.data.end = z.calculateAbruptCommentDataEnd() - return - } else if c == '>' { - z.data.end = z.raw.end - len("--!>") - return - } else if c == '-' { - dashCount = 1 - beginning = false - continue - } - } - } - dashCount = 0 - beginning = false - } -} - -func (z *Tokenizer) calculateAbruptCommentDataEnd() int { - raw := z.Raw() - const prefixLen = len("<!--") - if len(raw) >= prefixLen { - raw = raw[prefixLen:] - if hasSuffix(raw, "--!") { - return z.raw.end - 3 - } else if hasSuffix(raw, "--") { - return z.raw.end - 2 - } else if hasSuffix(raw, "-") { - return z.raw.end - 1 - } - } - return z.raw.end -} - -func hasSuffix(b []byte, suffix string) bool { - if len(b) < len(suffix) { - return false - } - b = b[len(b)-len(suffix):] - for i := range b { - if b[i] != suffix[i] { - return false - } - } - return true -} - -// readUntilCloseAngle reads until the next ">". -func (z *Tokenizer) readUntilCloseAngle() { - z.data.start = z.raw.end - for { - c := z.readByte() - if z.err != nil { - z.data.end = z.raw.end - return - } - if c == '>' { - z.data.end = z.raw.end - len(">") - return - } - } -} - -// readMarkupDeclaration reads the next token starting with "<!". It might be -// a "<!--comment-->", a "<!DOCTYPE foo>", a "<![CDATA[section]]>" or -// "<!a bogus comment". The opening "<!" has already been consumed. -func (z *Tokenizer) readMarkupDeclaration() TokenType { - z.data.start = z.raw.end - var c [2]byte - for i := 0; i < 2; i++ { - c[i] = z.readByte() - if z.err != nil { - z.data.end = z.raw.end - return CommentToken - } - } - if c[0] == '-' && c[1] == '-' { - z.readComment() - return CommentToken - } - z.raw.end -= 2 - if z.readDoctype() { - return DoctypeToken - } - if z.allowCDATA && z.readCDATA() { - z.convertNUL = true - return TextToken - } - // It's a bogus comment. - z.readUntilCloseAngle() - return CommentToken -} - -// readDoctype attempts to read a doctype declaration and returns true if -// successful. The opening "<!" has already been consumed. -func (z *Tokenizer) readDoctype() bool { - const s = "DOCTYPE" - for i := 0; i < len(s); i++ { - c := z.readByte() - if z.err != nil { - z.data.end = z.raw.end - return false - } - if c != s[i] && c != s[i]+('a'-'A') { - // Back up to read the fragment of "DOCTYPE" again. - z.raw.end = z.data.start - return false - } - } - if z.skipWhiteSpace(); z.err != nil { - z.data.start = z.raw.end - z.data.end = z.raw.end - return true - } - z.readUntilCloseAngle() - return true -} - -// readCDATA attempts to read a CDATA section and returns true if -// successful. The opening "<!" has already been consumed. -func (z *Tokenizer) readCDATA() bool { - const s = "[CDATA[" - for i := 0; i < len(s); i++ { - c := z.readByte() - if z.err != nil { - z.data.end = z.raw.end - return false - } - if c != s[i] { - // Back up to read the fragment of "[CDATA[" again. - z.raw.end = z.data.start - return false - } - } - z.data.start = z.raw.end - brackets := 0 - for { - c := z.readByte() - if z.err != nil { - z.data.end = z.raw.end - return true - } - switch c { - case ']': - brackets++ - case '>': - if brackets >= 2 { - z.data.end = z.raw.end - len("]]>") - return true - } - brackets = 0 - default: - brackets = 0 - } - } -} - -// startTagIn returns whether the start tag in z.buf[z.data.start:z.data.end] -// case-insensitively matches any element of ss. -func (z *Tokenizer) startTagIn(ss ...string) bool { -loop: - for _, s := range ss { - if z.data.end-z.data.start != len(s) { - continue loop - } - for i := 0; i < len(s); i++ { - c := z.buf[z.data.start+i] - if 'A' <= c && c <= 'Z' { - c += 'a' - 'A' - } - if c != s[i] { - continue loop - } - } - return true - } - return false -} - -// readStartTag reads the next start tag token. The opening "<a" has already -// been consumed, where 'a' means anything in [A-Za-z]. -func (z *Tokenizer) readStartTag() TokenType { - z.readTag(true) - if z.err != nil { - return ErrorToken - } - // Several tags flag the tokenizer's next token as raw. - c, raw := z.buf[z.data.start], false - if 'A' <= c && c <= 'Z' { - c += 'a' - 'A' - } - switch c { - case 'i': - raw = z.startTagIn("iframe") - case 'n': - raw = z.startTagIn("noembed", "noframes", "noscript") - case 'p': - raw = z.startTagIn("plaintext") - case 's': - raw = z.startTagIn("script", "style") - case 't': - raw = z.startTagIn("textarea", "title") - case 'x': - raw = z.startTagIn("xmp") - } - if raw { - z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end])) - } - // Look for a self-closing token (e.g. <br/>). - // - // Originally, we did this by just checking that the last character of the - // tag (ignoring the closing bracket) was a solidus (/) character, but this - // is not always accurate. - // - // We need to be careful that we don't misinterpret a non-self-closing tag - // as self-closing, as can happen if the tag contains unquoted attribute - // values (i.e. <p a=/>). - // - // To avoid this, we check that the last non-bracket character of the tag - // (z.raw.end-2) isn't the same character as the last non-quote character of - // the last attribute of the tag (z.pendingAttr[1].end-1), if the tag has - // attributes. - nAttrs := len(z.attr) - if z.err == nil && z.buf[z.raw.end-2] == '/' && (nAttrs == 0 || z.raw.end-2 != z.attr[nAttrs-1][1].end-1) { - return SelfClosingTagToken - } - return StartTagToken -} - -// readTag reads the next tag token and its attributes. If saveAttr, those -// attributes are saved in z.attr, otherwise z.attr is set to an empty slice. -// The opening "<a" or "</a" has already been consumed, where 'a' means anything -// in [A-Za-z]. -func (z *Tokenizer) readTag(saveAttr bool) { - z.attr = z.attr[:0] - z.nAttrReturned = 0 - // Read the tag name and attribute key/value pairs. - z.readTagName() - if z.skipWhiteSpace(); z.err != nil { - return - } - for { - c := z.readByte() - if z.err != nil || c == '>' { - break - } - z.raw.end-- - z.readTagAttrKey() - z.readTagAttrVal() - // Save pendingAttr if saveAttr and that attribute has a non-empty key. - if saveAttr && z.pendingAttr[0].start != z.pendingAttr[0].end { - z.attr = append(z.attr, z.pendingAttr) - } - if z.skipWhiteSpace(); z.err != nil { - break - } - } -} - -// readTagName sets z.data to the "div" in "<div k=v>". The reader (z.raw.end) -// is positioned such that the first byte of the tag name (the "d" in "<div") -// has already been consumed. -func (z *Tokenizer) readTagName() { - z.data.start = z.raw.end - 1 - for { - c := z.readByte() - if z.err != nil { - z.data.end = z.raw.end - return - } - switch c { - case ' ', '\n', '\r', '\t', '\f': - z.data.end = z.raw.end - 1 - return - case '/', '>': - z.raw.end-- - z.data.end = z.raw.end - return - } - } -} - -// readTagAttrKey sets z.pendingAttr[0] to the "k" in "<div k=v>". -// Precondition: z.err == nil. -func (z *Tokenizer) readTagAttrKey() { - z.pendingAttr[0].start = z.raw.end - for { - c := z.readByte() - if z.err != nil { - z.pendingAttr[0].end = z.raw.end - return - } - switch c { - case '=': - if z.pendingAttr[0].start+1 == z.raw.end { - // WHATWG 13.2.5.32, if we see an equals sign before the attribute name - // begins, we treat it as a character in the attribute name and continue. - continue - } - fallthrough - case ' ', '\n', '\r', '\t', '\f', '/', '>': - // WHATWG 13.2.5.33 Attribute name state - // We need to reconsume the char in the after attribute name state to support the / character - z.raw.end-- - z.pendingAttr[0].end = z.raw.end - return - } - } -} - -// readTagAttrVal sets z.pendingAttr[1] to the "v" in "<div k=v>". -func (z *Tokenizer) readTagAttrVal() { - z.pendingAttr[1].start = z.raw.end - z.pendingAttr[1].end = z.raw.end - if z.skipWhiteSpace(); z.err != nil { - return - } - c := z.readByte() - if z.err != nil { - return - } - if c == '/' { - // WHATWG 13.2.5.34 After attribute name state - // U+002F SOLIDUS (/) - Switch to the self-closing start tag state. - return - } - if c != '=' { - z.raw.end-- - return - } - if z.skipWhiteSpace(); z.err != nil { - return - } - quote := z.readByte() - if z.err != nil { - return - } - switch quote { - case '>': - z.raw.end-- - return - - case '\'', '"': - z.pendingAttr[1].start = z.raw.end - for { - c := z.readByte() - if z.err != nil { - z.pendingAttr[1].end = z.raw.end - return - } - if c == quote { - z.pendingAttr[1].end = z.raw.end - 1 - return - } - } - - default: - z.pendingAttr[1].start = z.raw.end - 1 - for { - c := z.readByte() - if z.err != nil { - z.pendingAttr[1].end = z.raw.end - return - } - switch c { - case ' ', '\n', '\r', '\t', '\f': - z.pendingAttr[1].end = z.raw.end - 1 - return - case '>': - z.raw.end-- - z.pendingAttr[1].end = z.raw.end - return - } - } - } -} - -// Next scans the next token and returns its type. -func (z *Tokenizer) Next() TokenType { - z.raw.start = z.raw.end - z.data.start = z.raw.end - z.data.end = z.raw.end - if z.err != nil { - z.tt = ErrorToken - return z.tt - } - if z.rawTag != "" { - if z.rawTag == "plaintext" { - // Read everything up to EOF. - for z.err == nil { - z.readByte() - } - z.data.end = z.raw.end - z.textIsRaw = true - } else { - z.readRawOrRCDATA() - } - if z.data.end > z.data.start { - z.tt = TextToken - z.convertNUL = true - return z.tt - } - } - z.textIsRaw = false - z.convertNUL = false - -loop: - for { - c := z.readByte() - if z.err != nil { - break loop - } - if c != '<' { - continue loop - } - - // Check if the '<' we have just read is part of a tag, comment - // or doctype. If not, it's part of the accumulated text token. - c = z.readByte() - if z.err != nil { - break loop - } - var tokenType TokenType - switch { - case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z': - tokenType = StartTagToken - case c == '/': - tokenType = EndTagToken - case c == '!' || c == '?': - // We use CommentToken to mean any of "<!--actual comments-->", - // "<!DOCTYPE declarations>" and "<?xml processing instructions?>". - tokenType = CommentToken - default: - // Reconsume the current character. - z.raw.end-- - continue - } - - // We have a non-text token, but we might have accumulated some text - // before that. If so, we return the text first, and return the non- - // text token on the subsequent call to Next. - if x := z.raw.end - len("<a"); z.raw.start < x { - z.raw.end = x - z.data.end = x - z.tt = TextToken - return z.tt - } - switch tokenType { - case StartTagToken: - z.tt = z.readStartTag() - return z.tt - case EndTagToken: - c = z.readByte() - if z.err != nil { - break loop - } - if c == '>' { - // "</>" does not generate a token at all. Generate an empty comment - // to allow passthrough clients to pick up the data using Raw. - // Reset the tokenizer state and start again. - z.tt = CommentToken - return z.tt - } - if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' { - z.readTag(false) - if z.err != nil { - z.tt = ErrorToken - } else { - z.tt = EndTagToken - } - return z.tt - } - z.raw.end-- - z.readUntilCloseAngle() - z.tt = CommentToken - return z.tt - case CommentToken: - if c == '!' { - z.tt = z.readMarkupDeclaration() - return z.tt - } - z.raw.end-- - z.readUntilCloseAngle() - z.tt = CommentToken - return z.tt - } - } - if z.raw.start < z.raw.end { - z.data.end = z.raw.end - z.tt = TextToken - return z.tt - } - z.tt = ErrorToken - return z.tt -} - -// Raw returns the unmodified text of the current token. Calling Next, Token, -// Text, TagName or TagAttr may change the contents of the returned slice. -// -// The token stream's raw bytes partition the byte stream (up until an -// ErrorToken). There are no overlaps or gaps between two consecutive token's -// raw bytes. One implication is that the byte offset of the current token is -// the sum of the lengths of all previous tokens' raw bytes. -func (z *Tokenizer) Raw() []byte { - return z.buf[z.raw.start:z.raw.end] -} - -// convertNewlines converts "\r" and "\r\n" in s to "\n". -// The conversion happens in place, but the resulting slice may be shorter. -func convertNewlines(s []byte) []byte { - for i, c := range s { - if c != '\r' { - continue - } - - src := i + 1 - if src >= len(s) || s[src] != '\n' { - s[i] = '\n' - continue - } - - dst := i - for src < len(s) { - if s[src] == '\r' { - if src+1 < len(s) && s[src+1] == '\n' { - src++ - } - s[dst] = '\n' - } else { - s[dst] = s[src] - } - src++ - dst++ - } - return s[:dst] - } - return s -} - -var ( - nul = []byte("\x00") - replacement = []byte("\ufffd") -) - -// Text returns the unescaped text of a text, comment or doctype token. The -// contents of the returned slice may change on the next call to Next. -func (z *Tokenizer) Text() []byte { - switch z.tt { - case TextToken, CommentToken, DoctypeToken: - s := z.buf[z.data.start:z.data.end] - z.data.start = z.raw.end - z.data.end = z.raw.end - s = convertNewlines(s) - if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) { - s = bytes.Replace(s, nul, replacement, -1) - } - if !z.textIsRaw { - s = unescape(s, false) - } - return s - } - return nil -} - -// TagName returns the lower-cased name of a tag token (the `img` out of -// `<IMG SRC="foo">`) and whether the tag has attributes. -// The contents of the returned slice may change on the next call to Next. -func (z *Tokenizer) TagName() (name []byte, hasAttr bool) { - if z.data.start < z.data.end { - switch z.tt { - case StartTagToken, EndTagToken, SelfClosingTagToken: - s := z.buf[z.data.start:z.data.end] - z.data.start = z.raw.end - z.data.end = z.raw.end - return lower(s), z.nAttrReturned < len(z.attr) - } - } - return nil, false -} - -// TagAttr returns the lower-cased key and unescaped value of the next unparsed -// attribute for the current tag token and whether there are more attributes. -// The contents of the returned slices may change on the next call to Next. -func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) { - if z.nAttrReturned < len(z.attr) { - switch z.tt { - case StartTagToken, SelfClosingTagToken: - x := z.attr[z.nAttrReturned] - z.nAttrReturned++ - key = z.buf[x[0].start:x[0].end] - val = z.buf[x[1].start:x[1].end] - return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr) - } - } - return nil, nil, false -} - -// Token returns the current Token. The result's Data and Attr values remain -// valid after subsequent Next calls. -func (z *Tokenizer) Token() Token { - t := Token{Type: z.tt} - switch z.tt { - case TextToken, CommentToken, DoctypeToken: - t.Data = string(z.Text()) - case StartTagToken, SelfClosingTagToken, EndTagToken: - name, moreAttr := z.TagName() - for moreAttr { - var key, val []byte - key, val, moreAttr = z.TagAttr() - t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)}) - } - if a := atom.Lookup(name); a != 0 { - t.DataAtom, t.Data = a, a.String() - } else { - t.DataAtom, t.Data = 0, string(name) - } - } - return t -} - -// SetMaxBuf sets a limit on the amount of data buffered during tokenization. -// A value of 0 means unlimited. -func (z *Tokenizer) SetMaxBuf(n int) { - z.maxBuf = n -} - -// NewTokenizer returns a new HTML Tokenizer for the given Reader. -// The input is assumed to be UTF-8 encoded. -func NewTokenizer(r io.Reader) *Tokenizer { - return NewTokenizerFragment(r, "") -} - -// NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for -// tokenizing an existing element's InnerHTML fragment. contextTag is that -// element's tag, such as "div" or "iframe". -// -// For example, how the InnerHTML "a<b" is tokenized depends on whether it is -// for a <p> tag or a <script> tag. -// -// The input is assumed to be UTF-8 encoded. -func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer { - z := &Tokenizer{ - r: r, - buf: make([]byte, 0, 4096), - } - if contextTag != "" { - switch s := strings.ToLower(contextTag); s { - case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp": - z.rawTag = s - } - } - return z -} diff --git a/vendor/golang.org/x/net/http2/config.go b/vendor/golang.org/x/net/http2/config.go index 02fe0c2..8a7a89d 100644 --- a/vendor/golang.org/x/net/http2/config.go +++ b/vendor/golang.org/x/net/http2/config.go @@ -27,6 +27,7 @@ import ( // - If the resulting value is zero or out of range, use a default. type http2Config struct { MaxConcurrentStreams uint32 + StrictMaxConcurrentRequests bool MaxDecoderHeaderTableSize uint32 MaxEncoderHeaderTableSize uint32 MaxReadFrameSize uint32 @@ -64,12 +65,13 @@ func configFromServer(h1 *http.Server, h2 *Server) http2Config { // (the net/http Transport). func configFromTransport(h2 *Transport) http2Config { conf := http2Config{ - MaxEncoderHeaderTableSize: h2.MaxEncoderHeaderTableSize, - MaxDecoderHeaderTableSize: h2.MaxDecoderHeaderTableSize, - MaxReadFrameSize: h2.MaxReadFrameSize, - SendPingTimeout: h2.ReadIdleTimeout, - PingTimeout: h2.PingTimeout, - WriteByteTimeout: h2.WriteByteTimeout, + StrictMaxConcurrentRequests: h2.StrictMaxConcurrentStreams, + MaxEncoderHeaderTableSize: h2.MaxEncoderHeaderTableSize, + MaxDecoderHeaderTableSize: h2.MaxDecoderHeaderTableSize, + MaxReadFrameSize: h2.MaxReadFrameSize, + SendPingTimeout: h2.ReadIdleTimeout, + PingTimeout: h2.PingTimeout, + WriteByteTimeout: h2.WriteByteTimeout, } // Unlike most config fields, where out-of-range values revert to the default, @@ -128,6 +130,9 @@ func fillNetHTTPConfig(conf *http2Config, h2 *http.HTTP2Config) { if h2.MaxConcurrentStreams != 0 { conf.MaxConcurrentStreams = uint32(h2.MaxConcurrentStreams) } + if http2ConfigStrictMaxConcurrentRequests(h2) { + conf.StrictMaxConcurrentRequests = true + } if h2.MaxEncoderHeaderTableSize != 0 { conf.MaxEncoderHeaderTableSize = uint32(h2.MaxEncoderHeaderTableSize) } diff --git a/vendor/golang.org/x/net/http2/config_go125.go b/vendor/golang.org/x/net/http2/config_go125.go new file mode 100644 index 0000000..b4373fe --- /dev/null +++ b/vendor/golang.org/x/net/http2/config_go125.go @@ -0,0 +1,15 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !go1.26 + +package http2 + +import ( + "net/http" +) + +func http2ConfigStrictMaxConcurrentRequests(h2 *http.HTTP2Config) bool { + return false +} diff --git a/vendor/golang.org/x/net/http2/config_go126.go b/vendor/golang.org/x/net/http2/config_go126.go new file mode 100644 index 0000000..6b071c1 --- /dev/null +++ b/vendor/golang.org/x/net/http2/config_go126.go @@ -0,0 +1,15 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.26 + +package http2 + +import ( + "net/http" +) + +func http2ConfigStrictMaxConcurrentRequests(h2 *http.HTTP2Config) bool { + return h2.StrictMaxConcurrentRequests +} diff --git a/vendor/golang.org/x/net/http2/frame.go b/vendor/golang.org/x/net/http2/frame.go index db3264d..93bcaab 100644 --- a/vendor/golang.org/x/net/http2/frame.go +++ b/vendor/golang.org/x/net/http2/frame.go @@ -347,7 +347,7 @@ func (fr *Framer) maxHeaderListSize() uint32 { func (f *Framer) startWrite(ftype FrameType, flags Flags, streamID uint32) { // Write the FrameHeader. f.wbuf = append(f.wbuf[:0], - 0, // 3 bytes of length, filled in in endWrite + 0, // 3 bytes of length, filled in endWrite 0, 0, byte(ftype), @@ -1152,6 +1152,15 @@ type PriorityFrame struct { PriorityParam } +var defaultRFC9218Priority = PriorityParam{ + incremental: 0, + urgency: 3, +} + +// Note that HTTP/2 has had two different prioritization schemes, and +// PriorityParam struct below is a superset of both schemes. The exported +// symbols are from RFC 7540 and the non-exported ones are from RFC 9218. + // PriorityParam are the stream prioritzation parameters. type PriorityParam struct { // StreamDep is a 31-bit stream identifier for the @@ -1167,6 +1176,20 @@ type PriorityParam struct { // the spec, "Add one to the value to obtain a weight between // 1 and 256." Weight uint8 + + // "The urgency (u) parameter value is Integer (see Section 3.3.1 of + // [STRUCTURED-FIELDS]), between 0 and 7 inclusive, in descending order of + // priority. The default is 3." + urgency uint8 + + // "The incremental (i) parameter value is Boolean (see Section 3.3.6 of + // [STRUCTURED-FIELDS]). It indicates if an HTTP response can be processed + // incrementally, i.e., provide some meaningful output as chunks of the + // response arrive." + // + // We use uint8 (i.e. 0 is false, 1 is true) instead of bool so we can + // avoid unnecessary type conversions and because either type takes 1 byte. + incremental uint8 } func (p PriorityParam) IsZero() bool { diff --git a/vendor/golang.org/x/net/http2/http2.go b/vendor/golang.org/x/net/http2/http2.go index 6878f8e..105fe12 100644 --- a/vendor/golang.org/x/net/http2/http2.go +++ b/vendor/golang.org/x/net/http2/http2.go @@ -34,7 +34,6 @@ var ( VerboseLogs bool logFrameWrites bool logFrameReads bool - inTests bool // Enabling extended CONNECT by causes browsers to attempt to use // WebSockets-over-HTTP/2. This results in problems when the server's websocket diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go index 64085f6..bdc5520 100644 --- a/vendor/golang.org/x/net/http2/server.go +++ b/vendor/golang.org/x/net/http2/server.go @@ -181,6 +181,10 @@ type Server struct { type serverInternalState struct { mu sync.Mutex activeConns map[*serverConn]struct{} + + // Pool of error channels. This is per-Server rather than global + // because channels can't be reused across synctest bubbles. + errChanPool sync.Pool } func (s *serverInternalState) registerConn(sc *serverConn) { @@ -212,6 +216,27 @@ func (s *serverInternalState) startGracefulShutdown() { s.mu.Unlock() } +// Global error channel pool used for uninitialized Servers. +// We use a per-Server pool when possible to avoid using channels across synctest bubbles. +var errChanPool = sync.Pool{ + New: func() any { return make(chan error, 1) }, +} + +func (s *serverInternalState) getErrChan() chan error { + if s == nil { + return errChanPool.Get().(chan error) // Server used without calling ConfigureServer + } + return s.errChanPool.Get().(chan error) +} + +func (s *serverInternalState) putErrChan(ch chan error) { + if s == nil { + errChanPool.Put(ch) // Server used without calling ConfigureServer + return + } + s.errChanPool.Put(ch) +} + // ConfigureServer adds HTTP/2 support to a net/http Server. // // The configuration conf may be nil. @@ -224,7 +249,10 @@ func ConfigureServer(s *http.Server, conf *Server) error { if conf == nil { conf = new(Server) } - conf.state = &serverInternalState{activeConns: make(map[*serverConn]struct{})} + conf.state = &serverInternalState{ + activeConns: make(map[*serverConn]struct{}), + errChanPool: sync.Pool{New: func() any { return make(chan error, 1) }}, + } if h1, h2 := s, conf; h2.IdleTimeout == 0 { if h1.IdleTimeout != 0 { h2.IdleTimeout = h1.IdleTimeout @@ -1124,25 +1152,6 @@ func (sc *serverConn) readPreface() error { } } -var errChanPool = sync.Pool{ - New: func() interface{} { return make(chan error, 1) }, -} - -func getErrChan() chan error { - if inTests { - // Channels cannot be reused across synctest tests. - return make(chan error, 1) - } else { - return errChanPool.Get().(chan error) - } -} - -func putErrChan(ch chan error) { - if !inTests { - errChanPool.Put(ch) - } -} - var writeDataPool = sync.Pool{ New: func() interface{} { return new(writeData) }, } @@ -1150,7 +1159,7 @@ var writeDataPool = sync.Pool{ // writeDataFromHandler writes DATA response frames from a handler on // the given stream. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error { - ch := getErrChan() + ch := sc.srv.state.getErrChan() writeArg := writeDataPool.Get().(*writeData) *writeArg = writeData{stream.id, data, endStream} err := sc.writeFrameFromHandler(FrameWriteRequest{ @@ -1182,7 +1191,7 @@ func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStrea return errStreamClosed } } - putErrChan(ch) + sc.srv.state.putErrChan(ch) if frameWriteDone { writeDataPool.Put(writeArg) } @@ -2436,7 +2445,7 @@ func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) erro // waiting for this frame to be written, so an http.Flush mid-handler // writes out the correct value of keys, before a handler later potentially // mutates it. - errc = getErrChan() + errc = sc.srv.state.getErrChan() } if err := sc.writeFrameFromHandler(FrameWriteRequest{ write: headerData, @@ -2448,7 +2457,7 @@ func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) erro if errc != nil { select { case err := <-errc: - putErrChan(errc) + sc.srv.state.putErrChan(errc) return err case <-sc.doneServing: return errClientDisconnected @@ -3129,7 +3138,7 @@ func (w *responseWriter) Push(target string, opts *http.PushOptions) error { method: opts.Method, url: u, header: cloneHeader(opts.Header), - done: getErrChan(), + done: sc.srv.state.getErrChan(), } select { @@ -3146,7 +3155,7 @@ func (w *responseWriter) Push(target string, opts *http.PushOptions) error { case <-st.cw: return errStreamClosed case err := <-msg.done: - putErrChan(msg.done) + sc.srv.state.putErrChan(msg.done) return err } } diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index 35e3902..be759b6 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -355,6 +355,7 @@ type ClientConn struct { readIdleTimeout time.Duration pingTimeout time.Duration extendedConnectAllowed bool + strictMaxConcurrentStreams bool // rstStreamPingsBlocked works around an unfortunate gRPC behavior. // gRPC strictly limits the number of PING frames that it will receive. @@ -784,7 +785,8 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, erro initialWindowSize: 65535, // spec default initialStreamRecvWindowSize: conf.MaxUploadBufferPerStream, maxConcurrentStreams: initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings. - peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead. + strictMaxConcurrentStreams: conf.StrictMaxConcurrentRequests, + peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead. streams: make(map[uint32]*clientStream), singleUse: singleUse, seenSettingsChan: make(chan struct{}), @@ -1018,7 +1020,7 @@ func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) { return } var maxConcurrentOkay bool - if cc.t.StrictMaxConcurrentStreams { + if cc.strictMaxConcurrentStreams { // We'll tell the caller we can take a new request to // prevent the caller from dialing a new TCP // connection, but then we'll block later before diff --git a/vendor/golang.org/x/net/http2/writesched.go b/vendor/golang.org/x/net/http2/writesched.go index cc893ad..4d3890f 100644 --- a/vendor/golang.org/x/net/http2/writesched.go +++ b/vendor/golang.org/x/net/http2/writesched.go @@ -42,6 +42,8 @@ type OpenStreamOptions struct { // PusherID is zero if the stream was initiated by the client. Otherwise, // PusherID names the stream that pushed the newly opened stream. PusherID uint32 + // priority is used to set the priority of the newly opened stream. + priority PriorityParam } // FrameWriteRequest is a request to write a frame. diff --git a/vendor/golang.org/x/net/http2/writesched_priority.go b/vendor/golang.org/x/net/http2/writesched_priority_rfc7540.go similarity index 78% rename from vendor/golang.org/x/net/http2/writesched_priority.go rename to vendor/golang.org/x/net/http2/writesched_priority_rfc7540.go index f678333..6d24d6a 100644 --- a/vendor/golang.org/x/net/http2/writesched_priority.go +++ b/vendor/golang.org/x/net/http2/writesched_priority_rfc7540.go @@ -11,7 +11,7 @@ import ( ) // RFC 7540, Section 5.3.5: the default weight is 16. -const priorityDefaultWeight = 15 // 16 = 15 + 1 +const priorityDefaultWeightRFC7540 = 15 // 16 = 15 + 1 // PriorityWriteSchedulerConfig configures a priorityWriteScheduler. type PriorityWriteSchedulerConfig struct { @@ -66,8 +66,8 @@ func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler } } - ws := &priorityWriteScheduler{ - nodes: make(map[uint32]*priorityNode), + ws := &priorityWriteSchedulerRFC7540{ + nodes: make(map[uint32]*priorityNodeRFC7540), maxClosedNodesInTree: cfg.MaxClosedNodesInTree, maxIdleNodesInTree: cfg.MaxIdleNodesInTree, enableWriteThrottle: cfg.ThrottleOutOfOrderWrites, @@ -81,32 +81,32 @@ func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler return ws } -type priorityNodeState int +type priorityNodeStateRFC7540 int const ( - priorityNodeOpen priorityNodeState = iota - priorityNodeClosed - priorityNodeIdle + priorityNodeOpenRFC7540 priorityNodeStateRFC7540 = iota + priorityNodeClosedRFC7540 + priorityNodeIdleRFC7540 ) -// priorityNode is a node in an HTTP/2 priority tree. +// priorityNodeRFC7540 is a node in an HTTP/2 priority tree. // Each node is associated with a single stream ID. // See RFC 7540, Section 5.3. -type priorityNode struct { - q writeQueue // queue of pending frames to write - id uint32 // id of the stream, or 0 for the root of the tree - weight uint8 // the actual weight is weight+1, so the value is in [1,256] - state priorityNodeState // open | closed | idle - bytes int64 // number of bytes written by this node, or 0 if closed - subtreeBytes int64 // sum(node.bytes) of all nodes in this subtree +type priorityNodeRFC7540 struct { + q writeQueue // queue of pending frames to write + id uint32 // id of the stream, or 0 for the root of the tree + weight uint8 // the actual weight is weight+1, so the value is in [1,256] + state priorityNodeStateRFC7540 // open | closed | idle + bytes int64 // number of bytes written by this node, or 0 if closed + subtreeBytes int64 // sum(node.bytes) of all nodes in this subtree // These links form the priority tree. - parent *priorityNode - kids *priorityNode // start of the kids list - prev, next *priorityNode // doubly-linked list of siblings + parent *priorityNodeRFC7540 + kids *priorityNodeRFC7540 // start of the kids list + prev, next *priorityNodeRFC7540 // doubly-linked list of siblings } -func (n *priorityNode) setParent(parent *priorityNode) { +func (n *priorityNodeRFC7540) setParent(parent *priorityNodeRFC7540) { if n == parent { panic("setParent to self") } @@ -141,7 +141,7 @@ func (n *priorityNode) setParent(parent *priorityNode) { } } -func (n *priorityNode) addBytes(b int64) { +func (n *priorityNodeRFC7540) addBytes(b int64) { n.bytes += b for ; n != nil; n = n.parent { n.subtreeBytes += b @@ -154,7 +154,7 @@ func (n *priorityNode) addBytes(b int64) { // // f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true // if any ancestor p of n is still open (ignoring the root node). -func (n *priorityNode) walkReadyInOrder(openParent bool, tmp *[]*priorityNode, f func(*priorityNode, bool) bool) bool { +func (n *priorityNodeRFC7540) walkReadyInOrder(openParent bool, tmp *[]*priorityNodeRFC7540, f func(*priorityNodeRFC7540, bool) bool) bool { if !n.q.empty() && f(n, openParent) { return true } @@ -165,7 +165,7 @@ func (n *priorityNode) walkReadyInOrder(openParent bool, tmp *[]*priorityNode, f // Don't consider the root "open" when updating openParent since // we can't send data frames on the root stream (only control frames). if n.id != 0 { - openParent = openParent || (n.state == priorityNodeOpen) + openParent = openParent || (n.state == priorityNodeOpenRFC7540) } // Common case: only one kid or all kids have the same weight. @@ -195,7 +195,7 @@ func (n *priorityNode) walkReadyInOrder(openParent bool, tmp *[]*priorityNode, f *tmp = append(*tmp, n.kids) n.kids.setParent(nil) } - sort.Sort(sortPriorityNodeSiblings(*tmp)) + sort.Sort(sortPriorityNodeSiblingsRFC7540(*tmp)) for i := len(*tmp) - 1; i >= 0; i-- { (*tmp)[i].setParent(n) // setParent inserts at the head of n.kids } @@ -207,11 +207,11 @@ func (n *priorityNode) walkReadyInOrder(openParent bool, tmp *[]*priorityNode, f return false } -type sortPriorityNodeSiblings []*priorityNode +type sortPriorityNodeSiblingsRFC7540 []*priorityNodeRFC7540 -func (z sortPriorityNodeSiblings) Len() int { return len(z) } -func (z sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] } -func (z sortPriorityNodeSiblings) Less(i, k int) bool { +func (z sortPriorityNodeSiblingsRFC7540) Len() int { return len(z) } +func (z sortPriorityNodeSiblingsRFC7540) Swap(i, k int) { z[i], z[k] = z[k], z[i] } +func (z sortPriorityNodeSiblingsRFC7540) Less(i, k int) bool { // Prefer the subtree that has sent fewer bytes relative to its weight. // See sections 5.3.2 and 5.3.4. wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes) @@ -225,13 +225,13 @@ func (z sortPriorityNodeSiblings) Less(i, k int) bool { return bi/bk <= wi/wk } -type priorityWriteScheduler struct { +type priorityWriteSchedulerRFC7540 struct { // root is the root of the priority tree, where root.id = 0. // The root queues control frames that are not associated with any stream. - root priorityNode + root priorityNodeRFC7540 // nodes maps stream ids to priority tree nodes. - nodes map[uint32]*priorityNode + nodes map[uint32]*priorityNodeRFC7540 // maxID is the maximum stream id in nodes. maxID uint32 @@ -239,7 +239,7 @@ type priorityWriteScheduler struct { // lists of nodes that have been closed or are idle, but are kept in // the tree for improved prioritization. When the lengths exceed either // maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded. - closedNodes, idleNodes []*priorityNode + closedNodes, idleNodes []*priorityNodeRFC7540 // From the config. maxClosedNodesInTree int @@ -248,19 +248,19 @@ type priorityWriteScheduler struct { enableWriteThrottle bool // tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations. - tmp []*priorityNode + tmp []*priorityNodeRFC7540 // pool of empty queues for reuse. queuePool writeQueuePool } -func (ws *priorityWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { +func (ws *priorityWriteSchedulerRFC7540) OpenStream(streamID uint32, options OpenStreamOptions) { // The stream may be currently idle but cannot be opened or closed. if curr := ws.nodes[streamID]; curr != nil { - if curr.state != priorityNodeIdle { + if curr.state != priorityNodeIdleRFC7540 { panic(fmt.Sprintf("stream %d already opened", streamID)) } - curr.state = priorityNodeOpen + curr.state = priorityNodeOpenRFC7540 return } @@ -272,11 +272,11 @@ func (ws *priorityWriteScheduler) OpenStream(streamID uint32, options OpenStream if parent == nil { parent = &ws.root } - n := &priorityNode{ + n := &priorityNodeRFC7540{ q: *ws.queuePool.get(), id: streamID, - weight: priorityDefaultWeight, - state: priorityNodeOpen, + weight: priorityDefaultWeightRFC7540, + state: priorityNodeOpenRFC7540, } n.setParent(parent) ws.nodes[streamID] = n @@ -285,19 +285,19 @@ func (ws *priorityWriteScheduler) OpenStream(streamID uint32, options OpenStream } } -func (ws *priorityWriteScheduler) CloseStream(streamID uint32) { +func (ws *priorityWriteSchedulerRFC7540) CloseStream(streamID uint32) { if streamID == 0 { panic("violation of WriteScheduler interface: cannot close stream 0") } if ws.nodes[streamID] == nil { panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID)) } - if ws.nodes[streamID].state != priorityNodeOpen { + if ws.nodes[streamID].state != priorityNodeOpenRFC7540 { panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID)) } n := ws.nodes[streamID] - n.state = priorityNodeClosed + n.state = priorityNodeClosedRFC7540 n.addBytes(-n.bytes) q := n.q @@ -310,7 +310,7 @@ func (ws *priorityWriteScheduler) CloseStream(streamID uint32) { } } -func (ws *priorityWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) { +func (ws *priorityWriteSchedulerRFC7540) AdjustStream(streamID uint32, priority PriorityParam) { if streamID == 0 { panic("adjustPriority on root") } @@ -324,11 +324,11 @@ func (ws *priorityWriteScheduler) AdjustStream(streamID uint32, priority Priorit return } ws.maxID = streamID - n = &priorityNode{ + n = &priorityNodeRFC7540{ q: *ws.queuePool.get(), id: streamID, - weight: priorityDefaultWeight, - state: priorityNodeIdle, + weight: priorityDefaultWeightRFC7540, + state: priorityNodeIdleRFC7540, } n.setParent(&ws.root) ws.nodes[streamID] = n @@ -340,7 +340,7 @@ func (ws *priorityWriteScheduler) AdjustStream(streamID uint32, priority Priorit parent := ws.nodes[priority.StreamDep] if parent == nil { n.setParent(&ws.root) - n.weight = priorityDefaultWeight + n.weight = priorityDefaultWeightRFC7540 return } @@ -381,8 +381,8 @@ func (ws *priorityWriteScheduler) AdjustStream(streamID uint32, priority Priorit n.weight = priority.Weight } -func (ws *priorityWriteScheduler) Push(wr FrameWriteRequest) { - var n *priorityNode +func (ws *priorityWriteSchedulerRFC7540) Push(wr FrameWriteRequest) { + var n *priorityNodeRFC7540 if wr.isControl() { n = &ws.root } else { @@ -401,8 +401,8 @@ func (ws *priorityWriteScheduler) Push(wr FrameWriteRequest) { n.q.push(wr) } -func (ws *priorityWriteScheduler) Pop() (wr FrameWriteRequest, ok bool) { - ws.root.walkReadyInOrder(false, &ws.tmp, func(n *priorityNode, openParent bool) bool { +func (ws *priorityWriteSchedulerRFC7540) Pop() (wr FrameWriteRequest, ok bool) { + ws.root.walkReadyInOrder(false, &ws.tmp, func(n *priorityNodeRFC7540, openParent bool) bool { limit := int32(math.MaxInt32) if openParent { limit = ws.writeThrottleLimit @@ -428,7 +428,7 @@ func (ws *priorityWriteScheduler) Pop() (wr FrameWriteRequest, ok bool) { return wr, ok } -func (ws *priorityWriteScheduler) addClosedOrIdleNode(list *[]*priorityNode, maxSize int, n *priorityNode) { +func (ws *priorityWriteSchedulerRFC7540) addClosedOrIdleNode(list *[]*priorityNodeRFC7540, maxSize int, n *priorityNodeRFC7540) { if maxSize == 0 { return } @@ -442,7 +442,7 @@ func (ws *priorityWriteScheduler) addClosedOrIdleNode(list *[]*priorityNode, max *list = append(*list, n) } -func (ws *priorityWriteScheduler) removeNode(n *priorityNode) { +func (ws *priorityWriteSchedulerRFC7540) removeNode(n *priorityNodeRFC7540) { for n.kids != nil { n.kids.setParent(n.parent) } diff --git a/vendor/golang.org/x/net/http2/writesched_priority_rfc9128.go b/vendor/golang.org/x/net/http2/writesched_priority_rfc9128.go new file mode 100644 index 0000000..9b5b880 --- /dev/null +++ b/vendor/golang.org/x/net/http2/writesched_priority_rfc9128.go @@ -0,0 +1,209 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package http2 + +import ( + "fmt" + "math" +) + +type streamMetadata struct { + location *writeQueue + priority PriorityParam +} + +type priorityWriteSchedulerRFC9218 struct { + // control contains control frames (SETTINGS, PING, etc.). + control writeQueue + + // heads contain the head of a circular list of streams. + // We put these heads within a nested array that represents urgency and + // incremental, as defined in + // https://www.rfc-editor.org/rfc/rfc9218.html#name-priority-parameters. + // 8 represents u=0 up to u=7, and 2 represents i=false and i=true. + heads [8][2]*writeQueue + + // streams contains a mapping between each stream ID and their metadata, so + // we can quickly locate them when needing to, for example, adjust their + // priority. + streams map[uint32]streamMetadata + + // queuePool are empty queues for reuse. + queuePool writeQueuePool + + // prioritizeIncremental is used to determine whether we should prioritize + // incremental streams or not, when urgency is the same in a given Pop() + // call. + prioritizeIncremental bool +} + +func newPriorityWriteSchedulerRFC9128() WriteScheduler { + ws := &priorityWriteSchedulerRFC9218{ + streams: make(map[uint32]streamMetadata), + } + return ws +} + +func (ws *priorityWriteSchedulerRFC9218) OpenStream(streamID uint32, opt OpenStreamOptions) { + if ws.streams[streamID].location != nil { + panic(fmt.Errorf("stream %d already opened", streamID)) + } + q := ws.queuePool.get() + ws.streams[streamID] = streamMetadata{ + location: q, + priority: opt.priority, + } + + u, i := opt.priority.urgency, opt.priority.incremental + if ws.heads[u][i] == nil { + ws.heads[u][i] = q + q.next = q + q.prev = q + } else { + // Queues are stored in a ring. + // Insert the new stream before ws.head, putting it at the end of the list. + q.prev = ws.heads[u][i].prev + q.next = ws.heads[u][i] + q.prev.next = q + q.next.prev = q + } +} + +func (ws *priorityWriteSchedulerRFC9218) CloseStream(streamID uint32) { + metadata := ws.streams[streamID] + q, u, i := metadata.location, metadata.priority.urgency, metadata.priority.incremental + if q == nil { + return + } + if q.next == q { + // This was the only open stream. + ws.heads[u][i] = nil + } else { + q.prev.next = q.next + q.next.prev = q.prev + if ws.heads[u][i] == q { + ws.heads[u][i] = q.next + } + } + delete(ws.streams, streamID) + ws.queuePool.put(q) +} + +func (ws *priorityWriteSchedulerRFC9218) AdjustStream(streamID uint32, priority PriorityParam) { + metadata := ws.streams[streamID] + q, u, i := metadata.location, metadata.priority.urgency, metadata.priority.incremental + if q == nil { + return + } + + // Remove stream from current location. + if q.next == q { + // This was the only open stream. + ws.heads[u][i] = nil + } else { + q.prev.next = q.next + q.next.prev = q.prev + if ws.heads[u][i] == q { + ws.heads[u][i] = q.next + } + } + + // Insert stream to the new queue. + u, i = priority.urgency, priority.incremental + if ws.heads[u][i] == nil { + ws.heads[u][i] = q + q.next = q + q.prev = q + } else { + // Queues are stored in a ring. + // Insert the new stream before ws.head, putting it at the end of the list. + q.prev = ws.heads[u][i].prev + q.next = ws.heads[u][i] + q.prev.next = q + q.next.prev = q + } + + // Update the metadata. + ws.streams[streamID] = streamMetadata{ + location: q, + priority: priority, + } +} + +func (ws *priorityWriteSchedulerRFC9218) Push(wr FrameWriteRequest) { + if wr.isControl() { + ws.control.push(wr) + return + } + q := ws.streams[wr.StreamID()].location + if q == nil { + // This is a closed stream. + // wr should not be a HEADERS or DATA frame. + // We push the request onto the control queue. + if wr.DataSize() > 0 { + panic("add DATA on non-open stream") + } + ws.control.push(wr) + return + } + q.push(wr) +} + +func (ws *priorityWriteSchedulerRFC9218) Pop() (FrameWriteRequest, bool) { + // Control and RST_STREAM frames first. + if !ws.control.empty() { + return ws.control.shift(), true + } + + // On the next Pop(), we want to prioritize incremental if we prioritized + // non-incremental request of the same urgency this time. Vice-versa. + // i.e. when there are incremental and non-incremental requests at the same + // priority, we give 50% of our bandwidth to the incremental ones in + // aggregate and 50% to the first non-incremental one (since + // non-incremental streams do not use round-robin writes). + ws.prioritizeIncremental = !ws.prioritizeIncremental + + // Always prioritize lowest u (i.e. highest urgency level). + for u := range ws.heads { + for i := range ws.heads[u] { + // When we want to prioritize incremental, we try to pop i=true + // first before i=false when u is the same. + if ws.prioritizeIncremental { + i = (i + 1) % 2 + } + q := ws.heads[u][i] + if q == nil { + continue + } + for { + if wr, ok := q.consume(math.MaxInt32); ok { + if i == 1 { + // For incremental streams, we update head to q.next so + // we can round-robin between multiple streams that can + // immediately benefit from partial writes. + ws.heads[u][i] = q.next + } else { + // For non-incremental streams, we try to finish one to + // completion rather than doing round-robin. However, + // we update head here so that if q.consume() is !ok + // (e.g. the stream has no more frame to consume), head + // is updated to the next q that has frames to consume + // on future iterations. This way, we do not prioritize + // writing to unavailable stream on next Pop() calls, + // preventing head-of-line blocking. + ws.heads[u][i] = q + } + return wr, true + } + q = q.next + if q == ws.heads[u][i] { + break + } + } + + } + } + return FrameWriteRequest{}, false +} diff --git a/vendor/golang.org/x/net/http2/writesched_roundrobin.go b/vendor/golang.org/x/net/http2/writesched_roundrobin.go index 54fe863..737cff9 100644 --- a/vendor/golang.org/x/net/http2/writesched_roundrobin.go +++ b/vendor/golang.org/x/net/http2/writesched_roundrobin.go @@ -25,7 +25,7 @@ type roundRobinWriteScheduler struct { } // newRoundRobinWriteScheduler constructs a new write scheduler. -// The round robin scheduler priorizes control frames +// The round robin scheduler prioritizes control frames // like SETTINGS and PING over DATA frames. // When there are no control frames to send, it performs a round-robin // selection from the ready streams. diff --git a/vendor/golang.org/x/net/internal/httpcommon/request.go b/vendor/golang.org/x/net/internal/httpcommon/request.go index 4b70553..1e10f89 100644 --- a/vendor/golang.org/x/net/internal/httpcommon/request.go +++ b/vendor/golang.org/x/net/internal/httpcommon/request.go @@ -51,7 +51,7 @@ type EncodeHeadersParam struct { DefaultUserAgent string } -// EncodeHeadersParam is the result of EncodeHeaders. +// EncodeHeadersResult is the result of EncodeHeaders. type EncodeHeadersResult struct { HasBody bool HasTrailers bool @@ -399,7 +399,7 @@ type ServerRequestResult struct { // If the request should be rejected, this is a short string suitable for passing // to the http2 package's CountError function. - // It might be a bit odd to return errors this way rather than returing an error, + // It might be a bit odd to return errors this way rather than returning an error, // but this ensures we don't forget to include a CountError reason. InvalidReason string } diff --git a/vendor/golang.org/x/sys/unix/affinity_linux.go b/vendor/golang.org/x/sys/unix/affinity_linux.go index 3c7a6d6..3ea4703 100644 --- a/vendor/golang.org/x/sys/unix/affinity_linux.go +++ b/vendor/golang.org/x/sys/unix/affinity_linux.go @@ -41,6 +41,15 @@ func (s *CPUSet) Zero() { clear(s[:]) } +// Fill adds all possible CPU bits to the set s. On Linux, [SchedSetaffinity] +// will silently ignore any invalid CPU bits in [CPUSet] so this is an +// efficient way of resetting the CPU affinity of a process. +func (s *CPUSet) Fill() { + for i := range s { + s[i] = ^cpuMask(0) + } +} + func cpuBitsIndex(cpu int) int { return cpu / _NCPUBITS } diff --git a/vendor/golang.org/x/sys/unix/fdset.go b/vendor/golang.org/x/sys/unix/fdset.go index 9e83d18..62ed126 100644 --- a/vendor/golang.org/x/sys/unix/fdset.go +++ b/vendor/golang.org/x/sys/unix/fdset.go @@ -23,7 +23,5 @@ func (fds *FdSet) IsSet(fd int) bool { // Zero clears the set fds. func (fds *FdSet) Zero() { - for i := range fds.Bits { - fds.Bits[i] = 0 - } + clear(fds.Bits[:]) } diff --git a/vendor/golang.org/x/sys/unix/ifreq_linux.go b/vendor/golang.org/x/sys/unix/ifreq_linux.go index 848840a..309f5a2 100644 --- a/vendor/golang.org/x/sys/unix/ifreq_linux.go +++ b/vendor/golang.org/x/sys/unix/ifreq_linux.go @@ -111,9 +111,7 @@ func (ifr *Ifreq) SetUint32(v uint32) { // clear zeroes the ifreq's union field to prevent trailing garbage data from // being sent to the kernel if an ifreq is reused. func (ifr *Ifreq) clear() { - for i := range ifr.raw.Ifru { - ifr.raw.Ifru[i] = 0 - } + clear(ifr.raw.Ifru[:]) } // TODO(mdlayher): export as IfreqData? For now we can provide helpers such as diff --git a/vendor/golang.org/x/sys/unix/mkall.sh b/vendor/golang.org/x/sys/unix/mkall.sh index e6f31d3..d0ed611 100644 --- a/vendor/golang.org/x/sys/unix/mkall.sh +++ b/vendor/golang.org/x/sys/unix/mkall.sh @@ -49,6 +49,7 @@ esac if [[ "$GOOS" = "linux" ]]; then # Use the Docker-based build system # Files generated through docker (use $cmd so you can Ctl-C the build or run) + set -e $cmd docker build --tag generate:$GOOS $GOOS $cmd docker run --interactive --tty --volume $(cd -- "$(dirname -- "$0")/.." && pwd):/build generate:$GOOS exit diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 4958a65..9439af9 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -801,9 +801,7 @@ func (sa *SockaddrPPPoE) sockaddr() (unsafe.Pointer, _Socklen, error) { // one. The kernel expects SID to be in network byte order. binary.BigEndian.PutUint16(sa.raw[6:8], sa.SID) copy(sa.raw[8:14], sa.Remote) - for i := 14; i < 14+IFNAMSIZ; i++ { - sa.raw[i] = 0 - } + clear(sa.raw[14 : 14+IFNAMSIZ]) copy(sa.raw[14:], sa.Dev) return unsafe.Pointer(&sa.raw), SizeofSockaddrPPPoX, nil } diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go index 8816209..34a4676 100644 --- a/vendor/golang.org/x/sys/unix/syscall_netbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_netbsd.go @@ -248,6 +248,23 @@ func Statvfs(path string, buf *Statvfs_t) (err error) { return Statvfs1(path, buf, ST_WAIT) } +func Getvfsstat(buf []Statvfs_t, flags int) (n int, err error) { + var ( + _p0 unsafe.Pointer + bufsize uintptr + ) + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + bufsize = unsafe.Sizeof(Statvfs_t{}) * uintptr(len(buf)) + } + r0, _, e1 := Syscall(SYS_GETVFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} + /* * Exposed directly */ diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index 640f6b1..bd51337 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -321,6 +321,8 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys SetConsoleOutputCP(cp uint32) (err error) = kernel32.SetConsoleOutputCP //sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW //sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW +//sys GetNumberOfConsoleInputEvents(console Handle, numevents *uint32) (err error) = kernel32.GetNumberOfConsoleInputEvents +//sys FlushConsoleInputBuffer(console Handle) (err error) = kernel32.FlushConsoleInputBuffer //sys resizePseudoConsole(pconsole Handle, size uint32) (hr error) = kernel32.ResizePseudoConsole //sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot //sys Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32FirstW diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index 993a229..358be3c 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -65,6 +65,22 @@ var signals = [...]string{ 15: "terminated", } +// File flags for [os.OpenFile]. The O_ prefix is used to indicate +// that these flags are specific to the OpenFile function. +const ( + O_FILE_FLAG_OPEN_NO_RECALL = FILE_FLAG_OPEN_NO_RECALL + O_FILE_FLAG_OPEN_REPARSE_POINT = FILE_FLAG_OPEN_REPARSE_POINT + O_FILE_FLAG_SESSION_AWARE = FILE_FLAG_SESSION_AWARE + O_FILE_FLAG_POSIX_SEMANTICS = FILE_FLAG_POSIX_SEMANTICS + O_FILE_FLAG_BACKUP_SEMANTICS = FILE_FLAG_BACKUP_SEMANTICS + O_FILE_FLAG_DELETE_ON_CLOSE = FILE_FLAG_DELETE_ON_CLOSE + O_FILE_FLAG_SEQUENTIAL_SCAN = FILE_FLAG_SEQUENTIAL_SCAN + O_FILE_FLAG_RANDOM_ACCESS = FILE_FLAG_RANDOM_ACCESS + O_FILE_FLAG_NO_BUFFERING = FILE_FLAG_NO_BUFFERING + O_FILE_FLAG_OVERLAPPED = FILE_FLAG_OVERLAPPED + O_FILE_FLAG_WRITE_THROUGH = FILE_FLAG_WRITE_THROUGH +) + const ( FILE_READ_DATA = 0x00000001 FILE_READ_ATTRIBUTES = 0x00000080 diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go index 641a5f4..426151a 100644 --- a/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -238,6 +238,7 @@ var ( procFindResourceW = modkernel32.NewProc("FindResourceW") procFindVolumeClose = modkernel32.NewProc("FindVolumeClose") procFindVolumeMountPointClose = modkernel32.NewProc("FindVolumeMountPointClose") + procFlushConsoleInputBuffer = modkernel32.NewProc("FlushConsoleInputBuffer") procFlushFileBuffers = modkernel32.NewProc("FlushFileBuffers") procFlushViewOfFile = modkernel32.NewProc("FlushViewOfFile") procFormatMessageW = modkernel32.NewProc("FormatMessageW") @@ -284,6 +285,7 @@ var ( procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") procGetNamedPipeServerProcessId = modkernel32.NewProc("GetNamedPipeServerProcessId") + procGetNumberOfConsoleInputEvents = modkernel32.NewProc("GetNumberOfConsoleInputEvents") procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult") procGetPriorityClass = modkernel32.NewProc("GetPriorityClass") procGetProcAddress = modkernel32.NewProc("GetProcAddress") @@ -2111,6 +2113,14 @@ func FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error) { return } +func FlushConsoleInputBuffer(console Handle) (err error) { + r1, _, e1 := syscall.SyscallN(procFlushConsoleInputBuffer.Addr(), uintptr(console)) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func FlushFileBuffers(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procFlushFileBuffers.Addr(), uintptr(handle)) if r1 == 0 { @@ -2481,6 +2491,14 @@ func GetNamedPipeServerProcessId(pipe Handle, serverProcessID *uint32) (err erro return } +func GetNumberOfConsoleInputEvents(console Handle, numevents *uint32) (err error) { + r1, _, e1 := syscall.SyscallN(procGetNumberOfConsoleInputEvents.Addr(), uintptr(console), uintptr(unsafe.Pointer(numevents))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error) { var _p0 uint32 if wait { diff --git a/vendor/golang.org/x/text/unicode/bidi/core.go b/vendor/golang.org/x/text/unicode/bidi/core.go index 9d2ae54..fb82732 100644 --- a/vendor/golang.org/x/text/unicode/bidi/core.go +++ b/vendor/golang.org/x/text/unicode/bidi/core.go @@ -427,13 +427,6 @@ type isolatingRunSequence struct { func (i *isolatingRunSequence) Len() int { return len(i.indexes) } -func maxLevel(a, b level) level { - if a > b { - return a - } - return b -} - // Rule X10, second bullet: Determine the start-of-sequence (sos) and end-of-sequence (eos) types, // either L or R, for each isolating run sequence. func (p *paragraph) isolatingRunSequence(indexes []int) *isolatingRunSequence { @@ -474,8 +467,8 @@ func (p *paragraph) isolatingRunSequence(indexes []int) *isolatingRunSequence { indexes: indexes, types: types, level: level, - sos: typeForLevel(maxLevel(prevLevel, level)), - eos: typeForLevel(maxLevel(succLevel, level)), + sos: typeForLevel(max(prevLevel, level)), + eos: typeForLevel(max(succLevel, level)), } } diff --git a/vendor/golang.org/x/time/rate/rate.go b/vendor/golang.org/x/time/rate/rate.go index 794b2e3..563270c 100644 --- a/vendor/golang.org/x/time/rate/rate.go +++ b/vendor/golang.org/x/time/rate/rate.go @@ -195,7 +195,7 @@ func (r *Reservation) CancelAt(t time.Time) { // update state r.lim.last = t r.lim.tokens = tokens - if r.timeToAct == r.lim.lastEvent { + if r.timeToAct.Equal(r.lim.lastEvent) { prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens))) if !prevEvent.Before(t) { r.lim.lastEvent = prevEvent diff --git a/vendor/golang.org/x/time/rate/sometimes.go b/vendor/golang.org/x/time/rate/sometimes.go index 6ba99dd..9b83932 100644 --- a/vendor/golang.org/x/time/rate/sometimes.go +++ b/vendor/golang.org/x/time/rate/sometimes.go @@ -61,7 +61,9 @@ func (s *Sometimes) Do(f func()) { (s.Every > 0 && s.count%s.Every == 0) || (s.Interval > 0 && time.Since(s.last) >= s.Interval) { f() - s.last = time.Now() + if s.Interval > 0 { + s.last = time.Now() + } } s.count++ } diff --git a/vendor/golang.org/x/tools/go/ast/edge/edge.go b/vendor/golang.org/x/tools/go/ast/edge/edge.go new file mode 100644 index 0000000..4f6ccfd --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/edge/edge.go @@ -0,0 +1,295 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package edge defines identifiers for each field of an ast.Node +// struct type that refers to another Node. +package edge + +import ( + "fmt" + "go/ast" + "reflect" +) + +// A Kind describes a field of an ast.Node struct. +type Kind uint8 + +// String returns a description of the edge kind. +func (k Kind) String() string { + if k == Invalid { + return "<invalid>" + } + info := fieldInfos[k] + return fmt.Sprintf("%v.%s", info.nodeType.Elem().Name(), info.name) +} + +// NodeType returns the pointer-to-struct type of the ast.Node implementation. +func (k Kind) NodeType() reflect.Type { return fieldInfos[k].nodeType } + +// FieldName returns the name of the field. +func (k Kind) FieldName() string { return fieldInfos[k].name } + +// FieldType returns the declared type of the field. +func (k Kind) FieldType() reflect.Type { return fieldInfos[k].fieldType } + +// Get returns the direct child of n identified by (k, idx). +// n's type must match k.NodeType(). +// idx must be a valid slice index, or -1 for a non-slice. +func (k Kind) Get(n ast.Node, idx int) ast.Node { + if k.NodeType() != reflect.TypeOf(n) { + panic(fmt.Sprintf("%v.Get(%T): invalid node type", k, n)) + } + v := reflect.ValueOf(n).Elem().Field(fieldInfos[k].index) + if idx != -1 { + v = v.Index(idx) // asserts valid index + } else { + // (The type assertion below asserts that v is not a slice.) + } + return v.Interface().(ast.Node) // may be nil +} + +const ( + Invalid Kind = iota // for nodes at the root of the traversal + + // Kinds are sorted alphabetically. + // Numbering is not stable. + // Each is named Type_Field, where Type is the + // ast.Node struct type and Field is the name of the field + + ArrayType_Elt + ArrayType_Len + AssignStmt_Lhs + AssignStmt_Rhs + BinaryExpr_X + BinaryExpr_Y + BlockStmt_List + BranchStmt_Label + CallExpr_Args + CallExpr_Fun + CaseClause_Body + CaseClause_List + ChanType_Value + CommClause_Body + CommClause_Comm + CommentGroup_List + CompositeLit_Elts + CompositeLit_Type + DeclStmt_Decl + DeferStmt_Call + Ellipsis_Elt + ExprStmt_X + FieldList_List + Field_Comment + Field_Doc + Field_Names + Field_Tag + Field_Type + File_Decls + File_Doc + File_Name + ForStmt_Body + ForStmt_Cond + ForStmt_Init + ForStmt_Post + FuncDecl_Body + FuncDecl_Doc + FuncDecl_Name + FuncDecl_Recv + FuncDecl_Type + FuncLit_Body + FuncLit_Type + FuncType_Params + FuncType_Results + FuncType_TypeParams + GenDecl_Doc + GenDecl_Specs + GoStmt_Call + IfStmt_Body + IfStmt_Cond + IfStmt_Else + IfStmt_Init + ImportSpec_Comment + ImportSpec_Doc + ImportSpec_Name + ImportSpec_Path + IncDecStmt_X + IndexExpr_Index + IndexExpr_X + IndexListExpr_Indices + IndexListExpr_X + InterfaceType_Methods + KeyValueExpr_Key + KeyValueExpr_Value + LabeledStmt_Label + LabeledStmt_Stmt + MapType_Key + MapType_Value + ParenExpr_X + RangeStmt_Body + RangeStmt_Key + RangeStmt_Value + RangeStmt_X + ReturnStmt_Results + SelectStmt_Body + SelectorExpr_Sel + SelectorExpr_X + SendStmt_Chan + SendStmt_Value + SliceExpr_High + SliceExpr_Low + SliceExpr_Max + SliceExpr_X + StarExpr_X + StructType_Fields + SwitchStmt_Body + SwitchStmt_Init + SwitchStmt_Tag + TypeAssertExpr_Type + TypeAssertExpr_X + TypeSpec_Comment + TypeSpec_Doc + TypeSpec_Name + TypeSpec_Type + TypeSpec_TypeParams + TypeSwitchStmt_Assign + TypeSwitchStmt_Body + TypeSwitchStmt_Init + UnaryExpr_X + ValueSpec_Comment + ValueSpec_Doc + ValueSpec_Names + ValueSpec_Type + ValueSpec_Values + + maxKind +) + +// Assert that the encoding fits in 7 bits, +// as the inspector relies on this. +// (We are currently at 104.) +var _ = [1 << 7]struct{}{}[maxKind] + +type fieldInfo struct { + nodeType reflect.Type // pointer-to-struct type of ast.Node implementation + name string + index int + fieldType reflect.Type +} + +func info[N ast.Node](fieldName string) fieldInfo { + nodePtrType := reflect.TypeFor[N]() + f, ok := nodePtrType.Elem().FieldByName(fieldName) + if !ok { + panic(fieldName) + } + return fieldInfo{nodePtrType, fieldName, f.Index[0], f.Type} +} + +var fieldInfos = [...]fieldInfo{ + Invalid: {}, + ArrayType_Elt: info[*ast.ArrayType]("Elt"), + ArrayType_Len: info[*ast.ArrayType]("Len"), + AssignStmt_Lhs: info[*ast.AssignStmt]("Lhs"), + AssignStmt_Rhs: info[*ast.AssignStmt]("Rhs"), + BinaryExpr_X: info[*ast.BinaryExpr]("X"), + BinaryExpr_Y: info[*ast.BinaryExpr]("Y"), + BlockStmt_List: info[*ast.BlockStmt]("List"), + BranchStmt_Label: info[*ast.BranchStmt]("Label"), + CallExpr_Args: info[*ast.CallExpr]("Args"), + CallExpr_Fun: info[*ast.CallExpr]("Fun"), + CaseClause_Body: info[*ast.CaseClause]("Body"), + CaseClause_List: info[*ast.CaseClause]("List"), + ChanType_Value: info[*ast.ChanType]("Value"), + CommClause_Body: info[*ast.CommClause]("Body"), + CommClause_Comm: info[*ast.CommClause]("Comm"), + CommentGroup_List: info[*ast.CommentGroup]("List"), + CompositeLit_Elts: info[*ast.CompositeLit]("Elts"), + CompositeLit_Type: info[*ast.CompositeLit]("Type"), + DeclStmt_Decl: info[*ast.DeclStmt]("Decl"), + DeferStmt_Call: info[*ast.DeferStmt]("Call"), + Ellipsis_Elt: info[*ast.Ellipsis]("Elt"), + ExprStmt_X: info[*ast.ExprStmt]("X"), + FieldList_List: info[*ast.FieldList]("List"), + Field_Comment: info[*ast.Field]("Comment"), + Field_Doc: info[*ast.Field]("Doc"), + Field_Names: info[*ast.Field]("Names"), + Field_Tag: info[*ast.Field]("Tag"), + Field_Type: info[*ast.Field]("Type"), + File_Decls: info[*ast.File]("Decls"), + File_Doc: info[*ast.File]("Doc"), + File_Name: info[*ast.File]("Name"), + ForStmt_Body: info[*ast.ForStmt]("Body"), + ForStmt_Cond: info[*ast.ForStmt]("Cond"), + ForStmt_Init: info[*ast.ForStmt]("Init"), + ForStmt_Post: info[*ast.ForStmt]("Post"), + FuncDecl_Body: info[*ast.FuncDecl]("Body"), + FuncDecl_Doc: info[*ast.FuncDecl]("Doc"), + FuncDecl_Name: info[*ast.FuncDecl]("Name"), + FuncDecl_Recv: info[*ast.FuncDecl]("Recv"), + FuncDecl_Type: info[*ast.FuncDecl]("Type"), + FuncLit_Body: info[*ast.FuncLit]("Body"), + FuncLit_Type: info[*ast.FuncLit]("Type"), + FuncType_Params: info[*ast.FuncType]("Params"), + FuncType_Results: info[*ast.FuncType]("Results"), + FuncType_TypeParams: info[*ast.FuncType]("TypeParams"), + GenDecl_Doc: info[*ast.GenDecl]("Doc"), + GenDecl_Specs: info[*ast.GenDecl]("Specs"), + GoStmt_Call: info[*ast.GoStmt]("Call"), + IfStmt_Body: info[*ast.IfStmt]("Body"), + IfStmt_Cond: info[*ast.IfStmt]("Cond"), + IfStmt_Else: info[*ast.IfStmt]("Else"), + IfStmt_Init: info[*ast.IfStmt]("Init"), + ImportSpec_Comment: info[*ast.ImportSpec]("Comment"), + ImportSpec_Doc: info[*ast.ImportSpec]("Doc"), + ImportSpec_Name: info[*ast.ImportSpec]("Name"), + ImportSpec_Path: info[*ast.ImportSpec]("Path"), + IncDecStmt_X: info[*ast.IncDecStmt]("X"), + IndexExpr_Index: info[*ast.IndexExpr]("Index"), + IndexExpr_X: info[*ast.IndexExpr]("X"), + IndexListExpr_Indices: info[*ast.IndexListExpr]("Indices"), + IndexListExpr_X: info[*ast.IndexListExpr]("X"), + InterfaceType_Methods: info[*ast.InterfaceType]("Methods"), + KeyValueExpr_Key: info[*ast.KeyValueExpr]("Key"), + KeyValueExpr_Value: info[*ast.KeyValueExpr]("Value"), + LabeledStmt_Label: info[*ast.LabeledStmt]("Label"), + LabeledStmt_Stmt: info[*ast.LabeledStmt]("Stmt"), + MapType_Key: info[*ast.MapType]("Key"), + MapType_Value: info[*ast.MapType]("Value"), + ParenExpr_X: info[*ast.ParenExpr]("X"), + RangeStmt_Body: info[*ast.RangeStmt]("Body"), + RangeStmt_Key: info[*ast.RangeStmt]("Key"), + RangeStmt_Value: info[*ast.RangeStmt]("Value"), + RangeStmt_X: info[*ast.RangeStmt]("X"), + ReturnStmt_Results: info[*ast.ReturnStmt]("Results"), + SelectStmt_Body: info[*ast.SelectStmt]("Body"), + SelectorExpr_Sel: info[*ast.SelectorExpr]("Sel"), + SelectorExpr_X: info[*ast.SelectorExpr]("X"), + SendStmt_Chan: info[*ast.SendStmt]("Chan"), + SendStmt_Value: info[*ast.SendStmt]("Value"), + SliceExpr_High: info[*ast.SliceExpr]("High"), + SliceExpr_Low: info[*ast.SliceExpr]("Low"), + SliceExpr_Max: info[*ast.SliceExpr]("Max"), + SliceExpr_X: info[*ast.SliceExpr]("X"), + StarExpr_X: info[*ast.StarExpr]("X"), + StructType_Fields: info[*ast.StructType]("Fields"), + SwitchStmt_Body: info[*ast.SwitchStmt]("Body"), + SwitchStmt_Init: info[*ast.SwitchStmt]("Init"), + SwitchStmt_Tag: info[*ast.SwitchStmt]("Tag"), + TypeAssertExpr_Type: info[*ast.TypeAssertExpr]("Type"), + TypeAssertExpr_X: info[*ast.TypeAssertExpr]("X"), + TypeSpec_Comment: info[*ast.TypeSpec]("Comment"), + TypeSpec_Doc: info[*ast.TypeSpec]("Doc"), + TypeSpec_Name: info[*ast.TypeSpec]("Name"), + TypeSpec_Type: info[*ast.TypeSpec]("Type"), + TypeSpec_TypeParams: info[*ast.TypeSpec]("TypeParams"), + TypeSwitchStmt_Assign: info[*ast.TypeSwitchStmt]("Assign"), + TypeSwitchStmt_Body: info[*ast.TypeSwitchStmt]("Body"), + TypeSwitchStmt_Init: info[*ast.TypeSwitchStmt]("Init"), + UnaryExpr_X: info[*ast.UnaryExpr]("X"), + ValueSpec_Comment: info[*ast.ValueSpec]("Comment"), + ValueSpec_Doc: info[*ast.ValueSpec]("Doc"), + ValueSpec_Names: info[*ast.ValueSpec]("Names"), + ValueSpec_Type: info[*ast.ValueSpec]("Type"), + ValueSpec_Values: info[*ast.ValueSpec]("Values"), +} diff --git a/vendor/golang.org/x/tools/go/ast/inspector/cursor.go b/vendor/golang.org/x/tools/go/ast/inspector/cursor.go new file mode 100644 index 0000000..7e72d3c --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/inspector/cursor.go @@ -0,0 +1,502 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package inspector + +import ( + "fmt" + "go/ast" + "go/token" + "iter" + "reflect" + + "golang.org/x/tools/go/ast/edge" +) + +// A Cursor represents an [ast.Node]. It is immutable. +// +// Two Cursors compare equal if they represent the same node. +// +// Call [Inspector.Root] to obtain a valid cursor for the virtual root +// node of the traversal. +// +// Use the following methods to navigate efficiently around the tree: +// - for ancestors, use [Cursor.Parent] and [Cursor.Enclosing]; +// - for children, use [Cursor.Child], [Cursor.Children], +// [Cursor.FirstChild], and [Cursor.LastChild]; +// - for siblings, use [Cursor.PrevSibling] and [Cursor.NextSibling]; +// - for descendants, use [Cursor.FindByPos], [Cursor.FindNode], +// [Cursor.Inspect], and [Cursor.Preorder]. +// +// Use the [Cursor.ChildAt] and [Cursor.ParentEdge] methods for +// information about the edges in a tree: which field (and slice +// element) of the parent node holds the child. +type Cursor struct { + in *Inspector + index int32 // index of push node; -1 for virtual root node +} + +// Root returns a cursor for the virtual root node, +// whose children are the files provided to [New]. +// +// Its [Cursor.Node] method return nil. +func (in *Inspector) Root() Cursor { + return Cursor{in, -1} +} + +// At returns the cursor at the specified index in the traversal, +// which must have been obtained from [Cursor.Index] on a Cursor +// belonging to the same Inspector (see [Cursor.Inspector]). +func (in *Inspector) At(index int32) Cursor { + if index < 0 { + panic("negative index") + } + if int(index) >= len(in.events) { + panic("index out of range for this inspector") + } + if in.events[index].index < index { + panic("invalid index") // (a push, not a pop) + } + return Cursor{in, index} +} + +// Inspector returns the cursor's Inspector. +func (c Cursor) Inspector() *Inspector { return c.in } + +// Index returns the index of this cursor position within the package. +// +// Clients should not assume anything about the numeric Index value +// except that it increases monotonically throughout the traversal. +// It is provided for use with [At]. +// +// Index must not be called on the Root node. +func (c Cursor) Index() int32 { + if c.index < 0 { + panic("Index called on Root node") + } + return c.index +} + +// Node returns the node at the current cursor position, +// or nil for the cursor returned by [Inspector.Root]. +func (c Cursor) Node() ast.Node { + if c.index < 0 { + return nil + } + return c.in.events[c.index].node +} + +// String returns information about the cursor's node, if any. +func (c Cursor) String() string { + if c.in == nil { + return "(invalid)" + } + if c.index < 0 { + return "(root)" + } + return reflect.TypeOf(c.Node()).String() +} + +// indices return the [start, end) half-open interval of event indices. +func (c Cursor) indices() (int32, int32) { + if c.index < 0 { + return 0, int32(len(c.in.events)) // root: all events + } else { + return c.index, c.in.events[c.index].index + 1 // just one subtree + } +} + +// Preorder returns an iterator over the nodes of the subtree +// represented by c in depth-first order. Each node in the sequence is +// represented by a Cursor that allows access to the Node, but may +// also be used to start a new traversal, or to obtain the stack of +// nodes enclosing the cursor. +// +// The traversal sequence is determined by [ast.Inspect]. The types +// argument, if non-empty, enables type-based filtering of events. The +// function f if is called only for nodes whose type matches an +// element of the types slice. +// +// If you need control over descent into subtrees, +// or need both pre- and post-order notifications, use [Cursor.Inspect] +func (c Cursor) Preorder(types ...ast.Node) iter.Seq[Cursor] { + mask := maskOf(types) + + return func(yield func(Cursor) bool) { + events := c.in.events + + for i, limit := c.indices(); i < limit; { + ev := events[i] + if ev.index > i { // push? + if ev.typ&mask != 0 && !yield(Cursor{c.in, i}) { + break + } + pop := ev.index + if events[pop].typ&mask == 0 { + // Subtree does not contain types: skip. + i = pop + 1 + continue + } + } + i++ + } + } +} + +// Inspect visits the nodes of the subtree represented by c in +// depth-first order. It calls f(n) for each node n before it +// visits n's children. If f returns true, Inspect invokes f +// recursively for each of the non-nil children of the node. +// +// Each node is represented by a Cursor that allows access to the +// Node, but may also be used to start a new traversal, or to obtain +// the stack of nodes enclosing the cursor. +// +// The complete traversal sequence is determined by [ast.Inspect]. +// The types argument, if non-empty, enables type-based filtering of +// events. The function f if is called only for nodes whose type +// matches an element of the types slice. +func (c Cursor) Inspect(types []ast.Node, f func(c Cursor) (descend bool)) { + mask := maskOf(types) + events := c.in.events + for i, limit := c.indices(); i < limit; { + ev := events[i] + if ev.index > i { + // push + pop := ev.index + if ev.typ&mask != 0 && !f(Cursor{c.in, i}) || + events[pop].typ&mask == 0 { + // The user opted not to descend, or the + // subtree does not contain types: + // skip past the pop. + i = pop + 1 + continue + } + } + i++ + } +} + +// Enclosing returns an iterator over the nodes enclosing the current +// current node, starting with the Cursor itself. +// +// Enclosing must not be called on the Root node (whose [Cursor.Node] returns nil). +// +// The types argument, if non-empty, enables type-based filtering of +// events: the sequence includes only enclosing nodes whose type +// matches an element of the types slice. +func (c Cursor) Enclosing(types ...ast.Node) iter.Seq[Cursor] { + if c.index < 0 { + panic("Cursor.Enclosing called on Root node") + } + + mask := maskOf(types) + + return func(yield func(Cursor) bool) { + events := c.in.events + for i := c.index; i >= 0; i = events[i].parent { + if events[i].typ&mask != 0 && !yield(Cursor{c.in, i}) { + break + } + } + } +} + +// Parent returns the parent of the current node. +// +// Parent must not be called on the Root node (whose [Cursor.Node] returns nil). +func (c Cursor) Parent() Cursor { + if c.index < 0 { + panic("Cursor.Parent called on Root node") + } + + return Cursor{c.in, c.in.events[c.index].parent} +} + +// ParentEdge returns the identity of the field in the parent node +// that holds this cursor's node, and if it is a list, the index within it. +// +// For example, f(x, y) is a CallExpr whose three children are Idents. +// f has edge kind [edge.CallExpr_Fun] and index -1. +// x and y have kind [edge.CallExpr_Args] and indices 0 and 1, respectively. +// +// If called on a child of the Root node, it returns ([edge.Invalid], -1). +// +// ParentEdge must not be called on the Root node (whose [Cursor.Node] returns nil). +func (c Cursor) ParentEdge() (edge.Kind, int) { + if c.index < 0 { + panic("Cursor.ParentEdge called on Root node") + } + events := c.in.events + pop := events[c.index].index + return unpackEdgeKindAndIndex(events[pop].parent) +} + +// ChildAt returns the cursor for the child of the +// current node identified by its edge and index. +// The index must be -1 if the edge.Kind is not a slice. +// The indicated child node must exist. +// +// ChildAt must not be called on the Root node (whose [Cursor.Node] returns nil). +// +// Invariant: c.Parent().ChildAt(c.ParentEdge()) == c. +func (c Cursor) ChildAt(k edge.Kind, idx int) Cursor { + target := packEdgeKindAndIndex(k, idx) + + // Unfortunately there's no shortcut to looping. + events := c.in.events + i := c.index + 1 + for { + pop := events[i].index + if pop < i { + break + } + if events[pop].parent == target { + return Cursor{c.in, i} + } + i = pop + 1 + } + panic(fmt.Sprintf("ChildAt(%v, %d): no such child of %v", k, idx, c)) +} + +// Child returns the cursor for n, which must be a direct child of c's Node. +// +// Child must not be called on the Root node (whose [Cursor.Node] returns nil). +func (c Cursor) Child(n ast.Node) Cursor { + if c.index < 0 { + panic("Cursor.Child called on Root node") + } + + if false { + // reference implementation + for child := range c.Children() { + if child.Node() == n { + return child + } + } + + } else { + // optimized implementation + events := c.in.events + for i := c.index + 1; events[i].index > i; i = events[i].index + 1 { + if events[i].node == n { + return Cursor{c.in, i} + } + } + } + panic(fmt.Sprintf("Child(%T): not a child of %v", n, c)) +} + +// NextSibling returns the cursor for the next sibling node in the same list +// (for example, of files, decls, specs, statements, fields, or expressions) as +// the current node. It returns (zero, false) if the node is the last node in +// the list, or is not part of a list. +// +// NextSibling must not be called on the Root node. +// +// See note at [Cursor.Children]. +func (c Cursor) NextSibling() (Cursor, bool) { + if c.index < 0 { + panic("Cursor.NextSibling called on Root node") + } + + events := c.in.events + i := events[c.index].index + 1 // after corresponding pop + if i < int32(len(events)) { + if events[i].index > i { // push? + return Cursor{c.in, i}, true + } + } + return Cursor{}, false +} + +// PrevSibling returns the cursor for the previous sibling node in the +// same list (for example, of files, decls, specs, statements, fields, +// or expressions) as the current node. It returns zero if the node is +// the first node in the list, or is not part of a list. +// +// It must not be called on the Root node. +// +// See note at [Cursor.Children]. +func (c Cursor) PrevSibling() (Cursor, bool) { + if c.index < 0 { + panic("Cursor.PrevSibling called on Root node") + } + + events := c.in.events + i := c.index - 1 + if i >= 0 { + if j := events[i].index; j < i { // pop? + return Cursor{c.in, j}, true + } + } + return Cursor{}, false +} + +// FirstChild returns the first direct child of the current node, +// or zero if it has no children. +func (c Cursor) FirstChild() (Cursor, bool) { + events := c.in.events + i := c.index + 1 // i=0 if c is root + if i < int32(len(events)) && events[i].index > i { // push? + return Cursor{c.in, i}, true + } + return Cursor{}, false +} + +// LastChild returns the last direct child of the current node, +// or zero if it has no children. +func (c Cursor) LastChild() (Cursor, bool) { + events := c.in.events + if c.index < 0 { // root? + if len(events) > 0 { + // return push of final event (a pop) + return Cursor{c.in, events[len(events)-1].index}, true + } + } else { + j := events[c.index].index - 1 // before corresponding pop + // Inv: j == c.index if c has no children + // or j is last child's pop. + if j > c.index { // c has children + return Cursor{c.in, events[j].index}, true + } + } + return Cursor{}, false +} + +// Children returns an iterator over the direct children of the +// current node, if any. +// +// When using Children, NextChild, and PrevChild, bear in mind that a +// Node's children may come from different fields, some of which may +// be lists of nodes without a distinguished intervening container +// such as [ast.BlockStmt]. +// +// For example, [ast.CaseClause] has a field List of expressions and a +// field Body of statements, so the children of a CaseClause are a mix +// of expressions and statements. Other nodes that have "uncontained" +// list fields include: +// +// - [ast.ValueSpec] (Names, Values) +// - [ast.CompositeLit] (Type, Elts) +// - [ast.IndexListExpr] (X, Indices) +// - [ast.CallExpr] (Fun, Args) +// - [ast.AssignStmt] (Lhs, Rhs) +// +// So, do not assume that the previous sibling of an ast.Stmt is also +// an ast.Stmt, or if it is, that they are executed sequentially, +// unless you have established that, say, its parent is a BlockStmt +// or its [Cursor.ParentEdge] is [edge.BlockStmt_List]. +// For example, given "for S1; ; S2 {}", the predecessor of S2 is S1, +// even though they are not executed in sequence. +func (c Cursor) Children() iter.Seq[Cursor] { + return func(yield func(Cursor) bool) { + c, ok := c.FirstChild() + for ok && yield(c) { + c, ok = c.NextSibling() + } + } +} + +// Contains reports whether c contains or is equal to c2. +// +// Both Cursors must belong to the same [Inspector]; +// neither may be its Root node. +func (c Cursor) Contains(c2 Cursor) bool { + if c.in != c2.in { + panic("different inspectors") + } + events := c.in.events + return c.index <= c2.index && events[c2.index].index <= events[c.index].index +} + +// FindNode returns the cursor for node n if it belongs to the subtree +// rooted at c. It returns zero if n is not found. +func (c Cursor) FindNode(n ast.Node) (Cursor, bool) { + + // FindNode is equivalent to this code, + // but more convenient and 15-20% faster: + if false { + for candidate := range c.Preorder(n) { + if candidate.Node() == n { + return candidate, true + } + } + return Cursor{}, false + } + + // TODO(adonovan): opt: should we assume Node.Pos is accurate + // and combine type-based filtering with position filtering + // like FindByPos? + + mask := maskOf([]ast.Node{n}) + events := c.in.events + + for i, limit := c.indices(); i < limit; i++ { + ev := events[i] + if ev.index > i { // push? + if ev.typ&mask != 0 && ev.node == n { + return Cursor{c.in, i}, true + } + pop := ev.index + if events[pop].typ&mask == 0 { + // Subtree does not contain type of n: skip. + i = pop + } + } + } + return Cursor{}, false +} + +// FindByPos returns the cursor for the innermost node n in the tree +// rooted at c such that n.Pos() <= start && end <= n.End(). +// (For an *ast.File, it uses the bounds n.FileStart-n.FileEnd.) +// +// It returns zero if none is found. +// Precondition: start <= end. +// +// See also [astutil.PathEnclosingInterval], which +// tolerates adjoining whitespace. +func (c Cursor) FindByPos(start, end token.Pos) (Cursor, bool) { + if end < start { + panic("end < start") + } + events := c.in.events + + // This algorithm could be implemented using c.Inspect, + // but it is about 2.5x slower. + + best := int32(-1) // push index of latest (=innermost) node containing range + for i, limit := c.indices(); i < limit; i++ { + ev := events[i] + if ev.index > i { // push? + n := ev.node + var nodeEnd token.Pos + if file, ok := n.(*ast.File); ok { + nodeEnd = file.FileEnd + // Note: files may be out of Pos order. + if file.FileStart > start { + i = ev.index // disjoint, after; skip to next file + continue + } + } else { + nodeEnd = n.End() + if n.Pos() > start { + break // disjoint, after; stop + } + } + // Inv: node.{Pos,FileStart} <= start + if end <= nodeEnd { + // node fully contains target range + best = i + } else if nodeEnd < start { + i = ev.index // disjoint, before; skip forward + } + } + } + if best >= 0 { + return Cursor{c.in, best}, true + } + return Cursor{}, false +} diff --git a/vendor/golang.org/x/tools/go/ast/inspector/inspector.go b/vendor/golang.org/x/tools/go/ast/inspector/inspector.go new file mode 100644 index 0000000..a703cdf --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/inspector/inspector.go @@ -0,0 +1,311 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package inspector provides helper functions for traversal over the +// syntax trees of a package, including node filtering by type, and +// materialization of the traversal stack. +// +// During construction, the inspector does a complete traversal and +// builds a list of push/pop events and their node type. Subsequent +// method calls that request a traversal scan this list, rather than walk +// the AST, and perform type filtering using efficient bit sets. +// This representation is sometimes called a "balanced parenthesis tree." +// +// Experiments suggest the inspector's traversals are about 2.5x faster +// than [ast.Inspect], but it may take around 5 traversals for this +// benefit to amortize the inspector's construction cost. +// If efficiency is the primary concern, do not use Inspector for +// one-off traversals. +// +// The [Cursor] type provides a more flexible API for efficient +// navigation of syntax trees in all four "cardinal directions". For +// example, traversals may be nested, so you can find each node of +// type A and then search within it for nodes of type B. Or you can +// traverse from a node to its immediate neighbors: its parent, its +// previous and next sibling, or its first and last child. We +// recommend using methods of Cursor in preference to Inspector where +// possible. +package inspector + +// There are four orthogonal features in a traversal: +// 1 type filtering +// 2 pruning +// 3 postorder calls to f +// 4 stack +// Rather than offer all of them in the API, +// only a few combinations are exposed: +// - Preorder is the fastest and has fewest features, +// but is the most commonly needed traversal. +// - Nodes and WithStack both provide pruning and postorder calls, +// even though few clients need it, because supporting two versions +// is not justified. +// More combinations could be supported by expressing them as +// wrappers around a more generic traversal, but this was measured +// and found to degrade performance significantly (30%). + +import ( + "go/ast" + + "golang.org/x/tools/go/ast/edge" +) + +// An Inspector provides methods for inspecting +// (traversing) the syntax trees of a package. +type Inspector struct { + events []event +} + +func packEdgeKindAndIndex(ek edge.Kind, index int) int32 { + return int32(uint32(index+1)<<7 | uint32(ek)) +} + +// unpackEdgeKindAndIndex unpacks the edge kind and edge index (within +// an []ast.Node slice) from the parent field of a pop event. +func unpackEdgeKindAndIndex(x int32) (edge.Kind, int) { + // The "parent" field of a pop node holds the + // edge Kind in the lower 7 bits and the index+1 + // in the upper 25. + return edge.Kind(x & 0x7f), int(x>>7) - 1 +} + +// New returns an Inspector for the specified syntax trees. +func New(files []*ast.File) *Inspector { + return &Inspector{traverse(files)} +} + +// An event represents a push or a pop +// of an ast.Node during a traversal. +type event struct { + node ast.Node + typ uint64 // typeOf(node) on push event, or union of typ strictly between push and pop events on pop events + index int32 // index of corresponding push or pop event + parent int32 // index of parent's push node (push nodes only), or packed edge kind/index (pop nodes only) +} + +// TODO: Experiment with storing only the second word of event.node (unsafe.Pointer). +// Type can be recovered from the sole bit in typ. +// [Tried this, wasn't faster. --adonovan] + +// Preorder visits all the nodes of the files supplied to New in +// depth-first order. It calls f(n) for each node n before it visits +// n's children. +// +// The complete traversal sequence is determined by [ast.Inspect]. +// The types argument, if non-empty, enables type-based filtering of +// events. The function f is called only for nodes whose type +// matches an element of the types slice. +// +// The [Cursor.Preorder] method provides a richer alternative interface. +// Example: +// +// for c := range in.Root().Preorder(types) { ... } +func (in *Inspector) Preorder(types []ast.Node, f func(ast.Node)) { + // Because it avoids postorder calls to f, and the pruning + // check, Preorder is almost twice as fast as Nodes. The two + // features seem to contribute similar slowdowns (~1.4x each). + + // This function is equivalent to the PreorderSeq call below, + // but to avoid the additional dynamic call (which adds 13-35% + // to the benchmarks), we expand it out. + // + // in.PreorderSeq(types...)(func(n ast.Node) bool { + // f(n) + // return true + // }) + + mask := maskOf(types) + for i := int32(0); i < int32(len(in.events)); { + ev := in.events[i] + if ev.index > i { + // push + if ev.typ&mask != 0 { + f(ev.node) + } + pop := ev.index + if in.events[pop].typ&mask == 0 { + // Subtrees do not contain types: skip them and pop. + i = pop + 1 + continue + } + } + i++ + } +} + +// Nodes visits the nodes of the files supplied to New in depth-first +// order. It calls f(n, true) for each node n before it visits n's +// children. If f returns true, Nodes invokes f recursively for each +// of the non-nil children of the node, followed by a call of +// f(n, false). +// +// The complete traversal sequence is determined by [ast.Inspect]. +// The types argument, if non-empty, enables type-based filtering of +// events. The function f if is called only for nodes whose type +// matches an element of the types slice. +// +// The [Cursor.Inspect] method provides a richer alternative interface. +// Example: +// +// in.Root().Inspect(types, func(c Cursor) bool { +// ... +// return true +// } +func (in *Inspector) Nodes(types []ast.Node, f func(n ast.Node, push bool) (proceed bool)) { + mask := maskOf(types) + for i := int32(0); i < int32(len(in.events)); { + ev := in.events[i] + if ev.index > i { + // push + pop := ev.index + if ev.typ&mask != 0 { + if !f(ev.node, true) { + i = pop + 1 // jump to corresponding pop + 1 + continue + } + } + if in.events[pop].typ&mask == 0 { + // Subtrees do not contain types: skip them. + i = pop + continue + } + } else { + // pop + push := ev.index + if in.events[push].typ&mask != 0 { + f(ev.node, false) + } + } + i++ + } +} + +// WithStack visits nodes in a similar manner to Nodes, but it +// supplies each call to f an additional argument, the current +// traversal stack. The stack's first element is the outermost node, +// an *ast.File; its last is the innermost, n. +// +// The [Cursor.Inspect] method provides a richer alternative interface. +// Example: +// +// in.Root().Inspect(types, func(c Cursor) bool { +// stack := slices.Collect(c.Enclosing()) +// ... +// return true +// }) +func (in *Inspector) WithStack(types []ast.Node, f func(n ast.Node, push bool, stack []ast.Node) (proceed bool)) { + mask := maskOf(types) + var stack []ast.Node + for i := int32(0); i < int32(len(in.events)); { + ev := in.events[i] + if ev.index > i { + // push + pop := ev.index + stack = append(stack, ev.node) + if ev.typ&mask != 0 { + if !f(ev.node, true, stack) { + i = pop + 1 + stack = stack[:len(stack)-1] + continue + } + } + if in.events[pop].typ&mask == 0 { + // Subtrees does not contain types: skip them. + i = pop + continue + } + } else { + // pop + push := ev.index + if in.events[push].typ&mask != 0 { + f(ev.node, false, stack) + } + stack = stack[:len(stack)-1] + } + i++ + } +} + +// traverse builds the table of events representing a traversal. +func traverse(files []*ast.File) []event { + // Preallocate approximate number of events + // based on source file extent of the declarations. + // (We use End-Pos not FileStart-FileEnd to neglect + // the effect of long doc comments.) + // This makes traverse faster by 4x (!). + var extent int + for _, f := range files { + extent += int(f.End() - f.Pos()) + } + // This estimate is based on the net/http package. + capacity := min(extent*33/100, 1e6) // impose some reasonable maximum (1M) + + v := &visitor{ + events: make([]event, 0, capacity), + stack: []item{{index: -1}}, // include an extra event so file nodes have a parent + } + for _, file := range files { + walk(v, edge.Invalid, -1, file) + } + return v.events +} + +type visitor struct { + events []event + stack []item +} + +type item struct { + index int32 // index of current node's push event + parentIndex int32 // index of parent node's push event + typAccum uint64 // accumulated type bits of current node's descendants + edgeKindAndIndex int32 // edge.Kind and index, bit packed +} + +func (v *visitor) push(ek edge.Kind, eindex int, node ast.Node) { + var ( + index = int32(len(v.events)) + parentIndex = v.stack[len(v.stack)-1].index + ) + v.events = append(v.events, event{ + node: node, + parent: parentIndex, + typ: typeOf(node), + index: 0, // (pop index is set later by visitor.pop) + }) + v.stack = append(v.stack, item{ + index: index, + parentIndex: parentIndex, + edgeKindAndIndex: packEdgeKindAndIndex(ek, eindex), + }) + + // 2B nodes ought to be enough for anyone! + if int32(len(v.events)) < 0 { + panic("event index exceeded int32") + } + + // 32M elements in an []ast.Node ought to be enough for anyone! + if ek2, eindex2 := unpackEdgeKindAndIndex(packEdgeKindAndIndex(ek, eindex)); ek2 != ek || eindex2 != eindex { + panic("Node slice index exceeded uint25") + } +} + +func (v *visitor) pop(node ast.Node) { + top := len(v.stack) - 1 + current := v.stack[top] + + push := &v.events[current.index] + parent := &v.stack[top-1] + + push.index = int32(len(v.events)) // make push event refer to pop + parent.typAccum |= current.typAccum | push.typ // accumulate type bits into parent + + v.stack = v.stack[:top] + + v.events = append(v.events, event{ + node: node, + typ: current.typAccum, + index: current.index, + parent: current.edgeKindAndIndex, // see [unpackEdgeKindAndIndex] + }) +} diff --git a/vendor/golang.org/x/tools/go/ast/inspector/iter.go b/vendor/golang.org/x/tools/go/ast/inspector/iter.go new file mode 100644 index 0000000..c576dc7 --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/inspector/iter.go @@ -0,0 +1,85 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.23 + +package inspector + +import ( + "go/ast" + "iter" +) + +// PreorderSeq returns an iterator that visits all the +// nodes of the files supplied to New in depth-first order. +// It visits each node n before n's children. +// The complete traversal sequence is determined by ast.Inspect. +// +// The types argument, if non-empty, enables type-based +// filtering of events: only nodes whose type matches an +// element of the types slice are included in the sequence. +func (in *Inspector) PreorderSeq(types ...ast.Node) iter.Seq[ast.Node] { + + // This implementation is identical to Preorder, + // except that it supports breaking out of the loop. + + return func(yield func(ast.Node) bool) { + mask := maskOf(types) + for i := int32(0); i < int32(len(in.events)); { + ev := in.events[i] + if ev.index > i { + // push + if ev.typ&mask != 0 { + if !yield(ev.node) { + break + } + } + pop := ev.index + if in.events[pop].typ&mask == 0 { + // Subtrees do not contain types: skip them and pop. + i = pop + 1 + continue + } + } + i++ + } + } +} + +// All[N] returns an iterator over all the nodes of type N. +// N must be a pointer-to-struct type that implements ast.Node. +// +// Example: +// +// for call := range All[*ast.CallExpr](in) { ... } +func All[N interface { + *S + ast.Node +}, S any](in *Inspector) iter.Seq[N] { + + // To avoid additional dynamic call overheads, + // we duplicate rather than call the logic of PreorderSeq. + + mask := typeOf((N)(nil)) + return func(yield func(N) bool) { + for i := int32(0); i < int32(len(in.events)); { + ev := in.events[i] + if ev.index > i { + // push + if ev.typ&mask != 0 { + if !yield(ev.node.(N)) { + break + } + } + pop := ev.index + if in.events[pop].typ&mask == 0 { + // Subtrees do not contain types: skip them and pop. + i = pop + 1 + continue + } + } + i++ + } + } +} diff --git a/vendor/golang.org/x/tools/go/ast/inspector/typeof.go b/vendor/golang.org/x/tools/go/ast/inspector/typeof.go new file mode 100644 index 0000000..9852331 --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/inspector/typeof.go @@ -0,0 +1,227 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package inspector + +// This file defines func typeOf(ast.Node) uint64. +// +// The initial map-based implementation was too slow; +// see https://go-review.googlesource.com/c/tools/+/135655/1/go/ast/inspector/inspector.go#196 + +import ( + "go/ast" + "math" +) + +const ( + nArrayType = iota + nAssignStmt + nBadDecl + nBadExpr + nBadStmt + nBasicLit + nBinaryExpr + nBlockStmt + nBranchStmt + nCallExpr + nCaseClause + nChanType + nCommClause + nComment + nCommentGroup + nCompositeLit + nDeclStmt + nDeferStmt + nEllipsis + nEmptyStmt + nExprStmt + nField + nFieldList + nFile + nForStmt + nFuncDecl + nFuncLit + nFuncType + nGenDecl + nGoStmt + nIdent + nIfStmt + nImportSpec + nIncDecStmt + nIndexExpr + nIndexListExpr + nInterfaceType + nKeyValueExpr + nLabeledStmt + nMapType + nPackage + nParenExpr + nRangeStmt + nReturnStmt + nSelectStmt + nSelectorExpr + nSendStmt + nSliceExpr + nStarExpr + nStructType + nSwitchStmt + nTypeAssertExpr + nTypeSpec + nTypeSwitchStmt + nUnaryExpr + nValueSpec +) + +// typeOf returns a distinct single-bit value that represents the type of n. +// +// Various implementations were benchmarked with BenchmarkNewInspector: +// +// GOGC=off +// - type switch 4.9-5.5ms 2.1ms +// - binary search over a sorted list of types 5.5-5.9ms 2.5ms +// - linear scan, frequency-ordered list 5.9-6.1ms 2.7ms +// - linear scan, unordered list 6.4ms 2.7ms +// - hash table 6.5ms 3.1ms +// +// A perfect hash seemed like overkill. +// +// The compiler's switch statement is the clear winner +// as it produces a binary tree in code, +// with constant conditions and good branch prediction. +// (Sadly it is the most verbose in source code.) +// Binary search suffered from poor branch prediction. +func typeOf(n ast.Node) uint64 { + // Fast path: nearly half of all nodes are identifiers. + if _, ok := n.(*ast.Ident); ok { + return 1 << nIdent + } + + // These cases include all nodes encountered by ast.Inspect. + switch n.(type) { + case *ast.ArrayType: + return 1 << nArrayType + case *ast.AssignStmt: + return 1 << nAssignStmt + case *ast.BadDecl: + return 1 << nBadDecl + case *ast.BadExpr: + return 1 << nBadExpr + case *ast.BadStmt: + return 1 << nBadStmt + case *ast.BasicLit: + return 1 << nBasicLit + case *ast.BinaryExpr: + return 1 << nBinaryExpr + case *ast.BlockStmt: + return 1 << nBlockStmt + case *ast.BranchStmt: + return 1 << nBranchStmt + case *ast.CallExpr: + return 1 << nCallExpr + case *ast.CaseClause: + return 1 << nCaseClause + case *ast.ChanType: + return 1 << nChanType + case *ast.CommClause: + return 1 << nCommClause + case *ast.Comment: + return 1 << nComment + case *ast.CommentGroup: + return 1 << nCommentGroup + case *ast.CompositeLit: + return 1 << nCompositeLit + case *ast.DeclStmt: + return 1 << nDeclStmt + case *ast.DeferStmt: + return 1 << nDeferStmt + case *ast.Ellipsis: + return 1 << nEllipsis + case *ast.EmptyStmt: + return 1 << nEmptyStmt + case *ast.ExprStmt: + return 1 << nExprStmt + case *ast.Field: + return 1 << nField + case *ast.FieldList: + return 1 << nFieldList + case *ast.File: + return 1 << nFile + case *ast.ForStmt: + return 1 << nForStmt + case *ast.FuncDecl: + return 1 << nFuncDecl + case *ast.FuncLit: + return 1 << nFuncLit + case *ast.FuncType: + return 1 << nFuncType + case *ast.GenDecl: + return 1 << nGenDecl + case *ast.GoStmt: + return 1 << nGoStmt + case *ast.Ident: + return 1 << nIdent + case *ast.IfStmt: + return 1 << nIfStmt + case *ast.ImportSpec: + return 1 << nImportSpec + case *ast.IncDecStmt: + return 1 << nIncDecStmt + case *ast.IndexExpr: + return 1 << nIndexExpr + case *ast.IndexListExpr: + return 1 << nIndexListExpr + case *ast.InterfaceType: + return 1 << nInterfaceType + case *ast.KeyValueExpr: + return 1 << nKeyValueExpr + case *ast.LabeledStmt: + return 1 << nLabeledStmt + case *ast.MapType: + return 1 << nMapType + case *ast.Package: + return 1 << nPackage + case *ast.ParenExpr: + return 1 << nParenExpr + case *ast.RangeStmt: + return 1 << nRangeStmt + case *ast.ReturnStmt: + return 1 << nReturnStmt + case *ast.SelectStmt: + return 1 << nSelectStmt + case *ast.SelectorExpr: + return 1 << nSelectorExpr + case *ast.SendStmt: + return 1 << nSendStmt + case *ast.SliceExpr: + return 1 << nSliceExpr + case *ast.StarExpr: + return 1 << nStarExpr + case *ast.StructType: + return 1 << nStructType + case *ast.SwitchStmt: + return 1 << nSwitchStmt + case *ast.TypeAssertExpr: + return 1 << nTypeAssertExpr + case *ast.TypeSpec: + return 1 << nTypeSpec + case *ast.TypeSwitchStmt: + return 1 << nTypeSwitchStmt + case *ast.UnaryExpr: + return 1 << nUnaryExpr + case *ast.ValueSpec: + return 1 << nValueSpec + } + return 0 +} + +func maskOf(nodes []ast.Node) uint64 { + if len(nodes) == 0 { + return math.MaxUint64 // match all node types + } + var mask uint64 + for _, n := range nodes { + mask |= typeOf(n) + } + return mask +} diff --git a/vendor/golang.org/x/tools/go/ast/inspector/walk.go b/vendor/golang.org/x/tools/go/ast/inspector/walk.go new file mode 100644 index 0000000..5f1c93c --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/inspector/walk.go @@ -0,0 +1,341 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package inspector + +// This file is a fork of ast.Inspect to reduce unnecessary dynamic +// calls and to gather edge information. +// +// Consistency with the original is ensured by TestInspectAllNodes. + +import ( + "fmt" + "go/ast" + + "golang.org/x/tools/go/ast/edge" +) + +func walkList[N ast.Node](v *visitor, ek edge.Kind, list []N) { + for i, node := range list { + walk(v, ek, i, node) + } +} + +func walk(v *visitor, ek edge.Kind, index int, node ast.Node) { + v.push(ek, index, node) + + // walk children + // (the order of the cases matches the order + // of the corresponding node types in ast.go) + switch n := node.(type) { + // Comments and fields + case *ast.Comment: + // nothing to do + + case *ast.CommentGroup: + walkList(v, edge.CommentGroup_List, n.List) + + case *ast.Field: + if n.Doc != nil { + walk(v, edge.Field_Doc, -1, n.Doc) + } + walkList(v, edge.Field_Names, n.Names) + if n.Type != nil { + walk(v, edge.Field_Type, -1, n.Type) + } + if n.Tag != nil { + walk(v, edge.Field_Tag, -1, n.Tag) + } + if n.Comment != nil { + walk(v, edge.Field_Comment, -1, n.Comment) + } + + case *ast.FieldList: + walkList(v, edge.FieldList_List, n.List) + + // Expressions + case *ast.BadExpr, *ast.Ident, *ast.BasicLit: + // nothing to do + + case *ast.Ellipsis: + if n.Elt != nil { + walk(v, edge.Ellipsis_Elt, -1, n.Elt) + } + + case *ast.FuncLit: + walk(v, edge.FuncLit_Type, -1, n.Type) + walk(v, edge.FuncLit_Body, -1, n.Body) + + case *ast.CompositeLit: + if n.Type != nil { + walk(v, edge.CompositeLit_Type, -1, n.Type) + } + walkList(v, edge.CompositeLit_Elts, n.Elts) + + case *ast.ParenExpr: + walk(v, edge.ParenExpr_X, -1, n.X) + + case *ast.SelectorExpr: + walk(v, edge.SelectorExpr_X, -1, n.X) + walk(v, edge.SelectorExpr_Sel, -1, n.Sel) + + case *ast.IndexExpr: + walk(v, edge.IndexExpr_X, -1, n.X) + walk(v, edge.IndexExpr_Index, -1, n.Index) + + case *ast.IndexListExpr: + walk(v, edge.IndexListExpr_X, -1, n.X) + walkList(v, edge.IndexListExpr_Indices, n.Indices) + + case *ast.SliceExpr: + walk(v, edge.SliceExpr_X, -1, n.X) + if n.Low != nil { + walk(v, edge.SliceExpr_Low, -1, n.Low) + } + if n.High != nil { + walk(v, edge.SliceExpr_High, -1, n.High) + } + if n.Max != nil { + walk(v, edge.SliceExpr_Max, -1, n.Max) + } + + case *ast.TypeAssertExpr: + walk(v, edge.TypeAssertExpr_X, -1, n.X) + if n.Type != nil { + walk(v, edge.TypeAssertExpr_Type, -1, n.Type) + } + + case *ast.CallExpr: + walk(v, edge.CallExpr_Fun, -1, n.Fun) + walkList(v, edge.CallExpr_Args, n.Args) + + case *ast.StarExpr: + walk(v, edge.StarExpr_X, -1, n.X) + + case *ast.UnaryExpr: + walk(v, edge.UnaryExpr_X, -1, n.X) + + case *ast.BinaryExpr: + walk(v, edge.BinaryExpr_X, -1, n.X) + walk(v, edge.BinaryExpr_Y, -1, n.Y) + + case *ast.KeyValueExpr: + walk(v, edge.KeyValueExpr_Key, -1, n.Key) + walk(v, edge.KeyValueExpr_Value, -1, n.Value) + + // Types + case *ast.ArrayType: + if n.Len != nil { + walk(v, edge.ArrayType_Len, -1, n.Len) + } + walk(v, edge.ArrayType_Elt, -1, n.Elt) + + case *ast.StructType: + walk(v, edge.StructType_Fields, -1, n.Fields) + + case *ast.FuncType: + if n.TypeParams != nil { + walk(v, edge.FuncType_TypeParams, -1, n.TypeParams) + } + if n.Params != nil { + walk(v, edge.FuncType_Params, -1, n.Params) + } + if n.Results != nil { + walk(v, edge.FuncType_Results, -1, n.Results) + } + + case *ast.InterfaceType: + walk(v, edge.InterfaceType_Methods, -1, n.Methods) + + case *ast.MapType: + walk(v, edge.MapType_Key, -1, n.Key) + walk(v, edge.MapType_Value, -1, n.Value) + + case *ast.ChanType: + walk(v, edge.ChanType_Value, -1, n.Value) + + // Statements + case *ast.BadStmt: + // nothing to do + + case *ast.DeclStmt: + walk(v, edge.DeclStmt_Decl, -1, n.Decl) + + case *ast.EmptyStmt: + // nothing to do + + case *ast.LabeledStmt: + walk(v, edge.LabeledStmt_Label, -1, n.Label) + walk(v, edge.LabeledStmt_Stmt, -1, n.Stmt) + + case *ast.ExprStmt: + walk(v, edge.ExprStmt_X, -1, n.X) + + case *ast.SendStmt: + walk(v, edge.SendStmt_Chan, -1, n.Chan) + walk(v, edge.SendStmt_Value, -1, n.Value) + + case *ast.IncDecStmt: + walk(v, edge.IncDecStmt_X, -1, n.X) + + case *ast.AssignStmt: + walkList(v, edge.AssignStmt_Lhs, n.Lhs) + walkList(v, edge.AssignStmt_Rhs, n.Rhs) + + case *ast.GoStmt: + walk(v, edge.GoStmt_Call, -1, n.Call) + + case *ast.DeferStmt: + walk(v, edge.DeferStmt_Call, -1, n.Call) + + case *ast.ReturnStmt: + walkList(v, edge.ReturnStmt_Results, n.Results) + + case *ast.BranchStmt: + if n.Label != nil { + walk(v, edge.BranchStmt_Label, -1, n.Label) + } + + case *ast.BlockStmt: + walkList(v, edge.BlockStmt_List, n.List) + + case *ast.IfStmt: + if n.Init != nil { + walk(v, edge.IfStmt_Init, -1, n.Init) + } + walk(v, edge.IfStmt_Cond, -1, n.Cond) + walk(v, edge.IfStmt_Body, -1, n.Body) + if n.Else != nil { + walk(v, edge.IfStmt_Else, -1, n.Else) + } + + case *ast.CaseClause: + walkList(v, edge.CaseClause_List, n.List) + walkList(v, edge.CaseClause_Body, n.Body) + + case *ast.SwitchStmt: + if n.Init != nil { + walk(v, edge.SwitchStmt_Init, -1, n.Init) + } + if n.Tag != nil { + walk(v, edge.SwitchStmt_Tag, -1, n.Tag) + } + walk(v, edge.SwitchStmt_Body, -1, n.Body) + + case *ast.TypeSwitchStmt: + if n.Init != nil { + walk(v, edge.TypeSwitchStmt_Init, -1, n.Init) + } + walk(v, edge.TypeSwitchStmt_Assign, -1, n.Assign) + walk(v, edge.TypeSwitchStmt_Body, -1, n.Body) + + case *ast.CommClause: + if n.Comm != nil { + walk(v, edge.CommClause_Comm, -1, n.Comm) + } + walkList(v, edge.CommClause_Body, n.Body) + + case *ast.SelectStmt: + walk(v, edge.SelectStmt_Body, -1, n.Body) + + case *ast.ForStmt: + if n.Init != nil { + walk(v, edge.ForStmt_Init, -1, n.Init) + } + if n.Cond != nil { + walk(v, edge.ForStmt_Cond, -1, n.Cond) + } + if n.Post != nil { + walk(v, edge.ForStmt_Post, -1, n.Post) + } + walk(v, edge.ForStmt_Body, -1, n.Body) + + case *ast.RangeStmt: + if n.Key != nil { + walk(v, edge.RangeStmt_Key, -1, n.Key) + } + if n.Value != nil { + walk(v, edge.RangeStmt_Value, -1, n.Value) + } + walk(v, edge.RangeStmt_X, -1, n.X) + walk(v, edge.RangeStmt_Body, -1, n.Body) + + // Declarations + case *ast.ImportSpec: + if n.Doc != nil { + walk(v, edge.ImportSpec_Doc, -1, n.Doc) + } + if n.Name != nil { + walk(v, edge.ImportSpec_Name, -1, n.Name) + } + walk(v, edge.ImportSpec_Path, -1, n.Path) + if n.Comment != nil { + walk(v, edge.ImportSpec_Comment, -1, n.Comment) + } + + case *ast.ValueSpec: + if n.Doc != nil { + walk(v, edge.ValueSpec_Doc, -1, n.Doc) + } + walkList(v, edge.ValueSpec_Names, n.Names) + if n.Type != nil { + walk(v, edge.ValueSpec_Type, -1, n.Type) + } + walkList(v, edge.ValueSpec_Values, n.Values) + if n.Comment != nil { + walk(v, edge.ValueSpec_Comment, -1, n.Comment) + } + + case *ast.TypeSpec: + if n.Doc != nil { + walk(v, edge.TypeSpec_Doc, -1, n.Doc) + } + walk(v, edge.TypeSpec_Name, -1, n.Name) + if n.TypeParams != nil { + walk(v, edge.TypeSpec_TypeParams, -1, n.TypeParams) + } + walk(v, edge.TypeSpec_Type, -1, n.Type) + if n.Comment != nil { + walk(v, edge.TypeSpec_Comment, -1, n.Comment) + } + + case *ast.BadDecl: + // nothing to do + + case *ast.GenDecl: + if n.Doc != nil { + walk(v, edge.GenDecl_Doc, -1, n.Doc) + } + walkList(v, edge.GenDecl_Specs, n.Specs) + + case *ast.FuncDecl: + if n.Doc != nil { + walk(v, edge.FuncDecl_Doc, -1, n.Doc) + } + if n.Recv != nil { + walk(v, edge.FuncDecl_Recv, -1, n.Recv) + } + walk(v, edge.FuncDecl_Name, -1, n.Name) + walk(v, edge.FuncDecl_Type, -1, n.Type) + if n.Body != nil { + walk(v, edge.FuncDecl_Body, -1, n.Body) + } + + case *ast.File: + if n.Doc != nil { + walk(v, edge.File_Doc, -1, n.Doc) + } + walk(v, edge.File_Name, -1, n.Name) + walkList(v, edge.File_Decls, n.Decls) + // don't walk n.Comments - they have been + // visited already through the individual + // nodes + + default: + // (includes *ast.Package) + panic(fmt.Sprintf("Walk: unexpected node type %T", n)) + } + + v.pop(node) +} diff --git a/vendor/golang.org/x/tools/go/packages/golist.go b/vendor/golang.org/x/tools/go/packages/golist.go index 89f89dd..680a70c 100644 --- a/vendor/golang.org/x/tools/go/packages/golist.go +++ b/vendor/golang.org/x/tools/go/packages/golist.go @@ -364,12 +364,6 @@ type jsonPackage struct { DepsErrors []*packagesinternal.PackageError } -type jsonPackageError struct { - ImportStack []string - Pos string - Err string -} - func otherFiles(p *jsonPackage) [][]string { return [][]string{p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.FFiles, p.SFiles, p.SwigFiles, p.SwigCXXFiles, p.SysoFiles} } diff --git a/vendor/golang.org/x/tools/go/packages/visit.go b/vendor/golang.org/x/tools/go/packages/visit.go index df14ffd..af6a60d 100644 --- a/vendor/golang.org/x/tools/go/packages/visit.go +++ b/vendor/golang.org/x/tools/go/packages/visit.go @@ -5,9 +5,11 @@ package packages import ( + "cmp" "fmt" + "iter" "os" - "sort" + "slices" ) // Visit visits all the packages in the import graph whose roots are @@ -16,6 +18,20 @@ import ( // package's dependencies have been visited (postorder). // The boolean result of pre(pkg) determines whether // the imports of package pkg are visited. +// +// Example: +// +// pkgs, err := Load(...) +// if err != nil { ... } +// Visit(pkgs, nil, func(pkg *Package) { +// log.Println(pkg) +// }) +// +// In most cases, it is more convenient to use [Postorder]: +// +// for pkg := range Postorder(pkgs) { +// log.Println(pkg) +// } func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) { seen := make(map[*Package]bool) var visit func(*Package) @@ -24,13 +40,8 @@ func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) { seen[pkg] = true if pre == nil || pre(pkg) { - paths := make([]string, 0, len(pkg.Imports)) - for path := range pkg.Imports { - paths = append(paths, path) - } - sort.Strings(paths) // Imports is a map, this makes visit stable - for _, path := range paths { - visit(pkg.Imports[path]) + for _, imp := range sorted(pkg.Imports) { // for determinism + visit(imp) } } @@ -50,7 +61,7 @@ func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) { func PrintErrors(pkgs []*Package) int { var n int errModules := make(map[*Module]bool) - Visit(pkgs, nil, func(pkg *Package) { + for pkg := range Postorder(pkgs) { for _, err := range pkg.Errors { fmt.Fprintln(os.Stderr, err) n++ @@ -63,6 +74,60 @@ func PrintErrors(pkgs []*Package) int { fmt.Fprintln(os.Stderr, mod.Error.Err) n++ } - }) + } return n } + +// Postorder returns an iterator over the the packages in +// the import graph whose roots are pkg. +// Packages are enumerated in dependencies-first order. +func Postorder(pkgs []*Package) iter.Seq[*Package] { + return func(yield func(*Package) bool) { + seen := make(map[*Package]bool) + var visit func(*Package) bool + visit = func(pkg *Package) bool { + if !seen[pkg] { + seen[pkg] = true + for _, imp := range sorted(pkg.Imports) { // for determinism + if !visit(imp) { + return false + } + } + if !yield(pkg) { + return false + } + } + return true + } + for _, pkg := range pkgs { + if !visit(pkg) { + break + } + } + } +} + +// -- copied from golang.org.x/tools/gopls/internal/util/moremaps -- + +// sorted returns an iterator over the entries of m in key order. +func sorted[M ~map[K]V, K cmp.Ordered, V any](m M) iter.Seq2[K, V] { + // TODO(adonovan): use maps.Sorted if proposal #68598 is accepted. + return func(yield func(K, V) bool) { + keys := keySlice(m) + slices.Sort(keys) + for _, k := range keys { + if !yield(k, m[k]) { + break + } + } + } +} + +// KeySlice returns the keys of the map M, like slices.Collect(maps.Keys(m)). +func keySlice[M ~map[K]V, K comparable, V any](m M) []K { + r := make([]K, 0, len(m)) + for k := range m { + r = append(r, k) + } + return r +} diff --git a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go index d3c2913..6c0c749 100644 --- a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go +++ b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go @@ -698,7 +698,10 @@ func Object(pkg *types.Package, p Path) (types.Object, error) { } else if false && aliases.Enabled() { // The Enabled check is too expensive, so for now we // simply assume that aliases are not enabled. - // TODO(adonovan): replace with "if true {" when go1.24 is assured. + // + // Now that go1.24 is assured, we should be able to + // replace this with "if true {", but it causes tests + // to fail. TODO(adonovan): investigate. return nil, fmt.Errorf("cannot apply %q to %s (got %T, want alias)", code, t, t) } diff --git a/vendor/golang.org/x/tools/go/types/typeutil/map.go b/vendor/golang.org/x/tools/go/types/typeutil/map.go index b6d542c..f035a0b 100644 --- a/vendor/golang.org/x/tools/go/types/typeutil/map.go +++ b/vendor/golang.org/x/tools/go/types/typeutil/map.go @@ -11,7 +11,6 @@ import ( "fmt" "go/types" "hash/maphash" - "unsafe" "golang.org/x/tools/internal/typeparams" ) @@ -380,22 +379,8 @@ var theSeed = maphash.MakeSeed() func (hasher) hashTypeName(tname *types.TypeName) uint32 { // Since types.Identical uses == to compare TypeNames, // the Hash function uses maphash.Comparable. - // TODO(adonovan): or will, when it becomes available in go1.24. - // In the meantime we use the pointer's numeric value. - // - // hash := maphash.Comparable(theSeed, tname) - // - // (Another approach would be to hash the name and package - // path, and whether or not it is a package-level typename. It - // is rare for a package to define multiple local types with - // the same name.) - ptr := uintptr(unsafe.Pointer(tname)) - if unsafe.Sizeof(ptr) == 8 { - hash := uint64(ptr) - return uint32(hash ^ (hash >> 32)) - } else { - return uint32(ptr) - } + hash := maphash.Comparable(theSeed, tname) + return uint32(hash ^ (hash >> 32)) } // shallowHash computes a hash of t without looking at any of its diff --git a/vendor/golang.org/x/tools/internal/event/core/event.go b/vendor/golang.org/x/tools/internal/event/core/event.go index a6cf0e6..ade5d1e 100644 --- a/vendor/golang.org/x/tools/internal/event/core/event.go +++ b/vendor/golang.org/x/tools/internal/event/core/event.go @@ -28,11 +28,6 @@ type Event struct { dynamic []label.Label // dynamically sized storage for remaining labels } -// eventLabelMap implements label.Map for a the labels of an Event. -type eventLabelMap struct { - event Event -} - func (ev Event) At() time.Time { return ev.at } func (ev Event) Format(f fmt.State, r rune) { diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iexport.go b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go index 780873e..4a4357d 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/iexport.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go @@ -569,7 +569,6 @@ func (p *iexporter) exportName(obj types.Object) (res string) { type iexporter struct { fset *token.FileSet - out *bytes.Buffer version int shallow bool // don't put types from other packages in the index diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go b/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go deleted file mode 100644 index 7586bfa..0000000 --- a/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2024 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.22 && !go1.24 - -package gcimporter - -import ( - "go/token" - "go/types" - "unsafe" -) - -// TODO(rfindley): delete this workaround once go1.24 is assured. - -func init() { - // Update markBlack so that it correctly sets the color - // of imported TypeNames. - // - // See the doc comment for markBlack for details. - - type color uint32 - const ( - white color = iota - black - grey - ) - type object struct { - _ *types.Scope - _ token.Pos - _ *types.Package - _ string - _ types.Type - _ uint32 - color_ color - _ token.Pos - } - type typeName struct { - object - } - - // If the size of types.TypeName changes, this will fail to compile. - const delta = int64(unsafe.Sizeof(typeName{})) - int64(unsafe.Sizeof(types.TypeName{})) - var _ [-delta * delta]int - - markBlack = func(obj *types.TypeName) { - type uP = unsafe.Pointer - var ptr *typeName - *(*uP)(uP(&ptr)) = uP(obj) - ptr.color_ = black - } -} diff --git a/vendor/golang.org/x/tools/internal/stdlib/deps.go b/vendor/golang.org/x/tools/internal/stdlib/deps.go index 77cf8d2..96ad6c5 100644 --- a/vendor/golang.org/x/tools/internal/stdlib/deps.go +++ b/vendor/golang.org/x/tools/internal/stdlib/deps.go @@ -12,348 +12,354 @@ type pkginfo struct { } var deps = [...]pkginfo{ - {"archive/tar", "\x03j\x03E5\x01\v\x01#\x01\x01\x02\x05\n\x02\x01\x02\x02\v"}, - {"archive/zip", "\x02\x04`\a\x16\x0205\x01+\x05\x01\x11\x03\x02\r\x04"}, - {"bufio", "\x03j}F\x13"}, - {"bytes", "m+R\x03\fH\x02\x02"}, + {"archive/tar", "\x03k\x03E;\x01\n\x01$\x01\x01\x02\x05\b\x02\x01\x02\x02\f"}, + {"archive/zip", "\x02\x04a\a\x03\x12\x021;\x01+\x05\x01\x0f\x03\x02\x0e\x04"}, + {"bufio", "\x03k\x83\x01D\x14"}, + {"bytes", "n*Y\x03\fG\x02\x02"}, {"cmp", ""}, - {"compress/bzip2", "\x02\x02\xe6\x01C"}, - {"compress/flate", "\x02k\x03z\r\x025\x01\x03"}, - {"compress/gzip", "\x02\x04`\a\x03\x15eU"}, - {"compress/lzw", "\x02k\x03z"}, - {"compress/zlib", "\x02\x04`\a\x03\x13\x01f"}, - {"container/heap", "\xae\x02"}, + {"compress/bzip2", "\x02\x02\xed\x01A"}, + {"compress/flate", "\x02l\x03\x80\x01\f\x033\x01\x03"}, + {"compress/gzip", "\x02\x04a\a\x03\x14lT"}, + {"compress/lzw", "\x02l\x03\x80\x01"}, + {"compress/zlib", "\x02\x04a\a\x03\x12\x01m"}, + {"container/heap", "\xb3\x02"}, {"container/list", ""}, {"container/ring", ""}, - {"context", "m\\i\x01\f"}, - {"crypto", "\x83\x01gE"}, - {"crypto/aes", "\x10\n\a\x8e\x02"}, - {"crypto/cipher", "\x03\x1e\x01\x01\x1d\x11\x1c,Q"}, - {"crypto/des", "\x10\x13\x1d-,\x96\x01\x03"}, - {"crypto/dsa", "@\x04)}\x0e"}, - {"crypto/ecdh", "\x03\v\f\x0e\x04\x14\x04\r\x1c}"}, - {"crypto/ecdsa", "\x0e\x05\x03\x04\x01\x0e\x16\x01\x04\f\x01\x1c}\x0e\x04L\x01"}, - {"crypto/ed25519", "\x0e\x1c\x16\n\a\x1c}E"}, - {"crypto/elliptic", "0=}\x0e:"}, - {"crypto/fips140", " \x05\x90\x01"}, - {"crypto/hkdf", "-\x12\x01-\x16"}, - {"crypto/hmac", "\x1a\x14\x11\x01\x112"}, + {"context", "n\\m\x01\r"}, + {"crypto", "\x83\x01nC"}, + {"crypto/aes", "\x10\n\a\x93\x02"}, + {"crypto/cipher", "\x03\x1e\x01\x01\x1e\x11\x1c+X"}, + {"crypto/des", "\x10\x13\x1e-+\x9b\x01\x03"}, + {"crypto/dsa", "A\x04)\x83\x01\r"}, + {"crypto/ecdh", "\x03\v\f\x0e\x04\x15\x04\r\x1c\x83\x01"}, + {"crypto/ecdsa", "\x0e\x05\x03\x04\x01\x0e\a\v\x05\x01\x04\f\x01\x1c\x83\x01\r\x05K\x01"}, + {"crypto/ed25519", "\x0e\x1c\x11\x06\n\a\x1c\x83\x01C"}, + {"crypto/elliptic", "0>\x83\x01\r9"}, + {"crypto/fips140", " \x05"}, + {"crypto/hkdf", "-\x13\x01-\x15"}, + {"crypto/hmac", "\x1a\x14\x12\x01\x111"}, {"crypto/internal/boring", "\x0e\x02\rf"}, - {"crypto/internal/boring/bbig", "\x1a\xde\x01M"}, - {"crypto/internal/boring/bcache", "\xb3\x02\x12"}, + {"crypto/internal/boring/bbig", "\x1a\xe4\x01M"}, + {"crypto/internal/boring/bcache", "\xb8\x02\x13"}, {"crypto/internal/boring/sig", ""}, - {"crypto/internal/cryptotest", "\x03\r\n)\x0e\x19\x06\x13\x12#\a\t\x11\x11\x11\x1b\x01\f\r\x05\n"}, - {"crypto/internal/entropy", "E"}, - {"crypto/internal/fips140", ">/}9\r\x15"}, - {"crypto/internal/fips140/aes", "\x03\x1d\x03\x02\x13\x04\x01\x01\x05*\x8c\x016"}, - {"crypto/internal/fips140/aes/gcm", " \x01\x02\x02\x02\x11\x04\x01\x06*\x8a\x01"}, - {"crypto/internal/fips140/alias", "\xc5\x02"}, - {"crypto/internal/fips140/bigmod", "%\x17\x01\x06*\x8c\x01"}, - {"crypto/internal/fips140/check", " \x0e\x06\b\x02\xac\x01["}, - {"crypto/internal/fips140/check/checktest", "%\xfe\x01\""}, - {"crypto/internal/fips140/drbg", "\x03\x1c\x01\x01\x04\x13\x04\b\x01(}\x0f9"}, - {"crypto/internal/fips140/ecdh", "\x03\x1d\x05\x02\t\f1}\x0f9"}, - {"crypto/internal/fips140/ecdsa", "\x03\x1d\x04\x01\x02\a\x02\x067}H"}, - {"crypto/internal/fips140/ed25519", "\x03\x1d\x05\x02\x04\v7\xc2\x01\x03"}, - {"crypto/internal/fips140/edwards25519", "%\a\f\x041\x8c\x019"}, - {"crypto/internal/fips140/edwards25519/field", "%\x13\x041\x8c\x01"}, - {"crypto/internal/fips140/hkdf", "\x03\x1d\x05\t\x069"}, - {"crypto/internal/fips140/hmac", "\x03\x1d\x14\x01\x017"}, - {"crypto/internal/fips140/mlkem", "\x03\x1d\x05\x02\x0e\x03\x041"}, - {"crypto/internal/fips140/nistec", "%\f\a\x041\x8c\x01*\x0f\x13"}, - {"crypto/internal/fips140/nistec/fiat", "%\x135\x8c\x01"}, - {"crypto/internal/fips140/pbkdf2", "\x03\x1d\x05\t\x069"}, - {"crypto/internal/fips140/rsa", "\x03\x1d\x04\x01\x02\r\x01\x01\x025}H"}, - {"crypto/internal/fips140/sha256", "\x03\x1d\x1c\x01\x06*\x8c\x01"}, - {"crypto/internal/fips140/sha3", "\x03\x1d\x18\x04\x010\x8c\x01L"}, - {"crypto/internal/fips140/sha512", "\x03\x1d\x1c\x01\x06*\x8c\x01"}, - {"crypto/internal/fips140/ssh", " \x05"}, - {"crypto/internal/fips140/subtle", "#"}, - {"crypto/internal/fips140/tls12", "\x03\x1d\x05\t\x06\x027"}, - {"crypto/internal/fips140/tls13", "\x03\x1d\x05\b\a\b1"}, + {"crypto/internal/cryptotest", "\x03\r\n\x06$\x0e\x19\x06\x12\x12 \x04\a\t\x16\x01\x11\x11\x1b\x01\a\x05\b\x03\x05\v"}, + {"crypto/internal/entropy", "F"}, + {"crypto/internal/fips140", "?/\x15\xa7\x01\v\x16"}, + {"crypto/internal/fips140/aes", "\x03\x1d\x03\x02\x13\x05\x01\x01\x05*\x92\x014"}, + {"crypto/internal/fips140/aes/gcm", " \x01\x02\x02\x02\x11\x05\x01\x06*\x8f\x01"}, + {"crypto/internal/fips140/alias", "\xcb\x02"}, + {"crypto/internal/fips140/bigmod", "%\x18\x01\x06*\x92\x01"}, + {"crypto/internal/fips140/check", " \x0e\x06\t\x02\xb2\x01Z"}, + {"crypto/internal/fips140/check/checktest", "%\x85\x02!"}, + {"crypto/internal/fips140/drbg", "\x03\x1c\x01\x01\x04\x13\x05\b\x01(\x83\x01\x0f7"}, + {"crypto/internal/fips140/ecdh", "\x03\x1d\x05\x02\t\r1\x83\x01\x0f7"}, + {"crypto/internal/fips140/ecdsa", "\x03\x1d\x04\x01\x02\a\x02\x068\x15nF"}, + {"crypto/internal/fips140/ed25519", "\x03\x1d\x05\x02\x04\v8\xc6\x01\x03"}, + {"crypto/internal/fips140/edwards25519", "%\a\f\x051\x92\x017"}, + {"crypto/internal/fips140/edwards25519/field", "%\x13\x051\x92\x01"}, + {"crypto/internal/fips140/hkdf", "\x03\x1d\x05\t\x06:\x15"}, + {"crypto/internal/fips140/hmac", "\x03\x1d\x14\x01\x018\x15"}, + {"crypto/internal/fips140/mlkem", "\x03\x1d\x05\x02\x0e\x03\x051"}, + {"crypto/internal/fips140/nistec", "%\f\a\x051\x92\x01*\r\x14"}, + {"crypto/internal/fips140/nistec/fiat", "%\x136\x92\x01"}, + {"crypto/internal/fips140/pbkdf2", "\x03\x1d\x05\t\x06:\x15"}, + {"crypto/internal/fips140/rsa", "\x03\x1d\x04\x01\x02\r\x01\x01\x026\x15nF"}, + {"crypto/internal/fips140/sha256", "\x03\x1d\x1d\x01\x06*\x15}"}, + {"crypto/internal/fips140/sha3", "\x03\x1d\x18\x05\x010\x92\x01K"}, + {"crypto/internal/fips140/sha512", "\x03\x1d\x1d\x01\x06*\x15}"}, + {"crypto/internal/fips140/ssh", "%^"}, + {"crypto/internal/fips140/subtle", "#\x1a\xc3\x01"}, + {"crypto/internal/fips140/tls12", "\x03\x1d\x05\t\x06\x028\x15"}, + {"crypto/internal/fips140/tls13", "\x03\x1d\x05\b\a\t1\x15"}, + {"crypto/internal/fips140cache", "\xaa\x02\r&"}, {"crypto/internal/fips140deps", ""}, {"crypto/internal/fips140deps/byteorder", "\x99\x01"}, - {"crypto/internal/fips140deps/cpu", "\xad\x01\a"}, - {"crypto/internal/fips140deps/godebug", "\xb5\x01"}, - {"crypto/internal/fips140hash", "5\x1a4\xc2\x01"}, - {"crypto/internal/fips140only", "'\r\x01\x01M25"}, + {"crypto/internal/fips140deps/cpu", "\xae\x01\a"}, + {"crypto/internal/fips140deps/godebug", "\xb6\x01"}, + {"crypto/internal/fips140hash", "5\x1b3\xc8\x01"}, + {"crypto/internal/fips140only", "'\r\x01\x01M3;"}, {"crypto/internal/fips140test", ""}, - {"crypto/internal/hpke", "\x0e\x01\x01\x03\x1a\x1d#,`N"}, - {"crypto/internal/impl", "\xb0\x02"}, - {"crypto/internal/randutil", "\xea\x01\x12"}, - {"crypto/internal/sysrand", "mi!\x1f\r\x0f\x01\x01\v\x06"}, - {"crypto/internal/sysrand/internal/seccomp", "m"}, - {"crypto/md5", "\x0e2-\x16\x16`"}, + {"crypto/internal/hpke", "\x0e\x01\x01\x03\x053#+gM"}, + {"crypto/internal/impl", "\xb5\x02"}, + {"crypto/internal/randutil", "\xf1\x01\x12"}, + {"crypto/internal/sysrand", "nn! \r\r\x01\x01\f\x06"}, + {"crypto/internal/sysrand/internal/seccomp", "n"}, + {"crypto/md5", "\x0e3-\x15\x16g"}, {"crypto/mlkem", "/"}, - {"crypto/pbkdf2", "2\r\x01-\x16"}, - {"crypto/rand", "\x1a\x06\a\x19\x04\x01(}\x0eM"}, - {"crypto/rc4", "#\x1d-\xc2\x01"}, - {"crypto/rsa", "\x0e\f\x01\t\x0f\f\x01\x04\x06\a\x1c\x03\x1325\r\x01"}, - {"crypto/sha1", "\x0e\f&-\x16\x16\x14L"}, + {"crypto/pbkdf2", "2\x0e\x01-\x15"}, + {"crypto/rand", "\x1a\x06\a\x1a\x04\x01(\x83\x01\rM"}, + {"crypto/rc4", "#\x1e-\xc6\x01"}, + {"crypto/rsa", "\x0e\f\x01\t\x0f\r\x01\x04\x06\a\x1c\x03\x123;\f\x01"}, + {"crypto/sha1", "\x0e\f'\x03*\x15\x16\x15R"}, {"crypto/sha256", "\x0e\f\x1aO"}, - {"crypto/sha3", "\x0e'N\xc2\x01"}, + {"crypto/sha3", "\x0e'N\xc8\x01"}, {"crypto/sha512", "\x0e\f\x1cM"}, - {"crypto/subtle", "8\x96\x01U"}, - {"crypto/tls", "\x03\b\x02\x01\x01\x01\x01\x02\x01\x01\x01\x03\x01\a\x01\v\x02\n\x01\b\x05\x03\x01\x01\x01\x01\x02\x01\x02\x01\x17\x02\x03\x13\x16\x14\b5\x16\x16\r\n\x01\x01\x01\x02\x01\f\x06\x02\x01"}, - {"crypto/tls/internal/fips140tls", " \x93\x02"}, - {"crypto/x509", "\x03\v\x01\x01\x01\x01\x01\x01\x01\x011\x03\x02\x01\x01\x02\x05\x0e\x06\x02\x02\x03E\x032\x01\x02\t\x01\x01\x01\a\x10\x05\x01\x06\x02\x05\f\x01\x02\r\x02\x01\x01\x02\x03\x01"}, - {"crypto/x509/pkix", "c\x06\a\x88\x01G"}, - {"database/sql", "\x03\nJ\x16\x03z\f\x06\"\x05\n\x02\x03\x01\f\x02\x02\x02"}, - {"database/sql/driver", "\r`\x03\xae\x01\x11\x10"}, - {"debug/buildinfo", "\x03W\x02\x01\x01\b\a\x03`\x18\x02\x01+\x0f "}, - {"debug/dwarf", "\x03c\a\x03z1\x13\x01\x01"}, - {"debug/elf", "\x03\x06P\r\a\x03`\x19\x01,\x19\x01\x15"}, - {"debug/gosym", "\x03c\n\xbe\x01\x01\x01\x02"}, - {"debug/macho", "\x03\x06P\r\n`\x1a,\x19\x01"}, - {"debug/pe", "\x03\x06P\r\a\x03`\x1a,\x19\x01\x15"}, - {"debug/plan9obj", "f\a\x03`\x1a,"}, - {"embed", "m+:\x18\x01T"}, + {"crypto/subtle", "8\x9b\x01W"}, + {"crypto/tls", "\x03\b\x02\x01\x01\x01\x01\x02\x01\x01\x01\x02\x01\x01\a\x01\r\n\x01\t\x05\x03\x01\x01\x01\x01\x02\x01\x02\x01\x17\x02\x03\x12\x16\x15\b;\x16\x16\r\b\x01\x01\x01\x02\x01\r\x06\x02\x01\x0f"}, + {"crypto/tls/internal/fips140tls", "\x17\xa1\x02"}, + {"crypto/x509", "\x03\v\x01\x01\x01\x01\x01\x01\x01\x012\x05\x01\x01\x02\x05\x0e\x06\x02\x02\x03E\x038\x01\x02\b\x01\x01\x02\a\x10\x05\x01\x06\x02\x05\n\x01\x02\x0e\x02\x01\x01\x02\x03\x01"}, + {"crypto/x509/pkix", "d\x06\a\x8d\x01G"}, + {"database/sql", "\x03\nK\x16\x03\x80\x01\v\a\"\x05\b\x02\x03\x01\r\x02\x02\x02"}, + {"database/sql/driver", "\ra\x03\xb4\x01\x0f\x11"}, + {"debug/buildinfo", "\x03X\x02\x01\x01\b\a\x03e\x19\x02\x01+\x0f\x1f"}, + {"debug/dwarf", "\x03d\a\x03\x80\x011\x11\x01\x01"}, + {"debug/elf", "\x03\x06Q\r\a\x03e\x1a\x01,\x17\x01\x16"}, + {"debug/gosym", "\x03d\n\xc2\x01\x01\x01\x02"}, + {"debug/macho", "\x03\x06Q\r\ne\x1b,\x17\x01"}, + {"debug/pe", "\x03\x06Q\r\a\x03e\x1b,\x17\x01\x16"}, + {"debug/plan9obj", "g\a\x03e\x1b,"}, + {"embed", "n*@\x19\x01S"}, {"embed/internal/embedtest", ""}, {"encoding", ""}, - {"encoding/ascii85", "\xea\x01E"}, - {"encoding/asn1", "\x03j\x03\x87\x01\x01&\x0f\x02\x01\x0f\x03\x01"}, - {"encoding/base32", "\xea\x01C\x02"}, - {"encoding/base64", "\x99\x01QC\x02"}, - {"encoding/binary", "m}\r'\x0f\x05"}, - {"encoding/csv", "\x02\x01j\x03zF\x11\x02"}, - {"encoding/gob", "\x02_\x05\a\x03`\x1a\f\x01\x02\x1d\b\x14\x01\x0e\x02"}, - {"encoding/hex", "m\x03zC\x03"}, - {"encoding/json", "\x03\x01]\x04\b\x03z\r'\x0f\x02\x01\x02\x0f\x01\x01\x02"}, - {"encoding/pem", "\x03b\b}C\x03"}, - {"encoding/xml", "\x02\x01^\f\x03z4\x05\f\x01\x02\x0f\x02"}, - {"errors", "\xc9\x01|"}, - {"expvar", "jK9\t\n\x15\r\n\x02\x03\x01\x10"}, - {"flag", "a\f\x03z,\b\x05\n\x02\x01\x0f"}, - {"fmt", "mE8\r\x1f\b\x0f\x02\x03\x11"}, - {"go/ast", "\x03\x01l\x0f\x01j\x03)\b\x0f\x02\x01"}, - {"go/ast/internal/tests", ""}, - {"go/build", "\x02\x01j\x03\x01\x03\x02\a\x02\x01\x17\x1e\x04\x02\t\x14\x12\x01+\x01\x04\x01\a\n\x02\x01\x11\x02\x02"}, - {"go/build/constraint", "m\xc2\x01\x01\x11\x02"}, - {"go/constant", "p\x10w\x01\x016\x01\x02\x11"}, - {"go/doc", "\x04l\x01\x06\t=-1\x12\x02\x01\x11\x02"}, - {"go/doc/comment", "\x03m\xbd\x01\x01\x01\x01\x11\x02"}, - {"go/format", "\x03m\x01\f\x01\x02jF"}, - {"go/importer", "s\a\x01\x01\x04\x01i9"}, - {"go/internal/gccgoimporter", "\x02\x01W\x13\x03\x05\v\x01g\x02,\x01\x05\x13\x01\v\b"}, - {"go/internal/gcimporter", "\x02n\x10\x01/\x05\x0e',\x17\x03\x02"}, - {"go/internal/srcimporter", "p\x01\x02\n\x03\x01i,\x01\x05\x14\x02\x13"}, - {"go/parser", "\x03j\x03\x01\x03\v\x01j\x01+\x06\x14"}, - {"go/printer", "p\x01\x03\x03\tj\r\x1f\x17\x02\x01\x02\n\x05\x02"}, - {"go/scanner", "\x03m\x10j2\x12\x01\x12\x02"}, - {"go/token", "\x04l\xbd\x01\x02\x03\x01\x0e\x02"}, - {"go/types", "\x03\x01\x06c\x03\x01\x04\b\x03\x02\x15\x1e\x06+\x04\x03\n%\a\n\x01\x01\x01\x02\x01\x0e\x02\x02"}, - {"go/version", "\xba\x01v"}, - {"hash", "\xea\x01"}, - {"hash/adler32", "m\x16\x16"}, - {"hash/crc32", "m\x16\x16\x14\x85\x01\x01\x12"}, - {"hash/crc64", "m\x16\x16\x99\x01"}, - {"hash/fnv", "m\x16\x16`"}, - {"hash/maphash", "\x94\x01\x05\x1b\x03@N"}, - {"html", "\xb0\x02\x02\x11"}, - {"html/template", "\x03g\x06\x19,5\x01\v \x05\x01\x02\x03\x0e\x01\x02\v\x01\x03\x02"}, - {"image", "\x02k\x1f^\x0f6\x03\x01"}, + {"encoding/ascii85", "\xf1\x01C"}, + {"encoding/asn1", "\x03k\x03\x8c\x01\x01'\r\x02\x01\x10\x03\x01"}, + {"encoding/base32", "\xf1\x01A\x02"}, + {"encoding/base64", "\x99\x01XA\x02"}, + {"encoding/binary", "n\x83\x01\f(\r\x05"}, + {"encoding/csv", "\x02\x01k\x03\x80\x01D\x12\x02"}, + {"encoding/gob", "\x02`\x05\a\x03e\x1b\v\x01\x03\x1d\b\x12\x01\x0f\x02"}, + {"encoding/hex", "n\x03\x80\x01A\x03"}, + {"encoding/json", "\x03\x01^\x04\b\x03\x80\x01\f(\r\x02\x01\x02\x10\x01\x01\x02"}, + {"encoding/pem", "\x03c\b\x83\x01A\x03"}, + {"encoding/xml", "\x02\x01_\f\x03\x80\x014\x05\n\x01\x02\x10\x02"}, + {"errors", "\xca\x01\x81\x01"}, + {"expvar", "kK?\b\v\x15\r\b\x02\x03\x01\x11"}, + {"flag", "b\f\x03\x80\x01,\b\x05\b\x02\x01\x10"}, + {"fmt", "nE>\f \b\r\x02\x03\x12"}, + {"go/ast", "\x03\x01m\x0e\x01q\x03)\b\r\x02\x01"}, + {"go/build", "\x02\x01k\x03\x01\x02\x02\a\x02\x01\x17\x1f\x04\x02\t\x19\x13\x01+\x01\x04\x01\a\b\x02\x01\x12\x02\x02"}, + {"go/build/constraint", "n\xc6\x01\x01\x12\x02"}, + {"go/constant", "q\x0f}\x01\x024\x01\x02\x12"}, + {"go/doc", "\x04m\x01\x05\t>31\x10\x02\x01\x12\x02"}, + {"go/doc/comment", "\x03n\xc1\x01\x01\x01\x01\x12\x02"}, + {"go/format", "\x03n\x01\v\x01\x02qD"}, + {"go/importer", "s\a\x01\x01\x04\x01p9"}, + {"go/internal/gccgoimporter", "\x02\x01X\x13\x03\x04\v\x01n\x02,\x01\x05\x11\x01\f\b"}, + {"go/internal/gcimporter", "\x02o\x0f\x010\x05\x0e-,\x15\x03\x02"}, + {"go/internal/srcimporter", "q\x01\x01\n\x03\x01p,\x01\x05\x12\x02\x14"}, + {"go/parser", "\x03k\x03\x01\x02\v\x01q\x01+\x06\x12"}, + {"go/printer", "q\x01\x02\x03\tq\f \x15\x02\x01\x02\v\x05\x02"}, + {"go/scanner", "\x03n\x0fq2\x10\x01\x13\x02"}, + {"go/token", "\x04m\x83\x01>\x02\x03\x01\x0f\x02"}, + {"go/types", "\x03\x01\x06d\x03\x01\x03\b\x03\x02\x15\x1f\x061\x04\x03\t \x06\a\b\x01\x01\x01\x02\x01\x0f\x02\x02"}, + {"go/version", "\xbb\x01z"}, + {"hash", "\xf1\x01"}, + {"hash/adler32", "n\x15\x16"}, + {"hash/crc32", "n\x15\x16\x15\x89\x01\x01\x13"}, + {"hash/crc64", "n\x15\x16\x9e\x01"}, + {"hash/fnv", "n\x15\x16g"}, + {"hash/maphash", "\x83\x01\x11!\x03\x93\x01"}, + {"html", "\xb5\x02\x02\x12"}, + {"html/template", "\x03h\x06\x18-;\x01\n!\x05\x01\x02\x03\f\x01\x02\f\x01\x03\x02"}, + {"image", "\x02l\x1ee\x0f4\x03\x01"}, {"image/color", ""}, {"image/color/palette", "\x8c\x01"}, {"image/draw", "\x8b\x01\x01\x04"}, - {"image/gif", "\x02\x01\x05e\x03\x1b\x01\x01\x01\vQ"}, + {"image/gif", "\x02\x01\x05f\x03\x1a\x01\x01\x01\vX"}, {"image/internal/imageutil", "\x8b\x01"}, - {"image/jpeg", "\x02k\x1e\x01\x04Z"}, - {"image/png", "\x02\a]\n\x13\x02\x06\x01^E"}, - {"index/suffixarray", "\x03c\a}\r*\f\x01"}, - {"internal/abi", "\xb4\x01\x91\x01"}, - {"internal/asan", "\xc5\x02"}, - {"internal/bisect", "\xa3\x02\x0f\x01"}, - {"internal/buildcfg", "pG_\x06\x02\x05\f\x01"}, - {"internal/bytealg", "\xad\x01\x98\x01"}, + {"image/jpeg", "\x02l\x1d\x01\x04a"}, + {"image/png", "\x02\a^\n\x12\x02\x06\x01eC"}, + {"index/suffixarray", "\x03d\a\x83\x01\f+\n\x01"}, + {"internal/abi", "\xb5\x01\x96\x01"}, + {"internal/asan", "\xcb\x02"}, + {"internal/bisect", "\xaa\x02\r\x01"}, + {"internal/buildcfg", "qGe\x06\x02\x05\n\x01"}, + {"internal/bytealg", "\xae\x01\x9d\x01"}, {"internal/byteorder", ""}, {"internal/cfg", ""}, - {"internal/chacha8rand", "\x99\x01\x1b\x91\x01"}, + {"internal/cgrouptest", "q[Q\x06\x0f\x02\x01\x04\x01"}, + {"internal/chacha8rand", "\x99\x01\x15\a\x96\x01"}, {"internal/copyright", ""}, {"internal/coverage", ""}, {"internal/coverage/calloc", ""}, - {"internal/coverage/cfile", "j\x06\x17\x16\x01\x02\x01\x01\x01\x01\x01\x01\x01#\x01\x1f,\x06\a\f\x01\x03\f\x06"}, - {"internal/coverage/cformat", "\x04l-\x04I\f7\x01\x02\f"}, - {"internal/coverage/cmerge", "p-Z"}, - {"internal/coverage/decodecounter", "f\n-\v\x02@,\x19\x16"}, - {"internal/coverage/decodemeta", "\x02d\n\x17\x16\v\x02@,"}, - {"internal/coverage/encodecounter", "\x02d\n-\f\x01\x02>\f \x17"}, - {"internal/coverage/encodemeta", "\x02\x01c\n\x13\x04\x16\r\x02>,/"}, - {"internal/coverage/pods", "\x04l-y\x06\x05\f\x02\x01"}, - {"internal/coverage/rtcov", "\xc5\x02"}, - {"internal/coverage/slicereader", "f\nz["}, - {"internal/coverage/slicewriter", "pz"}, - {"internal/coverage/stringtab", "p8\x04>"}, + {"internal/coverage/cfile", "k\x06\x16\x17\x01\x02\x01\x01\x01\x01\x01\x01\x01#\x02$,\x06\a\n\x01\x03\r\x06"}, + {"internal/coverage/cformat", "\x04m-\x04O\v6\x01\x02\r"}, + {"internal/coverage/cmerge", "q-_"}, + {"internal/coverage/decodecounter", "g\n-\v\x02F,\x17\x17"}, + {"internal/coverage/decodemeta", "\x02e\n\x16\x17\v\x02F,"}, + {"internal/coverage/encodecounter", "\x02e\n-\f\x01\x02D\v!\x15"}, + {"internal/coverage/encodemeta", "\x02\x01d\n\x12\x04\x17\r\x02D,."}, + {"internal/coverage/pods", "\x04m-\x7f\x06\x05\n\x02\x01"}, + {"internal/coverage/rtcov", "\xcb\x02"}, + {"internal/coverage/slicereader", "g\n\x80\x01Z"}, + {"internal/coverage/slicewriter", "q\x80\x01"}, + {"internal/coverage/stringtab", "q8\x04D"}, {"internal/coverage/test", ""}, {"internal/coverage/uleb128", ""}, - {"internal/cpu", "\xc5\x02"}, - {"internal/dag", "\x04l\xbd\x01\x03"}, - {"internal/diff", "\x03m\xbe\x01\x02"}, - {"internal/exportdata", "\x02\x01j\x03\x03]\x1a,\x01\x05\x13\x01\x02"}, - {"internal/filepathlite", "m+:\x19B"}, - {"internal/fmtsort", "\x04\x9a\x02\x0f"}, - {"internal/fuzz", "\x03\nA\x18\x04\x03\x03\x01\f\x0355\r\x02\x1d\x01\x05\x02\x05\f\x01\x02\x01\x01\v\x04\x02"}, + {"internal/cpu", "\xcb\x02"}, + {"internal/dag", "\x04m\xc1\x01\x03"}, + {"internal/diff", "\x03n\xc2\x01\x02"}, + {"internal/exportdata", "\x02\x01k\x03\x02c\x1b,\x01\x05\x11\x01\x02"}, + {"internal/filepathlite", "n*@\x1a@"}, + {"internal/fmtsort", "\x04\xa1\x02\r"}, + {"internal/fuzz", "\x03\nB\x18\x04\x03\x03\x01\v\x036;\f\x03\x1d\x01\x05\x02\x05\n\x01\x02\x01\x01\f\x04\x02"}, {"internal/goarch", ""}, - {"internal/godebug", "\x96\x01 |\x01\x12"}, + {"internal/godebug", "\x96\x01!\x80\x01\x01\x13"}, {"internal/godebugs", ""}, {"internal/goexperiment", ""}, {"internal/goos", ""}, - {"internal/goroot", "\x96\x02\x01\x05\x14\x02"}, + {"internal/goroot", "\x9d\x02\x01\x05\x12\x02"}, {"internal/gover", "\x04"}, {"internal/goversion", ""}, {"internal/itoa", ""}, - {"internal/lazyregexp", "\x96\x02\v\x0f\x02"}, - {"internal/lazytemplate", "\xea\x01,\x1a\x02\v"}, - {"internal/msan", "\xc5\x02"}, + {"internal/lazyregexp", "\x9d\x02\v\r\x02"}, + {"internal/lazytemplate", "\xf1\x01,\x18\x02\f"}, + {"internal/msan", "\xcb\x02"}, {"internal/nettrace", ""}, - {"internal/obscuretestdata", "e\x85\x01,"}, - {"internal/oserror", "m"}, - {"internal/pkgbits", "\x03K\x18\a\x03\x05\vj\x0e\x1e\r\f\x01"}, + {"internal/obscuretestdata", "f\x8b\x01,"}, + {"internal/oserror", "n"}, + {"internal/pkgbits", "\x03L\x18\a\x03\x04\vq\r\x1f\r\n\x01"}, {"internal/platform", ""}, - {"internal/poll", "mO\x1a\x149\x0f\x01\x01\v\x06"}, - {"internal/profile", "\x03\x04f\x03z7\r\x01\x01\x0f"}, + {"internal/poll", "nO\x1f\x159\r\x01\x01\f\x06"}, + {"internal/profile", "\x03\x04g\x03\x80\x017\v\x01\x01\x10"}, {"internal/profilerecord", ""}, - {"internal/race", "\x94\x01\xb1\x01"}, - {"internal/reflectlite", "\x94\x01 3<\""}, - {"internal/runtime/atomic", "\xc5\x02"}, - {"internal/runtime/exithook", "\xca\x01{"}, - {"internal/runtime/maps", "\x94\x01\x01\x1f\v\t\x05\x01w"}, - {"internal/runtime/math", "\xb4\x01"}, - {"internal/runtime/sys", "\xb4\x01\x04"}, - {"internal/runtime/syscall", "\xc5\x02"}, - {"internal/saferio", "\xea\x01["}, - {"internal/singleflight", "\xb2\x02"}, - {"internal/stringslite", "\x98\x01\xad\x01"}, - {"internal/sync", "\x94\x01 \x14k\x12"}, - {"internal/synctest", "\xc5\x02"}, - {"internal/syscall/execenv", "\xb4\x02"}, - {"internal/syscall/unix", "\xa3\x02\x10\x01\x11"}, - {"internal/sysinfo", "\x02\x01\xaa\x01=,\x1a\x02"}, + {"internal/race", "\x94\x01\xb7\x01"}, + {"internal/reflectlite", "\x94\x01!9<!"}, + {"internal/runtime/atomic", "\xb5\x01\x96\x01"}, + {"internal/runtime/cgroup", "\x98\x01:\x02w"}, + {"internal/runtime/exithook", "\xcb\x01\x80\x01"}, + {"internal/runtime/gc", "\xb5\x01"}, + {"internal/runtime/maps", "\x94\x01\x01 \v\t\a\x03x"}, + {"internal/runtime/math", "\xb5\x01"}, + {"internal/runtime/startlinetest", ""}, + {"internal/runtime/strconv", "\xd0\x01"}, + {"internal/runtime/sys", "\xb5\x01\x04"}, + {"internal/runtime/syscall", "\xb5\x01\x96\x01"}, + {"internal/runtime/wasitest", ""}, + {"internal/saferio", "\xf1\x01Z"}, + {"internal/singleflight", "\xb7\x02"}, + {"internal/stringslite", "\x98\x01\xb3\x01"}, + {"internal/sync", "\x94\x01!\x14o\x13"}, + {"internal/synctest", "\x94\x01\xb7\x01"}, + {"internal/syscall/execenv", "\xb9\x02"}, + {"internal/syscall/unix", "\xaa\x02\x0e\x01\x12"}, + {"internal/sysinfo", "\x02\x01\xab\x01C,\x18\x02"}, {"internal/syslist", ""}, - {"internal/testenv", "\x03\n`\x02\x01*\x1a\x10'+\x01\x05\a\f\x01\x02\x02\x01\n"}, - {"internal/testlog", "\xb2\x02\x01\x12"}, - {"internal/testpty", "m\x03\xa6\x01"}, - {"internal/trace", "\x02\x01\x01\x06\\\a\x03n\x03\x03\x06\x03\n6\x01\x02\x0f\x06"}, - {"internal/trace/internal/testgen", "\x03c\nl\x03\x02\x03\x011\v\x0f"}, - {"internal/trace/internal/tracev1", "\x03\x01b\a\x03t\x06\r6\x01"}, - {"internal/trace/raw", "\x02d\nq\x03\x06E\x01\x11"}, - {"internal/trace/testtrace", "\x02\x01j\x03l\x03\x06\x057\f\x02\x01"}, + {"internal/testenv", "\x03\na\x02\x01)\x1b\x10-+\x01\x05\a\n\x01\x02\x02\x01\v"}, + {"internal/testhash", "\x03\x80\x01n\x118\v"}, + {"internal/testlog", "\xb7\x02\x01\x13"}, + {"internal/testpty", "n\x03\xac\x01"}, + {"internal/trace", "\x02\x01\x01\x06]\a\x03t\x03\x03\x06\x03\t5\x01\x01\x01\x10\x06"}, + {"internal/trace/internal/testgen", "\x03d\nr\x03\x02\x03\x011\v\r\x10"}, + {"internal/trace/internal/tracev1", "\x03\x01c\a\x03z\x06\f5\x01"}, + {"internal/trace/raw", "\x02e\nw\x03\x06C\x01\x12"}, + {"internal/trace/testtrace", "\x02\x01k\x03r\x03\x05\x01\x057\n\x02\x01"}, {"internal/trace/tracev2", ""}, - {"internal/trace/traceviewer", "\x02]\v\x06\x1a<\x16\a\a\x04\t\n\x15\x01\x05\a\f\x01\x02\r"}, + {"internal/trace/traceviewer", "\x02^\v\x06\x19=\x1c\a\a\x04\b\v\x15\x01\x05\a\n\x01\x02\x0e"}, {"internal/trace/traceviewer/format", ""}, - {"internal/trace/version", "pq\t"}, - {"internal/txtar", "\x03m\xa6\x01\x1a"}, - {"internal/types/errors", "\xaf\x02"}, - {"internal/unsafeheader", "\xc5\x02"}, - {"internal/xcoff", "Y\r\a\x03`\x1a,\x19\x01"}, - {"internal/zstd", "f\a\x03z\x0f"}, - {"io", "m\xc5\x01"}, - {"io/fs", "m+*(1\x12\x12\x04"}, - {"io/ioutil", "\xea\x01\x01+\x17\x03"}, - {"iter", "\xc8\x01[\""}, - {"log", "pz\x05'\r\x0f\x01\f"}, + {"internal/trace/version", "qw\t"}, + {"internal/txtar", "\x03n\xac\x01\x18"}, + {"internal/types/errors", "\xb4\x02"}, + {"internal/unsafeheader", "\xcb\x02"}, + {"internal/xcoff", "Z\r\a\x03e\x1b,\x17\x01"}, + {"internal/zstd", "g\a\x03\x80\x01\x0f"}, + {"io", "n\xc9\x01"}, + {"io/fs", "n*+.1\x10\x13\x04"}, + {"io/ioutil", "\xf1\x01\x01+\x15\x03"}, + {"iter", "\xc9\x01a!"}, + {"log", "q\x80\x01\x05'\r\r\x01\r"}, {"log/internal", ""}, - {"log/slog", "\x03\nT\t\x03\x03z\x04\x01\x02\x02\x04'\x05\n\x02\x01\x02\x01\f\x02\x02\x02"}, + {"log/slog", "\x03\nU\t\x03\x03\x80\x01\x04\x01\x02\x02\x03(\x05\b\x02\x01\x02\x01\r\x02\x02\x02"}, {"log/slog/internal", ""}, - {"log/slog/internal/benchmarks", "\r`\x03z\x06\x03<\x10"}, - {"log/slog/internal/buffer", "\xb2\x02"}, - {"log/slog/internal/slogtest", "\xf0\x01"}, - {"log/syslog", "m\x03~\x12\x16\x1a\x02\r"}, - {"maps", "\xed\x01X"}, - {"math", "\xad\x01LL"}, - {"math/big", "\x03j\x03)\x14=\r\x02\x024\x01\x02\x13"}, - {"math/bits", "\xc5\x02"}, - {"math/cmplx", "\xf7\x01\x02"}, - {"math/rand", "\xb5\x01B;\x01\x12"}, - {"math/rand/v2", "m,\x02\\\x02L"}, - {"mime", "\x02\x01b\b\x03z\f \x17\x03\x02\x0f\x02"}, - {"mime/multipart", "\x02\x01G#\x03E5\f\x01\x06\x02\x15\x02\x06\x11\x02\x01\x15"}, - {"mime/quotedprintable", "\x02\x01mz"}, - {"net", "\x04\t`+\x1d\a\x04\x05\f\x01\x04\x14\x01%\x06\r\n\x05\x01\x01\v\x06\a"}, - {"net/http", "\x02\x01\x04\x04\x02=\b\x13\x01\a\x03E5\x01\x03\b\x01\x02\x02\x02\x01\x02\x06\x02\x01\x01\n\x01\x01\x05\x01\x02\x05\n\x01\x01\x01\x02\x01\x01\v\x02\x02\x02\b\x01\x01\x01"}, - {"net/http/cgi", "\x02P\x1b\x03z\x04\b\n\x01\x13\x01\x01\x01\x04\x01\x05\x02\n\x02\x01\x0f\x0e"}, - {"net/http/cookiejar", "\x04i\x03\x90\x01\x01\b\f\x18\x03\x02\r\x04"}, - {"net/http/fcgi", "\x02\x01\nY\a\x03z\x16\x01\x01\x14\x1a\x02\r"}, - {"net/http/httptest", "\x02\x01\nE\x02\x1b\x01z\x04\x12\x01\n\t\x02\x19\x01\x02\r\x0e"}, - {"net/http/httptrace", "\rEn@\x14\n!"}, - {"net/http/httputil", "\x02\x01\n`\x03z\x04\x0f\x03\x01\x05\x02\x01\v\x01\x1b\x02\r\x0e"}, - {"net/http/internal", "\x02\x01j\x03z"}, - {"net/http/internal/ascii", "\xb0\x02\x11"}, - {"net/http/internal/httpcommon", "\r`\x03\x96\x01\x0e\x01\x19\x01\x01\x02\x1b\x02"}, - {"net/http/internal/testcert", "\xb0\x02"}, - {"net/http/pprof", "\x02\x01\nc\x19,\x11$\x04\x13\x14\x01\r\x06\x03\x01\x02\x01\x0f"}, + {"log/slog/internal/benchmarks", "\ra\x03\x80\x01\x06\x03:\x11"}, + {"log/slog/internal/buffer", "\xb7\x02"}, + {"log/syslog", "n\x03\x84\x01\x12\x16\x18\x02\x0e"}, + {"maps", "\xf4\x01W"}, + {"math", "\xae\x01RK"}, + {"math/big", "\x03k\x03(\x15C\f\x03\x020\x02\x01\x02\x14"}, + {"math/big/internal/asmgen", "\x03\x01m\x8f\x012\x03"}, + {"math/bits", "\xcb\x02"}, + {"math/cmplx", "\xfd\x01\x03"}, + {"math/rand", "\xb6\x01G:\x01\x13"}, + {"math/rand/v2", "n+\x03a\x03K"}, + {"mime", "\x02\x01c\b\x03\x80\x01\v!\x15\x03\x02\x10\x02"}, + {"mime/multipart", "\x02\x01H#\x03E;\v\x01\a\x02\x15\x02\x06\x0f\x02\x01\x16"}, + {"mime/quotedprintable", "\x02\x01n\x80\x01"}, + {"net", "\x04\ta*\x1e\a\x04\x05\x11\x01\x04\x15\x01%\x06\r\b\x05\x01\x01\f\x06\a"}, + {"net/http", "\x02\x01\x04\x04\x02>\b\x13\x01\a\x03E;\x01\x03\a\x01\x03\x02\x02\x01\x02\x06\x02\x01\x01\n\x01\x01\x05\x01\x02\x05\b\x01\x01\x01\x02\x01\r\x02\x02\x02\b\x01\x01\x01"}, + {"net/http/cgi", "\x02Q\x1b\x03\x80\x01\x04\a\v\x01\x13\x01\x01\x01\x04\x01\x05\x02\b\x02\x01\x10\x0e"}, + {"net/http/cookiejar", "\x04j\x03\x96\x01\x01\b\f\x16\x03\x02\x0e\x04"}, + {"net/http/fcgi", "\x02\x01\nZ\a\x03\x80\x01\x16\x01\x01\x14\x18\x02\x0e"}, + {"net/http/httptest", "\x02\x01\nF\x02\x1b\x01\x80\x01\x04\x12\x01\n\t\x02\x17\x01\x02\x0e\x0e"}, + {"net/http/httptrace", "\rFnF\x14\n "}, + {"net/http/httputil", "\x02\x01\na\x03\x80\x01\x04\x0f\x03\x01\x05\x02\x01\v\x01\x19\x02\x0e\x0e"}, + {"net/http/internal", "\x02\x01k\x03\x80\x01"}, + {"net/http/internal/ascii", "\xb5\x02\x12"}, + {"net/http/internal/httpcommon", "\ra\x03\x9c\x01\x0e\x01\x17\x01\x01\x02\x1c\x02"}, + {"net/http/internal/testcert", "\xb5\x02"}, + {"net/http/pprof", "\x02\x01\nd\x18-\x11*\x04\x13\x14\x01\r\x04\x03\x01\x02\x01\x10"}, {"net/internal/cgotest", ""}, - {"net/internal/socktest", "p\xc2\x01\x02"}, - {"net/mail", "\x02k\x03z\x04\x0f\x03\x14\x1c\x02\r\x04"}, - {"net/netip", "\x04i+\x01#;\x026\x15"}, - {"net/rpc", "\x02f\x05\x03\x10\n`\x04\x12\x01\x1d\x0f\x03\x02"}, - {"net/rpc/jsonrpc", "j\x03\x03z\x16\x11!"}, - {"net/smtp", "\x19.\v\x13\b\x03z\x16\x14\x1c"}, - {"net/textproto", "\x02\x01j\x03z\r\t/\x01\x02\x13"}, - {"net/url", "m\x03\x86\x01%\x12\x02\x01\x15"}, - {"os", "m+\x01\x18\x03\b\t\r\x03\x01\x04\x10\x018\n\x05\x01\x01\v\x06"}, - {"os/exec", "\x03\n`H \x01\x14\x01+\x06\a\f\x01\x04\v"}, - {"os/exec/internal/fdtest", "\xb4\x02"}, - {"os/signal", "\r\x89\x02\x17\x05\x02"}, - {"os/user", "\x02\x01j\x03z,\r\f\x01\x02"}, - {"path", "m+\xab\x01"}, - {"path/filepath", "m+\x19:+\r\n\x03\x04\x0f"}, - {"plugin", "m"}, - {"reflect", "m'\x04\x1c\b\f\x04\x02\x19\x10,\f\x03\x0f\x02\x02"}, + {"net/internal/socktest", "q\xc6\x01\x02"}, + {"net/mail", "\x02l\x03\x80\x01\x04\x0f\x03\x14\x1a\x02\x0e\x04"}, + {"net/netip", "\x04j*\x01$@\x034\x16"}, + {"net/rpc", "\x02g\x05\x03\x0f\ng\x04\x12\x01\x1d\r\x03\x02"}, + {"net/rpc/jsonrpc", "k\x03\x03\x80\x01\x16\x11\x1f"}, + {"net/smtp", "\x19/\v\x13\b\x03\x80\x01\x16\x14\x1a"}, + {"net/textproto", "\x02\x01k\x03\x80\x01\f\n-\x01\x02\x14"}, + {"net/url", "n\x03\x8b\x01&\x10\x02\x01\x16"}, + {"os", "n*\x01\x19\x03\b\t\x12\x03\x01\x05\x10\x018\b\x05\x01\x01\f\x06"}, + {"os/exec", "\x03\naH%\x01\x15\x01+\x06\a\n\x01\x04\f"}, + {"os/exec/internal/fdtest", "\xb9\x02"}, + {"os/signal", "\r\x90\x02\x15\x05\x02"}, + {"os/user", "\x02\x01k\x03\x80\x01,\r\n\x01\x02"}, + {"path", "n*\xb1\x01"}, + {"path/filepath", "n*\x1a@+\r\b\x03\x04\x10"}, + {"plugin", "n"}, + {"reflect", "n&\x04\x1d\b\f\x06\x04\x1b\x06\t-\n\x03\x10\x02\x02"}, {"reflect/internal/example1", ""}, {"reflect/internal/example2", ""}, - {"regexp", "\x03\xe7\x018\v\x02\x01\x02\x0f\x02"}, - {"regexp/syntax", "\xad\x02\x01\x01\x01\x11\x02"}, - {"runtime", "\x94\x01\x04\x01\x02\f\x06\a\x02\x01\x01\x0f\x03\x01\x01\x01\x01\x01\x03\x0fd"}, - {"runtime/coverage", "\x9f\x01K"}, - {"runtime/debug", "pUQ\r\n\x02\x01\x0f\x06"}, - {"runtime/internal/startlinetest", ""}, - {"runtime/internal/wasitest", ""}, - {"runtime/metrics", "\xb6\x01A,\""}, - {"runtime/pprof", "\x02\x01\x01\x03\x06Y\a\x03$3#\r\x1f\r\n\x01\x01\x01\x02\x02\b\x03\x06"}, - {"runtime/race", "\xab\x02"}, + {"regexp", "\x03\xee\x018\t\x02\x01\x02\x10\x02"}, + {"regexp/syntax", "\xb2\x02\x01\x01\x01\x02\x10\x02"}, + {"runtime", "\x94\x01\x04\x01\x03\f\x06\a\x02\x01\x01\x0f\x03\x01\x01\x01\x01\x01\x02\x01\x01\x04\x10c"}, + {"runtime/coverage", "\xa0\x01Q"}, + {"runtime/debug", "qUW\r\b\x02\x01\x10\x06"}, + {"runtime/metrics", "\xb7\x01F-!"}, + {"runtime/pprof", "\x02\x01\x01\x03\x06Z\a\x03#4)\f \r\b\x01\x01\x01\x02\x02\t\x03\x06"}, + {"runtime/race", "\xb0\x02"}, {"runtime/race/internal/amd64v1", ""}, - {"runtime/trace", "\rcz9\x0f\x01\x12"}, - {"slices", "\x04\xe9\x01\fL"}, - {"sort", "\xc9\x0104"}, - {"strconv", "m+:%\x02J"}, - {"strings", "m'\x04:\x18\x03\f9\x0f\x02\x02"}, + {"runtime/trace", "\ra\x03w\t9\b\x05\x01\r\x06"}, + {"slices", "\x04\xf0\x01\fK"}, + {"sort", "\xca\x0162"}, + {"strconv", "n*@%\x03I"}, + {"strings", "n&\x04@\x19\x03\f7\x10\x02\x02"}, {"structs", ""}, - {"sync", "\xc8\x01\vP\x10\x12"}, - {"sync/atomic", "\xc5\x02"}, - {"syscall", "m(\x03\x01\x1b\b\x03\x03\x06\aT\n\x05\x01\x12"}, - {"testing", "\x03\n`\x02\x01X\x0f\x13\r\x04\x1b\x06\x02\x05\x02\a\x01\x02\x01\x02\x01\f\x02\x02\x02"}, - {"testing/fstest", "m\x03z\x01\v%\x12\x03\b\a"}, - {"testing/internal/testdeps", "\x02\v\xa6\x01'\x10,\x03\x05\x03\b\a\x02\r"}, - {"testing/iotest", "\x03j\x03z\x04"}, - {"testing/quick", "o\x01\x87\x01\x04#\x12\x0f"}, - {"testing/slogtest", "\r`\x03\x80\x01.\x05\x12\n"}, - {"text/scanner", "\x03mz,+\x02"}, - {"text/tabwriter", "pzY"}, - {"text/template", "m\x03B8\x01\v\x1f\x01\x05\x01\x02\x05\r\x02\f\x03\x02"}, - {"text/template/parse", "\x03m\xb3\x01\f\x01\x11\x02"}, - {"time", "m+\x1d\x1d'*\x0f\x02\x11"}, - {"time/tzdata", "m\xc7\x01\x11"}, + {"sync", "\xc9\x01\x10\x01P\x0e\x13"}, + {"sync/atomic", "\xcb\x02"}, + {"syscall", "n'\x03\x01\x1c\b\x03\x03\x06\vV\b\x05\x01\x13"}, + {"testing", "\x03\na\x02\x01X\x14\x14\f\x05\x1b\x06\x02\x05\x02\x05\x01\x02\x01\x02\x01\r\x02\x02\x02"}, + {"testing/fstest", "n\x03\x80\x01\x01\n&\x10\x03\b\b"}, + {"testing/internal/testdeps", "\x02\v\xa7\x01-\x10,\x03\x05\x03\x06\a\x02\x0e"}, + {"testing/iotest", "\x03k\x03\x80\x01\x04"}, + {"testing/quick", "p\x01\x8c\x01\x05#\x10\x10"}, + {"testing/slogtest", "\ra\x03\x86\x01.\x05\x10\v"}, + {"testing/synctest", "\xda\x01`\x11"}, + {"text/scanner", "\x03n\x80\x01,*\x02"}, + {"text/tabwriter", "q\x80\x01X"}, + {"text/template", "n\x03B>\x01\n \x01\x05\x01\x02\x05\v\x02\r\x03\x02"}, + {"text/template/parse", "\x03n\xb9\x01\n\x01\x12\x02"}, + {"time", "n*\x1e\"(*\r\x02\x12"}, + {"time/tzdata", "n\xcb\x01\x12"}, {"unicode", ""}, {"unicode/utf16", ""}, {"unicode/utf8", ""}, - {"unique", "\x94\x01>\x01P\x0f\x13\x12"}, + {"unique", "\x94\x01!#\x01Q\r\x01\x13\x12"}, {"unsafe", ""}, - {"vendor/golang.org/x/crypto/chacha20", "\x10V\a\x8c\x01*'"}, - {"vendor/golang.org/x/crypto/chacha20poly1305", "\x10V\a\xd9\x01\x04\x01\a"}, - {"vendor/golang.org/x/crypto/cryptobyte", "c\n\x03\x88\x01&!\n"}, + {"vendor/golang.org/x/crypto/chacha20", "\x10W\a\x92\x01*&"}, + {"vendor/golang.org/x/crypto/chacha20poly1305", "\x10W\a\xde\x01\x04\x01\a"}, + {"vendor/golang.org/x/crypto/cryptobyte", "d\n\x03\x8d\x01' \n"}, {"vendor/golang.org/x/crypto/cryptobyte/asn1", ""}, - {"vendor/golang.org/x/crypto/internal/alias", "\xc5\x02"}, - {"vendor/golang.org/x/crypto/internal/poly1305", "Q\x15\x93\x01"}, - {"vendor/golang.org/x/net/dns/dnsmessage", "m"}, - {"vendor/golang.org/x/net/http/httpguts", "\x80\x02\x14\x1c\x13\r"}, - {"vendor/golang.org/x/net/http/httpproxy", "m\x03\x90\x01\x15\x01\x1a\x13\r"}, - {"vendor/golang.org/x/net/http2/hpack", "\x03j\x03zH"}, - {"vendor/golang.org/x/net/idna", "p\x87\x019\x13\x10\x02\x01"}, - {"vendor/golang.org/x/net/nettest", "\x03c\a\x03z\x11\x05\x16\x01\f\f\x01\x02\x02\x01\n"}, - {"vendor/golang.org/x/sys/cpu", "\x96\x02\r\f\x01\x15"}, - {"vendor/golang.org/x/text/secure/bidirule", "m\xd6\x01\x11\x01"}, - {"vendor/golang.org/x/text/transform", "\x03j}Y"}, - {"vendor/golang.org/x/text/unicode/bidi", "\x03\be~@\x15"}, - {"vendor/golang.org/x/text/unicode/norm", "f\nzH\x11\x11"}, - {"weak", "\x94\x01\x8f\x01\""}, + {"vendor/golang.org/x/crypto/internal/alias", "\xcb\x02"}, + {"vendor/golang.org/x/crypto/internal/poly1305", "R\x15\x99\x01"}, + {"vendor/golang.org/x/net/dns/dnsmessage", "n"}, + {"vendor/golang.org/x/net/http/httpguts", "\x87\x02\x14\x1a\x14\r"}, + {"vendor/golang.org/x/net/http/httpproxy", "n\x03\x96\x01\x10\x05\x01\x18\x14\r"}, + {"vendor/golang.org/x/net/http2/hpack", "\x03k\x03\x80\x01F"}, + {"vendor/golang.org/x/net/idna", "q\x8c\x018\x14\x10\x02\x01"}, + {"vendor/golang.org/x/net/nettest", "\x03d\a\x03\x80\x01\x11\x05\x16\x01\f\n\x01\x02\x02\x01\v"}, + {"vendor/golang.org/x/sys/cpu", "\x9d\x02\r\n\x01\x16"}, + {"vendor/golang.org/x/text/secure/bidirule", "n\xdb\x01\x11\x01"}, + {"vendor/golang.org/x/text/transform", "\x03k\x83\x01X"}, + {"vendor/golang.org/x/text/unicode/bidi", "\x03\bf\x84\x01>\x16"}, + {"vendor/golang.org/x/text/unicode/norm", "g\n\x80\x01F\x12\x11"}, + {"weak", "\x94\x01\x96\x01!"}, } diff --git a/vendor/golang.org/x/tools/internal/stdlib/manifest.go b/vendor/golang.org/x/tools/internal/stdlib/manifest.go index 64f0326..c1faa50 100644 --- a/vendor/golang.org/x/tools/internal/stdlib/manifest.go +++ b/vendor/golang.org/x/tools/internal/stdlib/manifest.go @@ -502,6 +502,7 @@ var PackageSymbols = map[string][]Symbol{ {"MD4", Const, 0, ""}, {"MD5", Const, 0, ""}, {"MD5SHA1", Const, 0, ""}, + {"MessageSigner", Type, 25, ""}, {"PrivateKey", Type, 0, ""}, {"PublicKey", Type, 2, ""}, {"RIPEMD160", Const, 0, ""}, @@ -517,6 +518,7 @@ var PackageSymbols = map[string][]Symbol{ {"SHA512", Const, 0, ""}, {"SHA512_224", Const, 5, ""}, {"SHA512_256", Const, 5, ""}, + {"SignMessage", Func, 25, "func(signer Signer, rand io.Reader, msg []byte, opts SignerOpts) (signature []byte, err error)"}, {"Signer", Type, 4, ""}, {"SignerOpts", Type, 4, ""}, }, @@ -600,10 +602,12 @@ var PackageSymbols = map[string][]Symbol{ {"X25519", Func, 20, "func() Curve"}, }, "crypto/ecdsa": { + {"(*PrivateKey).Bytes", Method, 25, ""}, {"(*PrivateKey).ECDH", Method, 20, ""}, {"(*PrivateKey).Equal", Method, 15, ""}, {"(*PrivateKey).Public", Method, 4, ""}, {"(*PrivateKey).Sign", Method, 4, ""}, + {"(*PublicKey).Bytes", Method, 25, ""}, {"(*PublicKey).ECDH", Method, 20, ""}, {"(*PublicKey).Equal", Method, 15, ""}, {"(PrivateKey).Add", Method, 0, ""}, @@ -619,6 +623,8 @@ var PackageSymbols = map[string][]Symbol{ {"(PublicKey).ScalarBaseMult", Method, 0, ""}, {"(PublicKey).ScalarMult", Method, 0, ""}, {"GenerateKey", Func, 0, "func(c elliptic.Curve, rand io.Reader) (*PrivateKey, error)"}, + {"ParseRawPrivateKey", Func, 25, "func(curve elliptic.Curve, data []byte) (*PrivateKey, error)"}, + {"ParseUncompressedPublicKey", Func, 25, "func(curve elliptic.Curve, data []byte) (*PublicKey, error)"}, {"PrivateKey", Type, 0, ""}, {"PrivateKey.D", Field, 0, ""}, {"PrivateKey.PublicKey", Field, 0, ""}, @@ -815,6 +821,7 @@ var PackageSymbols = map[string][]Symbol{ "crypto/sha3": { {"(*SHA3).AppendBinary", Method, 24, ""}, {"(*SHA3).BlockSize", Method, 24, ""}, + {"(*SHA3).Clone", Method, 25, ""}, {"(*SHA3).MarshalBinary", Method, 24, ""}, {"(*SHA3).Reset", Method, 24, ""}, {"(*SHA3).Size", Method, 24, ""}, @@ -967,6 +974,7 @@ var PackageSymbols = map[string][]Symbol{ {"Config.GetCertificate", Field, 4, ""}, {"Config.GetClientCertificate", Field, 8, ""}, {"Config.GetConfigForClient", Field, 8, ""}, + {"Config.GetEncryptedClientHelloKeys", Field, 25, ""}, {"Config.InsecureSkipVerify", Field, 0, ""}, {"Config.KeyLogWriter", Field, 8, ""}, {"Config.MaxVersion", Field, 2, ""}, @@ -5463,6 +5471,7 @@ var PackageSymbols = map[string][]Symbol{ {"ParenExpr.X", Field, 0, ""}, {"Pkg", Const, 0, ""}, {"Preorder", Func, 23, "func(root Node) iter.Seq[Node]"}, + {"PreorderStack", Func, 25, "func(root Node, stack []Node, f func(n Node, stack []Node) bool)"}, {"Print", Func, 0, "func(fset *token.FileSet, x any) error"}, {"RECV", Const, 0, ""}, {"RangeStmt", Type, 0, ""}, @@ -5933,6 +5942,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*File).SetLines", Method, 0, ""}, {"(*File).SetLinesForContent", Method, 0, ""}, {"(*File).Size", Method, 0, ""}, + {"(*FileSet).AddExistingFiles", Method, 25, ""}, {"(*FileSet).AddFile", Method, 0, ""}, {"(*FileSet).Base", Method, 0, ""}, {"(*FileSet).File", Method, 0, ""}, @@ -6382,7 +6392,7 @@ var PackageSymbols = map[string][]Symbol{ {"Label", Type, 5, ""}, {"LocalVar", Const, 25, ""}, {"LookupFieldOrMethod", Func, 5, "func(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)"}, - {"LookupSelection", Func, 25, ""}, + {"LookupSelection", Func, 25, "func(T Type, addressable bool, pkg *Package, name string) (Selection, bool)"}, {"Map", Type, 5, ""}, {"MethodExpr", Const, 5, ""}, {"MethodSet", Type, 5, ""}, @@ -6490,9 +6500,11 @@ var PackageSymbols = map[string][]Symbol{ {"Lang", Func, 22, "func(x string) string"}, }, "hash": { + {"Cloner", Type, 25, ""}, {"Hash", Type, 0, ""}, {"Hash32", Type, 0, ""}, {"Hash64", Type, 0, ""}, + {"XOF", Type, 25, ""}, }, "hash/adler32": { {"Checksum", Func, 0, "func(data []byte) uint32"}, @@ -6533,6 +6545,7 @@ var PackageSymbols = map[string][]Symbol{ }, "hash/maphash": { {"(*Hash).BlockSize", Method, 14, ""}, + {"(*Hash).Clone", Method, 25, ""}, {"(*Hash).Reset", Method, 14, ""}, {"(*Hash).Seed", Method, 14, ""}, {"(*Hash).SetSeed", Method, 14, ""}, @@ -7133,7 +7146,7 @@ var PackageSymbols = map[string][]Symbol{ {"FormatFileInfo", Func, 21, "func(info FileInfo) string"}, {"Glob", Func, 16, "func(fsys FS, pattern string) (matches []string, err error)"}, {"GlobFS", Type, 16, ""}, - {"Lstat", Func, 25, ""}, + {"Lstat", Func, 25, "func(fsys FS, name string) (FileInfo, error)"}, {"ModeAppend", Const, 16, ""}, {"ModeCharDevice", Const, 16, ""}, {"ModeDevice", Const, 16, ""}, @@ -7158,7 +7171,7 @@ var PackageSymbols = map[string][]Symbol{ {"ReadDirFile", Type, 16, ""}, {"ReadFile", Func, 16, "func(fsys FS, name string) ([]byte, error)"}, {"ReadFileFS", Type, 16, ""}, - {"ReadLink", Func, 25, ""}, + {"ReadLink", Func, 25, "func(fsys FS, name string) (string, error)"}, {"ReadLinkFS", Type, 25, ""}, {"SkipAll", Var, 20, ""}, {"SkipDir", Var, 16, ""}, @@ -7275,6 +7288,7 @@ var PackageSymbols = map[string][]Symbol{ {"(Record).Attrs", Method, 21, ""}, {"(Record).Clone", Method, 21, ""}, {"(Record).NumAttrs", Method, 21, ""}, + {"(Record).Source", Method, 25, ""}, {"(Value).Any", Method, 21, ""}, {"(Value).Bool", Method, 21, ""}, {"(Value).Duration", Method, 21, ""}, @@ -7306,6 +7320,7 @@ var PackageSymbols = map[string][]Symbol{ {"Float64", Func, 21, "func(key string, v float64) Attr"}, {"Float64Value", Func, 21, "func(v float64) Value"}, {"Group", Func, 21, "func(key string, args ...any) Attr"}, + {"GroupAttrs", Func, 25, "func(key string, attrs ...Attr) Attr"}, {"GroupValue", Func, 21, "func(as ...Attr) Value"}, {"Handler", Type, 21, ""}, {"HandlerOptions", Type, 21, ""}, @@ -7916,7 +7931,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*Writer).WriteField", Method, 0, ""}, {"ErrMessageTooLarge", Var, 9, ""}, {"File", Type, 0, ""}, - {"FileContentDisposition", Func, 25, ""}, + {"FileContentDisposition", Func, 25, "func(fieldname string, filename string) string"}, {"FileHeader", Type, 0, ""}, {"FileHeader.Filename", Field, 0, ""}, {"FileHeader.Header", Field, 0, ""}, @@ -8294,6 +8309,11 @@ var PackageSymbols = map[string][]Symbol{ {"(*Client).PostForm", Method, 0, ""}, {"(*Cookie).String", Method, 0, ""}, {"(*Cookie).Valid", Method, 18, ""}, + {"(*CrossOriginProtection).AddInsecureBypassPattern", Method, 25, ""}, + {"(*CrossOriginProtection).AddTrustedOrigin", Method, 25, ""}, + {"(*CrossOriginProtection).Check", Method, 25, ""}, + {"(*CrossOriginProtection).Handler", Method, 25, ""}, + {"(*CrossOriginProtection).SetDenyHandler", Method, 25, ""}, {"(*MaxBytesError).Error", Method, 19, ""}, {"(*ProtocolError).Error", Method, 0, ""}, {"(*ProtocolError).Is", Method, 21, ""}, @@ -8388,6 +8408,7 @@ var PackageSymbols = map[string][]Symbol{ {"Cookie.Unparsed", Field, 0, ""}, {"Cookie.Value", Field, 0, ""}, {"CookieJar", Type, 0, ""}, + {"CrossOriginProtection", Type, 25, ""}, {"DefaultClient", Var, 0, ""}, {"DefaultMaxHeaderBytes", Const, 0, ""}, {"DefaultMaxIdleConnsPerHost", Const, 0, ""}, @@ -8460,6 +8481,7 @@ var PackageSymbols = map[string][]Symbol{ {"MethodPost", Const, 6, ""}, {"MethodPut", Const, 6, ""}, {"MethodTrace", Const, 6, ""}, + {"NewCrossOriginProtection", Func, 25, "func() *CrossOriginProtection"}, {"NewFileTransport", Func, 0, "func(fs FileSystem) RoundTripper"}, {"NewFileTransportFS", Func, 22, "func(fsys fs.FS) RoundTripper"}, {"NewRequest", Func, 0, "func(method string, url string, body io.Reader) (*Request, error)"}, @@ -9174,15 +9196,19 @@ var PackageSymbols = map[string][]Symbol{ {"(*Root).Link", Method, 25, ""}, {"(*Root).Lstat", Method, 24, ""}, {"(*Root).Mkdir", Method, 24, ""}, + {"(*Root).MkdirAll", Method, 25, ""}, {"(*Root).Name", Method, 24, ""}, {"(*Root).Open", Method, 24, ""}, {"(*Root).OpenFile", Method, 24, ""}, {"(*Root).OpenRoot", Method, 24, ""}, + {"(*Root).ReadFile", Method, 25, ""}, {"(*Root).Readlink", Method, 25, ""}, {"(*Root).Remove", Method, 24, ""}, + {"(*Root).RemoveAll", Method, 25, ""}, {"(*Root).Rename", Method, 25, ""}, {"(*Root).Stat", Method, 24, ""}, {"(*Root).Symlink", Method, 25, ""}, + {"(*Root).WriteFile", Method, 25, ""}, {"(*SyscallError).Error", Method, 0, ""}, {"(*SyscallError).Timeout", Method, 10, ""}, {"(*SyscallError).Unwrap", Method, 13, ""}, @@ -9623,6 +9649,7 @@ var PackageSymbols = map[string][]Symbol{ {"StructTag", Type, 0, ""}, {"Swapper", Func, 8, "func(slice any) func(i int, j int)"}, {"Type", Type, 0, ""}, + {"TypeAssert", Func, 25, "func[T any](v Value) (T, bool)"}, {"TypeFor", Func, 22, "func[T any]() Type"}, {"TypeOf", Func, 0, "func(i any) Type"}, {"Uint", Const, 0, ""}, @@ -9909,6 +9936,7 @@ var PackageSymbols = map[string][]Symbol{ {"SetBlockProfileRate", Func, 1, "func(rate int)"}, {"SetCPUProfileRate", Func, 0, "func(hz int)"}, {"SetCgoTraceback", Func, 7, "func(version int, traceback unsafe.Pointer, context unsafe.Pointer, symbolizer unsafe.Pointer)"}, + {"SetDefaultGOMAXPROCS", Func, 25, "func()"}, {"SetFinalizer", Func, 0, "func(obj any, finalizer any)"}, {"SetMutexProfileFraction", Func, 8, "func(rate int) int"}, {"Stack", Func, 0, "func(buf []byte, all bool) int"}, @@ -10021,11 +10049,20 @@ var PackageSymbols = map[string][]Symbol{ {"WriteHeapProfile", Func, 0, "func(w io.Writer) error"}, }, "runtime/trace": { + {"(*FlightRecorder).Enabled", Method, 25, ""}, + {"(*FlightRecorder).Start", Method, 25, ""}, + {"(*FlightRecorder).Stop", Method, 25, ""}, + {"(*FlightRecorder).WriteTo", Method, 25, ""}, {"(*Region).End", Method, 11, ""}, {"(*Task).End", Method, 11, ""}, + {"FlightRecorder", Type, 25, ""}, + {"FlightRecorderConfig", Type, 25, ""}, + {"FlightRecorderConfig.MaxBytes", Field, 25, ""}, + {"FlightRecorderConfig.MinAge", Field, 25, ""}, {"IsEnabled", Func, 11, "func() bool"}, {"Log", Func, 11, "func(ctx context.Context, category string, message string)"}, {"Logf", Func, 11, "func(ctx context.Context, category string, format string, args ...any)"}, + {"NewFlightRecorder", Func, 25, "func(cfg FlightRecorderConfig) *FlightRecorder"}, {"NewTask", Func, 11, "func(pctx context.Context, taskType string) (ctx context.Context, task *Task)"}, {"Region", Type, 11, ""}, {"Start", Func, 5, "func(w io.Writer) error"}, @@ -16642,6 +16679,7 @@ var PackageSymbols = map[string][]Symbol{ {"ValueOf", Func, 0, ""}, }, "testing": { + {"(*B).Attr", Method, 25, ""}, {"(*B).Chdir", Method, 24, ""}, {"(*B).Cleanup", Method, 14, ""}, {"(*B).Context", Method, 24, ""}, @@ -16658,6 +16696,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*B).Logf", Method, 0, ""}, {"(*B).Loop", Method, 24, ""}, {"(*B).Name", Method, 8, ""}, + {"(*B).Output", Method, 25, ""}, {"(*B).ReportAllocs", Method, 1, ""}, {"(*B).ReportMetric", Method, 13, ""}, {"(*B).ResetTimer", Method, 0, ""}, @@ -16674,6 +16713,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*B).StopTimer", Method, 0, ""}, {"(*B).TempDir", Method, 15, ""}, {"(*F).Add", Method, 18, ""}, + {"(*F).Attr", Method, 25, ""}, {"(*F).Chdir", Method, 24, ""}, {"(*F).Cleanup", Method, 18, ""}, {"(*F).Context", Method, 24, ""}, @@ -16689,6 +16729,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*F).Log", Method, 18, ""}, {"(*F).Logf", Method, 18, ""}, {"(*F).Name", Method, 18, ""}, + {"(*F).Output", Method, 25, ""}, {"(*F).Setenv", Method, 18, ""}, {"(*F).Skip", Method, 18, ""}, {"(*F).SkipNow", Method, 18, ""}, @@ -16697,6 +16738,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*F).TempDir", Method, 18, ""}, {"(*M).Run", Method, 4, ""}, {"(*PB).Next", Method, 3, ""}, + {"(*T).Attr", Method, 25, ""}, {"(*T).Chdir", Method, 24, ""}, {"(*T).Cleanup", Method, 14, ""}, {"(*T).Context", Method, 24, ""}, @@ -16712,6 +16754,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*T).Log", Method, 0, ""}, {"(*T).Logf", Method, 0, ""}, {"(*T).Name", Method, 8, ""}, + {"(*T).Output", Method, 25, ""}, {"(*T).Parallel", Method, 0, ""}, {"(*T).Run", Method, 7, ""}, {"(*T).Setenv", Method, 17, ""}, @@ -16834,6 +16877,10 @@ var PackageSymbols = map[string][]Symbol{ {"Run", Func, 22, "func(t *testing.T, newHandler func(*testing.T) slog.Handler, result func(*testing.T) map[string]any)"}, {"TestHandler", Func, 21, "func(h slog.Handler, results func() []map[string]any) error"}, }, + "testing/synctest": { + {"Test", Func, 25, "func(t *testing.T, f func(*testing.T))"}, + {"Wait", Func, 25, "func()"}, + }, "text/scanner": { {"(*Position).IsValid", Method, 0, ""}, {"(*Scanner).Init", Method, 0, ""}, @@ -17347,6 +17394,7 @@ var PackageSymbols = map[string][]Symbol{ {"CaseRange.Lo", Field, 0, ""}, {"CaseRanges", Var, 0, ""}, {"Categories", Var, 0, ""}, + {"CategoryAliases", Var, 25, ""}, {"Caucasian_Albanian", Var, 4, ""}, {"Cc", Var, 0, ""}, {"Cf", Var, 0, ""}, @@ -17354,6 +17402,7 @@ var PackageSymbols = map[string][]Symbol{ {"Cham", Var, 0, ""}, {"Cherokee", Var, 0, ""}, {"Chorasmian", Var, 16, ""}, + {"Cn", Var, 25, ""}, {"Co", Var, 0, ""}, {"Common", Var, 0, ""}, {"Coptic", Var, 0, ""}, @@ -17432,6 +17481,7 @@ var PackageSymbols = map[string][]Symbol{ {"Khojki", Var, 4, ""}, {"Khudawadi", Var, 4, ""}, {"L", Var, 0, ""}, + {"LC", Var, 25, ""}, {"Lao", Var, 0, ""}, {"Latin", Var, 0, ""}, {"Lepcha", Var, 0, ""}, diff --git a/vendor/golang.org/x/tools/internal/typesinternal/fx.go b/vendor/golang.org/x/tools/internal/typesinternal/fx.go new file mode 100644 index 0000000..93acff2 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/fx.go @@ -0,0 +1,49 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package typesinternal + +import ( + "go/ast" + "go/token" + "go/types" +) + +// NoEffects reports whether the expression has no side effects, i.e., it +// does not modify the memory state. This function is conservative: it may +// return false even when the expression has no effect. +func NoEffects(info *types.Info, expr ast.Expr) bool { + noEffects := true + ast.Inspect(expr, func(n ast.Node) bool { + switch v := n.(type) { + case nil, *ast.Ident, *ast.BasicLit, *ast.BinaryExpr, *ast.ParenExpr, + *ast.SelectorExpr, *ast.IndexExpr, *ast.SliceExpr, *ast.TypeAssertExpr, + *ast.StarExpr, *ast.CompositeLit, *ast.ArrayType, *ast.StructType, + *ast.MapType, *ast.InterfaceType, *ast.KeyValueExpr: + // No effect + case *ast.UnaryExpr: + // Channel send <-ch has effects + if v.Op == token.ARROW { + noEffects = false + } + case *ast.CallExpr: + // Type conversion has no effects + if !info.Types[v.Fun].IsType() { + // TODO(adonovan): Add a case for built-in functions without side + // effects (by using callsPureBuiltin from tools/internal/refactor/inline) + + noEffects = false + } + case *ast.FuncLit: + // A FuncLit has no effects, but do not descend into it. + return false + default: + // All other expressions have effects + noEffects = false + } + + return noEffects + }) + return noEffects +} diff --git a/vendor/golang.org/x/tools/internal/typesinternal/isnamed.go b/vendor/golang.org/x/tools/internal/typesinternal/isnamed.go new file mode 100644 index 0000000..f2affec --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/isnamed.go @@ -0,0 +1,71 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package typesinternal + +import ( + "go/types" + "slices" +) + +// IsTypeNamed reports whether t is (or is an alias for) a +// package-level defined type with the given package path and one of +// the given names. It returns false if t is nil. +// +// This function avoids allocating the concatenation of "pkg.Name", +// which is important for the performance of syntax matching. +func IsTypeNamed(t types.Type, pkgPath string, names ...string) bool { + if named, ok := types.Unalias(t).(*types.Named); ok { + tname := named.Obj() + return tname != nil && + IsPackageLevel(tname) && + tname.Pkg().Path() == pkgPath && + slices.Contains(names, tname.Name()) + } + return false +} + +// IsPointerToNamed reports whether t is (or is an alias for) a pointer to a +// package-level defined type with the given package path and one of the given +// names. It returns false if t is not a pointer type. +func IsPointerToNamed(t types.Type, pkgPath string, names ...string) bool { + r := Unpointer(t) + if r == t { + return false + } + return IsTypeNamed(r, pkgPath, names...) +} + +// IsFunctionNamed reports whether obj is a package-level function +// defined in the given package and has one of the given names. +// It returns false if obj is nil. +// +// This function avoids allocating the concatenation of "pkg.Name", +// which is important for the performance of syntax matching. +func IsFunctionNamed(obj types.Object, pkgPath string, names ...string) bool { + f, ok := obj.(*types.Func) + return ok && + IsPackageLevel(obj) && + f.Pkg().Path() == pkgPath && + f.Type().(*types.Signature).Recv() == nil && + slices.Contains(names, f.Name()) +} + +// IsMethodNamed reports whether obj is a method defined on a +// package-level type with the given package and type name, and has +// one of the given names. It returns false if obj is nil. +// +// This function avoids allocating the concatenation of "pkg.TypeName.Name", +// which is important for the performance of syntax matching. +func IsMethodNamed(obj types.Object, pkgPath string, typeName string, names ...string) bool { + if fn, ok := obj.(*types.Func); ok { + if recv := fn.Type().(*types.Signature).Recv(); recv != nil { + _, T := ReceiverNamed(recv) + return T != nil && + IsTypeNamed(T, pkgPath, typeName) && + slices.Contains(names, fn.Name()) + } + } + return false +} diff --git a/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go b/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go index b64f714..64f4791 100644 --- a/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go +++ b/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go @@ -15,6 +15,14 @@ import ( // file. // If the same package is imported multiple times, the last appearance is // recorded. +// +// TODO(adonovan): this function ignores the effect of shadowing. It +// should accept a [token.Pos] and a [types.Info] and compute only the +// set of imports that are not shadowed at that point, analogous to +// [analysisinternal.AddImport]. It could also compute (as a side +// effect) the set of additional imports required to ensure that there +// is an accessible import for each necessary package, making it +// converge even more closely with AddImport. func FileQualifier(f *ast.File, pkg *types.Package) types.Qualifier { // Construct mapping of import paths to their defined names. // It is only necessary to look at renaming imports. diff --git a/vendor/golang.org/x/tools/internal/typesinternal/types.go b/vendor/golang.org/x/tools/internal/typesinternal/types.go index a5cd7e8..fef74a7 100644 --- a/vendor/golang.org/x/tools/internal/typesinternal/types.go +++ b/vendor/golang.org/x/tools/internal/typesinternal/types.go @@ -2,8 +2,20 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package typesinternal provides access to internal go/types APIs that are not -// yet exported. +// Package typesinternal provides helpful operators for dealing with +// go/types: +// +// - operators for querying typed syntax trees (e.g. [Imports], [IsFunctionNamed]); +// - functions for converting types to strings or syntax (e.g. [TypeExpr], FileQualifier]); +// - helpers for working with the [go/types] API (e.g. [NewTypesInfo]); +// - access to internal go/types APIs that are not yet +// exported (e.g. [SetUsesCgo], [ErrorCodeStartEnd], [VarKind]); and +// - common algorithms related to types (e.g. [TooNewStdSymbols]). +// +// See also: +// - [golang.org/x/tools/internal/astutil], for operations on untyped syntax; +// - [golang.org/x/tools/internal/analysisinernal], for helpers for analyzers; +// - [golang.org/x/tools/internal/refactor], for operators to compute text edits. package typesinternal import ( @@ -13,6 +25,7 @@ import ( "reflect" "unsafe" + "golang.org/x/tools/go/ast/inspector" "golang.org/x/tools/internal/aliases" ) @@ -60,6 +73,9 @@ func ErrorCodeStartEnd(err types.Error) (code ErrorCode, start, end token.Pos, o // which is often excessive.) // // If pkg is nil, it is equivalent to [*types.Package.Name]. +// +// TODO(adonovan): all uses of this with TypeString should be +// eliminated when https://go.dev/issues/75604 is resolved. func NameRelativeTo(pkg *types.Package) types.Qualifier { return func(other *types.Package) string { if pkg != nil && pkg == other { @@ -153,3 +169,31 @@ func NewTypesInfo() *types.Info { FileVersions: map[*ast.File]string{}, } } + +// EnclosingScope returns the innermost block logically enclosing the cursor. +func EnclosingScope(info *types.Info, cur inspector.Cursor) *types.Scope { + for cur := range cur.Enclosing() { + n := cur.Node() + // A function's Scope is associated with its FuncType. + switch f := n.(type) { + case *ast.FuncDecl: + n = f.Type + case *ast.FuncLit: + n = f.Type + } + if b := info.Scopes[n]; b != nil { + return b + } + } + panic("no Scope for *ast.File") +} + +// Imports reports whether path is imported by pkg. +func Imports(pkg *types.Package, path string) bool { + for _, imp := range pkg.Imports() { + if imp.Path() == path { + return true + } + } + return false +} diff --git a/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go b/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go index d272949..453bba2 100644 --- a/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go +++ b/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go @@ -204,23 +204,12 @@ func ZeroExpr(t types.Type, qual types.Qualifier) (_ ast.Expr, isValid bool) { } } -// IsZeroExpr uses simple syntactic heuristics to report whether expr -// is a obvious zero value, such as 0, "", nil, or false. -// It cannot do better without type information. -func IsZeroExpr(expr ast.Expr) bool { - switch e := expr.(type) { - case *ast.BasicLit: - return e.Value == "0" || e.Value == `""` - case *ast.Ident: - return e.Name == "nil" || e.Name == "false" - default: - return false - } -} - // TypeExpr returns syntax for the specified type. References to named types // are qualified by an appropriate (optional) qualifier function. // It may panic for types such as Tuple or Union. +// +// See also https://go.dev/issues/75604, which will provide a robust +// Type-to-valid-Go-syntax formatter. func TypeExpr(t types.Type, qual types.Qualifier) ast.Expr { switch t := t.(type) { case *types.Basic: diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc.go index 688aabe..dbcf90b 100644 --- a/vendor/google.golang.org/protobuf/internal/filedesc/desc.go +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc.go @@ -72,9 +72,10 @@ type ( EditionFeatures EditionFeatures } FileL2 struct { - Options func() protoreflect.ProtoMessage - Imports FileImports - Locations SourceLocations + Options func() protoreflect.ProtoMessage + Imports FileImports + OptionImports func() protoreflect.FileImports + Locations SourceLocations } // EditionFeatures is a frequently-instantiated struct, so please take care @@ -126,12 +127,9 @@ func (fd *File) ParentFile() protoreflect.FileDescriptor { return fd } func (fd *File) Parent() protoreflect.Descriptor { return nil } func (fd *File) Index() int { return 0 } func (fd *File) Syntax() protoreflect.Syntax { return fd.L1.Syntax } - -// Not exported and just used to reconstruct the original FileDescriptor proto -func (fd *File) Edition() int32 { return int32(fd.L1.Edition) } -func (fd *File) Name() protoreflect.Name { return fd.L1.Package.Name() } -func (fd *File) FullName() protoreflect.FullName { return fd.L1.Package } -func (fd *File) IsPlaceholder() bool { return false } +func (fd *File) Name() protoreflect.Name { return fd.L1.Package.Name() } +func (fd *File) FullName() protoreflect.FullName { return fd.L1.Package } +func (fd *File) IsPlaceholder() bool { return false } func (fd *File) Options() protoreflect.ProtoMessage { if f := fd.lazyInit().Options; f != nil { return f() @@ -150,6 +148,16 @@ func (fd *File) Format(s fmt.State, r rune) { descfmt.FormatD func (fd *File) ProtoType(protoreflect.FileDescriptor) {} func (fd *File) ProtoInternal(pragma.DoNotImplement) {} +// The next two are not part of the FileDescriptor interface. They are just used to reconstruct +// the original FileDescriptor proto. +func (fd *File) Edition() int32 { return int32(fd.L1.Edition) } +func (fd *File) OptionImports() protoreflect.FileImports { + if f := fd.lazyInit().OptionImports; f != nil { + return f() + } + return emptyFiles +} + func (fd *File) lazyInit() *FileL2 { if atomic.LoadUint32(&fd.once) == 0 { fd.lazyInitOnce() @@ -182,9 +190,9 @@ type ( L2 *EnumL2 // protected by fileDesc.once } EnumL1 struct { - eagerValues bool // controls whether EnumL2.Values is already populated - EditionFeatures EditionFeatures + Visibility int32 + eagerValues bool // controls whether EnumL2.Values is already populated } EnumL2 struct { Options func() protoreflect.ProtoMessage @@ -219,6 +227,11 @@ func (ed *Enum) ReservedNames() protoreflect.Names { return &ed.lazyInit() func (ed *Enum) ReservedRanges() protoreflect.EnumRanges { return &ed.lazyInit().ReservedRanges } func (ed *Enum) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, ed) } func (ed *Enum) ProtoType(protoreflect.EnumDescriptor) {} + +// This is not part of the EnumDescriptor interface. It is just used to reconstruct +// the original FileDescriptor proto. +func (ed *Enum) Visibility() int32 { return ed.L1.Visibility } + func (ed *Enum) lazyInit() *EnumL2 { ed.L0.ParentFile.lazyInit() // implicitly initializes L2 return ed.L2 @@ -244,13 +257,13 @@ type ( L2 *MessageL2 // protected by fileDesc.once } MessageL1 struct { - Enums Enums - Messages Messages - Extensions Extensions - IsMapEntry bool // promoted from google.protobuf.MessageOptions - IsMessageSet bool // promoted from google.protobuf.MessageOptions - + Enums Enums + Messages Messages + Extensions Extensions EditionFeatures EditionFeatures + Visibility int32 + IsMapEntry bool // promoted from google.protobuf.MessageOptions + IsMessageSet bool // promoted from google.protobuf.MessageOptions } MessageL2 struct { Options func() protoreflect.ProtoMessage @@ -319,6 +332,11 @@ func (md *Message) Messages() protoreflect.MessageDescriptors { return &md.L func (md *Message) Extensions() protoreflect.ExtensionDescriptors { return &md.L1.Extensions } func (md *Message) ProtoType(protoreflect.MessageDescriptor) {} func (md *Message) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, md) } + +// This is not part of the MessageDescriptor interface. It is just used to reconstruct +// the original FileDescriptor proto. +func (md *Message) Visibility() int32 { return md.L1.Visibility } + func (md *Message) lazyInit() *MessageL2 { md.L0.ParentFile.lazyInit() // implicitly initializes L2 return md.L2 diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go index d2f5494..e91860f 100644 --- a/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go @@ -284,6 +284,13 @@ func (ed *Enum) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd protorefl case genid.EnumDescriptorProto_Value_field_number: numValues++ } + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.EnumDescriptorProto_Visibility_field_number: + ed.L1.Visibility = int32(v) + } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] @@ -365,6 +372,13 @@ func (md *Message) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd protor md.unmarshalSeedOptions(v) } prevField = num + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.DescriptorProto_Visibility_field_number: + md.L1.Visibility = int32(v) + } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go index d4c9445..dd31faa 100644 --- a/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go @@ -134,6 +134,7 @@ func (fd *File) unmarshalFull(b []byte) { var enumIdx, messageIdx, extensionIdx, serviceIdx int var rawOptions []byte + var optionImports []string fd.L2 = new(FileL2) for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) @@ -157,6 +158,8 @@ func (fd *File) unmarshalFull(b []byte) { imp = PlaceholderFile(path) } fd.L2.Imports = append(fd.L2.Imports, protoreflect.FileImport{FileDescriptor: imp}) + case genid.FileDescriptorProto_OptionDependency_field_number: + optionImports = append(optionImports, sb.MakeString(v)) case genid.FileDescriptorProto_EnumType_field_number: fd.L1.Enums.List[enumIdx].unmarshalFull(v, sb) enumIdx++ @@ -178,6 +181,23 @@ func (fd *File) unmarshalFull(b []byte) { } } fd.L2.Options = fd.builder.optionsUnmarshaler(&descopts.File, rawOptions) + if len(optionImports) > 0 { + var imps FileImports + var once sync.Once + fd.L2.OptionImports = func() protoreflect.FileImports { + once.Do(func() { + imps = make(FileImports, len(optionImports)) + for i, path := range optionImports { + imp, _ := fd.builder.FileRegistry.FindFileByPath(path) + if imp == nil { + imp = PlaceholderFile(path) + } + imps[i] = protoreflect.FileImport{FileDescriptor: imp} + } + }) + return &imps + } + } } func (ed *Enum) unmarshalFull(b []byte, sb *strs.Builder) { diff --git a/vendor/google.golang.org/protobuf/internal/version/version.go b/vendor/google.golang.org/protobuf/internal/version/version.go index 31e79a6..77de0f2 100644 --- a/vendor/google.golang.org/protobuf/internal/version/version.go +++ b/vendor/google.golang.org/protobuf/internal/version/version.go @@ -52,7 +52,7 @@ import ( const ( Major = 1 Minor = 36 - Patch = 9 + Patch = 10 PreRelease = "" ) diff --git a/vendor/modules.txt b/vendor/modules.txt index 04568f0..4fa5120 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -16,22 +16,28 @@ github.com/cespare/xxhash/v2 ## explicit github.com/codemodus/kace github.com/codemodus/kace/ktrie -# github.com/gabriel-vasile/mimetype v1.4.9 -## explicit; go 1.23.0 +# github.com/gabriel-vasile/mimetype v1.4.10 +## explicit; go 1.21 github.com/gabriel-vasile/mimetype 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/getsentry/sentry-go v0.35.3 -## explicit; go 1.22 +github.com/gabriel-vasile/mimetype/internal/markup +github.com/gabriel-vasile/mimetype/internal/scan +# github.com/getsentry/sentry-go v0.36.2 +## explicit; go 1.23 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/otel/baggage github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage +github.com/getsentry/sentry-go/internal/protocol github.com/getsentry/sentry-go/internal/ratelimit -# github.com/getsentry/sentry-go/echo v0.35.3 -## explicit; go 1.22 +# github.com/getsentry/sentry-go/echo v0.36.2 +## explicit; go 1.23 github.com/getsentry/sentry-go/echo # github.com/go-pg/pg/v10 v10.15.0 ## explicit; go 1.23.0 @@ -55,8 +61,8 @@ github.com/go-playground/locales/currency # github.com/go-playground/universal-translator v0.18.1 ## explicit; go 1.18 github.com/go-playground/universal-translator -# github.com/go-playground/validator/v10 v10.27.0 -## explicit; go 1.20 +# github.com/go-playground/validator/v10 v10.28.0 +## explicit; go 1.24.0 github.com/go-playground/validator/v10 # github.com/gopherjs/gopherjs v1.17.2 ## explicit; go 1.17 @@ -122,12 +128,12 @@ 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.66.1 -## explicit; go 1.23.0 +# github.com/prometheus/common v0.67.2 +## explicit; go 1.24.0 github.com/prometheus/common/expfmt github.com/prometheus/common/model -# github.com/prometheus/procfs v0.17.0 -## explicit; go 1.23.0 +# github.com/prometheus/procfs v0.19.1 +## explicit; go 1.24.0 github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util @@ -168,7 +174,7 @@ github.com/vmihailenco/tagparser/internal/parser github.com/vmihailenco/tagparser/v2 github.com/vmihailenco/tagparser/v2/internal github.com/vmihailenco/tagparser/v2/internal/parser -# github.com/vmkteam/appkit v0.0.1 +# github.com/vmkteam/appkit v0.1.1 ## explicit; go 1.24.5 github.com/vmkteam/appkit # github.com/vmkteam/embedlog v0.1.3 @@ -177,28 +183,29 @@ github.com/vmkteam/embedlog # github.com/vmkteam/meta-schema/v2 v2.0.1 ## explicit; go 1.13 github.com/vmkteam/meta-schema/v2 -# github.com/vmkteam/rpcgen/v2 v2.4.6 +# github.com/vmkteam/rpcgen/v2 v2.5.0 ## explicit; go 1.24.0 github.com/vmkteam/rpcgen/v2 github.com/vmkteam/rpcgen/v2/dart github.com/vmkteam/rpcgen/v2/gen github.com/vmkteam/rpcgen/v2/golang +github.com/vmkteam/rpcgen/v2/kotlin github.com/vmkteam/rpcgen/v2/openrpc github.com/vmkteam/rpcgen/v2/php github.com/vmkteam/rpcgen/v2/swift github.com/vmkteam/rpcgen/v2/typescript -# github.com/vmkteam/vfs v1.4.0 +# github.com/vmkteam/vfs v1.4.1 ## explicit; go 1.24.5 github.com/vmkteam/vfs github.com/vmkteam/vfs/db # github.com/vmkteam/zenrpc v1.1.1 ## explicit github.com/vmkteam/zenrpc/smd -# github.com/vmkteam/zenrpc-middleware v1.3.0 +# github.com/vmkteam/zenrpc-middleware v1.3.2 ## explicit; go 1.24.5 github.com/vmkteam/zenrpc-middleware -# github.com/vmkteam/zenrpc/v2 v2.2.12 -## explicit; go 1.18 +# github.com/vmkteam/zenrpc/v2 v2.3.0 +## explicit; go 1.24.0 github.com/vmkteam/zenrpc/v2 github.com/vmkteam/zenrpc/v2/parser github.com/vmkteam/zenrpc/v2/smd @@ -209,7 +216,7 @@ go.uber.org/atomic # go.yaml.in/yaml/v2 v2.4.3 ## explicit; go 1.15 go.yaml.in/yaml/v2 -# golang.org/x/crypto v0.42.0 +# golang.org/x/crypto v0.43.0 ## explicit; go 1.24.0 golang.org/x/crypto/acme golang.org/x/crypto/acme/autocert @@ -217,13 +224,11 @@ golang.org/x/crypto/bcrypt golang.org/x/crypto/blowfish golang.org/x/crypto/pbkdf2 golang.org/x/crypto/sha3 -# golang.org/x/mod v0.27.0 -## explicit; go 1.23.0 +# golang.org/x/mod v0.29.0 +## explicit; go 1.24.0 golang.org/x/mod/semver -# golang.org/x/net v0.44.0 +# golang.org/x/net v0.46.0 ## explicit; go 1.24.0 -golang.org/x/net/html -golang.org/x/net/html/atom golang.org/x/net/http/httpguts golang.org/x/net/http2 golang.org/x/net/http2/h2c @@ -233,13 +238,13 @@ golang.org/x/net/internal/httpcommon # golang.org/x/sync v0.17.0 ## explicit; go 1.24.0 golang.org/x/sync/errgroup -# golang.org/x/sys v0.36.0 +# golang.org/x/sys v0.37.0 ## explicit; go 1.24.0 golang.org/x/sys/cpu golang.org/x/sys/execabs golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/text v0.29.0 +# golang.org/x/text v0.30.0 ## explicit; go 1.24.0 golang.org/x/text/cases golang.org/x/text/internal @@ -251,11 +256,13 @@ golang.org/x/text/secure/bidirule golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm -# golang.org/x/time v0.11.0 -## explicit; go 1.23.0 +# golang.org/x/time v0.14.0 +## explicit; go 1.24.0 golang.org/x/time/rate -# golang.org/x/tools v0.36.0 -## explicit; go 1.23.0 +# golang.org/x/tools v0.38.0 +## explicit; go 1.24.0 +golang.org/x/tools/go/ast/edge +golang.org/x/tools/go/ast/inspector golang.org/x/tools/go/gcexportdata golang.org/x/tools/go/packages golang.org/x/tools/go/types/objectpath @@ -273,7 +280,7 @@ golang.org/x/tools/internal/stdlib golang.org/x/tools/internal/typeparams golang.org/x/tools/internal/typesinternal golang.org/x/tools/internal/versions -# google.golang.org/protobuf v1.36.9 +# google.golang.org/protobuf v1.36.10 ## explicit; go 1.23 google.golang.org/protobuf/encoding/protodelim google.golang.org/protobuf/encoding/prototext