From ed7ee524a57d44713723fe2c03dcc2275427de6b Mon Sep 17 00:00:00 2001 From: ianmuchyri Date: Fri, 10 Nov 2023 16:03:05 +0300 Subject: [PATCH] remove vendoring Signed-off-by: ianmuchyri --- .github/workflows/ci.yaml | 2 +- Makefile | 2 +- vendor/github.com/absmach/agent/LICENSE | 191 - .../absmach/agent/pkg/agent/config.go | 161 - .../absmach/agent/pkg/agent/heartbeat.go | 82 - .../absmach/agent/pkg/agent/service.go | 430 - .../absmach/agent/pkg/bootstrap/bootstrap.go | 228 - .../absmach/agent/pkg/edgex/client.go | 125 - .../absmach/agent/pkg/encoder/encoder.go | 29 - .../absmach/agent/pkg/terminal/terminal.go | 129 - .../absmach/magistrala/.dockerignore | 6 - .../github.com/absmach/magistrala/.gitignore | 13 - .../absmach/magistrala/.golangci.yml | 73 - .../github.com/absmach/magistrala/ADOPTERS.md | 36 - .../absmach/magistrala/CHANGELOG.md | 708 -- .../absmach/magistrala/CONTRIBUTING.md | 87 - vendor/github.com/absmach/magistrala/LICENSE | 191 - .../github.com/absmach/magistrala/MAINTAINERS | 30 - vendor/github.com/absmach/magistrala/Makefile | 249 - .../github.com/absmach/magistrala/README.md | 203 - vendor/github.com/absmach/magistrala/api.go | 16 - .../github.com/absmach/magistrala/auth.pb.go | 2060 ---- .../github.com/absmach/magistrala/auth.proto | 169 - .../absmach/magistrala/auth_grpc.pb.go | 650 -- .../absmach/magistrala/bootstrap/README.md | 125 - .../absmach/magistrala/bootstrap/configs.go | 116 - .../absmach/magistrala/bootstrap/doc.go | 6 - .../absmach/magistrala/bootstrap/reader.go | 95 - .../absmach/magistrala/bootstrap/service.go | 486 - .../absmach/magistrala/bootstrap/state.go | 26 - .../github.com/absmach/magistrala/config.toml | 16 - vendor/github.com/absmach/magistrala/doc.go | 6 - .../github.com/absmach/magistrala/health.go | 78 - .../magistrala/internal/apiutil/errors.go | 155 - .../magistrala/internal/apiutil/responses.go | 10 - .../magistrala/internal/apiutil/token.go | 37 - .../magistrala/internal/apiutil/transport.go | 152 - .../absmach/magistrala/logger/doc.go | 6 - .../absmach/magistrala/logger/exit.go | 11 - .../absmach/magistrala/logger/level.go | 58 - .../absmach/magistrala/logger/logger.go | 75 - .../absmach/magistrala/logger/mock.go | 28 - .../absmach/magistrala/pkg/clients/clients.go | 169 - .../absmach/magistrala/pkg/clients/doc.go | 6 - .../absmach/magistrala/pkg/clients/errors.go | 17 - .../absmach/magistrala/pkg/clients/page.go | 21 - .../absmach/magistrala/pkg/clients/roles.go | 60 - .../absmach/magistrala/pkg/clients/status.go | 80 - .../absmach/magistrala/pkg/clients/types.go | 7 - .../absmach/magistrala/pkg/errors/README.md | 5 - .../absmach/magistrala/pkg/errors/doc.go | 5 - .../absmach/magistrala/pkg/errors/errors.go | 144 - .../magistrala/pkg/errors/sdk_errors.go | 111 - .../absmach/magistrala/pkg/errors/types.go | 44 - .../magistrala/pkg/messaging/README.md | 9 - .../magistrala/pkg/messaging/message.pb.go | 195 - .../magistrala/pkg/messaging/message.proto | 17 - .../magistrala/pkg/messaging/pubsub.go | 80 - .../absmach/magistrala/pkg/sdk/go/README.md | 83 - .../magistrala/pkg/sdk/go/bootstrap.go | 250 - .../absmach/magistrala/pkg/sdk/go/certs.go | 105 - .../absmach/magistrala/pkg/sdk/go/channels.go | 294 - .../magistrala/pkg/sdk/go/consumers.go | 89 - .../absmach/magistrala/pkg/sdk/go/doc.go | 5 - .../absmach/magistrala/pkg/sdk/go/groups.go | 219 - .../absmach/magistrala/pkg/sdk/go/health.go | 65 - .../absmach/magistrala/pkg/sdk/go/message.go | 67 - .../absmach/magistrala/pkg/sdk/go/metadata.go | 6 - .../absmach/magistrala/pkg/sdk/go/requests.go | 58 - .../magistrala/pkg/sdk/go/responses.go | 88 - .../absmach/magistrala/pkg/sdk/go/sdk.go | 1128 -- .../absmach/magistrala/pkg/sdk/go/things.go | 299 - .../absmach/magistrala/pkg/sdk/go/tokens.go | 60 - .../absmach/magistrala/pkg/sdk/go/users.go | 346 - .../magistrala/pkg/transformers/README.md | 10 - .../magistrala/pkg/transformers/doc.go | 6 - .../pkg/transformers/senml/README.md | 4 - .../magistrala/pkg/transformers/senml/doc.go | 5 - .../pkg/transformers/senml/message.go | 18 - .../pkg/transformers/senml/transformer.go | 84 - .../pkg/transformers/transformer.go | 12 - .../absmach/magistrala/pkg/uuid/README.md | 3 - .../absmach/magistrala/pkg/uuid/doc.go | 5 - .../absmach/magistrala/pkg/uuid/mock.go | 35 - .../absmach/magistrala/pkg/uuid/uuid.go | 32 - vendor/github.com/absmach/magistrala/uuid.go | 10 - vendor/github.com/beorn7/perks/LICENSE | 20 - .../beorn7/perks/quantile/exampledata.txt | 2388 ----- .../beorn7/perks/quantile/stream.go | 316 - vendor/github.com/caarlos0/env/v9/.gitignore | 4 - .../github.com/caarlos0/env/v9/.golangci.yml | 8 - .../caarlos0/env/v9/.goreleaser.yml | 3 - vendor/github.com/caarlos0/env/v9/.mailmap | 7 - vendor/github.com/caarlos0/env/v9/LICENSE.md | 21 - vendor/github.com/caarlos0/env/v9/Makefile | 37 - vendor/github.com/caarlos0/env/v9/README.md | 577 - vendor/github.com/caarlos0/env/v9/env.go | 520 - .../github.com/caarlos0/env/v9/env_tomap.go | 16 - .../caarlos0/env/v9/env_tomap_windows.go | 29 - vendor/github.com/caarlos0/env/v9/error.go | 164 - .../github.com/cespare/xxhash/v2/LICENSE.txt | 22 - vendor/github.com/cespare/xxhash/v2/README.md | 72 - .../github.com/cespare/xxhash/v2/testall.sh | 10 - vendor/github.com/cespare/xxhash/v2/xxhash.go | 228 - .../cespare/xxhash/v2/xxhash_amd64.s | 209 - .../cespare/xxhash/v2/xxhash_arm64.s | 183 - .../cespare/xxhash/v2/xxhash_asm.go | 15 - .../cespare/xxhash/v2/xxhash_other.go | 76 - .../cespare/xxhash/v2/xxhash_safe.go | 16 - .../cespare/xxhash/v2/xxhash_unsafe.go | 58 - vendor/github.com/creack/pty/.gitignore | 4 - .../github.com/creack/pty/Dockerfile.golang | 17 - vendor/github.com/creack/pty/Dockerfile.riscv | 23 - vendor/github.com/creack/pty/LICENSE | 23 - vendor/github.com/creack/pty/README.md | 107 - .../github.com/creack/pty/asm_solaris_amd64.s | 18 - vendor/github.com/creack/pty/doc.go | 16 - vendor/github.com/creack/pty/ioctl.go | 19 - vendor/github.com/creack/pty/ioctl_bsd.go | 40 - vendor/github.com/creack/pty/ioctl_solaris.go | 48 - .../creack/pty/ioctl_unsupported.go | 13 - vendor/github.com/creack/pty/mktypes.bash | 19 - vendor/github.com/creack/pty/pty_darwin.go | 68 - vendor/github.com/creack/pty/pty_dragonfly.go | 83 - vendor/github.com/creack/pty/pty_freebsd.go | 81 - vendor/github.com/creack/pty/pty_linux.go | 54 - vendor/github.com/creack/pty/pty_netbsd.go | 69 - vendor/github.com/creack/pty/pty_openbsd.go | 36 - vendor/github.com/creack/pty/pty_solaris.go | 152 - .../github.com/creack/pty/pty_unsupported.go | 12 - vendor/github.com/creack/pty/run.go | 57 - vendor/github.com/creack/pty/start.go | 25 - vendor/github.com/creack/pty/start_windows.go | 19 - .../creack/pty/test_crosscompile.sh | 64 - vendor/github.com/creack/pty/winsize.go | 27 - vendor/github.com/creack/pty/winsize_unix.go | 35 - .../creack/pty/winsize_unsupported.go | 23 - vendor/github.com/creack/pty/ztypes_386.go | 12 - vendor/github.com/creack/pty/ztypes_amd64.go | 12 - vendor/github.com/creack/pty/ztypes_arm.go | 12 - vendor/github.com/creack/pty/ztypes_arm64.go | 12 - .../creack/pty/ztypes_dragonfly_amd64.go | 17 - .../creack/pty/ztypes_freebsd_386.go | 16 - .../creack/pty/ztypes_freebsd_amd64.go | 17 - .../creack/pty/ztypes_freebsd_arm.go | 16 - .../creack/pty/ztypes_freebsd_arm64.go | 16 - .../creack/pty/ztypes_freebsd_ppc64.go | 14 - .../github.com/creack/pty/ztypes_loong64.go | 12 - vendor/github.com/creack/pty/ztypes_mipsx.go | 13 - .../creack/pty/ztypes_netbsd_32bit_int.go | 17 - .../creack/pty/ztypes_openbsd_32bit_int.go | 14 - vendor/github.com/creack/pty/ztypes_ppc64.go | 12 - .../github.com/creack/pty/ztypes_ppc64le.go | 12 - vendor/github.com/creack/pty/ztypes_riscvx.go | 12 - vendor/github.com/creack/pty/ztypes_s390x.go | 12 - .../eclipse/paho.mqtt.golang/.gitignore | 36 - .../eclipse/paho.mqtt.golang/CONTRIBUTING.md | 56 - .../eclipse/paho.mqtt.golang/LICENSE | 294 - .../eclipse/paho.mqtt.golang/NOTICE.md | 77 - .../eclipse/paho.mqtt.golang/README.md | 198 - .../eclipse/paho.mqtt.golang/backoff.go | 104 - .../eclipse/paho.mqtt.golang/client.go | 1240 --- .../eclipse/paho.mqtt.golang/components.go | 36 - .../eclipse/paho.mqtt.golang/edl-v10 | 15 - .../eclipse/paho.mqtt.golang/epl-v20 | 277 - .../eclipse/paho.mqtt.golang/filestore.go | 261 - .../eclipse/paho.mqtt.golang/memstore.go | 142 - .../paho.mqtt.golang/memstore_ordered.go | 166 - .../eclipse/paho.mqtt.golang/message.go | 131 - .../eclipse/paho.mqtt.golang/messageids.go | 200 - .../eclipse/paho.mqtt.golang/net.go | 470 - .../eclipse/paho.mqtt.golang/netconn.go | 110 - .../eclipse/paho.mqtt.golang/oops.go | 25 - .../eclipse/paho.mqtt.golang/options.go | 457 - .../paho.mqtt.golang/options_reader.go | 171 - .../paho.mqtt.golang/packets/connack.go | 68 - .../paho.mqtt.golang/packets/connect.go | 171 - .../paho.mqtt.golang/packets/disconnect.go | 50 - .../paho.mqtt.golang/packets/packets.go | 372 - .../paho.mqtt.golang/packets/pingreq.go | 50 - .../paho.mqtt.golang/packets/pingresp.go | 50 - .../paho.mqtt.golang/packets/puback.go | 58 - .../paho.mqtt.golang/packets/pubcomp.go | 58 - .../paho.mqtt.golang/packets/publish.go | 99 - .../paho.mqtt.golang/packets/pubrec.go | 58 - .../paho.mqtt.golang/packets/pubrel.go | 58 - .../paho.mqtt.golang/packets/suback.go | 73 - .../paho.mqtt.golang/packets/subscribe.go | 85 - .../paho.mqtt.golang/packets/unsuback.go | 58 - .../paho.mqtt.golang/packets/unsubscribe.go | 72 - .../eclipse/paho.mqtt.golang/ping.go | 78 - .../eclipse/paho.mqtt.golang/router.go | 239 - .../eclipse/paho.mqtt.golang/status.go | 296 - .../eclipse/paho.mqtt.golang/store.go | 140 - .../eclipse/paho.mqtt.golang/token.go | 204 - .../eclipse/paho.mqtt.golang/topic.go | 90 - .../eclipse/paho.mqtt.golang/trace.go | 44 - .../eclipse/paho.mqtt.golang/websocket.go | 132 - .../go-mod-core-contracts/LICENSE | 202 - .../clients/constants.go | 81 - .../go-mod-core-contracts/clients/context.go | 29 - .../go-mod-core-contracts/clients/doc.go | 26 - .../clients/interfaces/url.go | 26 - .../clients/interfaces/urlstream.go | 17 - .../go-mod-core-contracts/clients/request.go | 353 - .../clients/types/errors.go | 51 - .../go-mod-core-contracts/models/action.go | 35 - .../models/actiontype.go | 30 - .../models/addressable.go | 120 - .../models/adminstate.go | 69 - .../go-mod-core-contracts/models/autoevent.go | 43 - .../models/callbackalert.go | 37 - .../go-mod-core-contracts/models/category.go | 55 - .../go-mod-core-contracts/models/channel.go | 35 - .../models/channel_type.go | 53 - .../go-mod-core-contracts/models/command.go | 129 - .../models/commandresponse.go | 73 - .../go-mod-core-contracts/models/constants.go | 28 - .../models/describedobject.go | 34 - .../go-mod-core-contracts/models/device.go | 170 - .../models/deviceprofile.go | 114 - .../models/devicereport.go | 40 - .../models/deviceresource.go | 66 - .../models/deviceservice.go | 129 - .../models/encryptiondetails.go | 29 - .../go-mod-core-contracts/models/errors.go | 32 - .../go-mod-core-contracts/models/event.go | 108 - .../go-mod-core-contracts/models/filter.go | 21 - .../go-mod-core-contracts/models/get.go | 44 - .../go-mod-core-contracts/models/interval.go | 168 - .../models/interval_action.go | 153 - .../go-mod-core-contracts/models/log_entry.go | 86 - .../models/notifications.go | 169 - .../models/operatingstate.go | 71 - .../models/profileproperty.go | 54 - .../models/profileresource.go | 32 - .../models/propertyvalue.go | 53 - .../models/provisionwatcher.go | 135 - .../go-mod-core-contracts/models/put.go | 42 - .../go-mod-core-contracts/models/reading.go | 178 - .../models/resourceoperation.go | 151 - .../go-mod-core-contracts/models/response.go | 54 - .../go-mod-core-contracts/models/severity.go | 51 - .../models/sma_operation.go | 64 - .../go-mod-core-contracts/models/status.go | 52 - .../models/subscription.go | 41 - .../models/timestamps.go | 44 - .../models/transmission.go | 147 - .../models/transmission_record.go | 35 - .../models/transmission_status.go | 62 - .../go-mod-core-contracts/models/units.go | 32 - .../go-mod-core-contracts/models/validator.go | 53 - .../models/value-descriptor.go | 164 - .../github.com/fxamacker/cbor/v2/.gitignore | 12 - .../fxamacker/cbor/v2/.golangci.yml | 76 - .../fxamacker/cbor/v2/CODE_OF_CONDUCT.md | 133 - .../fxamacker/cbor/v2/CONTRIBUTING.md | 41 - vendor/github.com/fxamacker/cbor/v2/LICENSE | 21 - vendor/github.com/fxamacker/cbor/v2/README.md | 452 - .../github.com/fxamacker/cbor/v2/SECURITY.md | 7 - .../fxamacker/cbor/v2/bytestring.go | 62 - vendor/github.com/fxamacker/cbor/v2/cache.go | 315 - vendor/github.com/fxamacker/cbor/v2/decode.go | 2171 ---- .../github.com/fxamacker/cbor/v2/diagnose.go | 741 -- vendor/github.com/fxamacker/cbor/v2/doc.go | 129 - vendor/github.com/fxamacker/cbor/v2/encode.go | 1521 --- .../fxamacker/cbor/v2/simplevalue.go | 17 - vendor/github.com/fxamacker/cbor/v2/stream.go | 277 - .../fxamacker/cbor/v2/structfields.go | 251 - vendor/github.com/fxamacker/cbor/v2/tag.go | 297 - vendor/github.com/fxamacker/cbor/v2/valid.go | 318 - vendor/github.com/go-chi/chi/v5/.gitignore | 3 - vendor/github.com/go-chi/chi/v5/CHANGELOG.md | 331 - .../github.com/go-chi/chi/v5/CONTRIBUTING.md | 31 - vendor/github.com/go-chi/chi/v5/LICENSE | 20 - vendor/github.com/go-chi/chi/v5/Makefile | 22 - vendor/github.com/go-chi/chi/v5/README.md | 500 - vendor/github.com/go-chi/chi/v5/chain.go | 49 - vendor/github.com/go-chi/chi/v5/chi.go | 134 - vendor/github.com/go-chi/chi/v5/context.go | 160 - vendor/github.com/go-chi/chi/v5/mux.go | 493 - vendor/github.com/go-chi/chi/v5/tree.go | 892 -- vendor/github.com/go-kit/kit/LICENSE | 22 - vendor/github.com/go-kit/kit/endpoint/doc.go | 5 - .../go-kit/kit/endpoint/endpoint.go | 40 - .../github.com/go-kit/kit/metrics/README.md | 98 - vendor/github.com/go-kit/kit/metrics/doc.go | 97 - .../kit/metrics/internal/lv/labelvalues.go | 14 - .../go-kit/kit/metrics/internal/lv/space.go | 145 - .../github.com/go-kit/kit/metrics/metrics.go | 25 - .../kit/metrics/prometheus/prometheus.go | 165 - vendor/github.com/go-kit/kit/metrics/timer.go | 36 - vendor/github.com/go-kit/kit/transport/doc.go | 2 - .../go-kit/kit/transport/error_handler.go | 39 - .../go-kit/kit/transport/http/client.go | 219 - .../go-kit/kit/transport/http/doc.go | 2 - .../kit/transport/http/encode_decode.go | 36 - .../kit/transport/http/intercepting_writer.go | 257 - .../transport/http/request_response_funcs.go | 133 - .../go-kit/kit/transport/http/server.go | 225 - vendor/github.com/go-kit/log/.gitignore | 15 - vendor/github.com/go-kit/log/LICENSE | 21 - vendor/github.com/go-kit/log/README.md | 156 - vendor/github.com/go-kit/log/doc.go | 116 - vendor/github.com/go-kit/log/json_logger.go | 91 - vendor/github.com/go-kit/log/log.go | 179 - vendor/github.com/go-kit/log/logfmt_logger.go | 62 - vendor/github.com/go-kit/log/nop_logger.go | 8 - vendor/github.com/go-kit/log/staticcheck.conf | 1 - vendor/github.com/go-kit/log/stdlib.go | 151 - vendor/github.com/go-kit/log/sync.go | 113 - vendor/github.com/go-kit/log/value.go | 110 - vendor/github.com/go-logfmt/logfmt/.gitignore | 1 - .../github.com/go-logfmt/logfmt/CHANGELOG.md | 82 - vendor/github.com/go-logfmt/logfmt/LICENSE | 22 - vendor/github.com/go-logfmt/logfmt/README.md | 41 - vendor/github.com/go-logfmt/logfmt/decode.go | 254 - vendor/github.com/go-logfmt/logfmt/doc.go | 6 - vendor/github.com/go-logfmt/logfmt/encode.go | 322 - .../github.com/go-logfmt/logfmt/jsonstring.go | 277 - vendor/github.com/go-zoo/bone/.gitignore | 1 - vendor/github.com/go-zoo/bone/.travis.yml | 7 - vendor/github.com/go-zoo/bone/CHANGELOG.md | 56 - .../github.com/go-zoo/bone/CODE_OF_CONDUCT.md | 46 - vendor/github.com/go-zoo/bone/CONTRIBUTING.md | 8 - vendor/github.com/go-zoo/bone/LICENSE | 22 - vendor/github.com/go-zoo/bone/README.md | 91 - vendor/github.com/go-zoo/bone/bone.go | 91 - vendor/github.com/go-zoo/bone/helper.go | 170 - vendor/github.com/go-zoo/bone/helper_15.go | 45 - vendor/github.com/go-zoo/bone/helper_17.go | 39 - vendor/github.com/go-zoo/bone/mux.go | 137 - vendor/github.com/go-zoo/bone/route.go | 264 - vendor/github.com/go-zoo/bone/validator.go | 61 - vendor/github.com/gofrs/uuid/.gitignore | 15 - vendor/github.com/gofrs/uuid/LICENSE | 20 - vendor/github.com/gofrs/uuid/README.md | 117 - vendor/github.com/gofrs/uuid/codec.go | 234 - vendor/github.com/gofrs/uuid/fuzz.go | 48 - vendor/github.com/gofrs/uuid/generator.go | 456 - vendor/github.com/gofrs/uuid/sql.go | 116 - vendor/github.com/gofrs/uuid/uuid.go | 285 - vendor/github.com/golang-jwt/jwt/.gitignore | 4 - vendor/github.com/golang-jwt/jwt/LICENSE | 9 - .../golang-jwt/jwt/MIGRATION_GUIDE.md | 22 - vendor/github.com/golang-jwt/jwt/README.md | 113 - .../golang-jwt/jwt/VERSION_HISTORY.md | 131 - vendor/github.com/golang-jwt/jwt/claims.go | 146 - vendor/github.com/golang-jwt/jwt/doc.go | 4 - vendor/github.com/golang-jwt/jwt/ecdsa.go | 142 - .../github.com/golang-jwt/jwt/ecdsa_utils.go | 69 - vendor/github.com/golang-jwt/jwt/ed25519.go | 81 - .../golang-jwt/jwt/ed25519_utils.go | 64 - vendor/github.com/golang-jwt/jwt/errors.go | 59 - vendor/github.com/golang-jwt/jwt/hmac.go | 95 - .../github.com/golang-jwt/jwt/map_claims.go | 120 - vendor/github.com/golang-jwt/jwt/none.go | 52 - vendor/github.com/golang-jwt/jwt/parser.go | 148 - vendor/github.com/golang-jwt/jwt/rsa.go | 101 - vendor/github.com/golang-jwt/jwt/rsa_pss.go | 142 - vendor/github.com/golang-jwt/jwt/rsa_utils.go | 101 - .../golang-jwt/jwt/signing_method.go | 35 - vendor/github.com/golang-jwt/jwt/token.go | 104 - vendor/github.com/golang/protobuf/AUTHORS | 3 - .../github.com/golang/protobuf/CONTRIBUTORS | 3 - vendor/github.com/golang/protobuf/LICENSE | 28 - .../golang/protobuf/jsonpb/decode.go | 530 - .../golang/protobuf/jsonpb/encode.go | 559 - .../github.com/golang/protobuf/jsonpb/json.go | 69 - .../golang/protobuf/proto/buffer.go | 324 - .../golang/protobuf/proto/defaults.go | 63 - .../golang/protobuf/proto/deprecated.go | 113 - .../golang/protobuf/proto/discard.go | 58 - .../golang/protobuf/proto/extensions.go | 356 - .../golang/protobuf/proto/properties.go | 306 - .../github.com/golang/protobuf/proto/proto.go | 167 - .../golang/protobuf/proto/registry.go | 317 - .../golang/protobuf/proto/text_decode.go | 801 -- .../golang/protobuf/proto/text_encode.go | 560 - .../github.com/golang/protobuf/proto/wire.go | 78 - .../golang/protobuf/proto/wrappers.go | 34 - .../github.com/golang/protobuf/ptypes/any.go | 179 - .../golang/protobuf/ptypes/any/any.pb.go | 62 - .../github.com/golang/protobuf/ptypes/doc.go | 10 - .../golang/protobuf/ptypes/duration.go | 76 - .../protobuf/ptypes/duration/duration.pb.go | 63 - .../golang/protobuf/ptypes/timestamp.go | 112 - .../protobuf/ptypes/timestamp/timestamp.pb.go | 64 - vendor/github.com/google/uuid/CHANGELOG.md | 21 - vendor/github.com/google/uuid/CONTRIBUTING.md | 26 - vendor/github.com/google/uuid/CONTRIBUTORS | 9 - vendor/github.com/google/uuid/LICENSE | 27 - vendor/github.com/google/uuid/README.md | 21 - vendor/github.com/google/uuid/dce.go | 80 - vendor/github.com/google/uuid/doc.go | 12 - vendor/github.com/google/uuid/hash.go | 53 - vendor/github.com/google/uuid/marshal.go | 38 - vendor/github.com/google/uuid/node.go | 90 - vendor/github.com/google/uuid/node_js.go | 12 - vendor/github.com/google/uuid/node_net.go | 33 - vendor/github.com/google/uuid/null.go | 118 - vendor/github.com/google/uuid/sql.go | 59 - vendor/github.com/google/uuid/time.go | 123 - vendor/github.com/google/uuid/util.go | 43 - vendor/github.com/google/uuid/uuid.go | 312 - vendor/github.com/google/uuid/version1.go | 44 - vendor/github.com/google/uuid/version4.go | 76 - .../github.com/gorilla/websocket/.gitignore | 25 - vendor/github.com/gorilla/websocket/AUTHORS | 9 - vendor/github.com/gorilla/websocket/LICENSE | 22 - vendor/github.com/gorilla/websocket/README.md | 39 - vendor/github.com/gorilla/websocket/client.go | 422 - .../gorilla/websocket/compression.go | 148 - vendor/github.com/gorilla/websocket/conn.go | 1230 --- vendor/github.com/gorilla/websocket/doc.go | 227 - vendor/github.com/gorilla/websocket/join.go | 42 - vendor/github.com/gorilla/websocket/json.go | 60 - vendor/github.com/gorilla/websocket/mask.go | 55 - .../github.com/gorilla/websocket/mask_safe.go | 16 - .../github.com/gorilla/websocket/prepared.go | 102 - vendor/github.com/gorilla/websocket/proxy.go | 77 - vendor/github.com/gorilla/websocket/server.go | 365 - .../gorilla/websocket/tls_handshake.go | 21 - .../gorilla/websocket/tls_handshake_116.go | 21 - vendor/github.com/gorilla/websocket/util.go | 283 - .../gorilla/websocket/x_net_proxy.go | 473 - .../mainflux/export/pkg/config/config.go | 111 - vendor/github.com/mainflux/mainflux/LICENSE | 191 - .../mainflux/mainflux/pkg/errors/README.md | 5 - .../mainflux/mainflux/pkg/errors/errors.go | 96 - .../mainflux/mainflux/pkg/errors/types.go | 18 - vendor/github.com/mainflux/senml/LICENSE | 191 - vendor/github.com/mainflux/senml/README.md | 30 - vendor/github.com/mainflux/senml/senml.go | 251 - .../golang_protobuf_extensions/v2/LICENSE | 201 - .../golang_protobuf_extensions/v2/NOTICE | 1 - .../v2/pbutil/.gitignore | 1 - .../v2/pbutil/Makefile | 7 - .../v2/pbutil/decode.go | 81 - .../v2/pbutil/doc.go | 16 - .../v2/pbutil/encode.go | 49 - .../pelletier/go-toml/.dockerignore | 2 - .../github.com/pelletier/go-toml/.gitignore | 5 - .../pelletier/go-toml/CONTRIBUTING.md | 132 - .../github.com/pelletier/go-toml/Dockerfile | 11 - vendor/github.com/pelletier/go-toml/LICENSE | 247 - vendor/github.com/pelletier/go-toml/Makefile | 29 - .../go-toml/PULL_REQUEST_TEMPLATE.md | 5 - vendor/github.com/pelletier/go-toml/README.md | 176 - .../github.com/pelletier/go-toml/SECURITY.md | 19 - .../pelletier/go-toml/azure-pipelines.yml | 188 - .../github.com/pelletier/go-toml/benchmark.sh | 35 - vendor/github.com/pelletier/go-toml/doc.go | 23 - .../pelletier/go-toml/example-crlf.toml | 30 - .../github.com/pelletier/go-toml/example.toml | 30 - vendor/github.com/pelletier/go-toml/fuzz.go | 31 - vendor/github.com/pelletier/go-toml/fuzz.sh | 15 - .../pelletier/go-toml/keysparsing.go | 112 - vendor/github.com/pelletier/go-toml/lexer.go | 1031 -- .../github.com/pelletier/go-toml/localtime.go | 287 - .../github.com/pelletier/go-toml/marshal.go | 1308 --- .../go-toml/marshal_OrderPreserve_test.toml | 39 - .../pelletier/go-toml/marshal_test.toml | 39 - vendor/github.com/pelletier/go-toml/parser.go | 507 - .../github.com/pelletier/go-toml/position.go | 29 - vendor/github.com/pelletier/go-toml/token.go | 136 - vendor/github.com/pelletier/go-toml/toml.go | 533 - .../github.com/pelletier/go-toml/tomlpub.go | 71 - .../pelletier/go-toml/tomltree_create.go | 155 - .../pelletier/go-toml/tomltree_write.go | 552 - .../pelletier/go-toml/tomltree_writepub.go | 6 - .../prometheus/client_golang/LICENSE | 201 - .../prometheus/client_golang/NOTICE | 23 - .../client_golang/prometheus/.gitignore | 1 - .../client_golang/prometheus/README.md | 1 - .../prometheus/build_info_collector.go | 38 - .../client_golang/prometheus/collector.go | 128 - .../client_golang/prometheus/counter.go | 358 - .../client_golang/prometheus/desc.go | 207 - .../client_golang/prometheus/doc.go | 210 - .../prometheus/expvar_collector.go | 86 - .../client_golang/prometheus/fnv.go | 42 - .../client_golang/prometheus/gauge.go | 311 - .../client_golang/prometheus/get_pid.go | 26 - .../prometheus/get_pid_gopherjs.go | 23 - .../client_golang/prometheus/go_collector.go | 281 - .../prometheus/go_collector_go116.go | 122 - .../prometheus/go_collector_latest.go | 567 - .../client_golang/prometheus/histogram.go | 1531 --- .../prometheus/internal/almost_equal.go | 60 - .../prometheus/internal/difflib.go | 654 -- .../internal/go_collector_options.go | 32 - .../prometheus/internal/go_runtime_metrics.go | 142 - .../prometheus/internal/metric.go | 101 - .../client_golang/prometheus/labels.go | 186 - .../client_golang/prometheus/metric.go | 257 - .../client_golang/prometheus/num_threads.go | 25 - .../prometheus/num_threads_gopherjs.go | 22 - .../client_golang/prometheus/observer.go | 64 - .../prometheus/process_collector.go | 164 - .../prometheus/process_collector_js.go | 26 - .../prometheus/process_collector_other.go | 66 - .../prometheus/process_collector_windows.go | 116 - .../prometheus/promhttp/delegator.go | 374 - .../client_golang/prometheus/promhttp/http.go | 408 - .../prometheus/promhttp/instrument_client.go | 249 - .../prometheus/promhttp/instrument_server.go | 576 - .../prometheus/promhttp/option.go | 84 - .../client_golang/prometheus/registry.go | 1075 -- .../client_golang/prometheus/summary.go | 785 -- .../client_golang/prometheus/timer.go | 81 - .../client_golang/prometheus/untyped.go | 42 - .../client_golang/prometheus/value.go | 274 - .../client_golang/prometheus/vec.go | 709 -- .../client_golang/prometheus/vnext.go | 23 - .../client_golang/prometheus/wrap.go | 214 - .../prometheus/client_model/LICENSE | 201 - .../github.com/prometheus/client_model/NOTICE | 5 - .../prometheus/client_model/go/metrics.pb.go | 1376 --- vendor/github.com/prometheus/common/LICENSE | 201 - vendor/github.com/prometheus/common/NOTICE | 5 - .../prometheus/common/expfmt/decode.go | 428 - .../prometheus/common/expfmt/encode.go | 165 - .../prometheus/common/expfmt/expfmt.go | 43 - .../prometheus/common/expfmt/fuzz.go | 37 - .../common/expfmt/openmetrics_create.go | 527 - .../prometheus/common/expfmt/text_create.go | 464 - .../prometheus/common/expfmt/text_parse.go | 779 -- .../bitbucket.org/ww/goautoneg/README.txt | 67 - .../bitbucket.org/ww/goautoneg/autoneg.go | 160 - .../prometheus/common/model/alert.go | 136 - .../prometheus/common/model/fingerprinting.go | 105 - .../github.com/prometheus/common/model/fnv.go | 42 - .../prometheus/common/model/labels.go | 218 - .../prometheus/common/model/labelset.go | 169 - .../prometheus/common/model/metric.go | 102 - .../prometheus/common/model/model.go | 16 - .../prometheus/common/model/signature.go | 144 - .../prometheus/common/model/silence.go | 106 - .../prometheus/common/model/time.go | 340 - .../prometheus/common/model/value.go | 366 - .../prometheus/common/model/value_float.go | 100 - .../common/model/value_histogram.go | 178 - .../prometheus/common/model/value_type.go | 83 - .../github.com/prometheus/procfs/.gitignore | 2 - .../prometheus/procfs/.golangci.yml | 15 - .../prometheus/procfs/CODE_OF_CONDUCT.md | 3 - .../prometheus/procfs/CONTRIBUTING.md | 121 - vendor/github.com/prometheus/procfs/LICENSE | 201 - .../prometheus/procfs/MAINTAINERS.md | 2 - vendor/github.com/prometheus/procfs/Makefile | 31 - .../prometheus/procfs/Makefile.common | 269 - vendor/github.com/prometheus/procfs/NOTICE | 7 - vendor/github.com/prometheus/procfs/README.md | 61 - .../github.com/prometheus/procfs/SECURITY.md | 6 - vendor/github.com/prometheus/procfs/arp.go | 116 - .../github.com/prometheus/procfs/buddyinfo.go | 85 - .../github.com/prometheus/procfs/cmdline.go | 30 - .../github.com/prometheus/procfs/cpuinfo.go | 519 - .../prometheus/procfs/cpuinfo_armx.go | 20 - .../prometheus/procfs/cpuinfo_loong64.go | 19 - .../prometheus/procfs/cpuinfo_mipsx.go | 20 - .../prometheus/procfs/cpuinfo_others.go | 19 - .../prometheus/procfs/cpuinfo_ppcx.go | 20 - .../prometheus/procfs/cpuinfo_riscvx.go | 20 - .../prometheus/procfs/cpuinfo_s390x.go | 19 - .../prometheus/procfs/cpuinfo_x86.go | 20 - vendor/github.com/prometheus/procfs/crypto.go | 154 - vendor/github.com/prometheus/procfs/doc.go | 44 - vendor/github.com/prometheus/procfs/fs.go | 50 - .../prometheus/procfs/fs_statfs_notype.go | 23 - .../prometheus/procfs/fs_statfs_type.go | 33 - .../github.com/prometheus/procfs/fscache.go | 422 - .../prometheus/procfs/internal/fs/fs.go | 55 - .../prometheus/procfs/internal/util/parse.go | 112 - .../procfs/internal/util/readfile.go | 37 - .../procfs/internal/util/sysreadfile.go | 50 - .../internal/util/sysreadfile_compat.go | 27 - .../procfs/internal/util/valueparser.go | 91 - vendor/github.com/prometheus/procfs/ipvs.go | 241 - .../prometheus/procfs/kernel_random.go | 63 - .../github.com/prometheus/procfs/loadavg.go | 62 - vendor/github.com/prometheus/procfs/mdstat.go | 266 - .../github.com/prometheus/procfs/meminfo.go | 277 - .../github.com/prometheus/procfs/mountinfo.go | 180 - .../prometheus/procfs/mountstats.go | 712 -- .../prometheus/procfs/net_conntrackstat.go | 118 - .../github.com/prometheus/procfs/net_dev.go | 205 - .../prometheus/procfs/net_ip_socket.go | 228 - .../prometheus/procfs/net_protocols.go | 180 - .../github.com/prometheus/procfs/net_route.go | 143 - .../prometheus/procfs/net_sockstat.go | 162 - .../prometheus/procfs/net_softnet.go | 155 - .../github.com/prometheus/procfs/net_tcp.go | 64 - .../github.com/prometheus/procfs/net_udp.go | 64 - .../github.com/prometheus/procfs/net_unix.go | 257 - .../prometheus/procfs/net_wireless.go | 182 - .../github.com/prometheus/procfs/net_xfrm.go | 189 - .../github.com/prometheus/procfs/netstat.go | 82 - vendor/github.com/prometheus/procfs/proc.go | 338 - .../prometheus/procfs/proc_cgroup.go | 98 - .../prometheus/procfs/proc_cgroups.go | 98 - .../prometheus/procfs/proc_environ.go | 37 - .../prometheus/procfs/proc_fdinfo.go | 138 - .../prometheus/procfs/proc_interrupts.go | 98 - .../github.com/prometheus/procfs/proc_io.go | 59 - .../prometheus/procfs/proc_limits.go | 160 - .../github.com/prometheus/procfs/proc_maps.go | 211 - .../prometheus/procfs/proc_netstat.go | 443 - .../github.com/prometheus/procfs/proc_ns.go | 68 - .../github.com/prometheus/procfs/proc_psi.go | 102 - .../prometheus/procfs/proc_smaps.go | 166 - .../github.com/prometheus/procfs/proc_snmp.go | 353 - .../prometheus/procfs/proc_snmp6.go | 381 - .../github.com/prometheus/procfs/proc_stat.go | 222 - .../prometheus/procfs/proc_status.go | 221 - .../github.com/prometheus/procfs/proc_sys.go | 51 - .../github.com/prometheus/procfs/schedstat.go | 121 - vendor/github.com/prometheus/procfs/slab.go | 151 - .../github.com/prometheus/procfs/softirqs.go | 160 - vendor/github.com/prometheus/procfs/stat.go | 258 - vendor/github.com/prometheus/procfs/swaps.go | 89 - vendor/github.com/prometheus/procfs/thread.go | 80 - vendor/github.com/prometheus/procfs/ttar | 413 - vendor/github.com/prometheus/procfs/vm.go | 212 - .../github.com/prometheus/procfs/zoneinfo.go | 196 - vendor/github.com/x448/float16/.travis.yml | 13 - vendor/github.com/x448/float16/LICENSE | 22 - vendor/github.com/x448/float16/README.md | 133 - vendor/github.com/x448/float16/float16.go | 302 - vendor/golang.org/x/exp/LICENSE | 27 - vendor/golang.org/x/exp/PATENTS | 22 - .../x/exp/constraints/constraints.go | 50 - vendor/golang.org/x/exp/slices/cmp.go | 44 - vendor/golang.org/x/exp/slices/slices.go | 499 - vendor/golang.org/x/exp/slices/sort.go | 195 - .../golang.org/x/exp/slices/zsortanyfunc.go | 479 - .../golang.org/x/exp/slices/zsortordered.go | 481 - vendor/golang.org/x/net/LICENSE | 27 - vendor/golang.org/x/net/PATENTS | 22 - vendor/golang.org/x/net/http/httpguts/guts.go | 50 - .../golang.org/x/net/http/httpguts/httplex.go | 352 - vendor/golang.org/x/net/http2/.gitignore | 2 - vendor/golang.org/x/net/http2/ascii.go | 53 - vendor/golang.org/x/net/http2/ciphers.go | 641 -- .../x/net/http2/client_conn_pool.go | 311 - vendor/golang.org/x/net/http2/databuffer.go | 146 - vendor/golang.org/x/net/http2/errors.go | 145 - vendor/golang.org/x/net/http2/flow.go | 120 - vendor/golang.org/x/net/http2/frame.go | 1658 --- vendor/golang.org/x/net/http2/go111.go | 30 - vendor/golang.org/x/net/http2/go115.go | 27 - vendor/golang.org/x/net/http2/go118.go | 17 - vendor/golang.org/x/net/http2/gotrack.go | 170 - vendor/golang.org/x/net/http2/headermap.go | 105 - vendor/golang.org/x/net/http2/hpack/encode.go | 245 - vendor/golang.org/x/net/http2/hpack/hpack.go | 523 - .../golang.org/x/net/http2/hpack/huffman.go | 226 - .../x/net/http2/hpack/static_table.go | 188 - vendor/golang.org/x/net/http2/hpack/tables.go | 403 - vendor/golang.org/x/net/http2/http2.go | 385 - vendor/golang.org/x/net/http2/not_go111.go | 21 - vendor/golang.org/x/net/http2/not_go115.go | 31 - vendor/golang.org/x/net/http2/not_go118.go | 17 - vendor/golang.org/x/net/http2/pipe.go | 175 - vendor/golang.org/x/net/http2/server.go | 3296 ------ vendor/golang.org/x/net/http2/transport.go | 3203 ------ vendor/golang.org/x/net/http2/write.go | 370 - vendor/golang.org/x/net/http2/writesched.go | 251 - .../x/net/http2/writesched_priority.go | 451 - .../x/net/http2/writesched_random.go | 77 - .../x/net/http2/writesched_roundrobin.go | 119 - vendor/golang.org/x/net/idna/go118.go | 14 - vendor/golang.org/x/net/idna/idna10.0.0.go | 770 -- vendor/golang.org/x/net/idna/idna9.0.0.go | 718 -- vendor/golang.org/x/net/idna/pre_go118.go | 12 - vendor/golang.org/x/net/idna/punycode.go | 217 - vendor/golang.org/x/net/idna/tables10.0.0.go | 4560 -------- vendor/golang.org/x/net/idna/tables11.0.0.go | 4654 -------- vendor/golang.org/x/net/idna/tables12.0.0.go | 4734 --------- vendor/golang.org/x/net/idna/tables13.0.0.go | 4960 --------- vendor/golang.org/x/net/idna/tables15.0.0.go | 5145 --------- vendor/golang.org/x/net/idna/tables9.0.0.go | 4487 -------- vendor/golang.org/x/net/idna/trie.go | 51 - vendor/golang.org/x/net/idna/trie12.0.0.go | 31 - vendor/golang.org/x/net/idna/trie13.0.0.go | 31 - vendor/golang.org/x/net/idna/trieval.go | 119 - .../golang.org/x/net/internal/socks/client.go | 168 - .../golang.org/x/net/internal/socks/socks.go | 317 - .../x/net/internal/timeseries/timeseries.go | 525 - vendor/golang.org/x/net/proxy/dial.go | 54 - vendor/golang.org/x/net/proxy/direct.go | 31 - vendor/golang.org/x/net/proxy/per_host.go | 155 - vendor/golang.org/x/net/proxy/proxy.go | 149 - vendor/golang.org/x/net/proxy/socks5.go | 42 - vendor/golang.org/x/net/trace/events.go | 532 - vendor/golang.org/x/net/trace/histogram.go | 365 - vendor/golang.org/x/net/trace/trace.go | 1130 -- vendor/golang.org/x/sync/LICENSE | 27 - vendor/golang.org/x/sync/PATENTS | 22 - vendor/golang.org/x/sync/errgroup/errgroup.go | 132 - vendor/golang.org/x/sync/errgroup/go120.go | 14 - .../golang.org/x/sync/errgroup/pre_go120.go | 15 - .../golang.org/x/sync/semaphore/semaphore.go | 136 - vendor/golang.org/x/sys/LICENSE | 27 - vendor/golang.org/x/sys/PATENTS | 22 - vendor/golang.org/x/sys/unix/.gitignore | 2 - vendor/golang.org/x/sys/unix/README.md | 184 - .../golang.org/x/sys/unix/affinity_linux.go | 86 - vendor/golang.org/x/sys/unix/aliases.go | 15 - vendor/golang.org/x/sys/unix/asm_aix_ppc64.s | 18 - vendor/golang.org/x/sys/unix/asm_bsd_386.s | 29 - vendor/golang.org/x/sys/unix/asm_bsd_amd64.s | 29 - vendor/golang.org/x/sys/unix/asm_bsd_arm.s | 29 - vendor/golang.org/x/sys/unix/asm_bsd_arm64.s | 29 - vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s | 31 - .../golang.org/x/sys/unix/asm_bsd_riscv64.s | 29 - vendor/golang.org/x/sys/unix/asm_linux_386.s | 66 - .../golang.org/x/sys/unix/asm_linux_amd64.s | 58 - vendor/golang.org/x/sys/unix/asm_linux_arm.s | 57 - .../golang.org/x/sys/unix/asm_linux_arm64.s | 53 - .../golang.org/x/sys/unix/asm_linux_loong64.s | 54 - .../golang.org/x/sys/unix/asm_linux_mips64x.s | 57 - .../golang.org/x/sys/unix/asm_linux_mipsx.s | 55 - .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 45 - .../golang.org/x/sys/unix/asm_linux_riscv64.s | 49 - .../golang.org/x/sys/unix/asm_linux_s390x.s | 57 - .../x/sys/unix/asm_openbsd_mips64.s | 30 - .../golang.org/x/sys/unix/asm_solaris_amd64.s | 18 - vendor/golang.org/x/sys/unix/asm_zos_s390x.s | 426 - .../golang.org/x/sys/unix/bluetooth_linux.go | 36 - vendor/golang.org/x/sys/unix/cap_freebsd.go | 196 - vendor/golang.org/x/sys/unix/constants.go | 14 - vendor/golang.org/x/sys/unix/dev_aix_ppc.go | 27 - vendor/golang.org/x/sys/unix/dev_aix_ppc64.go | 29 - vendor/golang.org/x/sys/unix/dev_darwin.go | 24 - vendor/golang.org/x/sys/unix/dev_dragonfly.go | 30 - vendor/golang.org/x/sys/unix/dev_freebsd.go | 30 - vendor/golang.org/x/sys/unix/dev_linux.go | 42 - vendor/golang.org/x/sys/unix/dev_netbsd.go | 29 - vendor/golang.org/x/sys/unix/dev_openbsd.go | 29 - vendor/golang.org/x/sys/unix/dev_zos.go | 29 - vendor/golang.org/x/sys/unix/dirent.go | 103 - vendor/golang.org/x/sys/unix/endian_big.go | 10 - vendor/golang.org/x/sys/unix/endian_little.go | 10 - vendor/golang.org/x/sys/unix/env_unix.go | 32 - vendor/golang.org/x/sys/unix/epoll_zos.go | 221 - vendor/golang.org/x/sys/unix/fcntl.go | 37 - vendor/golang.org/x/sys/unix/fcntl_darwin.go | 24 - .../x/sys/unix/fcntl_linux_32bit.go | 14 - vendor/golang.org/x/sys/unix/fdset.go | 30 - vendor/golang.org/x/sys/unix/fstatfs_zos.go | 164 - vendor/golang.org/x/sys/unix/gccgo.go | 60 - vendor/golang.org/x/sys/unix/gccgo_c.c | 45 - .../x/sys/unix/gccgo_linux_amd64.go | 21 - vendor/golang.org/x/sys/unix/ifreq_linux.go | 142 - vendor/golang.org/x/sys/unix/ioctl_linux.go | 233 - vendor/golang.org/x/sys/unix/ioctl_signed.go | 70 - .../golang.org/x/sys/unix/ioctl_unsigned.go | 70 - vendor/golang.org/x/sys/unix/ioctl_zos.go | 72 - vendor/golang.org/x/sys/unix/mkall.sh | 249 - vendor/golang.org/x/sys/unix/mkerrors.sh | 784 -- vendor/golang.org/x/sys/unix/mmap_nomremap.go | 14 - vendor/golang.org/x/sys/unix/mremap.go | 53 - vendor/golang.org/x/sys/unix/pagesize_unix.go | 16 - .../golang.org/x/sys/unix/pledge_openbsd.go | 163 - vendor/golang.org/x/sys/unix/ptrace_darwin.go | 12 - vendor/golang.org/x/sys/unix/ptrace_ios.go | 12 - vendor/golang.org/x/sys/unix/race.go | 31 - vendor/golang.org/x/sys/unix/race0.go | 26 - .../x/sys/unix/readdirent_getdents.go | 13 - .../x/sys/unix/readdirent_getdirentries.go | 20 - .../x/sys/unix/sockcmsg_dragonfly.go | 16 - .../golang.org/x/sys/unix/sockcmsg_linux.go | 85 - vendor/golang.org/x/sys/unix/sockcmsg_unix.go | 107 - .../x/sys/unix/sockcmsg_unix_other.go | 47 - vendor/golang.org/x/sys/unix/syscall.go | 87 - vendor/golang.org/x/sys/unix/syscall_aix.go | 582 - .../golang.org/x/sys/unix/syscall_aix_ppc.go | 53 - .../x/sys/unix/syscall_aix_ppc64.go | 84 - vendor/golang.org/x/sys/unix/syscall_bsd.go | 610 -- .../golang.org/x/sys/unix/syscall_darwin.go | 646 -- .../x/sys/unix/syscall_darwin_amd64.go | 51 - .../x/sys/unix/syscall_darwin_arm64.go | 51 - .../x/sys/unix/syscall_darwin_libSystem.go | 27 - .../x/sys/unix/syscall_dragonfly.go | 347 - .../x/sys/unix/syscall_dragonfly_amd64.go | 57 - .../golang.org/x/sys/unix/syscall_freebsd.go | 453 - .../x/sys/unix/syscall_freebsd_386.go | 65 - .../x/sys/unix/syscall_freebsd_amd64.go | 65 - .../x/sys/unix/syscall_freebsd_arm.go | 61 - .../x/sys/unix/syscall_freebsd_arm64.go | 61 - .../x/sys/unix/syscall_freebsd_riscv64.go | 61 - vendor/golang.org/x/sys/unix/syscall_hurd.go | 30 - .../golang.org/x/sys/unix/syscall_hurd_386.go | 29 - .../golang.org/x/sys/unix/syscall_illumos.go | 79 - vendor/golang.org/x/sys/unix/syscall_linux.go | 2484 ----- .../x/sys/unix/syscall_linux_386.go | 315 - .../x/sys/unix/syscall_linux_alarm.go | 14 - .../x/sys/unix/syscall_linux_amd64.go | 146 - .../x/sys/unix/syscall_linux_amd64_gc.go | 13 - .../x/sys/unix/syscall_linux_arm.go | 217 - .../x/sys/unix/syscall_linux_arm64.go | 185 - .../golang.org/x/sys/unix/syscall_linux_gc.go | 15 - .../x/sys/unix/syscall_linux_gc_386.go | 17 - .../x/sys/unix/syscall_linux_gc_arm.go | 14 - .../x/sys/unix/syscall_linux_gccgo_386.go | 31 - .../x/sys/unix/syscall_linux_gccgo_arm.go | 21 - .../x/sys/unix/syscall_linux_loong64.go | 217 - .../x/sys/unix/syscall_linux_mips64x.go | 190 - .../x/sys/unix/syscall_linux_mipsx.go | 176 - .../x/sys/unix/syscall_linux_ppc.go | 205 - .../x/sys/unix/syscall_linux_ppc64x.go | 117 - .../x/sys/unix/syscall_linux_riscv64.go | 190 - .../x/sys/unix/syscall_linux_s390x.go | 297 - .../x/sys/unix/syscall_linux_sparc64.go | 113 - .../golang.org/x/sys/unix/syscall_netbsd.go | 371 - .../x/sys/unix/syscall_netbsd_386.go | 38 - .../x/sys/unix/syscall_netbsd_amd64.go | 38 - .../x/sys/unix/syscall_netbsd_arm.go | 38 - .../x/sys/unix/syscall_netbsd_arm64.go | 38 - .../golang.org/x/sys/unix/syscall_openbsd.go | 329 - .../x/sys/unix/syscall_openbsd_386.go | 42 - .../x/sys/unix/syscall_openbsd_amd64.go | 42 - .../x/sys/unix/syscall_openbsd_arm.go | 42 - .../x/sys/unix/syscall_openbsd_arm64.go | 42 - .../x/sys/unix/syscall_openbsd_libc.go | 27 - .../x/sys/unix/syscall_openbsd_mips64.go | 39 - .../x/sys/unix/syscall_openbsd_ppc64.go | 42 - .../x/sys/unix/syscall_openbsd_riscv64.go | 42 - .../golang.org/x/sys/unix/syscall_solaris.go | 1103 -- .../x/sys/unix/syscall_solaris_amd64.go | 28 - vendor/golang.org/x/sys/unix/syscall_unix.go | 607 -- .../golang.org/x/sys/unix/syscall_unix_gc.go | 16 - .../x/sys/unix/syscall_unix_gc_ppc64x.go | 25 - .../x/sys/unix/syscall_zos_s390x.go | 1979 ---- vendor/golang.org/x/sys/unix/sysvshm_linux.go | 21 - vendor/golang.org/x/sys/unix/sysvshm_unix.go | 52 - .../x/sys/unix/sysvshm_unix_other.go | 14 - vendor/golang.org/x/sys/unix/timestruct.go | 77 - .../golang.org/x/sys/unix/unveil_openbsd.go | 42 - vendor/golang.org/x/sys/unix/xattr_bsd.go | 281 - .../golang.org/x/sys/unix/zerrors_aix_ppc.go | 1385 --- .../x/sys/unix/zerrors_aix_ppc64.go | 1386 --- .../x/sys/unix/zerrors_darwin_amd64.go | 1911 ---- .../x/sys/unix/zerrors_darwin_arm64.go | 1911 ---- .../x/sys/unix/zerrors_dragonfly_amd64.go | 1738 --- .../x/sys/unix/zerrors_freebsd_386.go | 2043 ---- .../x/sys/unix/zerrors_freebsd_amd64.go | 2040 ---- .../x/sys/unix/zerrors_freebsd_arm.go | 2034 ---- .../x/sys/unix/zerrors_freebsd_arm64.go | 2034 ---- .../x/sys/unix/zerrors_freebsd_riscv64.go | 2148 ---- vendor/golang.org/x/sys/unix/zerrors_linux.go | 3539 ------ .../x/sys/unix/zerrors_linux_386.go | 840 -- .../x/sys/unix/zerrors_linux_amd64.go | 840 -- .../x/sys/unix/zerrors_linux_arm.go | 846 -- .../x/sys/unix/zerrors_linux_arm64.go | 840 -- .../x/sys/unix/zerrors_linux_loong64.go | 832 -- .../x/sys/unix/zerrors_linux_mips.go | 847 -- .../x/sys/unix/zerrors_linux_mips64.go | 847 -- .../x/sys/unix/zerrors_linux_mips64le.go | 847 -- .../x/sys/unix/zerrors_linux_mipsle.go | 847 -- .../x/sys/unix/zerrors_linux_ppc.go | 899 -- .../x/sys/unix/zerrors_linux_ppc64.go | 903 -- .../x/sys/unix/zerrors_linux_ppc64le.go | 903 -- .../x/sys/unix/zerrors_linux_riscv64.go | 827 -- .../x/sys/unix/zerrors_linux_s390x.go | 902 -- .../x/sys/unix/zerrors_linux_sparc64.go | 945 -- .../x/sys/unix/zerrors_netbsd_386.go | 1780 ---- .../x/sys/unix/zerrors_netbsd_amd64.go | 1770 --- .../x/sys/unix/zerrors_netbsd_arm.go | 1759 --- .../x/sys/unix/zerrors_netbsd_arm64.go | 1770 --- .../x/sys/unix/zerrors_openbsd_386.go | 1906 ---- .../x/sys/unix/zerrors_openbsd_amd64.go | 1906 ---- .../x/sys/unix/zerrors_openbsd_arm.go | 1906 ---- .../x/sys/unix/zerrors_openbsd_arm64.go | 1906 ---- .../x/sys/unix/zerrors_openbsd_mips64.go | 1906 ---- .../x/sys/unix/zerrors_openbsd_ppc64.go | 1905 ---- .../x/sys/unix/zerrors_openbsd_riscv64.go | 1904 ---- .../x/sys/unix/zerrors_solaris_amd64.go | 1557 --- .../x/sys/unix/zerrors_zos_s390x.go | 860 -- .../x/sys/unix/zptrace_armnn_linux.go | 42 - .../x/sys/unix/zptrace_linux_arm64.go | 17 - .../x/sys/unix/zptrace_mipsnn_linux.go | 51 - .../x/sys/unix/zptrace_mipsnnle_linux.go | 51 - .../x/sys/unix/zptrace_x86_linux.go | 81 - .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 1462 --- .../x/sys/unix/zsyscall_aix_ppc64.go | 1421 --- .../x/sys/unix/zsyscall_aix_ppc64_gc.go | 1189 --- .../x/sys/unix/zsyscall_aix_ppc64_gccgo.go | 1070 -- .../x/sys/unix/zsyscall_darwin_amd64.go | 2544 ----- .../x/sys/unix/zsyscall_darwin_amd64.s | 754 -- .../x/sys/unix/zsyscall_darwin_arm64.go | 2544 ----- .../x/sys/unix/zsyscall_darwin_arm64.s | 754 -- .../x/sys/unix/zsyscall_dragonfly_amd64.go | 1667 --- .../x/sys/unix/zsyscall_freebsd_386.go | 1887 ---- .../x/sys/unix/zsyscall_freebsd_amd64.go | 1887 ---- .../x/sys/unix/zsyscall_freebsd_arm.go | 1887 ---- .../x/sys/unix/zsyscall_freebsd_arm64.go | 1887 ---- .../x/sys/unix/zsyscall_freebsd_riscv64.go | 1887 ---- .../x/sys/unix/zsyscall_illumos_amd64.go | 102 - .../golang.org/x/sys/unix/zsyscall_linux.go | 2197 ---- .../x/sys/unix/zsyscall_linux_386.go | 487 - .../x/sys/unix/zsyscall_linux_amd64.go | 654 -- .../x/sys/unix/zsyscall_linux_arm.go | 602 -- .../x/sys/unix/zsyscall_linux_arm64.go | 553 - .../x/sys/unix/zsyscall_linux_loong64.go | 487 - .../x/sys/unix/zsyscall_linux_mips.go | 654 -- .../x/sys/unix/zsyscall_linux_mips64.go | 648 -- .../x/sys/unix/zsyscall_linux_mips64le.go | 637 -- .../x/sys/unix/zsyscall_linux_mipsle.go | 654 -- .../x/sys/unix/zsyscall_linux_ppc.go | 659 -- .../x/sys/unix/zsyscall_linux_ppc64.go | 705 -- .../x/sys/unix/zsyscall_linux_ppc64le.go | 705 -- .../x/sys/unix/zsyscall_linux_riscv64.go | 549 - .../x/sys/unix/zsyscall_linux_s390x.go | 496 - .../x/sys/unix/zsyscall_linux_sparc64.go | 649 -- .../x/sys/unix/zsyscall_netbsd_386.go | 1849 ---- .../x/sys/unix/zsyscall_netbsd_amd64.go | 1849 ---- .../x/sys/unix/zsyscall_netbsd_arm.go | 1849 ---- .../x/sys/unix/zsyscall_netbsd_arm64.go | 1849 ---- .../x/sys/unix/zsyscall_openbsd_386.go | 2231 ---- .../x/sys/unix/zsyscall_openbsd_386.s | 674 -- .../x/sys/unix/zsyscall_openbsd_amd64.go | 2231 ---- .../x/sys/unix/zsyscall_openbsd_amd64.s | 674 -- .../x/sys/unix/zsyscall_openbsd_arm.go | 2231 ---- .../x/sys/unix/zsyscall_openbsd_arm.s | 674 -- .../x/sys/unix/zsyscall_openbsd_arm64.go | 2231 ---- .../x/sys/unix/zsyscall_openbsd_arm64.s | 674 -- .../x/sys/unix/zsyscall_openbsd_mips64.go | 2231 ---- .../x/sys/unix/zsyscall_openbsd_mips64.s | 674 -- .../x/sys/unix/zsyscall_openbsd_ppc64.go | 2231 ---- .../x/sys/unix/zsyscall_openbsd_ppc64.s | 808 -- .../x/sys/unix/zsyscall_openbsd_riscv64.go | 2231 ---- .../x/sys/unix/zsyscall_openbsd_riscv64.s | 674 -- .../x/sys/unix/zsyscall_solaris_amd64.go | 2104 ---- .../x/sys/unix/zsyscall_zos_s390x.go | 1254 --- .../x/sys/unix/zsysctl_openbsd_386.go | 281 - .../x/sys/unix/zsysctl_openbsd_amd64.go | 281 - .../x/sys/unix/zsysctl_openbsd_arm.go | 281 - .../x/sys/unix/zsysctl_openbsd_arm64.go | 281 - .../x/sys/unix/zsysctl_openbsd_mips64.go | 281 - .../x/sys/unix/zsysctl_openbsd_ppc64.go | 281 - .../x/sys/unix/zsysctl_openbsd_riscv64.go | 282 - .../x/sys/unix/zsysnum_darwin_amd64.go | 440 - .../x/sys/unix/zsysnum_darwin_arm64.go | 438 - .../x/sys/unix/zsysnum_dragonfly_amd64.go | 317 - .../x/sys/unix/zsysnum_freebsd_386.go | 394 - .../x/sys/unix/zsysnum_freebsd_amd64.go | 394 - .../x/sys/unix/zsysnum_freebsd_arm.go | 394 - .../x/sys/unix/zsysnum_freebsd_arm64.go | 394 - .../x/sys/unix/zsysnum_freebsd_riscv64.go | 394 - .../x/sys/unix/zsysnum_linux_386.go | 451 - .../x/sys/unix/zsysnum_linux_amd64.go | 373 - .../x/sys/unix/zsysnum_linux_arm.go | 415 - .../x/sys/unix/zsysnum_linux_arm64.go | 318 - .../x/sys/unix/zsysnum_linux_loong64.go | 312 - .../x/sys/unix/zsysnum_linux_mips.go | 435 - .../x/sys/unix/zsysnum_linux_mips64.go | 365 - .../x/sys/unix/zsysnum_linux_mips64le.go | 365 - .../x/sys/unix/zsysnum_linux_mipsle.go | 435 - .../x/sys/unix/zsysnum_linux_ppc.go | 442 - .../x/sys/unix/zsysnum_linux_ppc64.go | 414 - .../x/sys/unix/zsysnum_linux_ppc64le.go | 414 - .../x/sys/unix/zsysnum_linux_riscv64.go | 319 - .../x/sys/unix/zsysnum_linux_s390x.go | 380 - .../x/sys/unix/zsysnum_linux_sparc64.go | 393 - .../x/sys/unix/zsysnum_netbsd_386.go | 275 - .../x/sys/unix/zsysnum_netbsd_amd64.go | 275 - .../x/sys/unix/zsysnum_netbsd_arm.go | 275 - .../x/sys/unix/zsysnum_netbsd_arm64.go | 275 - .../x/sys/unix/zsysnum_openbsd_386.go | 220 - .../x/sys/unix/zsysnum_openbsd_amd64.go | 220 - .../x/sys/unix/zsysnum_openbsd_arm.go | 220 - .../x/sys/unix/zsysnum_openbsd_arm64.go | 219 - .../x/sys/unix/zsysnum_openbsd_mips64.go | 222 - .../x/sys/unix/zsysnum_openbsd_ppc64.go | 218 - .../x/sys/unix/zsysnum_openbsd_riscv64.go | 219 - .../x/sys/unix/zsysnum_zos_s390x.go | 2670 ----- .../golang.org/x/sys/unix/ztypes_aix_ppc.go | 354 - .../golang.org/x/sys/unix/ztypes_aix_ppc64.go | 358 - .../x/sys/unix/ztypes_darwin_amd64.go | 806 -- .../x/sys/unix/ztypes_darwin_arm64.go | 806 -- .../x/sys/unix/ztypes_dragonfly_amd64.go | 474 - .../x/sys/unix/ztypes_freebsd_386.go | 651 -- .../x/sys/unix/ztypes_freebsd_amd64.go | 656 -- .../x/sys/unix/ztypes_freebsd_arm.go | 642 -- .../x/sys/unix/ztypes_freebsd_arm64.go | 636 -- .../x/sys/unix/ztypes_freebsd_riscv64.go | 638 -- vendor/golang.org/x/sys/unix/ztypes_linux.go | 5885 ---------- .../golang.org/x/sys/unix/ztypes_linux_386.go | 698 -- .../x/sys/unix/ztypes_linux_amd64.go | 713 -- .../golang.org/x/sys/unix/ztypes_linux_arm.go | 693 -- .../x/sys/unix/ztypes_linux_arm64.go | 692 -- .../x/sys/unix/ztypes_linux_loong64.go | 693 -- .../x/sys/unix/ztypes_linux_mips.go | 698 -- .../x/sys/unix/ztypes_linux_mips64.go | 695 -- .../x/sys/unix/ztypes_linux_mips64le.go | 695 -- .../x/sys/unix/ztypes_linux_mipsle.go | 698 -- .../golang.org/x/sys/unix/ztypes_linux_ppc.go | 706 -- .../x/sys/unix/ztypes_linux_ppc64.go | 701 -- .../x/sys/unix/ztypes_linux_ppc64le.go | 701 -- .../x/sys/unix/ztypes_linux_riscv64.go | 747 -- .../x/sys/unix/ztypes_linux_s390x.go | 715 -- .../x/sys/unix/ztypes_linux_sparc64.go | 696 -- .../x/sys/unix/ztypes_netbsd_386.go | 586 - .../x/sys/unix/ztypes_netbsd_amd64.go | 594 -- .../x/sys/unix/ztypes_netbsd_arm.go | 591 - .../x/sys/unix/ztypes_netbsd_arm64.go | 594 -- .../x/sys/unix/ztypes_openbsd_386.go | 569 - .../x/sys/unix/ztypes_openbsd_amd64.go | 569 - .../x/sys/unix/ztypes_openbsd_arm.go | 576 - .../x/sys/unix/ztypes_openbsd_arm64.go | 569 - .../x/sys/unix/ztypes_openbsd_mips64.go | 569 - .../x/sys/unix/ztypes_openbsd_ppc64.go | 571 - .../x/sys/unix/ztypes_openbsd_riscv64.go | 571 - .../x/sys/unix/ztypes_solaris_amd64.go | 517 - .../golang.org/x/sys/unix/ztypes_zos_s390x.go | 415 - vendor/golang.org/x/sys/windows/aliases.go | 13 - .../golang.org/x/sys/windows/dll_windows.go | 416 - vendor/golang.org/x/sys/windows/empty.s | 9 - .../golang.org/x/sys/windows/env_windows.go | 54 - vendor/golang.org/x/sys/windows/eventlog.go | 21 - .../golang.org/x/sys/windows/exec_windows.go | 248 - .../x/sys/windows/memory_windows.go | 48 - vendor/golang.org/x/sys/windows/mkerrors.bash | 70 - .../x/sys/windows/mkknownfolderids.bash | 27 - vendor/golang.org/x/sys/windows/mksyscall.go | 10 - vendor/golang.org/x/sys/windows/race.go | 31 - vendor/golang.org/x/sys/windows/race0.go | 26 - .../x/sys/windows/security_windows.go | 1435 --- vendor/golang.org/x/sys/windows/service.go | 258 - .../x/sys/windows/setupapi_windows.go | 1425 --- vendor/golang.org/x/sys/windows/str.go | 23 - vendor/golang.org/x/sys/windows/syscall.go | 105 - .../x/sys/windows/syscall_windows.go | 1832 ---- .../golang.org/x/sys/windows/types_windows.go | 3356 ------ .../x/sys/windows/types_windows_386.go | 35 - .../x/sys/windows/types_windows_amd64.go | 34 - .../x/sys/windows/types_windows_arm.go | 35 - .../x/sys/windows/types_windows_arm64.go | 34 - .../x/sys/windows/zerrors_windows.go | 9468 ----------------- .../x/sys/windows/zknownfolderids_windows.go | 149 - .../x/sys/windows/zsyscall_windows.go | 4381 -------- vendor/golang.org/x/text/LICENSE | 27 - vendor/golang.org/x/text/PATENTS | 22 - .../x/text/secure/bidirule/bidirule.go | 336 - .../x/text/secure/bidirule/bidirule10.0.0.go | 12 - .../x/text/secure/bidirule/bidirule9.0.0.go | 15 - .../golang.org/x/text/transform/transform.go | 709 -- vendor/golang.org/x/text/unicode/bidi/bidi.go | 359 - .../golang.org/x/text/unicode/bidi/bracket.go | 335 - vendor/golang.org/x/text/unicode/bidi/core.go | 1071 -- vendor/golang.org/x/text/unicode/bidi/prop.go | 206 - .../x/text/unicode/bidi/tables10.0.0.go | 1816 ---- .../x/text/unicode/bidi/tables11.0.0.go | 1888 ---- .../x/text/unicode/bidi/tables12.0.0.go | 1924 ---- .../x/text/unicode/bidi/tables13.0.0.go | 1956 ---- .../x/text/unicode/bidi/tables15.0.0.go | 2043 ---- .../x/text/unicode/bidi/tables9.0.0.go | 1782 ---- .../golang.org/x/text/unicode/bidi/trieval.go | 48 - .../x/text/unicode/norm/composition.go | 512 - .../x/text/unicode/norm/forminfo.go | 279 - .../golang.org/x/text/unicode/norm/input.go | 109 - vendor/golang.org/x/text/unicode/norm/iter.go | 458 - .../x/text/unicode/norm/normalize.go | 610 -- .../x/text/unicode/norm/readwriter.go | 125 - .../x/text/unicode/norm/tables10.0.0.go | 7658 ------------- .../x/text/unicode/norm/tables11.0.0.go | 7694 -------------- .../x/text/unicode/norm/tables12.0.0.go | 7711 -------------- .../x/text/unicode/norm/tables13.0.0.go | 7761 -------------- .../x/text/unicode/norm/tables15.0.0.go | 7908 -------------- .../x/text/unicode/norm/tables9.0.0.go | 7638 ------------- .../x/text/unicode/norm/transform.go | 88 - vendor/golang.org/x/text/unicode/norm/trie.go | 54 - .../genproto/googleapis/rpc/LICENSE | 202 - .../googleapis/rpc/status/status.pb.go | 203 - vendor/google.golang.org/grpc/AUTHORS | 1 - .../google.golang.org/grpc/CODE-OF-CONDUCT.md | 3 - vendor/google.golang.org/grpc/CONTRIBUTING.md | 73 - vendor/google.golang.org/grpc/GOVERNANCE.md | 1 - vendor/google.golang.org/grpc/LICENSE | 202 - vendor/google.golang.org/grpc/MAINTAINERS.md | 28 - vendor/google.golang.org/grpc/Makefile | 46 - vendor/google.golang.org/grpc/NOTICE.txt | 13 - vendor/google.golang.org/grpc/README.md | 107 - vendor/google.golang.org/grpc/SECURITY.md | 3 - .../grpc/attributes/attributes.go | 141 - vendor/google.golang.org/grpc/backoff.go | 61 - .../google.golang.org/grpc/backoff/backoff.go | 52 - .../grpc/balancer/balancer.go | 442 - .../grpc/balancer/base/balancer.go | 264 - .../grpc/balancer/base/base.go | 71 - .../grpc/balancer/conn_state_evaluator.go | 74 - .../grpc/balancer/grpclb/state/state.go | 51 - .../grpc/balancer/roundrobin/roundrobin.go | 81 - .../grpc/balancer_conn_wrappers.go | 454 - .../grpc_binarylog_v1/binarylog.pb.go | 1183 -- vendor/google.golang.org/grpc/call.go | 74 - .../grpc/channelz/channelz.go | 36 - vendor/google.golang.org/grpc/clientconn.go | 2038 ---- vendor/google.golang.org/grpc/codec.go | 50 - vendor/google.golang.org/grpc/codegen.sh | 17 - .../grpc/codes/code_string.go | 111 - vendor/google.golang.org/grpc/codes/codes.go | 244 - .../grpc/connectivity/connectivity.go | 94 - .../grpc/credentials/credentials.go | 291 - .../grpc/credentials/insecure/insecure.go | 98 - .../google.golang.org/grpc/credentials/tls.go | 236 - vendor/google.golang.org/grpc/dialoptions.go | 716 -- vendor/google.golang.org/grpc/doc.go | 26 - .../grpc/encoding/encoding.go | 130 - .../grpc/encoding/proto/proto.go | 58 - .../grpc/grpclog/component.go | 117 - .../google.golang.org/grpc/grpclog/grpclog.go | 132 - .../google.golang.org/grpc/grpclog/logger.go | 87 - .../grpc/grpclog/loggerv2.go | 258 - vendor/google.golang.org/grpc/interceptor.go | 104 - .../grpc/internal/backoff/backoff.go | 109 - .../balancer/gracefulswitch/gracefulswitch.go | 385 - .../grpc/internal/balancerload/load.go | 46 - .../grpc/internal/binarylog/binarylog.go | 192 - .../internal/binarylog/binarylog_testutil.go | 42 - .../grpc/internal/binarylog/env_config.go | 208 - .../grpc/internal/binarylog/method_logger.go | 445 - .../grpc/internal/binarylog/sink.go | 170 - .../grpc/internal/buffer/unbounded.go | 105 - .../grpc/internal/channelz/funcs.go | 756 -- .../grpc/internal/channelz/id.go | 75 - .../grpc/internal/channelz/logging.go | 79 - .../grpc/internal/channelz/types.go | 727 -- .../grpc/internal/channelz/types_linux.go | 51 - .../grpc/internal/channelz/types_nonlinux.go | 43 - .../grpc/internal/channelz/util_linux.go | 37 - .../grpc/internal/channelz/util_nonlinux.go | 27 - .../grpc/internal/credentials/credentials.go | 49 - .../grpc/internal/credentials/spiffe.go | 75 - .../grpc/internal/credentials/syscallconn.go | 58 - .../grpc/internal/credentials/util.go | 52 - .../grpc/internal/envconfig/envconfig.go | 72 - .../grpc/internal/envconfig/observability.go | 42 - .../grpc/internal/envconfig/xds.go | 95 - .../grpc/internal/grpclog/grpclog.go | 126 - .../grpc/internal/grpclog/prefixLogger.go | 93 - .../grpc/internal/grpcrand/grpcrand.go | 95 - .../internal/grpcsync/callback_serializer.go | 125 - .../grpc/internal/grpcsync/event.go | 61 - .../grpc/internal/grpcsync/oncefunc.go | 32 - .../grpc/internal/grpcsync/pubsub.go | 121 - .../grpc/internal/grpcutil/compressor.go | 47 - .../grpc/internal/grpcutil/encode_duration.go | 63 - .../grpc/internal/grpcutil/grpcutil.go | 20 - .../grpc/internal/grpcutil/metadata.go | 40 - .../grpc/internal/grpcutil/method.go | 88 - .../grpc/internal/grpcutil/regex.go | 31 - .../grpc/internal/idle/idle.go | 301 - .../grpc/internal/internal.go | 211 - .../grpc/internal/metadata/metadata.go | 132 - .../grpc/internal/pretty/pretty.go | 82 - .../grpc/internal/resolver/config_selector.go | 167 - .../internal/resolver/dns/dns_resolver.go | 470 - .../resolver/passthrough/passthrough.go | 64 - .../grpc/internal/resolver/unix/unix.go | 74 - .../grpc/internal/serviceconfig/duration.go | 130 - .../internal/serviceconfig/serviceconfig.go | 180 - .../grpc/internal/status/status.go | 204 - .../grpc/internal/syscall/syscall_linux.go | 112 - .../grpc/internal/syscall/syscall_nonlinux.go | 77 - .../grpc/internal/transport/bdp_estimator.go | 141 - .../grpc/internal/transport/controlbuf.go | 1007 -- .../grpc/internal/transport/defaults.go | 55 - .../grpc/internal/transport/flowcontrol.go | 215 - .../grpc/internal/transport/handler_server.go | 483 - .../grpc/internal/transport/http2_client.go | 1788 ---- .../grpc/internal/transport/http2_server.go | 1466 --- .../grpc/internal/transport/http_util.go | 465 - .../grpc/internal/transport/logging.go | 40 - .../transport/networktype/networktype.go | 46 - .../grpc/internal/transport/proxy.go | 142 - .../grpc/internal/transport/transport.go | 837 -- .../grpc/internal/xds_handshake_cluster.go | 40 - .../grpc/keepalive/keepalive.go | 85 - .../grpc/metadata/metadata.go | 295 - vendor/google.golang.org/grpc/peer/peer.go | 51 - .../google.golang.org/grpc/picker_wrapper.go | 236 - vendor/google.golang.org/grpc/pickfirst.go | 263 - vendor/google.golang.org/grpc/preloader.go | 67 - vendor/google.golang.org/grpc/regenerate.sh | 123 - vendor/google.golang.org/grpc/resolver/map.go | 138 - .../grpc/resolver/resolver.go | 316 - .../grpc/resolver_conn_wrapper.go | 247 - vendor/google.golang.org/grpc/rpc_util.go | 959 -- vendor/google.golang.org/grpc/server.go | 2108 ---- .../google.golang.org/grpc/service_config.go | 347 - .../grpc/serviceconfig/serviceconfig.go | 44 - .../grpc/shared_buffer_pool.go | 154 - .../google.golang.org/grpc/stats/handlers.go | 63 - vendor/google.golang.org/grpc/stats/stats.go | 343 - .../google.golang.org/grpc/status/status.go | 162 - vendor/google.golang.org/grpc/stream.go | 1780 ---- vendor/google.golang.org/grpc/tap/tap.go | 62 - vendor/google.golang.org/grpc/trace.go | 123 - vendor/google.golang.org/grpc/version.go | 22 - vendor/google.golang.org/grpc/vet.sh | 212 - vendor/google.golang.org/protobuf/LICENSE | 27 - vendor/google.golang.org/protobuf/PATENTS | 22 - .../protobuf/encoding/protojson/decode.go | 665 -- .../protobuf/encoding/protojson/doc.go | 11 - .../protobuf/encoding/protojson/encode.go | 349 - .../encoding/protojson/well_known_types.go | 895 -- .../protobuf/encoding/prototext/decode.go | 770 -- .../protobuf/encoding/prototext/doc.go | 7 - .../protobuf/encoding/prototext/encode.go | 376 - .../protobuf/encoding/protowire/wire.go | 547 - .../protobuf/internal/descfmt/stringer.go | 318 - .../protobuf/internal/descopts/options.go | 29 - .../protobuf/internal/detrand/rand.go | 69 - .../internal/encoding/defval/default.go | 213 - .../protobuf/internal/encoding/json/decode.go | 340 - .../internal/encoding/json/decode_number.go | 254 - .../internal/encoding/json/decode_string.go | 91 - .../internal/encoding/json/decode_token.go | 192 - .../protobuf/internal/encoding/json/encode.go | 278 - .../encoding/messageset/messageset.go | 242 - .../protobuf/internal/encoding/tag/tag.go | 207 - .../protobuf/internal/encoding/text/decode.go | 686 -- .../internal/encoding/text/decode_number.go | 211 - .../internal/encoding/text/decode_string.go | 161 - .../internal/encoding/text/decode_token.go | 373 - .../protobuf/internal/encoding/text/doc.go | 29 - .../protobuf/internal/encoding/text/encode.go | 272 - .../protobuf/internal/errors/errors.go | 89 - .../protobuf/internal/errors/is_go112.go | 40 - .../protobuf/internal/errors/is_go113.go | 13 - .../protobuf/internal/filedesc/build.go | 157 - .../protobuf/internal/filedesc/desc.go | 633 -- .../protobuf/internal/filedesc/desc_init.go | 471 - .../protobuf/internal/filedesc/desc_lazy.go | 704 -- .../protobuf/internal/filedesc/desc_list.go | 457 - .../internal/filedesc/desc_list_gen.go | 356 - .../protobuf/internal/filedesc/placeholder.go | 109 - .../protobuf/internal/filetype/build.go | 296 - .../protobuf/internal/flags/flags.go | 24 - .../internal/flags/proto_legacy_disable.go | 10 - .../internal/flags/proto_legacy_enable.go | 10 - .../protobuf/internal/genid/any_gen.go | 34 - .../protobuf/internal/genid/api_gen.go | 106 - .../protobuf/internal/genid/descriptor_gen.go | 919 -- .../protobuf/internal/genid/doc.go | 11 - .../protobuf/internal/genid/duration_gen.go | 34 - .../protobuf/internal/genid/empty_gen.go | 19 - .../protobuf/internal/genid/field_mask_gen.go | 31 - .../protobuf/internal/genid/goname.go | 25 - .../protobuf/internal/genid/map_entry.go | 16 - .../internal/genid/source_context_gen.go | 31 - .../protobuf/internal/genid/struct_gen.go | 116 - .../protobuf/internal/genid/timestamp_gen.go | 34 - .../protobuf/internal/genid/type_gen.go | 190 - .../protobuf/internal/genid/wrappers.go | 13 - .../protobuf/internal/genid/wrappers_gen.go | 175 - .../protobuf/internal/impl/api_export.go | 177 - .../protobuf/internal/impl/checkinit.go | 141 - .../protobuf/internal/impl/codec_extension.go | 223 - .../protobuf/internal/impl/codec_field.go | 830 -- .../protobuf/internal/impl/codec_gen.go | 5637 ---------- .../protobuf/internal/impl/codec_map.go | 388 - .../protobuf/internal/impl/codec_map_go111.go | 38 - .../protobuf/internal/impl/codec_map_go112.go | 12 - .../protobuf/internal/impl/codec_message.go | 217 - .../internal/impl/codec_messageset.go | 123 - .../protobuf/internal/impl/codec_reflect.go | 210 - .../protobuf/internal/impl/codec_tables.go | 557 - .../protobuf/internal/impl/codec_unsafe.go | 18 - .../protobuf/internal/impl/convert.go | 495 - .../protobuf/internal/impl/convert_list.go | 141 - .../protobuf/internal/impl/convert_map.go | 121 - .../protobuf/internal/impl/decode.go | 285 - .../protobuf/internal/impl/encode.go | 201 - .../protobuf/internal/impl/enum.go | 21 - .../protobuf/internal/impl/extension.go | 156 - .../protobuf/internal/impl/legacy_enum.go | 218 - .../protobuf/internal/impl/legacy_export.go | 92 - .../internal/impl/legacy_extension.go | 176 - .../protobuf/internal/impl/legacy_file.go | 81 - .../protobuf/internal/impl/legacy_message.go | 563 - .../protobuf/internal/impl/merge.go | 176 - .../protobuf/internal/impl/merge_gen.go | 209 - .../protobuf/internal/impl/message.go | 279 - .../protobuf/internal/impl/message_reflect.go | 463 - .../internal/impl/message_reflect_field.go | 543 - .../internal/impl/message_reflect_gen.go | 249 - .../protobuf/internal/impl/pointer_reflect.go | 179 - .../protobuf/internal/impl/pointer_unsafe.go | 175 - .../protobuf/internal/impl/validate.go | 576 - .../protobuf/internal/impl/weak.go | 74 - .../protobuf/internal/order/order.go | 89 - .../protobuf/internal/order/range.go | 115 - .../protobuf/internal/pragma/pragma.go | 29 - .../protobuf/internal/set/ints.go | 58 - .../protobuf/internal/strs/strings.go | 196 - .../protobuf/internal/strs/strings_pure.go | 28 - .../protobuf/internal/strs/strings_unsafe.go | 95 - .../protobuf/internal/version/version.go | 79 - .../protobuf/proto/checkinit.go | 71 - .../protobuf/proto/decode.go | 294 - .../protobuf/proto/decode_gen.go | 603 -- .../google.golang.org/protobuf/proto/doc.go | 86 - .../protobuf/proto/encode.go | 322 - .../protobuf/proto/encode_gen.go | 97 - .../google.golang.org/protobuf/proto/equal.go | 57 - .../protobuf/proto/extension.go | 92 - .../google.golang.org/protobuf/proto/merge.go | 139 - .../protobuf/proto/messageset.go | 93 - .../google.golang.org/protobuf/proto/proto.go | 43 - .../protobuf/proto/proto_methods.go | 20 - .../protobuf/proto/proto_reflect.go | 20 - .../google.golang.org/protobuf/proto/reset.go | 43 - .../google.golang.org/protobuf/proto/size.go | 101 - .../protobuf/proto/size_gen.go | 55 - .../protobuf/proto/wrappers.go | 29 - .../protobuf/reflect/protodesc/desc.go | 276 - .../protobuf/reflect/protodesc/desc_init.go | 248 - .../reflect/protodesc/desc_resolve.go | 286 - .../reflect/protodesc/desc_validate.go | 374 - .../protobuf/reflect/protodesc/proto.go | 252 - .../protobuf/reflect/protoreflect/methods.go | 78 - .../protobuf/reflect/protoreflect/proto.go | 508 - .../protobuf/reflect/protoreflect/source.go | 129 - .../reflect/protoreflect/source_gen.go | 502 - .../protobuf/reflect/protoreflect/type.go | 666 -- .../protobuf/reflect/protoreflect/value.go | 285 - .../reflect/protoreflect/value_equal.go | 168 - .../reflect/protoreflect/value_pure.go | 60 - .../reflect/protoreflect/value_union.go | 438 - .../reflect/protoreflect/value_unsafe.go | 99 - .../reflect/protoregistry/registry.go | 882 -- .../protobuf/runtime/protoiface/legacy.go | 15 - .../protobuf/runtime/protoiface/methods.go | 168 - .../protobuf/runtime/protoimpl/impl.go | 44 - .../protobuf/runtime/protoimpl/version.go | 60 - .../types/descriptorpb/descriptor.pb.go | 4605 -------- .../protobuf/types/known/anypb/any.pb.go | 495 - .../types/known/durationpb/duration.pb.go | 374 - .../types/known/timestamppb/timestamp.pb.go | 383 - vendor/modules.txt | 237 - 1345 files changed, 2 insertions(+), 490287 deletions(-) delete mode 100644 vendor/github.com/absmach/agent/LICENSE delete mode 100644 vendor/github.com/absmach/agent/pkg/agent/config.go delete mode 100644 vendor/github.com/absmach/agent/pkg/agent/heartbeat.go delete mode 100644 vendor/github.com/absmach/agent/pkg/agent/service.go delete mode 100644 vendor/github.com/absmach/agent/pkg/bootstrap/bootstrap.go delete mode 100644 vendor/github.com/absmach/agent/pkg/edgex/client.go delete mode 100644 vendor/github.com/absmach/agent/pkg/encoder/encoder.go delete mode 100644 vendor/github.com/absmach/agent/pkg/terminal/terminal.go delete mode 100644 vendor/github.com/absmach/magistrala/.dockerignore delete mode 100644 vendor/github.com/absmach/magistrala/.gitignore delete mode 100644 vendor/github.com/absmach/magistrala/.golangci.yml delete mode 100644 vendor/github.com/absmach/magistrala/ADOPTERS.md delete mode 100644 vendor/github.com/absmach/magistrala/CHANGELOG.md delete mode 100644 vendor/github.com/absmach/magistrala/CONTRIBUTING.md delete mode 100644 vendor/github.com/absmach/magistrala/LICENSE delete mode 100644 vendor/github.com/absmach/magistrala/MAINTAINERS delete mode 100644 vendor/github.com/absmach/magistrala/Makefile delete mode 100644 vendor/github.com/absmach/magistrala/README.md delete mode 100644 vendor/github.com/absmach/magistrala/api.go delete mode 100644 vendor/github.com/absmach/magistrala/auth.pb.go delete mode 100644 vendor/github.com/absmach/magistrala/auth.proto delete mode 100644 vendor/github.com/absmach/magistrala/auth_grpc.pb.go delete mode 100644 vendor/github.com/absmach/magistrala/bootstrap/README.md delete mode 100644 vendor/github.com/absmach/magistrala/bootstrap/configs.go delete mode 100644 vendor/github.com/absmach/magistrala/bootstrap/doc.go delete mode 100644 vendor/github.com/absmach/magistrala/bootstrap/reader.go delete mode 100644 vendor/github.com/absmach/magistrala/bootstrap/service.go delete mode 100644 vendor/github.com/absmach/magistrala/bootstrap/state.go delete mode 100644 vendor/github.com/absmach/magistrala/config.toml delete mode 100644 vendor/github.com/absmach/magistrala/doc.go delete mode 100644 vendor/github.com/absmach/magistrala/health.go delete mode 100644 vendor/github.com/absmach/magistrala/internal/apiutil/errors.go delete mode 100644 vendor/github.com/absmach/magistrala/internal/apiutil/responses.go delete mode 100644 vendor/github.com/absmach/magistrala/internal/apiutil/token.go delete mode 100644 vendor/github.com/absmach/magistrala/internal/apiutil/transport.go delete mode 100644 vendor/github.com/absmach/magistrala/logger/doc.go delete mode 100644 vendor/github.com/absmach/magistrala/logger/exit.go delete mode 100644 vendor/github.com/absmach/magistrala/logger/level.go delete mode 100644 vendor/github.com/absmach/magistrala/logger/logger.go delete mode 100644 vendor/github.com/absmach/magistrala/logger/mock.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/clients/clients.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/clients/doc.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/clients/errors.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/clients/page.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/clients/roles.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/clients/status.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/clients/types.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/errors/README.md delete mode 100644 vendor/github.com/absmach/magistrala/pkg/errors/doc.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/errors/errors.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/errors/sdk_errors.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/errors/types.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/messaging/README.md delete mode 100644 vendor/github.com/absmach/magistrala/pkg/messaging/message.pb.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/messaging/message.proto delete mode 100644 vendor/github.com/absmach/magistrala/pkg/messaging/pubsub.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/README.md delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/bootstrap.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/certs.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/channels.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/consumers.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/doc.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/groups.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/health.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/message.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/metadata.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/requests.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/responses.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/sdk.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/things.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/tokens.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/sdk/go/users.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/transformers/README.md delete mode 100644 vendor/github.com/absmach/magistrala/pkg/transformers/doc.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/transformers/senml/README.md delete mode 100644 vendor/github.com/absmach/magistrala/pkg/transformers/senml/doc.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/transformers/senml/message.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/transformers/senml/transformer.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/transformers/transformer.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/uuid/README.md delete mode 100644 vendor/github.com/absmach/magistrala/pkg/uuid/doc.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/uuid/mock.go delete mode 100644 vendor/github.com/absmach/magistrala/pkg/uuid/uuid.go delete mode 100644 vendor/github.com/absmach/magistrala/uuid.go delete mode 100644 vendor/github.com/beorn7/perks/LICENSE delete mode 100644 vendor/github.com/beorn7/perks/quantile/exampledata.txt delete mode 100644 vendor/github.com/beorn7/perks/quantile/stream.go delete mode 100644 vendor/github.com/caarlos0/env/v9/.gitignore delete mode 100644 vendor/github.com/caarlos0/env/v9/.golangci.yml delete mode 100644 vendor/github.com/caarlos0/env/v9/.goreleaser.yml delete mode 100644 vendor/github.com/caarlos0/env/v9/.mailmap delete mode 100644 vendor/github.com/caarlos0/env/v9/LICENSE.md delete mode 100644 vendor/github.com/caarlos0/env/v9/Makefile delete mode 100644 vendor/github.com/caarlos0/env/v9/README.md delete mode 100644 vendor/github.com/caarlos0/env/v9/env.go delete mode 100644 vendor/github.com/caarlos0/env/v9/env_tomap.go delete mode 100644 vendor/github.com/caarlos0/env/v9/env_tomap_windows.go delete mode 100644 vendor/github.com/caarlos0/env/v9/error.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/LICENSE.txt delete mode 100644 vendor/github.com/cespare/xxhash/v2/README.md delete mode 100644 vendor/github.com/cespare/xxhash/v2/testall.sh delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_asm.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_other.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_safe.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go delete mode 100644 vendor/github.com/creack/pty/.gitignore delete mode 100644 vendor/github.com/creack/pty/Dockerfile.golang delete mode 100644 vendor/github.com/creack/pty/Dockerfile.riscv delete mode 100644 vendor/github.com/creack/pty/LICENSE delete mode 100644 vendor/github.com/creack/pty/README.md delete mode 100644 vendor/github.com/creack/pty/asm_solaris_amd64.s delete mode 100644 vendor/github.com/creack/pty/doc.go delete mode 100644 vendor/github.com/creack/pty/ioctl.go delete mode 100644 vendor/github.com/creack/pty/ioctl_bsd.go delete mode 100644 vendor/github.com/creack/pty/ioctl_solaris.go delete mode 100644 vendor/github.com/creack/pty/ioctl_unsupported.go delete mode 100644 vendor/github.com/creack/pty/mktypes.bash delete mode 100644 vendor/github.com/creack/pty/pty_darwin.go delete mode 100644 vendor/github.com/creack/pty/pty_dragonfly.go delete mode 100644 vendor/github.com/creack/pty/pty_freebsd.go delete mode 100644 vendor/github.com/creack/pty/pty_linux.go delete mode 100644 vendor/github.com/creack/pty/pty_netbsd.go delete mode 100644 vendor/github.com/creack/pty/pty_openbsd.go delete mode 100644 vendor/github.com/creack/pty/pty_solaris.go delete mode 100644 vendor/github.com/creack/pty/pty_unsupported.go delete mode 100644 vendor/github.com/creack/pty/run.go delete mode 100644 vendor/github.com/creack/pty/start.go delete mode 100644 vendor/github.com/creack/pty/start_windows.go delete mode 100644 vendor/github.com/creack/pty/test_crosscompile.sh delete mode 100644 vendor/github.com/creack/pty/winsize.go delete mode 100644 vendor/github.com/creack/pty/winsize_unix.go delete mode 100644 vendor/github.com/creack/pty/winsize_unsupported.go delete mode 100644 vendor/github.com/creack/pty/ztypes_386.go delete mode 100644 vendor/github.com/creack/pty/ztypes_amd64.go delete mode 100644 vendor/github.com/creack/pty/ztypes_arm.go delete mode 100644 vendor/github.com/creack/pty/ztypes_arm64.go delete mode 100644 vendor/github.com/creack/pty/ztypes_dragonfly_amd64.go delete mode 100644 vendor/github.com/creack/pty/ztypes_freebsd_386.go delete mode 100644 vendor/github.com/creack/pty/ztypes_freebsd_amd64.go delete mode 100644 vendor/github.com/creack/pty/ztypes_freebsd_arm.go delete mode 100644 vendor/github.com/creack/pty/ztypes_freebsd_arm64.go delete mode 100644 vendor/github.com/creack/pty/ztypes_freebsd_ppc64.go delete mode 100644 vendor/github.com/creack/pty/ztypes_loong64.go delete mode 100644 vendor/github.com/creack/pty/ztypes_mipsx.go delete mode 100644 vendor/github.com/creack/pty/ztypes_netbsd_32bit_int.go delete mode 100644 vendor/github.com/creack/pty/ztypes_openbsd_32bit_int.go delete mode 100644 vendor/github.com/creack/pty/ztypes_ppc64.go delete mode 100644 vendor/github.com/creack/pty/ztypes_ppc64le.go delete mode 100644 vendor/github.com/creack/pty/ztypes_riscvx.go delete mode 100644 vendor/github.com/creack/pty/ztypes_s390x.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/.gitignore delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/LICENSE delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/NOTICE.md delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/README.md delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/backoff.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/client.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/components.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/epl-v20 delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/filestore.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/memstore.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/memstore_ordered.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/message.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/messageids.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/net.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/netconn.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/oops.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/options.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/ping.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/router.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/status.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/store.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/token.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/topic.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/trace.go delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/websocket.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/LICENSE delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/constants.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/context.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/doc.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces/url.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces/urlstream.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/request.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/types/errors.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/action.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/actiontype.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/addressable.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/adminstate.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/autoevent.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/callbackalert.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/category.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/channel.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/channel_type.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/command.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/commandresponse.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/constants.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/describedobject.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/device.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceprofile.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/devicereport.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceresource.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceservice.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/encryptiondetails.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/errors.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/event.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/filter.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/get.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/interval.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/interval_action.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/log_entry.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/notifications.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/operatingstate.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/profileproperty.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/profileresource.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/propertyvalue.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/provisionwatcher.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/put.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/reading.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/resourceoperation.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/response.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/severity.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/sma_operation.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/status.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/subscription.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/timestamps.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission_record.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission_status.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/units.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/validator.go delete mode 100644 vendor/github.com/edgexfoundry/go-mod-core-contracts/models/value-descriptor.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/.gitignore delete mode 100644 vendor/github.com/fxamacker/cbor/v2/.golangci.yml delete mode 100644 vendor/github.com/fxamacker/cbor/v2/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/fxamacker/cbor/v2/CONTRIBUTING.md delete mode 100644 vendor/github.com/fxamacker/cbor/v2/LICENSE delete mode 100644 vendor/github.com/fxamacker/cbor/v2/README.md delete mode 100644 vendor/github.com/fxamacker/cbor/v2/SECURITY.md delete mode 100644 vendor/github.com/fxamacker/cbor/v2/bytestring.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/cache.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/decode.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/diagnose.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/doc.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/encode.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/simplevalue.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/stream.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/structfields.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/tag.go delete mode 100644 vendor/github.com/fxamacker/cbor/v2/valid.go delete mode 100644 vendor/github.com/go-chi/chi/v5/.gitignore delete mode 100644 vendor/github.com/go-chi/chi/v5/CHANGELOG.md delete mode 100644 vendor/github.com/go-chi/chi/v5/CONTRIBUTING.md delete mode 100644 vendor/github.com/go-chi/chi/v5/LICENSE delete mode 100644 vendor/github.com/go-chi/chi/v5/Makefile delete mode 100644 vendor/github.com/go-chi/chi/v5/README.md delete mode 100644 vendor/github.com/go-chi/chi/v5/chain.go delete mode 100644 vendor/github.com/go-chi/chi/v5/chi.go delete mode 100644 vendor/github.com/go-chi/chi/v5/context.go delete mode 100644 vendor/github.com/go-chi/chi/v5/mux.go delete mode 100644 vendor/github.com/go-chi/chi/v5/tree.go delete mode 100644 vendor/github.com/go-kit/kit/LICENSE delete mode 100644 vendor/github.com/go-kit/kit/endpoint/doc.go delete mode 100644 vendor/github.com/go-kit/kit/endpoint/endpoint.go delete mode 100644 vendor/github.com/go-kit/kit/metrics/README.md delete mode 100644 vendor/github.com/go-kit/kit/metrics/doc.go delete mode 100644 vendor/github.com/go-kit/kit/metrics/internal/lv/labelvalues.go delete mode 100644 vendor/github.com/go-kit/kit/metrics/internal/lv/space.go delete mode 100644 vendor/github.com/go-kit/kit/metrics/metrics.go delete mode 100644 vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go delete mode 100644 vendor/github.com/go-kit/kit/metrics/timer.go delete mode 100644 vendor/github.com/go-kit/kit/transport/doc.go delete mode 100644 vendor/github.com/go-kit/kit/transport/error_handler.go delete mode 100644 vendor/github.com/go-kit/kit/transport/http/client.go delete mode 100644 vendor/github.com/go-kit/kit/transport/http/doc.go delete mode 100644 vendor/github.com/go-kit/kit/transport/http/encode_decode.go delete mode 100644 vendor/github.com/go-kit/kit/transport/http/intercepting_writer.go delete mode 100644 vendor/github.com/go-kit/kit/transport/http/request_response_funcs.go delete mode 100644 vendor/github.com/go-kit/kit/transport/http/server.go delete mode 100644 vendor/github.com/go-kit/log/.gitignore delete mode 100644 vendor/github.com/go-kit/log/LICENSE delete mode 100644 vendor/github.com/go-kit/log/README.md delete mode 100644 vendor/github.com/go-kit/log/doc.go delete mode 100644 vendor/github.com/go-kit/log/json_logger.go delete mode 100644 vendor/github.com/go-kit/log/log.go delete mode 100644 vendor/github.com/go-kit/log/logfmt_logger.go delete mode 100644 vendor/github.com/go-kit/log/nop_logger.go delete mode 100644 vendor/github.com/go-kit/log/staticcheck.conf delete mode 100644 vendor/github.com/go-kit/log/stdlib.go delete mode 100644 vendor/github.com/go-kit/log/sync.go delete mode 100644 vendor/github.com/go-kit/log/value.go delete mode 100644 vendor/github.com/go-logfmt/logfmt/.gitignore delete mode 100644 vendor/github.com/go-logfmt/logfmt/CHANGELOG.md delete mode 100644 vendor/github.com/go-logfmt/logfmt/LICENSE delete mode 100644 vendor/github.com/go-logfmt/logfmt/README.md delete mode 100644 vendor/github.com/go-logfmt/logfmt/decode.go delete mode 100644 vendor/github.com/go-logfmt/logfmt/doc.go delete mode 100644 vendor/github.com/go-logfmt/logfmt/encode.go delete mode 100644 vendor/github.com/go-logfmt/logfmt/jsonstring.go delete mode 100644 vendor/github.com/go-zoo/bone/.gitignore delete mode 100644 vendor/github.com/go-zoo/bone/.travis.yml delete mode 100644 vendor/github.com/go-zoo/bone/CHANGELOG.md delete mode 100644 vendor/github.com/go-zoo/bone/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/go-zoo/bone/CONTRIBUTING.md delete mode 100644 vendor/github.com/go-zoo/bone/LICENSE delete mode 100644 vendor/github.com/go-zoo/bone/README.md delete mode 100644 vendor/github.com/go-zoo/bone/bone.go delete mode 100644 vendor/github.com/go-zoo/bone/helper.go delete mode 100644 vendor/github.com/go-zoo/bone/helper_15.go delete mode 100644 vendor/github.com/go-zoo/bone/helper_17.go delete mode 100644 vendor/github.com/go-zoo/bone/mux.go delete mode 100644 vendor/github.com/go-zoo/bone/route.go delete mode 100644 vendor/github.com/go-zoo/bone/validator.go delete mode 100644 vendor/github.com/gofrs/uuid/.gitignore delete mode 100644 vendor/github.com/gofrs/uuid/LICENSE delete mode 100644 vendor/github.com/gofrs/uuid/README.md delete mode 100644 vendor/github.com/gofrs/uuid/codec.go delete mode 100644 vendor/github.com/gofrs/uuid/fuzz.go delete mode 100644 vendor/github.com/gofrs/uuid/generator.go delete mode 100644 vendor/github.com/gofrs/uuid/sql.go delete mode 100644 vendor/github.com/gofrs/uuid/uuid.go delete mode 100644 vendor/github.com/golang-jwt/jwt/.gitignore delete mode 100644 vendor/github.com/golang-jwt/jwt/LICENSE delete mode 100644 vendor/github.com/golang-jwt/jwt/MIGRATION_GUIDE.md delete mode 100644 vendor/github.com/golang-jwt/jwt/README.md delete mode 100644 vendor/github.com/golang-jwt/jwt/VERSION_HISTORY.md delete mode 100644 vendor/github.com/golang-jwt/jwt/claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/doc.go delete mode 100644 vendor/github.com/golang-jwt/jwt/ecdsa.go delete mode 100644 vendor/github.com/golang-jwt/jwt/ecdsa_utils.go delete mode 100644 vendor/github.com/golang-jwt/jwt/ed25519.go delete mode 100644 vendor/github.com/golang-jwt/jwt/ed25519_utils.go delete mode 100644 vendor/github.com/golang-jwt/jwt/errors.go delete mode 100644 vendor/github.com/golang-jwt/jwt/hmac.go delete mode 100644 vendor/github.com/golang-jwt/jwt/map_claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/none.go delete mode 100644 vendor/github.com/golang-jwt/jwt/parser.go delete mode 100644 vendor/github.com/golang-jwt/jwt/rsa.go delete mode 100644 vendor/github.com/golang-jwt/jwt/rsa_pss.go delete mode 100644 vendor/github.com/golang-jwt/jwt/rsa_utils.go delete mode 100644 vendor/github.com/golang-jwt/jwt/signing_method.go delete mode 100644 vendor/github.com/golang-jwt/jwt/token.go delete mode 100644 vendor/github.com/golang/protobuf/AUTHORS delete mode 100644 vendor/github.com/golang/protobuf/CONTRIBUTORS delete mode 100644 vendor/github.com/golang/protobuf/LICENSE delete mode 100644 vendor/github.com/golang/protobuf/jsonpb/decode.go delete mode 100644 vendor/github.com/golang/protobuf/jsonpb/encode.go delete mode 100644 vendor/github.com/golang/protobuf/jsonpb/json.go delete mode 100644 vendor/github.com/golang/protobuf/proto/buffer.go delete mode 100644 vendor/github.com/golang/protobuf/proto/defaults.go delete mode 100644 vendor/github.com/golang/protobuf/proto/deprecated.go delete mode 100644 vendor/github.com/golang/protobuf/proto/discard.go delete mode 100644 vendor/github.com/golang/protobuf/proto/extensions.go delete mode 100644 vendor/github.com/golang/protobuf/proto/properties.go delete mode 100644 vendor/github.com/golang/protobuf/proto/proto.go delete mode 100644 vendor/github.com/golang/protobuf/proto/registry.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_decode.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_encode.go delete mode 100644 vendor/github.com/golang/protobuf/proto/wire.go delete mode 100644 vendor/github.com/golang/protobuf/proto/wrappers.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any/any.pb.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/doc.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go delete mode 100644 vendor/github.com/google/uuid/CHANGELOG.md delete mode 100644 vendor/github.com/google/uuid/CONTRIBUTING.md delete mode 100644 vendor/github.com/google/uuid/CONTRIBUTORS delete mode 100644 vendor/github.com/google/uuid/LICENSE delete mode 100644 vendor/github.com/google/uuid/README.md delete mode 100644 vendor/github.com/google/uuid/dce.go delete mode 100644 vendor/github.com/google/uuid/doc.go delete mode 100644 vendor/github.com/google/uuid/hash.go delete mode 100644 vendor/github.com/google/uuid/marshal.go delete mode 100644 vendor/github.com/google/uuid/node.go delete mode 100644 vendor/github.com/google/uuid/node_js.go delete mode 100644 vendor/github.com/google/uuid/node_net.go delete mode 100644 vendor/github.com/google/uuid/null.go delete mode 100644 vendor/github.com/google/uuid/sql.go delete mode 100644 vendor/github.com/google/uuid/time.go delete mode 100644 vendor/github.com/google/uuid/util.go delete mode 100644 vendor/github.com/google/uuid/uuid.go delete mode 100644 vendor/github.com/google/uuid/version1.go delete mode 100644 vendor/github.com/google/uuid/version4.go delete mode 100644 vendor/github.com/gorilla/websocket/.gitignore delete mode 100644 vendor/github.com/gorilla/websocket/AUTHORS delete mode 100644 vendor/github.com/gorilla/websocket/LICENSE delete mode 100644 vendor/github.com/gorilla/websocket/README.md delete mode 100644 vendor/github.com/gorilla/websocket/client.go delete mode 100644 vendor/github.com/gorilla/websocket/compression.go delete mode 100644 vendor/github.com/gorilla/websocket/conn.go delete mode 100644 vendor/github.com/gorilla/websocket/doc.go delete mode 100644 vendor/github.com/gorilla/websocket/join.go delete mode 100644 vendor/github.com/gorilla/websocket/json.go delete mode 100644 vendor/github.com/gorilla/websocket/mask.go delete mode 100644 vendor/github.com/gorilla/websocket/mask_safe.go delete mode 100644 vendor/github.com/gorilla/websocket/prepared.go delete mode 100644 vendor/github.com/gorilla/websocket/proxy.go delete mode 100644 vendor/github.com/gorilla/websocket/server.go delete mode 100644 vendor/github.com/gorilla/websocket/tls_handshake.go delete mode 100644 vendor/github.com/gorilla/websocket/tls_handshake_116.go delete mode 100644 vendor/github.com/gorilla/websocket/util.go delete mode 100644 vendor/github.com/gorilla/websocket/x_net_proxy.go delete mode 100644 vendor/github.com/mainflux/export/pkg/config/config.go delete mode 100644 vendor/github.com/mainflux/mainflux/LICENSE delete mode 100644 vendor/github.com/mainflux/mainflux/pkg/errors/README.md delete mode 100644 vendor/github.com/mainflux/mainflux/pkg/errors/errors.go delete mode 100644 vendor/github.com/mainflux/mainflux/pkg/errors/types.go delete mode 100644 vendor/github.com/mainflux/senml/LICENSE delete mode 100644 vendor/github.com/mainflux/senml/README.md delete mode 100644 vendor/github.com/mainflux/senml/senml.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/v2/LICENSE delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/v2/NOTICE delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/.gitignore delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/Makefile delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/decode.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/doc.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/encode.go delete mode 100644 vendor/github.com/pelletier/go-toml/.dockerignore delete mode 100644 vendor/github.com/pelletier/go-toml/.gitignore delete mode 100644 vendor/github.com/pelletier/go-toml/CONTRIBUTING.md delete mode 100644 vendor/github.com/pelletier/go-toml/Dockerfile delete mode 100644 vendor/github.com/pelletier/go-toml/LICENSE delete mode 100644 vendor/github.com/pelletier/go-toml/Makefile delete mode 100644 vendor/github.com/pelletier/go-toml/PULL_REQUEST_TEMPLATE.md delete mode 100644 vendor/github.com/pelletier/go-toml/README.md delete mode 100644 vendor/github.com/pelletier/go-toml/SECURITY.md delete mode 100644 vendor/github.com/pelletier/go-toml/azure-pipelines.yml delete mode 100644 vendor/github.com/pelletier/go-toml/benchmark.sh delete mode 100644 vendor/github.com/pelletier/go-toml/doc.go delete mode 100644 vendor/github.com/pelletier/go-toml/example-crlf.toml delete mode 100644 vendor/github.com/pelletier/go-toml/example.toml delete mode 100644 vendor/github.com/pelletier/go-toml/fuzz.go delete mode 100644 vendor/github.com/pelletier/go-toml/fuzz.sh delete mode 100644 vendor/github.com/pelletier/go-toml/keysparsing.go delete mode 100644 vendor/github.com/pelletier/go-toml/lexer.go delete mode 100644 vendor/github.com/pelletier/go-toml/localtime.go delete mode 100644 vendor/github.com/pelletier/go-toml/marshal.go delete mode 100644 vendor/github.com/pelletier/go-toml/marshal_OrderPreserve_test.toml delete mode 100644 vendor/github.com/pelletier/go-toml/marshal_test.toml delete mode 100644 vendor/github.com/pelletier/go-toml/parser.go delete mode 100644 vendor/github.com/pelletier/go-toml/position.go delete mode 100644 vendor/github.com/pelletier/go-toml/token.go delete mode 100644 vendor/github.com/pelletier/go-toml/toml.go delete mode 100644 vendor/github.com/pelletier/go-toml/tomlpub.go delete mode 100644 vendor/github.com/pelletier/go-toml/tomltree_create.go delete mode 100644 vendor/github.com/pelletier/go-toml/tomltree_write.go delete mode 100644 vendor/github.com/pelletier/go-toml/tomltree_writepub.go delete mode 100644 vendor/github.com/prometheus/client_golang/LICENSE delete mode 100644 vendor/github.com/prometheus/client_golang/NOTICE delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/.gitignore delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/README.md delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/counter.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/desc.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/doc.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/fnv.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/gauge.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/get_pid.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector_go116.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/histogram.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/almost_equal.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/go_collector_options.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/metric.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/labels.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/metric.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/num_threads.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/observer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_js.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/registry.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/summary.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/timer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/untyped.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/value.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/vec.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/vnext.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/wrap.go delete mode 100644 vendor/github.com/prometheus/client_model/LICENSE delete mode 100644 vendor/github.com/prometheus/client_model/NOTICE delete mode 100644 vendor/github.com/prometheus/client_model/go/metrics.pb.go delete mode 100644 vendor/github.com/prometheus/common/LICENSE delete mode 100644 vendor/github.com/prometheus/common/NOTICE delete mode 100644 vendor/github.com/prometheus/common/expfmt/decode.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/encode.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/expfmt.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/openmetrics_create.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_create.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_parse.go delete mode 100644 vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt delete mode 100644 vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go delete mode 100644 vendor/github.com/prometheus/common/model/alert.go delete mode 100644 vendor/github.com/prometheus/common/model/fingerprinting.go delete mode 100644 vendor/github.com/prometheus/common/model/fnv.go delete mode 100644 vendor/github.com/prometheus/common/model/labels.go delete mode 100644 vendor/github.com/prometheus/common/model/labelset.go delete mode 100644 vendor/github.com/prometheus/common/model/metric.go delete mode 100644 vendor/github.com/prometheus/common/model/model.go delete mode 100644 vendor/github.com/prometheus/common/model/signature.go delete mode 100644 vendor/github.com/prometheus/common/model/silence.go delete mode 100644 vendor/github.com/prometheus/common/model/time.go delete mode 100644 vendor/github.com/prometheus/common/model/value.go delete mode 100644 vendor/github.com/prometheus/common/model/value_float.go delete mode 100644 vendor/github.com/prometheus/common/model/value_histogram.go delete mode 100644 vendor/github.com/prometheus/common/model/value_type.go delete mode 100644 vendor/github.com/prometheus/procfs/.gitignore delete mode 100644 vendor/github.com/prometheus/procfs/.golangci.yml delete mode 100644 vendor/github.com/prometheus/procfs/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/prometheus/procfs/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/procfs/LICENSE delete mode 100644 vendor/github.com/prometheus/procfs/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/procfs/Makefile delete mode 100644 vendor/github.com/prometheus/procfs/Makefile.common delete mode 100644 vendor/github.com/prometheus/procfs/NOTICE delete mode 100644 vendor/github.com/prometheus/procfs/README.md delete mode 100644 vendor/github.com/prometheus/procfs/SECURITY.md delete mode 100644 vendor/github.com/prometheus/procfs/arp.go delete mode 100644 vendor/github.com/prometheus/procfs/buddyinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/cmdline.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_armx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_loong64.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_others.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_s390x.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_x86.go delete mode 100644 vendor/github.com/prometheus/procfs/crypto.go delete mode 100644 vendor/github.com/prometheus/procfs/doc.go delete mode 100644 vendor/github.com/prometheus/procfs/fs.go delete mode 100644 vendor/github.com/prometheus/procfs/fs_statfs_notype.go delete mode 100644 vendor/github.com/prometheus/procfs/fs_statfs_type.go delete mode 100644 vendor/github.com/prometheus/procfs/fscache.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/fs/fs.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/parse.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/readfile.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/valueparser.go delete mode 100644 vendor/github.com/prometheus/procfs/ipvs.go delete mode 100644 vendor/github.com/prometheus/procfs/kernel_random.go delete mode 100644 vendor/github.com/prometheus/procfs/loadavg.go delete mode 100644 vendor/github.com/prometheus/procfs/mdstat.go delete mode 100644 vendor/github.com/prometheus/procfs/meminfo.go delete mode 100644 vendor/github.com/prometheus/procfs/mountinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/mountstats.go delete mode 100644 vendor/github.com/prometheus/procfs/net_conntrackstat.go delete mode 100644 vendor/github.com/prometheus/procfs/net_dev.go delete mode 100644 vendor/github.com/prometheus/procfs/net_ip_socket.go delete mode 100644 vendor/github.com/prometheus/procfs/net_protocols.go delete mode 100644 vendor/github.com/prometheus/procfs/net_route.go delete mode 100644 vendor/github.com/prometheus/procfs/net_sockstat.go delete mode 100644 vendor/github.com/prometheus/procfs/net_softnet.go delete mode 100644 vendor/github.com/prometheus/procfs/net_tcp.go delete mode 100644 vendor/github.com/prometheus/procfs/net_udp.go delete mode 100644 vendor/github.com/prometheus/procfs/net_unix.go delete mode 100644 vendor/github.com/prometheus/procfs/net_wireless.go delete mode 100644 vendor/github.com/prometheus/procfs/net_xfrm.go delete mode 100644 vendor/github.com/prometheus/procfs/netstat.go delete mode 100644 vendor/github.com/prometheus/procfs/proc.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_cgroup.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_cgroups.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_environ.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_fdinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_interrupts.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_io.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_limits.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_maps.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_netstat.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_ns.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_psi.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_smaps.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_snmp.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_snmp6.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_stat.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_status.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_sys.go delete mode 100644 vendor/github.com/prometheus/procfs/schedstat.go delete mode 100644 vendor/github.com/prometheus/procfs/slab.go delete mode 100644 vendor/github.com/prometheus/procfs/softirqs.go delete mode 100644 vendor/github.com/prometheus/procfs/stat.go delete mode 100644 vendor/github.com/prometheus/procfs/swaps.go delete mode 100644 vendor/github.com/prometheus/procfs/thread.go delete mode 100644 vendor/github.com/prometheus/procfs/ttar delete mode 100644 vendor/github.com/prometheus/procfs/vm.go delete mode 100644 vendor/github.com/prometheus/procfs/zoneinfo.go delete mode 100644 vendor/github.com/x448/float16/.travis.yml delete mode 100644 vendor/github.com/x448/float16/LICENSE delete mode 100644 vendor/github.com/x448/float16/README.md delete mode 100644 vendor/github.com/x448/float16/float16.go delete mode 100644 vendor/golang.org/x/exp/LICENSE delete mode 100644 vendor/golang.org/x/exp/PATENTS delete mode 100644 vendor/golang.org/x/exp/constraints/constraints.go delete mode 100644 vendor/golang.org/x/exp/slices/cmp.go delete mode 100644 vendor/golang.org/x/exp/slices/slices.go delete mode 100644 vendor/golang.org/x/exp/slices/sort.go delete mode 100644 vendor/golang.org/x/exp/slices/zsortanyfunc.go delete mode 100644 vendor/golang.org/x/exp/slices/zsortordered.go delete mode 100644 vendor/golang.org/x/net/LICENSE delete mode 100644 vendor/golang.org/x/net/PATENTS delete mode 100644 vendor/golang.org/x/net/http/httpguts/guts.go delete mode 100644 vendor/golang.org/x/net/http/httpguts/httplex.go delete mode 100644 vendor/golang.org/x/net/http2/.gitignore delete mode 100644 vendor/golang.org/x/net/http2/ascii.go delete mode 100644 vendor/golang.org/x/net/http2/ciphers.go delete mode 100644 vendor/golang.org/x/net/http2/client_conn_pool.go delete mode 100644 vendor/golang.org/x/net/http2/databuffer.go delete mode 100644 vendor/golang.org/x/net/http2/errors.go delete mode 100644 vendor/golang.org/x/net/http2/flow.go delete mode 100644 vendor/golang.org/x/net/http2/frame.go delete mode 100644 vendor/golang.org/x/net/http2/go111.go delete mode 100644 vendor/golang.org/x/net/http2/go115.go delete mode 100644 vendor/golang.org/x/net/http2/go118.go delete mode 100644 vendor/golang.org/x/net/http2/gotrack.go delete mode 100644 vendor/golang.org/x/net/http2/headermap.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/encode.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/hpack.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/huffman.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/static_table.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/tables.go delete mode 100644 vendor/golang.org/x/net/http2/http2.go delete mode 100644 vendor/golang.org/x/net/http2/not_go111.go delete mode 100644 vendor/golang.org/x/net/http2/not_go115.go delete mode 100644 vendor/golang.org/x/net/http2/not_go118.go delete mode 100644 vendor/golang.org/x/net/http2/pipe.go delete mode 100644 vendor/golang.org/x/net/http2/server.go delete mode 100644 vendor/golang.org/x/net/http2/transport.go delete mode 100644 vendor/golang.org/x/net/http2/write.go delete mode 100644 vendor/golang.org/x/net/http2/writesched.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_priority.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_random.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_roundrobin.go delete mode 100644 vendor/golang.org/x/net/idna/go118.go delete mode 100644 vendor/golang.org/x/net/idna/idna10.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/idna9.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/pre_go118.go delete mode 100644 vendor/golang.org/x/net/idna/punycode.go delete mode 100644 vendor/golang.org/x/net/idna/tables10.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables11.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables12.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables13.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables15.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables9.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/trie.go delete mode 100644 vendor/golang.org/x/net/idna/trie12.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/trie13.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/trieval.go delete mode 100644 vendor/golang.org/x/net/internal/socks/client.go delete mode 100644 vendor/golang.org/x/net/internal/socks/socks.go delete mode 100644 vendor/golang.org/x/net/internal/timeseries/timeseries.go delete mode 100644 vendor/golang.org/x/net/proxy/dial.go delete mode 100644 vendor/golang.org/x/net/proxy/direct.go delete mode 100644 vendor/golang.org/x/net/proxy/per_host.go delete mode 100644 vendor/golang.org/x/net/proxy/proxy.go delete mode 100644 vendor/golang.org/x/net/proxy/socks5.go delete mode 100644 vendor/golang.org/x/net/trace/events.go delete mode 100644 vendor/golang.org/x/net/trace/histogram.go delete mode 100644 vendor/golang.org/x/net/trace/trace.go delete mode 100644 vendor/golang.org/x/sync/LICENSE delete mode 100644 vendor/golang.org/x/sync/PATENTS delete mode 100644 vendor/golang.org/x/sync/errgroup/errgroup.go delete mode 100644 vendor/golang.org/x/sync/errgroup/go120.go delete mode 100644 vendor/golang.org/x/sync/errgroup/pre_go120.go delete mode 100644 vendor/golang.org/x/sync/semaphore/semaphore.go delete mode 100644 vendor/golang.org/x/sys/LICENSE delete mode 100644 vendor/golang.org/x/sys/PATENTS delete mode 100644 vendor/golang.org/x/sys/unix/.gitignore delete mode 100644 vendor/golang.org/x/sys/unix/README.md delete mode 100644 vendor/golang.org/x/sys/unix/affinity_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/aliases.go delete mode 100644 vendor/golang.org/x/sys/unix/asm_aix_ppc64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_riscv64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_loong64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mips64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mipsx.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_riscv64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_solaris_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_zos_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/bluetooth_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/cap_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/constants.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/dirent.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_big.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_little.go delete mode 100644 vendor/golang.org/x/sys/unix/env_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/epoll_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go delete mode 100644 vendor/golang.org/x/sys/unix/fdset.go delete mode 100644 vendor/golang.org/x/sys/unix/fstatfs_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_c.c delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ifreq_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_signed.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_unsigned.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/mkall.sh delete mode 100644 vendor/golang.org/x/sys/unix/mkerrors.sh delete mode 100644 vendor/golang.org/x/sys/unix/mmap_nomremap.go delete mode 100644 vendor/golang.org/x/sys/unix/mremap.go delete mode 100644 vendor/golang.org/x/sys/unix/pagesize_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/pledge_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/ptrace_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/ptrace_ios.go delete mode 100644 vendor/golang.org/x/sys/unix/race.go delete mode 100644 vendor/golang.org/x/sys/unix/race0.go delete mode 100644 vendor/golang.org/x/sys/unix/readdirent_getdents.go delete mode 100644 vendor/golang.org/x/sys/unix/readdirent_getdirentries.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_hurd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_hurd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_illumos.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_alarm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_libc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/sysvshm_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/sysvshm_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/sysvshm_unix_other.go delete mode 100644 vendor/golang.org/x/sys/unix/timestruct.go delete mode 100644 vendor/golang.org/x/sys/unix/unveil_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/xattr_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_armnn_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_mipsnn_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_mipsnnle_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_x86_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/windows/aliases.go delete mode 100644 vendor/golang.org/x/sys/windows/dll_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/empty.s delete mode 100644 vendor/golang.org/x/sys/windows/env_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/eventlog.go delete mode 100644 vendor/golang.org/x/sys/windows/exec_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/memory_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/mkerrors.bash delete mode 100644 vendor/golang.org/x/sys/windows/mkknownfolderids.bash delete mode 100644 vendor/golang.org/x/sys/windows/mksyscall.go delete mode 100644 vendor/golang.org/x/sys/windows/race.go delete mode 100644 vendor/golang.org/x/sys/windows/race0.go delete mode 100644 vendor/golang.org/x/sys/windows/security_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/service.go delete mode 100644 vendor/golang.org/x/sys/windows/setupapi_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/str.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_386.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_amd64.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_arm.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_arm64.go delete mode 100644 vendor/golang.org/x/sys/windows/zerrors_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/zknownfolderids_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/zsyscall_windows.go delete mode 100644 vendor/golang.org/x/text/LICENSE delete mode 100644 vendor/golang.org/x/text/PATENTS delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go delete mode 100644 vendor/golang.org/x/text/transform/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bidi.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bracket.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/core.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/prop.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables13.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables15.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/trieval.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/composition.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/input.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/iter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/normalize.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables11.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables12.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables13.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables15.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/trie.go delete mode 100644 vendor/google.golang.org/genproto/googleapis/rpc/LICENSE delete mode 100644 vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go delete mode 100644 vendor/google.golang.org/grpc/AUTHORS delete mode 100644 vendor/google.golang.org/grpc/CODE-OF-CONDUCT.md delete mode 100644 vendor/google.golang.org/grpc/CONTRIBUTING.md delete mode 100644 vendor/google.golang.org/grpc/GOVERNANCE.md delete mode 100644 vendor/google.golang.org/grpc/LICENSE delete mode 100644 vendor/google.golang.org/grpc/MAINTAINERS.md delete mode 100644 vendor/google.golang.org/grpc/Makefile delete mode 100644 vendor/google.golang.org/grpc/NOTICE.txt delete mode 100644 vendor/google.golang.org/grpc/README.md delete mode 100644 vendor/google.golang.org/grpc/SECURITY.md delete mode 100644 vendor/google.golang.org/grpc/attributes/attributes.go delete mode 100644 vendor/google.golang.org/grpc/backoff.go delete mode 100644 vendor/google.golang.org/grpc/backoff/backoff.go delete mode 100644 vendor/google.golang.org/grpc/balancer/balancer.go delete mode 100644 vendor/google.golang.org/grpc/balancer/base/balancer.go delete mode 100644 vendor/google.golang.org/grpc/balancer/base/base.go delete mode 100644 vendor/google.golang.org/grpc/balancer/conn_state_evaluator.go delete mode 100644 vendor/google.golang.org/grpc/balancer/grpclb/state/state.go delete mode 100644 vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go delete mode 100644 vendor/google.golang.org/grpc/balancer_conn_wrappers.go delete mode 100644 vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go delete mode 100644 vendor/google.golang.org/grpc/call.go delete mode 100644 vendor/google.golang.org/grpc/channelz/channelz.go delete mode 100644 vendor/google.golang.org/grpc/clientconn.go delete mode 100644 vendor/google.golang.org/grpc/codec.go delete mode 100644 vendor/google.golang.org/grpc/codegen.sh delete mode 100644 vendor/google.golang.org/grpc/codes/code_string.go delete mode 100644 vendor/google.golang.org/grpc/codes/codes.go delete mode 100644 vendor/google.golang.org/grpc/connectivity/connectivity.go delete mode 100644 vendor/google.golang.org/grpc/credentials/credentials.go delete mode 100644 vendor/google.golang.org/grpc/credentials/insecure/insecure.go delete mode 100644 vendor/google.golang.org/grpc/credentials/tls.go delete mode 100644 vendor/google.golang.org/grpc/dialoptions.go delete mode 100644 vendor/google.golang.org/grpc/doc.go delete mode 100644 vendor/google.golang.org/grpc/encoding/encoding.go delete mode 100644 vendor/google.golang.org/grpc/encoding/proto/proto.go delete mode 100644 vendor/google.golang.org/grpc/grpclog/component.go delete mode 100644 vendor/google.golang.org/grpc/grpclog/grpclog.go delete mode 100644 vendor/google.golang.org/grpc/grpclog/logger.go delete mode 100644 vendor/google.golang.org/grpc/grpclog/loggerv2.go delete mode 100644 vendor/google.golang.org/grpc/interceptor.go delete mode 100644 vendor/google.golang.org/grpc/internal/backoff/backoff.go delete mode 100644 vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go delete mode 100644 vendor/google.golang.org/grpc/internal/balancerload/load.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/binarylog.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/binarylog_testutil.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/env_config.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/method_logger.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/sink.go delete mode 100644 vendor/google.golang.org/grpc/internal/buffer/unbounded.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/funcs.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/id.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/logging.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/types.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/types_linux.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/types_nonlinux.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/util_linux.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/util_nonlinux.go delete mode 100644 vendor/google.golang.org/grpc/internal/credentials/credentials.go delete mode 100644 vendor/google.golang.org/grpc/internal/credentials/spiffe.go delete mode 100644 vendor/google.golang.org/grpc/internal/credentials/syscallconn.go delete mode 100644 vendor/google.golang.org/grpc/internal/credentials/util.go delete mode 100644 vendor/google.golang.org/grpc/internal/envconfig/envconfig.go delete mode 100644 vendor/google.golang.org/grpc/internal/envconfig/observability.go delete mode 100644 vendor/google.golang.org/grpc/internal/envconfig/xds.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpclog/grpclog.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpclog/prefixLogger.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcsync/event.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcsync/oncefunc.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcsync/pubsub.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/compressor.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/grpcutil.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/metadata.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/method.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/regex.go delete mode 100644 vendor/google.golang.org/grpc/internal/idle/idle.go delete mode 100644 vendor/google.golang.org/grpc/internal/internal.go delete mode 100644 vendor/google.golang.org/grpc/internal/metadata/metadata.go delete mode 100644 vendor/google.golang.org/grpc/internal/pretty/pretty.go delete mode 100644 vendor/google.golang.org/grpc/internal/resolver/config_selector.go delete mode 100644 vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go delete mode 100644 vendor/google.golang.org/grpc/internal/resolver/passthrough/passthrough.go delete mode 100644 vendor/google.golang.org/grpc/internal/resolver/unix/unix.go delete mode 100644 vendor/google.golang.org/grpc/internal/serviceconfig/duration.go delete mode 100644 vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go delete mode 100644 vendor/google.golang.org/grpc/internal/status/status.go delete mode 100644 vendor/google.golang.org/grpc/internal/syscall/syscall_linux.go delete mode 100644 vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/bdp_estimator.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/controlbuf.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/defaults.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/flowcontrol.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/handler_server.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/http2_client.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/http2_server.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/http_util.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/logging.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/networktype/networktype.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/proxy.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/transport.go delete mode 100644 vendor/google.golang.org/grpc/internal/xds_handshake_cluster.go delete mode 100644 vendor/google.golang.org/grpc/keepalive/keepalive.go delete mode 100644 vendor/google.golang.org/grpc/metadata/metadata.go delete mode 100644 vendor/google.golang.org/grpc/peer/peer.go delete mode 100644 vendor/google.golang.org/grpc/picker_wrapper.go delete mode 100644 vendor/google.golang.org/grpc/pickfirst.go delete mode 100644 vendor/google.golang.org/grpc/preloader.go delete mode 100644 vendor/google.golang.org/grpc/regenerate.sh delete mode 100644 vendor/google.golang.org/grpc/resolver/map.go delete mode 100644 vendor/google.golang.org/grpc/resolver/resolver.go delete mode 100644 vendor/google.golang.org/grpc/resolver_conn_wrapper.go delete mode 100644 vendor/google.golang.org/grpc/rpc_util.go delete mode 100644 vendor/google.golang.org/grpc/server.go delete mode 100644 vendor/google.golang.org/grpc/service_config.go delete mode 100644 vendor/google.golang.org/grpc/serviceconfig/serviceconfig.go delete mode 100644 vendor/google.golang.org/grpc/shared_buffer_pool.go delete mode 100644 vendor/google.golang.org/grpc/stats/handlers.go delete mode 100644 vendor/google.golang.org/grpc/stats/stats.go delete mode 100644 vendor/google.golang.org/grpc/status/status.go delete mode 100644 vendor/google.golang.org/grpc/stream.go delete mode 100644 vendor/google.golang.org/grpc/tap/tap.go delete mode 100644 vendor/google.golang.org/grpc/trace.go delete mode 100644 vendor/google.golang.org/grpc/version.go delete mode 100644 vendor/google.golang.org/grpc/vet.sh delete mode 100644 vendor/google.golang.org/protobuf/LICENSE delete mode 100644 vendor/google.golang.org/protobuf/PATENTS delete mode 100644 vendor/google.golang.org/protobuf/encoding/protojson/decode.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/protojson/doc.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/protojson/encode.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/protojson/well_known_types.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/prototext/decode.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/prototext/doc.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/prototext/encode.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/protowire/wire.go delete mode 100644 vendor/google.golang.org/protobuf/internal/descfmt/stringer.go delete mode 100644 vendor/google.golang.org/protobuf/internal/descopts/options.go delete mode 100644 vendor/google.golang.org/protobuf/internal/detrand/rand.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/defval/default.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/decode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/decode_number.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/decode_string.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/decode_token.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/encode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/messageset/messageset.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode_number.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode_string.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode_token.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/doc.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/encode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/errors/errors.go delete mode 100644 vendor/google.golang.org/protobuf/internal/errors/is_go112.go delete mode 100644 vendor/google.golang.org/protobuf/internal/errors/is_go113.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/build.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_list.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/placeholder.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filetype/build.go delete mode 100644 vendor/google.golang.org/protobuf/internal/flags/flags.go delete mode 100644 vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go delete mode 100644 vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/any_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/api_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/doc.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/duration_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/empty_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/field_mask_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/goname.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/map_entry.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/struct_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/type_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/wrappers.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/api_export.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/checkinit.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_extension.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_field.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_map.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_message.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_messageset.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_tables.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/convert.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/convert_list.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/convert_map.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/decode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/encode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/enum.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/extension.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_export.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_extension.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_file.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_message.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/merge.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/merge_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message_reflect_field.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/pointer_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/validate.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/weak.go delete mode 100644 vendor/google.golang.org/protobuf/internal/order/order.go delete mode 100644 vendor/google.golang.org/protobuf/internal/order/range.go delete mode 100644 vendor/google.golang.org/protobuf/internal/pragma/pragma.go delete mode 100644 vendor/google.golang.org/protobuf/internal/set/ints.go delete mode 100644 vendor/google.golang.org/protobuf/internal/strs/strings.go delete mode 100644 vendor/google.golang.org/protobuf/internal/strs/strings_pure.go delete mode 100644 vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/internal/version/version.go delete mode 100644 vendor/google.golang.org/protobuf/proto/checkinit.go delete mode 100644 vendor/google.golang.org/protobuf/proto/decode.go delete mode 100644 vendor/google.golang.org/protobuf/proto/decode_gen.go delete mode 100644 vendor/google.golang.org/protobuf/proto/doc.go delete mode 100644 vendor/google.golang.org/protobuf/proto/encode.go delete mode 100644 vendor/google.golang.org/protobuf/proto/encode_gen.go delete mode 100644 vendor/google.golang.org/protobuf/proto/equal.go delete mode 100644 vendor/google.golang.org/protobuf/proto/extension.go delete mode 100644 vendor/google.golang.org/protobuf/proto/merge.go delete mode 100644 vendor/google.golang.org/protobuf/proto/messageset.go delete mode 100644 vendor/google.golang.org/protobuf/proto/proto.go delete mode 100644 vendor/google.golang.org/protobuf/proto/proto_methods.go delete mode 100644 vendor/google.golang.org/protobuf/proto/proto_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/proto/reset.go delete mode 100644 vendor/google.golang.org/protobuf/proto/size.go delete mode 100644 vendor/google.golang.org/protobuf/proto/size_gen.go delete mode 100644 vendor/google.golang.org/protobuf/proto/wrappers.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protodesc/desc.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protodesc/desc_init.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protodesc/desc_resolve.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protodesc/desc_validate.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protodesc/proto.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/proto.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/source.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/source_gen.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/type.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_equal.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoregistry/registry.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoiface/legacy.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoiface/methods.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoimpl/impl.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoimpl/version.go delete mode 100644 vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go delete mode 100644 vendor/google.golang.org/protobuf/types/known/anypb/any.pb.go delete mode 100644 vendor/google.golang.org/protobuf/types/known/durationpb/duration.pb.go delete mode 100644 vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go delete mode 100644 vendor/modules.txt diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 07524f82..577f7f22 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -49,4 +49,4 @@ jobs: run: go build -v ./... - name: Run tests - run: go test -mod=vendor -v --race -covermode=atomic -coverprofile cover.out ./... + run: go test -v --race -covermode=atomic -coverprofile cover.out ./... diff --git a/Makefile b/Makefile index d3592104..95df89d4 100644 --- a/Makefile +++ b/Makefile @@ -57,7 +57,7 @@ install: cp ${BUILD_DIR}/* $(GOBIN) test: - GOCACHE=off go test -mod=vendor -v -race -count 1 -tags test $(shell go list ./... | grep -v 'vendor\|cmd') + go test -v -race -count 1 -tags test $(shell go list ./... | grep -v 'vendor\|cmd') lint: golangci-lint run --no-config --disable-all --enable gosimple --enable errcheck --enable govet --enable unused --enable goconst --enable godot --timeout 3m diff --git a/vendor/github.com/absmach/agent/LICENSE b/vendor/github.com/absmach/agent/LICENSE deleted file mode 100644 index 478338e5..00000000 --- a/vendor/github.com/absmach/agent/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015-2019 Mainflux - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/absmach/agent/pkg/agent/config.go b/vendor/github.com/absmach/agent/pkg/agent/config.go deleted file mode 100644 index 5066c7f8..00000000 --- a/vendor/github.com/absmach/agent/pkg/agent/config.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) Abstract Machines -// SPDX-License-Identifier: Apache-2.0 - -package agent - -import ( - "crypto/tls" - "encoding/json" - "fmt" - "os" - "time" - - "github.com/absmach/magistrala/pkg/errors" - "github.com/pelletier/go-toml" -) - -type ServerConfig struct { - Port string `toml:"port" json:"port"` - BrokerURL string `toml:"broker_url" json:"broker_url"` -} - -type ChanConfig struct { - Control string `toml:"control"` - Data string `toml:"data"` -} - -type EdgexConfig struct { - URL string `toml:"url"` -} - -type LogConfig struct { - Level string `toml:"level"` -} - -type MQTTConfig struct { - URL string `json:"url" toml:"url"` - Username string `json:"username" toml:"username" mapstructure:"username"` - Password string `json:"password" toml:"password" mapstructure:"password"` - MTLS bool `json:"mtls" toml:"mtls" mapstructure:"mtls"` - SkipTLSVer bool `json:"skip_tls_ver" toml:"skip_tls_ver" mapstructure:"skip_tls_ver"` - Retain bool `json:"retain" toml:"retain" mapstructure:"retain"` - QoS byte `json:"qos" toml:"qos" mapstructure:"qos"` - CAPath string `json:"ca_path" toml:"ca_path" mapstructure:"ca_path"` - CertPath string `json:"cert_path" toml:"cert_path" mapstructure:"cert_path"` - PrivKeyPath string `json:"priv_key_path" toml:"priv_key_path" mapstructure:"priv_key_path"` - CA []byte `json:"-" toml:"-"` - Cert tls.Certificate `json:"-" toml:"-"` - ClientCert string `json:"client_cert" toml:"client_cert"` - ClientKey string `json:"client_key" toml:"client_key"` - CaCert string `json:"ca_cert" toml:"ca_cert"` -} - -type HeartbeatConfig struct { - Interval time.Duration `toml:"interval"` -} - -type TerminalConfig struct { - SessionTimeout time.Duration `toml:"session_timeout" json:"session_timeout"` -} - -type Config struct { - Server ServerConfig `toml:"server" json:"server"` - Terminal TerminalConfig `toml:"terminal" json:"terminal"` - Heartbeat HeartbeatConfig `toml:"heartbeat" json:"heartbeat"` - Channels ChanConfig `toml:"channels" json:"channels"` - Edgex EdgexConfig `toml:"edgex" json:"edgex"` - Log LogConfig `toml:"log" json:"log"` - MQTT MQTTConfig `toml:"mqtt" json:"mqtt"` - File string -} - -func NewConfig(sc ServerConfig, cc ChanConfig, ec EdgexConfig, lc LogConfig, mc MQTTConfig, hc HeartbeatConfig, tc TerminalConfig, file string) Config { - return Config{ - Server: sc, - Channels: cc, - Edgex: ec, - Log: lc, - MQTT: mc, - Heartbeat: hc, - Terminal: tc, - File: file, - } -} - -// Save - store config in a file. -func SaveConfig(c Config) error { - b, err := toml.Marshal(c) - if err != nil { - return errors.New(fmt.Sprintf("Error reading config file: %s", err)) - } - if err := os.WriteFile(c.File, b, 0644); err != nil { - return errors.New(fmt.Sprintf("Error writing toml: %s", err)) - } - return nil -} - -// Read - retrieve config from a file. -func ReadConfig(file string) (Config, error) { - data, err := os.ReadFile(file) - c := Config{} - if err != nil { - return c, errors.New(fmt.Sprintf("Error reading config file: %s", err)) - } - - if err := toml.Unmarshal(data, &c); err != nil { - return Config{}, errors.New(fmt.Sprintf("Error unmarshaling toml: %s", err)) - } - return c, nil -} - -// UnmarshalJSON parses the duration from JSON. -func (d *HeartbeatConfig) UnmarshalJSON(b []byte) error { - var v map[string]interface{} - if err := json.Unmarshal(b, &v); err != nil { - return err - } - interval, ok := v["interval"] - if !ok { - return errors.New("missing value") - } - switch value := interval.(type) { - case float64: - d.Interval = time.Duration(value) - return nil - case string: - var err error - d.Interval, err = time.ParseDuration(value) - if err != nil { - return err - } - return nil - default: - return errors.New("invalid duration") - } -} - -// UnmarshalJSON parses the duration from JSON. -func (d *TerminalConfig) UnmarshalJSON(b []byte) error { - var v map[string]interface{} - if err := json.Unmarshal(b, &v); err != nil { - return err - } - session_timeout, ok := v["session_timeout"] - if !ok { - return errors.New("missing value") - } - switch value := session_timeout.(type) { - case float64: - d.SessionTimeout = time.Duration(value) - return nil - case string: - var err error - d.SessionTimeout, err = time.ParseDuration(value) - if err != nil { - return err - } - return nil - default: - return errors.New("invalid duration") - } -} diff --git a/vendor/github.com/absmach/agent/pkg/agent/heartbeat.go b/vendor/github.com/absmach/agent/pkg/agent/heartbeat.go deleted file mode 100644 index 5eae5472..00000000 --- a/vendor/github.com/absmach/agent/pkg/agent/heartbeat.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Abstract Machines -// SPDX-License-Identifier: Apache-2.0 - -package agent - -import ( - "sync" - "time" -) - -const ( - online = "online" - offline = "offline" -) - -// svc keeps info on service live status. -// Services send heartbeat to nats thus updating last seen. -// When service doesnt send heartbeat for some time gets marked offline. -type svc struct { - info Info - interval time.Duration - ticker *time.Ticker - mu sync.Mutex -} - -type Info struct { - Name string `json:"name"` - LastSeen time.Time `json:"last_seen"` - Status string `json:"status"` - Type string `json:"type"` - Terminal int `json:"terminal"` -} - -// Heartbeat specifies api for updating status and keeping track on services -// that are sending heartbeat to NATS. -type Heartbeat interface { - Update() - Info() Info -} - -// interval - duration of interval -// if service doesnt send heartbeat during interval it is marked offline. -func NewHeartbeat(name, svcType string, interval time.Duration) Heartbeat { - ticker := time.NewTicker(interval) - s := svc{ - info: Info{ - Name: name, - Status: online, - Type: svcType, - LastSeen: time.Now(), - }, - ticker: ticker, - interval: interval, - } - s.listen() - return &s -} - -func (s *svc) listen() { - go func() { - for range s.ticker.C { - // TODO - we can disable ticker when the status gets OFFLINE - // and on the next heartbeat enable it again. - s.mu.Lock() - if time.Now().After(s.info.LastSeen.Add(s.interval)) { - s.info.Status = offline - } - s.mu.Unlock() - } - }() -} - -func (s *svc) Update() { - s.mu.Lock() - defer s.mu.Unlock() - s.info.LastSeen = time.Now() - s.info.Status = online -} - -func (s *svc) Info() Info { - return s.info -} diff --git a/vendor/github.com/absmach/agent/pkg/agent/service.go b/vendor/github.com/absmach/agent/pkg/agent/service.go deleted file mode 100644 index 4751e33a..00000000 --- a/vendor/github.com/absmach/agent/pkg/agent/service.go +++ /dev/null @@ -1,430 +0,0 @@ -// Copyright (c) Abstract Machines -// SPDX-License-Identifier: Apache-2.0 - -package agent - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "os/exec" - "sort" - "strings" - "time" - - "github.com/absmach/agent/pkg/edgex" - "github.com/absmach/agent/pkg/encoder" - "github.com/absmach/agent/pkg/terminal" - paho "github.com/eclipse/paho.mqtt.golang" - - log "github.com/absmach/magistrala/logger" - "github.com/absmach/magistrala/pkg/errors" - "github.com/absmach/magistrala/pkg/messaging" - exp "github.com/mainflux/export/pkg/config" -) - -const ( - Path = "./config.toml" - Hearbeat = "channels.heartbeat.>" - Commands = "commands" - config = "config" - - view = "view" - save = "save" - - char = "c" - open = "open" - close = "close" - control = "control" - data = "data" - - export = "export" - - pubSubID = "agent" -) - -var ( - // errInvalidCommand indicates malformed command. - errInvalidCommand = errors.New("invalid command") - - // ErrMalformedEntity indicates malformed entity specification. - ErrMalformedEntity = errors.New("malformed entity specification") - - // ErrInvalidQueryParams indicates malformed URL. - ErrInvalidQueryParams = errors.New("invalid query params") - - // errUnknownCommand indicates that command is not found. - errUnknownCommand = errors.New("Unknown command") - - // errNatsSubscribing indicates problem with sub to topic for heartbeat. - errNatsSubscribing = errors.New("failed to subscribe to heartbeat topic") - - // errNoSuchService indicates service not supported. - errNoSuchService = errors.New("no such service") - - // errFailedEncode indicates error in encoding. - errFailedEncode = errors.New("failed to encode") - - // errFailedToPublish. - errFailedToPublish = errors.New("failed to publish") - - // errEdgexFailed. - errEdgexFailed = errors.New("failed to execute edgex operation") - - // errFailedExecute. - errFailedExecute = errors.New("failed to execute command") - - // errFailedToCreateTerminalSession. - errFailedToCreateTerminalSession = errors.New("failed to create terminal session") - - // errNoSuchTerminalSession terminal session doesnt exist error on closing. - errNoSuchTerminalSession = errors.New("no such terminal session") -) - -// Service specifies API for publishing messages and subscribing to topics. -type Service interface { - // Execute command. - Execute(string, string) (string, error) - - // Control command. - Control(string, string) error - - // Update configuration file. - AddConfig(Config) error - - // Config returns Config struct created from config file. - Config() Config - - // Saves config file. - ServiceConfig(ctx context.Context, uuid, cmdStr string) error - - // Services returns service list. - Services() []Info - - // Terminal used for terminal control of gateway. - Terminal(string, string) error - - // Publish message. - Publish(string, string) error -} - -var _ Service = (*agent)(nil) - -type agent struct { - mqttClient paho.Client - config *Config - edgexClient edgex.Client - logger log.Logger - broker messaging.PubSub - svcs map[string]Heartbeat - terminals map[string]terminal.Session -} - -func (ag *agent) handle(ctx context.Context, pub messaging.Publisher, logger log.Logger, cfg HeartbeatConfig) handleFunc { - return func(msg *messaging.Message) error { - sub := msg.Channel - tok := strings.Split(sub, ".") - if len(tok) < 3 { - ag.logger.Error(fmt.Sprintf("Failed: Subject has incorrect length %s", sub)) - return fmt.Errorf("failed: Subject has incorrect length %s", sub) - } - svcname := tok[1] - svctype := tok[2] - // Service name is extracted from the subtopic - // if there is multiple instances of the same service - // we will have to add another distinction. - if _, ok := ag.svcs[svcname]; !ok { - svc := NewHeartbeat(svcname, svctype, cfg.Interval) - ag.svcs[svcname] = svc - ag.logger.Info(fmt.Sprintf("Services '%s-%s' registered", svcname, svctype)) - } - serv := ag.svcs[svcname] - serv.Update() - return nil - } -} - -type handleFunc func(msg *messaging.Message) error - -func (h handleFunc) Handle(msg *messaging.Message) error { - return h(msg) -} - -func (h handleFunc) Cancel() error { - return nil -} - -// New returns agent service implementation. -func New(ctx context.Context, mc paho.Client, cfg *Config, ec edgex.Client, broker messaging.PubSub, logger log.Logger) (Service, error) { - ag := &agent{ - mqttClient: mc, - edgexClient: ec, - config: cfg, - broker: broker, - logger: logger, - svcs: make(map[string]Heartbeat), - terminals: make(map[string]terminal.Session), - } - - if cfg.Heartbeat.Interval <= 0 { - ag.logger.Error(fmt.Sprintf("invalid heartbeat interval %d", cfg.Heartbeat.Interval)) - } - - subConfig := messaging.SubscriberConfig{ - ID: pubSubID, - Topic: Hearbeat, - Handler: ag.handle(ctx, ag.broker, logger, cfg.Heartbeat), - DeliveryPolicy: messaging.DeliverAllPolicy, - } - - err := ag.broker.Subscribe(ctx, subConfig) - - if err != nil { - return ag, errors.Wrap(errNatsSubscribing, err) - } - - return ag, nil - -} - -func (a *agent) Execute(uuid, cmd string) (string, error) { - cmdArr := strings.Split(strings.ReplaceAll(cmd, " ", ""), ",") - if len(cmdArr) < 2 { - return "", errInvalidCommand - } - - out, err := exec.Command(cmdArr[0], cmdArr[1:]...).CombinedOutput() - if err != nil { - return "", errors.Wrap(errFailedExecute, err) - } - - payload, err := encoder.EncodeSenML(uuid, cmdArr[0], string(out)) - if err != nil { - return "", errors.Wrap(errFailedEncode, err) - } - - if err := a.Publish(control, string(payload)); err != nil { - return "", errors.Wrap(errFailedToPublish, err) - } - - return string(payload), nil -} - -func (a *agent) Control(uuid, cmdStr string) error { - cmdArgs := strings.Split(strings.ReplaceAll(cmdStr, " ", ""), ",") - if len(cmdArgs) < 2 { - return errInvalidCommand - } - - var resp string - var err error - - cmd := cmdArgs[0] - switch cmd { - case "edgex-operation": - resp, err = a.edgexClient.PushOperation(cmdArgs[1:]) - case "edgex-config": - resp, err = a.edgexClient.FetchConfig(cmdArgs[1:]) - case "edgex-metrics": - resp, err = a.edgexClient.FetchMetrics(cmdArgs[1:]) - case "edgex-ping": - resp, err = a.edgexClient.Ping() - default: - err = errUnknownCommand - } - - if err != nil { - return errors.Wrap(errEdgexFailed, err) - } - - return a.processResponse(uuid, cmd, resp) -} - -// Message for this command -// [{"bn":"1:", "n":"services", "vs":"view"}] -// [{"bn":"1:", "n":"config", "vs":"save, export, filename, filecontent"}] -// config_file_content is base64 encoded marshaled structure representing service conf -// Example of creation: -// -// b, _ := toml.Marshal(cfg) -// config_file_content := base64.StdEncoding.EncodeToString(b). -func (a *agent) ServiceConfig(ctx context.Context, uuid, cmdStr string) error { - cmdArgs := strings.Split(strings.ReplaceAll(cmdStr, " ", ""), ",") - if len(cmdArgs) < 1 { - return errInvalidCommand - } - resp := "" - cmd := cmdArgs[0] - switch cmd { - case view: - services, err := json.Marshal(a.Services()) - if err != nil { - return errors.New(err.Error()) - } - resp = string(services) - case save: - if len(cmdArgs) < 4 { - return errInvalidCommand - } - service := cmdArgs[1] - fileName := cmdArgs[2] - fileCont := cmdArgs[3] - if err := a.saveConfig(ctx, service, fileName, fileCont); err != nil { - return err - } - } - return a.processResponse(uuid, cmd, resp) -} - -func (a *agent) Terminal(uuid, cmdStr string) error { - b, err := base64.StdEncoding.DecodeString(cmdStr) - if err != nil { - return errors.New(err.Error()) - } - cmdArgs := strings.Split(string(b), ",") - if len(cmdArgs) < 1 { - return errInvalidCommand - } - - cmd := cmdArgs[0] - ch := "" - if len(cmdArgs) > 1 { - ch = cmdArgs[1] - } - switch cmd { - case char: - if err := a.terminalWrite(uuid, ch); err != nil { - return err - } - case open: - if err := a.terminalOpen(uuid, a.config.Terminal.SessionTimeout); err != nil { - return err - } - case close: - if err := a.terminalClose(uuid); err != nil { - return err - } - } - return nil -} - -func (a *agent) terminalOpen(uuid string, timeout time.Duration) error { - if _, ok := a.terminals[uuid]; !ok { - term, err := terminal.NewSession(uuid, timeout, a.Publish, a.logger) - if err != nil { - return errors.Wrap(errors.Wrap(errFailedToCreateTerminalSession, fmt.Errorf(" for %s", uuid)), err) - } - a.terminals[uuid] = term - go func() { - for range term.IsDone() { - // Terminal is inactive, should be closed. - a.logger.Debug((fmt.Sprintf("Closing terminal session %s", uuid))) - a.terminalClose(uuid) - delete(a.terminals, uuid) - return - } - }() - } - a.logger.Debug(fmt.Sprintf("Opened terminal session %s", uuid)) - return nil -} - -func (a *agent) terminalClose(uuid string) error { - if _, ok := a.terminals[uuid]; ok { - delete(a.terminals, uuid) - a.logger.Debug(fmt.Sprintf("Terminal session: %s closed", uuid)) - return nil - } - return errors.Wrap(errNoSuchTerminalSession, fmt.Errorf("session :%s", uuid)) -} - -func (a *agent) terminalWrite(uuid, cmd string) error { - if err := a.terminalOpen(uuid, a.config.Terminal.SessionTimeout); err != nil { - return err - } - term := a.terminals[uuid] - p := []byte(cmd) - return term.Send(p) -} - -func (a *agent) processResponse(uuid, cmd, resp string) error { - payload, err := encoder.EncodeSenML(uuid, cmd, resp) - if err != nil { - return errors.Wrap(errFailedEncode, err) - } - if err := a.Publish(control, string(payload)); err != nil { - return errors.Wrap(errFailedToPublish, err) - } - return nil -} - -func (a *agent) saveConfig(ctx context.Context, service, fileName, fileCont string) error { - switch service { - case export: - content, err := base64.StdEncoding.DecodeString(fileCont) - if err != nil { - return errors.New(err.Error()) - } - c, err := exp.ReadBytes([]byte(content)) - if err != nil { - return errors.New(err.Error()) - } - c.File = fileName - if err := exp.Save(c); err != nil { - return errors.New(err.Error()) - } - - default: - return errNoSuchService - } - - return a.broker.Publish(ctx, fmt.Sprintf("%s.%s.%s", Commands, service, config), &messaging.Message{}) -} - -func (a *agent) AddConfig(c Config) error { - err := SaveConfig(c) - return errors.New(err.Error()) -} - -func (a *agent) Config() Config { - return *a.config -} - -func (a *agent) Services() []Info { - svcInfos := []Info{} - keys := []string{} - for k := range a.svcs { - keys = append(keys, k) - } - sort.Strings(keys) - for _, key := range keys { - service := a.svcs[key].Info() - svcInfos = append(svcInfos, service) - } - return svcInfos -} - -func (a *agent) Publish(t, payload string) error { - topic := a.getTopic(t) - mqtt := a.config.MQTT - token := a.mqttClient.Publish(topic, mqtt.QoS, mqtt.Retain, payload) - token.Wait() - err := token.Error() - if err != nil { - return errors.New(err.Error()) - } - return nil -} - -func (a *agent) getTopic(topic string) (t string) { - switch topic { - case control: - t = fmt.Sprintf("channels/%s/messages/res", a.config.Channels.Control) - case data: - t = fmt.Sprintf("channels/%s/messages/res", a.config.Channels.Data) - default: - t = fmt.Sprintf("channels/%s/messages/res/%s", a.config.Channels.Control, topic) - } - return t -} diff --git a/vendor/github.com/absmach/agent/pkg/bootstrap/bootstrap.go b/vendor/github.com/absmach/agent/pkg/bootstrap/bootstrap.go deleted file mode 100644 index fd3981d8..00000000 --- a/vendor/github.com/absmach/agent/pkg/bootstrap/bootstrap.go +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright (c) Abstract Machines -// SPDX-License-Identifier: Apache-2.0 - -package bootstrap - -import ( - "crypto/tls" - "crypto/x509" - "encoding/json" - "io" - "os" - - "fmt" - "net/http" - "strconv" - "time" - - "github.com/absmach/agent/pkg/agent" - - "github.com/absmach/magistrala/bootstrap" - log "github.com/absmach/magistrala/logger" - errors "github.com/absmach/magistrala/pkg/errors" - export "github.com/mainflux/export/pkg/config" -) - -const exportConfigFile = "/configs/export/config.toml" - -// Config represents the parameters for bootstrapping. -type Config struct { - URL string - ID string - Key string - Retries string - RetryDelaySec string - Encrypt string - SkipTLS bool -} - -type ServicesConfig struct { - Agent agent.Config `json:"agent"` - Export export.Config `json:"export"` -} - -type ConfigContent struct { - Content string `json:"content"` -} - -type deviceConfig struct { - MainfluxID string `json:"mainflux_id"` - MainfluxKey string `json:"mainflux_key"` - MainfluxChannels []bootstrap.Channel `json:"mainflux_channels"` - ClientKey string `json:"client_key"` - ClientCert string `json:"client_cert"` - CaCert string `json:"ca_cert"` - SvcsConf ServicesConfig `json:"-"` -} - -// Bootstrap - Retrieve device config. -func Bootstrap(cfg Config, logger log.Logger, file string) error { - retries, err := strconv.ParseUint(cfg.Retries, 10, 64) - if err != nil { - return errors.New(fmt.Sprintf("Invalid BOOTSTRAP_RETRIES value: %s", err)) - } - - if retries == 0 { - logger.Info("No bootstrapping, environment variables will be used") - return nil - } - - retryDelaySec, err := strconv.ParseUint(cfg.RetryDelaySec, 10, 64) - if err != nil { - return errors.New(fmt.Sprintf("Invalid BOOTSTRAP_RETRY_DELAY_SECONDS value: %s", err)) - } - - logger.Info(fmt.Sprintf("Requesting config for %s from %s", cfg.ID, cfg.URL)) - - dc := deviceConfig{} - - for i := 0; i < int(retries); i++ { - dc, err = getConfig(cfg.ID, cfg.Key, cfg.URL, cfg.SkipTLS, logger) - if err == nil { - break - } - logger.Error(fmt.Sprintf("Fetching bootstrap failed with error: %s", err)) - logger.Debug(fmt.Sprintf("Retries remaining: %d. Retrying in %d seconds", retries, retryDelaySec)) - time.Sleep(time.Duration(retryDelaySec) * time.Second) - if i == int(retries)-1 { - logger.Warn("Retries exhausted") - logger.Info("Continuing with local config") - return nil - } - } - - if len(dc.MainfluxChannels) < 2 { - return agent.ErrMalformedEntity - } - - ctrlChan := dc.MainfluxChannels[0].ID - dataChan := dc.MainfluxChannels[1].ID - if dc.MainfluxChannels[0].Metadata["type"] == "data" { - ctrlChan = dc.MainfluxChannels[1].ID - dataChan = dc.MainfluxChannels[0].ID - } - - sc := dc.SvcsConf.Agent.Server - cc := agent.ChanConfig{ - Control: ctrlChan, - Data: dataChan, - } - ec := dc.SvcsConf.Agent.Edgex - lc := dc.SvcsConf.Agent.Log - - mc := dc.SvcsConf.Agent.MQTT - mc.Password = dc.MainfluxKey - mc.Username = dc.MainfluxID - mc.ClientCert = dc.ClientCert - mc.ClientKey = dc.ClientKey - mc.CaCert = dc.CaCert - - hc := dc.SvcsConf.Agent.Heartbeat - tc := dc.SvcsConf.Agent.Terminal - c := agent.NewConfig(sc, cc, ec, lc, mc, hc, tc, file) - - dc.SvcsConf.Export = fillExportConfig(dc.SvcsConf.Export, c) - - saveExportConfig(dc.SvcsConf.Export, logger) - - return agent.SaveConfig(c) -} - -// if export config isnt filled use agent configs. -func fillExportConfig(econf export.Config, c agent.Config) export.Config { - if econf.MQTT.Username == "" { - econf.MQTT.Username = c.MQTT.Username - } - if econf.MQTT.Password == "" { - econf.MQTT.Password = c.MQTT.Password - } - if econf.MQTT.ClientCert == "" { - econf.MQTT.ClientCert = c.MQTT.ClientCert - } - if econf.MQTT.ClientCertKey == "" { - econf.MQTT.ClientCertKey = c.MQTT.ClientKey - } - if econf.MQTT.ClientCertPath == "" { - econf.MQTT.ClientCertPath = c.MQTT.CertPath - } - if econf.MQTT.ClientPrivKeyPath == "" { - econf.MQTT.ClientPrivKeyPath = c.MQTT.PrivKeyPath - } - for i, route := range econf.Routes { - if route.MqttTopic == "" { - econf.Routes[i].MqttTopic = "channels/" + c.Channels.Data + "/messages" - } - } - return econf -} - -func saveExportConfig(econf export.Config, logger log.Logger) { - if econf.File == "" { - econf.File = exportConfigFile - } - exConfFileExist := false - if _, err := os.Stat(econf.File); err == nil { - exConfFileExist = true - logger.Info(fmt.Sprintf("Export config file %s exists", econf.File)) - } - if !exConfFileExist { - logger.Info(fmt.Sprintf("Saving export config file %s", econf.File)) - if err := export.Save(econf); err != nil { - logger.Warn(fmt.Sprintf("Failed to save export config file %s", err)) - } - } -} - -func getConfig(bsID, bsKey, bsSvrURL string, skipTLS bool, logger log.Logger) (deviceConfig, error) { - // Get the SystemCertPool, continue with an empty pool on error. - rootCAs, err := x509.SystemCertPool() - if err != nil { - logger.Error(err.Error()) - } - if rootCAs == nil { - rootCAs = x509.NewCertPool() - } - // Trust the augmented cert pool in our client. - config := &tls.Config{ - InsecureSkipVerify: skipTLS, - RootCAs: rootCAs, - } - tr := &http.Transport{TLSClientConfig: config} - client := &http.Client{Transport: tr} - url := fmt.Sprintf("%s/%s", bsSvrURL, bsID) - - req, err := http.NewRequest(http.MethodGet, url, nil) - if err != nil { - return deviceConfig{}, err - } - - req.Header.Add("Authorization", fmt.Sprintf("Thing %s", bsKey)) - resp, err := client.Do(req) - if err != nil { - return deviceConfig{}, err - } - if resp.StatusCode >= http.StatusBadRequest { - return deviceConfig{}, errors.New(http.StatusText(resp.StatusCode)) - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - return deviceConfig{}, err - } - defer resp.Body.Close() - dc := deviceConfig{} - h := ConfigContent{} - if err := json.Unmarshal([]byte(body), &h); err != nil { - return deviceConfig{}, err - } - fmt.Println(h.Content) - sc := ServicesConfig{} - if err := json.Unmarshal([]byte(h.Content), &sc); err != nil { - return deviceConfig{}, err - } - if err := json.Unmarshal([]byte(body), &dc); err != nil { - return deviceConfig{}, err - } - dc.SvcsConf = sc - return dc, nil -} diff --git a/vendor/github.com/absmach/agent/pkg/edgex/client.go b/vendor/github.com/absmach/agent/pkg/edgex/client.go deleted file mode 100644 index 1a491b50..00000000 --- a/vendor/github.com/absmach/agent/pkg/edgex/client.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) Abstract Machines -// SPDX-License-Identifier: Apache-2.0 - -package edgex - -import ( - "bytes" - "encoding/json" - "io" - "net/http" - "strings" - - log "github.com/absmach/magistrala/logger" - - model "github.com/edgexfoundry/go-mod-core-contracts/models" -) - -type Client interface { - - // PushOperation - pushes operation to EdgeX components. - PushOperation([]string) (string, error) - - // FetchConfig - fetches config from EdgeX components. - FetchConfig([]string) (string, error) - - // FetchMetrics - fetches metrics from EdgeX components. - FetchMetrics(cmdArr []string) (string, error) - - // Ping - ping EdgeX SMA. - Ping() (string, error) -} - -type edgexClient struct { - url string - logger log.Logger -} - -// NewClient - Creates ne EdgeX client. -func NewClient(edgexURL string, logger log.Logger) Client { - return &edgexClient{ - url: edgexURL, - logger: logger, - } -} - -// PushOperation - pushes operation to EdgeX components. -func (ec *edgexClient) PushOperation(cmdArr []string) (string, error) { - url := ec.url + "operation" - - m := model.Operation{ - Action: cmdArr[0], - Services: cmdArr[1:], - } - data, err := json.Marshal(m) - if err != nil { - return "", err - } - - resp, err := http.Post(url, "application/json", bytes.NewReader(data)) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - return string(body), nil -} - -// FetchConfig - fetches config from EdgeX components. -func (ec *edgexClient) FetchConfig(cmdArr []string) (string, error) { - cmdStr := strings.ReplaceAll(strings.Join(cmdArr, ","), " ", "") - url := ec.url + "config/" + cmdStr - - resp, err := http.Get(url) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - return string(body), nil -} - -// FetchMetrics - fetches metrics from EdgeX components. -func (ec *edgexClient) FetchMetrics(cmdArr []string) (string, error) { - cmdStr := strings.ReplaceAll(strings.Join(cmdArr, ","), " ", "") - url := ec.url + "metrics/" + cmdStr - - resp, err := http.Get(url) - if err != nil { - - return "", err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - return string(body), nil -} - -// Ping - ping EdgeX SMA. -func (ec *edgexClient) Ping() (string, error) { - url := ec.url + "ping" - - resp, err := http.Get(url) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - - return string(body), nil -} diff --git a/vendor/github.com/absmach/agent/pkg/encoder/encoder.go b/vendor/github.com/absmach/agent/pkg/encoder/encoder.go deleted file mode 100644 index 452295fb..00000000 --- a/vendor/github.com/absmach/agent/pkg/encoder/encoder.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Abstract Machines -// SPDX-License-Identifier: Apache-2.0 - -package encoder - -import ( - "time" - - "github.com/mainflux/senml" -) - -func EncodeSenML(bn, n, sv string) ([]byte, error) { - ts := float64(time.Now().UnixNano()) / float64(time.Second) - s := senml.Pack{ - Records: []senml.Record{ - { - BaseName: bn, - Name: n, - Time: ts, - StringValue: &sv, - }, - }, - } - payload, err := senml.Encode(s, senml.JSON) - if err != nil { - return nil, err - } - return payload, nil -} diff --git a/vendor/github.com/absmach/agent/pkg/terminal/terminal.go b/vendor/github.com/absmach/agent/pkg/terminal/terminal.go deleted file mode 100644 index 26d3ad30..00000000 --- a/vendor/github.com/absmach/agent/pkg/terminal/terminal.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Abstract Machines -// SPDX-License-Identifier: Apache-2.0 - -package terminal - -import ( - "bytes" - "fmt" - "io" - "os" - "os/exec" - "sync" - "time" - - "github.com/creack/pty" - - "github.com/absmach/agent/pkg/encoder" - "github.com/absmach/magistrala/logger" - "github.com/absmach/magistrala/pkg/errors" -) - -const ( - terminal = "term" - second = time.Duration(1 * time.Second) -) - -type term struct { - uuid string - ptmx *os.File - done chan bool - topic string - timeout time.Duration - resetTimeout time.Duration - timer *time.Ticker - publish func(channel, payload string) error - logger logger.Logger - mu sync.Mutex -} - -type Session interface { - Send(p []byte) error - IsDone() chan bool - io.Writer -} - -func NewSession(uuid string, timeout time.Duration, publish func(channel, payload string) error, logger logger.Logger) (Session, error) { - t := &term{ - logger: logger, - uuid: uuid, - publish: publish, - timeout: timeout, - resetTimeout: timeout, - topic: fmt.Sprintf("term/%s", uuid), - done: make(chan bool), - } - - c := exec.Command("bash") - ptmx, err := pty.Start(c) - if err != nil { - return t, errors.New(err.Error()) - } - t.ptmx = ptmx - - // Copy output to mqtt - go func() { - n, err := io.Copy(t, t.ptmx) - if err != nil { - t.logger.Error(fmt.Sprintf("Error sending data: %s", err)) - } - t.logger.Debug(fmt.Sprintf("Data being sent: %d", n)) - }() - - t.timer = time.NewTicker(1 * time.Second) - - go func() { - for range t.timer.C { - t.decrementCounter() - } - t.logger.Debug("exiting timer routine") - }() - - return t, nil -} - -func (t *term) resetCounter(timeout time.Duration) { - t.mu.Lock() - defer t.mu.Unlock() - if timeout > 0 { - t.timeout = timeout - return - } -} -func (t *term) decrementCounter() { - t.mu.Lock() - defer t.mu.Unlock() - t.timeout -= second - if t.timeout == 0 { - t.done <- true - t.timer.Stop() - } -} - -func (t *term) IsDone() chan bool { - return t.done -} - -func (t *term) Write(p []byte) (int, error) { - t.resetCounter(t.resetTimeout) - n := len(p) - payload, err := encoder.EncodeSenML(t.uuid, terminal, string(p)) - if err != nil { - return n, err - } - - if err := t.publish(t.topic, string(payload)); err != nil { - return n, err - } - return n, nil -} - -func (t *term) Send(p []byte) error { - in := bytes.NewReader(p) - nr, err := io.Copy(t.ptmx, in) - t.logger.Debug(fmt.Sprintf("Written to ptmx: %d", nr)) - if err != nil { - return errors.New(err.Error()) - } - return nil -} diff --git a/vendor/github.com/absmach/magistrala/.dockerignore b/vendor/github.com/absmach/magistrala/.dockerignore deleted file mode 100644 index 2b37771e..00000000 --- a/vendor/github.com/absmach/magistrala/.dockerignore +++ /dev/null @@ -1,6 +0,0 @@ -.git -.github -build -docker -metrics -scripts diff --git a/vendor/github.com/absmach/magistrala/.gitignore b/vendor/github.com/absmach/magistrala/.gitignore deleted file mode 100644 index fb4ee7e8..00000000 --- a/vendor/github.com/absmach/magistrala/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) Abstract Machines -# SPDX-License-Identifier: Apache-2.0 - -# Set your private global .gitignore: -# https://digitalfortress.tech/tricks/creating-a-global-gitignore/ - -build - -# tools -tools/e2e/e2e -tools/mqtt-bench/mqtt-bench -tools/provision/provision -tools/provision/mgconn.toml diff --git a/vendor/github.com/absmach/magistrala/.golangci.yml b/vendor/github.com/absmach/magistrala/.golangci.yml deleted file mode 100644 index 829193f6..00000000 --- a/vendor/github.com/absmach/magistrala/.golangci.yml +++ /dev/null @@ -1,73 +0,0 @@ -run: - timeout: 3m - build-tags: - - "nats" - -issues: - max-issues-per-linter: 10 - max-same-issues: 10 - -linters-settings: - gocritic: - enabled-checks: - - captLocal - - dupImport - - singleCaseSwitch - disabled-checks: - - appendAssign - enabled-tags: - - diagnostic - disabled-tags: - - performance - - style - - experimental - - opinionated - misspell: - ignore-words: - - "mosquitto" - stylecheck: - checks: ["-ST1000", "-ST1003", "-ST1020", "-ST1021", "-ST1022"] - goheader: - template: |- - Copyright (c) Magistrala - SPDX-License-Identifier: Apache-2.0 - -linters: - disable-all: true - enable: - - gocritic - - gosimple - - errcheck - - govet - - unused - - goconst - - godot - - godox - - ineffassign - - misspell - - stylecheck - - whitespace - - gci - - gofmt - - goimports - - loggercheck - - goheader - - asasalint - - asciicheck - - bidichk - - contextcheck - - decorder - - dogsled - - errchkjson - - errname - - execinquery - - exportloopref - - ginkgolinter - - gocheckcompilerdirectives - - gofumpt - - goprintffuncname - - importas - - makezero - - mirror - - nakedret - - dupword diff --git a/vendor/github.com/absmach/magistrala/ADOPTERS.md b/vendor/github.com/absmach/magistrala/ADOPTERS.md deleted file mode 100644 index d0479a15..00000000 --- a/vendor/github.com/absmach/magistrala/ADOPTERS.md +++ /dev/null @@ -1,36 +0,0 @@ -# Adopters - -As Magistrala Community grows, we'd like to keep track of Magistrala adopters to grow the community, contact other users, share experiences and best practices. - -To accomplish this, we created a public ledger. The list of organizations and users who consider themselves as Magistrala adopters and that **publicly/officially** shared information and/or details of their adoption journey(optional). -Where users themselves directly maintain the list. - -## Adding yourself as an adopter -If you are using Magistrala, please consider adding yourself as an adopter with a brief description of your use case by opening a pull request to this file and adding a section describing your adoption of Magistrala technology. - -**Please send PRs to add or remove organizations/users** - -### Format - -``` -N: Name of user (company or individual) -D: Short Use Case Description (optional) -L: Link with further information (optional) -T: Type of adaptation: Evaluation, Core Technology, Production Usage (optional) -``` - -## Requirements -* You must represent the user or organization listed. Do NOT add entries on behalf of other organizations or individuals. -Pull request commit must be [signed](https://docs.github.com/en/github/authenticating-to-github/signing-commits) and auto-checked with [ Developer Certificate of Origin (DCO)](https://probot.github.io/apps/dco/) -* There is no minimum requirement or adaptation size, but we request to list permanent deployments only, i.e., no demo or trial deployments. Commercial or production use is not required. A well-done home lab setup can be equally impressive as a large-scale commercial deployment. - - -**The list of organizations/users that have publicly shared the usage of Magistrala:** - -**Note**: Several other organizations/users couldn't publicly share their usage details but are active project contributors and Magistrala Community members. - - -## Adopters list (alphabetical) - - -**Note:** The list is maintained by the users themselves. If you find yourself on this list, and you think it's inappropriate. Please contact [project maintainers](https://github.com/absmach/magistrala/blob/master/MAINTAINERS) and you will be permanently removed from the list. diff --git a/vendor/github.com/absmach/magistrala/CHANGELOG.md b/vendor/github.com/absmach/magistrala/CHANGELOG.md deleted file mode 100644 index edd5e6c5..00000000 --- a/vendor/github.com/absmach/magistrala/CHANGELOG.md +++ /dev/null @@ -1,708 +0,0 @@ -# Magistrala Changelog - -## Generation -Magistrala release notes for the latest release can be obtained via: -``` -make changelog -``` - -Otherwise, whole log in a similar format can be observed via: -``` -git log --pretty=oneline --abbrev-commit -``` - -## 0.13.0 - 15. APR 2022. -### Features and Bugfixes -- NOISSUE - Update changelog for release 0.13.0 -- Update VerneMQ release (#1593) -- NOISSUE - Update changelog and readme for release 0.13.0 -- MF-1582 - Fix lora-adapter MQTT client (#1583) -- NOISSUE - Fix CoAP adapter (#1572) -- NOISSUE - Unify MG_INFLUX_READER_DB_HOST and MG_INFLUX_WRITER_DB_HOST envars (#1585) -- MF-1580 - Influxdb Writer changes format of update-time to string (#1581) -- MF-1575 Add 'Name' field to ListMembers response in things svc (#1576) -- MF-1565 - Document Bearer, Thing and Basic Authorization header (#1566) -- MF-1567 - Use Bearer, Thing or Basic scheme in Authorization header (#1568) -- MF-1348 - Add transport errors logging (#1544) -- NOISSUE - Add nats wrapper for COAP (#1569) -- MF-1469 - Indicate proper authentication scheme in Authorization header (#1523) -- MF-1240 - Return to service transport layer only service errors (#1559) -- Update dependencies (#1564) -- NOISSUE - Separate Keto hosts for read and write (#1563) -- MF-1551 - Fix Cobra usage commands and clean unnecessary struct types (#1558) -- MF-1257 - Access messages from readers endpoint with user access token (#1470) -- NOISSUE - Refactor MQTT subscriber (#1561) -- MF-1059 - Add TLS support for email (#1560) -- MF-1261 - Use StatusUnauthorized for authn and StatusForbidden for authz (#1538) -- NOISSUE - Fix auth members list response (#1555) -- MF-1263 - Move repeating errors to the separate package (#1540) -- NOISSUE - Add API keys functions to CLI (#1537) -- Fix SDK for group members (#1553) -- NOISSUE - Fix Swagger UI (#1552) -- MF-1008 - Make token duration configurable (#1550) -- MF-1308 - Use IETF Health Check standard (#1541) -- Fix user listing access control (#1546) -- Update dependencies (#1545) -- MF-1478 - TimescaleDB writer and reader add-on (#1542) -- MF-1149 - Add AsyncAPI MQTT API doc (#1539) -- MF-1535 - Add API keys functions to SDK (#1536) -- NOISSUE - Add view and list serials endpoints in certs service (#1483) -- MF-1516 - Fix API key issuing (#1530) -- NOISSUE - Add disconnect endpoint in nginx conf (#1528) -- NOISSUE - Add timestamp transformation rules for specifc JSON fields (#1514) -- MF-1425 - Support external UUIDs for Things and Channels (#1518) -- MF-1521 - Fix email headers (#1522) -- Fix SenML lib dependency version (#1519) -- Bump vernemq to 1.12.3 (#1520) -- NOISSUE - Remove auth URL from SDK (#1511) -- NOISSUE - Apply policies to Channels (#1505) -- remove dead code (#1503) -- NOISSUE - Fix listing (#1502) -- NOISSUE - Listing Policies (#1498) -- Fix standalone mode (#1497) -- MF-1489 - Add API for deleting policies (#1491) -- NOISSUE - Update group sharing policies (#1494) -- NOISSUE - Refactor InfluxDB Reader: explicit check event + add safe conversion (#1460) -- NOISSUE - Update users create command for CLI (#1495) -- NOISSUE - Update self register environment variable name (#1493) -- Bring back the job add -- NOISSUE - Fix assigning invalid group policy (#1487) -- MF-1443 - Add policies (#1482) -- NOISSUE - Fix retrieving all users (#1477) -- MF-1468 - Fix ThingsURL in Certs Service (#1474) -- NOISSUE - Refactor single-user mode (#1471) -- Fix UpdateChannelHandler for Redis producer (#1473) -- NOISSUE - Add SMPP notifier (#1464) -- NOISSUE - Update dependencies (#1453) -- NOISSUE - Fix security warnings for dependencies (#1452) -- Bump docker-compose version in prereq (#1449) -- NOISSUE - Fix bootstraping (#1448) -- MF 1413 - Use per-service URL in SDK (#1444) -- MF-1439 - Add support for Basic Authentication in HTTP Adapter (#1441) -- MF-1421 - Make flattening of JSON transformer only available on InfluxDB (#1432) -- NOISSUE - Update the /disconnect endpoint HTTP method as PUT (#1438) -- MF-1389 - Add /disconnect endpoint in Things service (#1433) -- NOISSUE - Fix httputil implementation in users service (#1434) -- Fix fetching user members of an empty group (#1436) -- Change to user friendly docs urls (#1430) -- NOISSUE - Use github action for showing OpenAPI spec with Swagger UI (#1427) -- Fix JSON Transformer empty format handling (#1429) -- Update README -- NOISSUE - Update docker-compose images to latest release (#1419) -- MF-1378 - Update dependencies (#1379) - -## 0.12.1 - 05. MAY 2021. -### Features and Bugfixes -- NOISSUE - Refactor SDK memberships and fix openapi for memberships. -- NOISSUE - Fix incorrect influxdb credentials -- MF-1408 - Fix error handling for Thing update SQL(#1408) -- MF-1288 - Add tests for JSON messages in message writers and readers -- NOISSUE - Fix Postgres Reader order -- NOISSUE - Fix nginx configuration for groups -- NOISSUE - Add tests and connection route-map to lora-adapter -- MF-1403 - Change vernemq building source revision -- NOISSUE - Rm content-type check from list endpoint - -## 0.12.0 - 29. MAR 2021. -### Features and Bugfixes -- MF-1394 - SDK groups (#1396) -- NOISSUE - fix response for passwd endpoints (#1393) -- NOISSUE - dont retrieve groups (#1392) -- MF-1368 - Add internal http api package for query params reading (#1384) -- MF-1390 - Fix docker-compose env_file (#1391) -- NOISSUE - put order direction in response body (#1387) -- NOISSUE - Certs service refactor (#1369) -- MF-1357 - Add new endpoint for searching things (#1383) -- NOISSUE - Add missing auth port in nginx enrypoint.sh (#1380) -- MF-1346 - Create Groups API - add grouping of entities (#1334) -- NOISSUE - Fix certs and vault deployment, reorganize and remove unnecessary vars (#1368) -- MF-1317 - Configurable regexp rule for password (#1355) -- Fix CoAP Adapter README (#1376) -- NOISSUE - Fix default values for port and x509 provision (#1367) -- NOISSUE - Added missing endpoints for users service (#1372) -- MF-1365 - Add ADOPTERS.md file (#1371) -- Fix grpc endpoint parameter permutation (#1370) -- NOISSUE - Add IsChannelOwner grpc endpoint (#1366) -- MF-1362 - Sort Things and Channels connections by name (#1363) -- MF-1314 - Add value comparison filters for readers (#1353) -- Fix env configuration and documentation (#1360) -- NOISSUE - Support disabling Email Agent authentication (#1356) -- NOISSUE - Upgrade Mongo, Cassandra and Influx docker images (#1354) -- NOISSUE - Add READMEs to pkg packages (#1352) -- NOISSUE - Correct README (#1349) -- MF-1342 - Use environment variables in docker-compose to use tagged version of image (#1343) -- MF-1311 - Add Notifications service (#1324) -- MF-1344 - Fix links to API documentations #1345 -- NOISSUE - Upgrade influxdb and postgres docker images (#1341) -- NOISSUE - Revert cli to use user token from command args (#1339) -- MF-1276 - Fix openapi IDs and Keys format (#1338) -- MF-1061 - Add PageMetadata to readers (#1333) -- NOISSUE - Fix run script and compiler warnings (#1336) -- Fix Postgres writer transaction handling (#1335) -- Make Transformer type configurable (#1331) -- MF-1061 - Implement v, vb, vs, vd and from/to mongodb-reader filters (#1326) -- NOISSUE - Rename package aliases uuidProvider into uuid (#1323) -- MF-1034 - Wrapping MQTT client (#1318) -- MF-1061 - Fix cassandra-reader count for json format (#1327) -- MF-1061 - Implement v, vb, vs, vd and from/to cassandra-reader filters (#1325) -- NOISSUE - Switch to Consumers interface (#1316) -- MF-1061 - Implement protocol, name, v, vb, vs, vd and from/to Postgres reader… (#1322) -- MF-1061 - Add name, protocol and publisher tests to influxdb-reader (#1320) -- NOISSUE - Fix Auth typo (#1319) -- NOISSUE - Add health check for MQTT broker (#1305) -- MF-1264 - Add support for JSON readers (#1295) -- NOISSUE - Merge authz and authn into new service auth (#1313) -- MF-1061 - Implement InfluxDB filters value, v, vb, vs, vd, from, to (#1312) -- NOISSUE - Correct readers openapi.yml (#1310) -- NOISSUE - Fix MQTT Forwarder client id (#1309) -- NOISSUE - Fix dates not being init properly on save, change path construction, replace UUID with ULID for group ID (#1300) -- NOISSUE - Remove authz from docker comp (#1307) -- Shorten descriptions and add formats (#1306) -- NOISSUE - remove owner id from user table and object (#1303) -- NOISSUE - Add missing fields to openapi specs and enclose http codes in single quotes (#1302) -- MF-1290 - Sort Things and Channels by name (#1293) -- MF-1248 - Add access policies for users (#1246) -- Fixes, without spaces. (#1296) -- Add different CNs for CA and certs (#1292) -- MF-397 - Introduce Thing Groups (#1259) -- Add Enhancement section to the issue template (#1284) -- Fix hardcoded env var values (#1283) -- NOISSUE - Improve AuthN service docs (#1282) -- MF-1268 - CLI improvements (#1274) -- NOISSSUE - Vault integration as an addon. (#1266) -- Fix naming in Authn API tests (#1275) -- MF-1244 - Return UserID alongside with user Email in Identify response (#1245) -- NOISSUE - Fix ViewGroup and UpdateGroup (#1269) -- NOISSUE - Add ListUsers, ViewUser and ViewProfile methods (#1262) -- NOISSUE - Rm users http package (#1256) -- NOISSUE - Remove content-type check from decodeListUserGroupsRequest (#1255) -- NOISSUE - Migrate swaggers to openapi 3 spec (#1250) -- Update MQTT Broker Docker scripts (#1253) -- update mproxy version (#1251) -- NOISSUE - Fix group retrieval when parent id is not specified (#1247) -- NOISSUE - Add new endpoint to retrieve configuration to be used as a template. (#1242) -- NOISSUE - Add user groups (#1228) -- MF-1237 - Return to transport only things service errors (#1236) -- MF-928 - Change CoAP lib (#1233) -- NOISSUE - Simplify make cleandocker (#1230) -- NOISSUE - Fix malformed Swagger API specs (#1229) -- MF-435 - Add support for env file loading (#1223) -- update certs docs (#1227) -- NOISSUE - Fix certs update in bootstrap config and make content handling in config.toml user friendly (#1221) -- NOISSUE - Fix typo in authorization.js (#1226) -- MF-983 - Add HTTP query param to connections list endpoints to fetch disconnected Things or Channels (#1217) -- MF-1179 - Add a certificate service and certs endpoint to SDK (#1188) -- NOISUE - Fix cache error when key is not in Redis (#1220) -- MF-1199 - Add NATS messaging tests (#1209) -- NOISSUE: Fix emailer (#1219) -- NOISSUE - Update dependencies (#1218) -- NOISSUE - Add subtopic wildcard for twin attribute's definition (#1214) -- fix envs for nginx (#1215) -- Remove twin mqtt related obsolete var and fix es-redis address (#1213) -- NOISSUE - Remove unused `MG_THINGS_SECRET` env var (#1211) -- NOISSUE - Fix some typos (#1212) -- NOISSUE - Remove unknown Bootstrap requests (#1210) -- NOISSUE - Use `pgcrypto` instead `uuid-ossp` for UUIDs generation (version 4) (#1208) -- MF-1198 - Add errors package tests (#1207) -- MF-1025 - timeout env in sec, use parseduration (#1206) -- MF-1201 - Fix MG_THINGS_AUTH_GRPC_URL mongo reader ENVAR (#1203) -- NOISSUE - Fix CI (#1204) -- MF-1180 - Add redis based twins and states cache (#1184) -- MF-739 - Add ID to the User entity (#1152) -- NOISSUE - Fix default db name for storage databases (#1194) -- NOISSUE - Add `MG_DOCKER_IMAGE_NAME_PREFIX` to Makefile (#1173) -- MF-1154 - Move UUID provider to project root (#1172) -- Fix typo in error messages (#1193) -- MF-1190 - Add pkg for library packages (#1191) -- MF-1177 - Implement caching in MQTT adapter (#1187) -- NOISSUE - Refactor provision tool (#1189) - -## 0.11.0 - 29. MAY 2020. -### Features and Bugfixes -- Add VerneMQ docker image build from source (#1178) -- MF-994 - Add tracing middleware for twins and states repos (#1181) -- MF-995 - Add Twins tests for endpoint list twins and list states (#1174) -- NOISSUE - Update dependencies (#1176) -- MF-1163 - Fix influxdb-reader to use nanoseconds precision (#1171) -- Rename environment variable MG_MQTT_ADAPTER_PORT to MG_MQTT_ADAPTER_MQTT_PORT in docker environment (#1170) -- Remove thing related code from twins service (#1169) -- MF-997 - Add twins service swagger file (#1167) -- MF-1079 - Add MQTT forwarder (#1164) -- MF-1159 - add gateway metadata update in provision method (#1160) -- MF-1055 - rollback/release transaction on error (#1166) -- NOISSUE - Use log level error for VermeMQ docker (#1162) -- NOISSUE - Fix default nats pubsub subject (#1153) -- MF-1125 - Document Provision service (#1143) -- NOISSUE - Fix bootstrap SDK args naming (#1151) -- Use VerneMQ default log level (#1150) -- NOISSUE - Update provision service (#1133) -- NOISSUE - Refactor messaging (#1141) -- Add JSON tags to SDK entities (#1146) -- NOISSUE - Update CLI README.md (#1139) -- NOISSUE - Update mProxy version (#1137) -- fix nginx, channel connect (#1136) -- Remove concurrency flag for golangci-lint (#1134) -- MF-1088 - Remove message payload content type (#1121) -- MF-1129 - Use snake_case for Lora and OPC-UA metadata fields (#1130) -- MF-1128 - Add golangci-linter to a CI script (#1131) -- MF-1123 - Move Provision service to monorepo (#1132) -- MF-845 - Add FOSSA badge for licensing (#1127) -- MF-1087 - Remove WebSocket adapter (#1120) -- NOISSUE - Use HTTP Status in SDK error messages (#1119) -- NOISSUE - Fix bootstrap token naming and interfaces named args (#1117) -- MF-1115 - Improve the SDK error encoding (#1118) -- MF-862 - Add boostrap CRUD to SDK and CLI (#1114) -- NOISSUE - Update coding style in Things service (#1116) -- NOISSUE - Remove defers from TestMain (#1111) -- NOISSUE - Create func to encode SDK errors (#1110) -- MF-1078 - Add timestamp to published messages and use it in Transformer (#1106) -- Fix prometheus namespace in postgres reader & writer (#1109) -- NOISSUE - Implement errors package in senml transformer, readers and writers (#1108) -- NOISSUE - Implement errors package in Authentication service (#1105) -- MF-1103 - API key should ignore empty expiration time (#1104) -- MF-1096 - Fix AuthN and Things Auth ENVARS (#1066) -- fix Contains function for nil arguments (#1102) -- MF-1099 - Add email subdomain validator (#1101) -- MF-1091 - Use channels. as broker prefix (#1098) -- MF-1090 - Use named Interfaces args (#1097) -- NOISSUE - Create broker package for NATS (#1080) -- NOISSUE - Implement errors package in bootstrap service (#1093) -- NOISSUE - Fix writers loadSubjectsConfig if file is missing (#1094) -- NOISSUE - Adding subtopics filtering in writer services (#1072) -- NOISSUE - Improve errors package (#1086) -- NOISSUE - Enable MQTT over WS in docker composition (#1085) -- NOISSUE - Rm unused opc-ua envars (#1083) -- MF-798 - Add utf8 support for email validation (#1082) -- Remove unused Tokenizer interface (#1084) -- Update mqtt adapter imports (#1081) -- NOISSUE - Update state based on SenML time value (#1075) -- NOISSUE - Fix StatusBadDecodingError for opc-ua browse (#1074) -- Save senml array msg to multiple states (#1073) -- NOISSUE - Fix opc-ua message type handling (#1071) -- NOISSUE - Add Publisher field to MQTT adapter (#1067) -- NOISSUE - Fix users CLI (#1062) -- NOISSUE - Fix SDK Messages response (#1064) -- Merged MQTT docker compose in core composition file (#1060) -- MF-1016 - Add UserUpdate and UpdatePassword to sdk and CLI (#1057) -- Update mProxy (#1058) -- MF-1053 - Add disconnect event to MQTT adapter (#1056) -- Fix data type for data_value in databases (#1054) -- NOISSUE - Fix opc-ua subscriptions store (#1052) -- NOISSUE - Fix connect CLI command and remove ConnectThing func from SDK (#1051) -- NOISSUE - Update Vernemq image repository (#1050) -- Removed VerneMQ auth plugin, Aedes impl. Added mproxy support in docker (#1049) -- NOISSUE - Add default subscription nodeID and Interval ENVAR (#1046) -- MF-415 - Merge mProxy support (#1045) -- NOISSUE - Remove twins-service mqtt dependency and publish notifs to nats (#1042) -- Add arbitrary SenML value type saving to twin state (#1039) -- Fixed Aedes dependencies (#1036) -- MF-998 - Add Twins service to Makefile and docker-compose.yml (#1035) -- MF-1032 - Fix redis docker volume of opcua-adapter (#1033) -- NOISSUE - add nats conf (#1031) -- MF-442 - Add SSL encryption to the MongoDB, InfluxDB and Cassanda readers (#1024) -- NOISSUE - Add opc-ua type handling and unsubscription (#1029) -- NOISSUE - Add aggregate attribute-based search for twin retrieval (#1027) -- NOISSUE - Fix metadata in add Things endpoint (#1028) -- NOISSUE - Fix minimal password length (#1023) -- MF-1020 - Change default password for CLI provision test (#1021) -- NOISSUE - Add subtopic to opcua messages (#1022) -- NOISSUE - Add details to browsed OPC-UA nodes (#1019) -- NOISSUE Fix obsolete attribute persistance (#1018) -- Fix twins update revision counter (#1011) -- Fixed docs instructions in README (#1010) -- Fix copyright year (#1009) -- Fix issuing recovery key (#1007) -- Removed gatling load-test (#1005) -- Removed old k8s manifests (#1004) -- NOISSUE - Remove UI from docker-compose (#1001) -- NOISSUE - Store successfull OPC-UA subscriptions (#999) -- MF-730 - Add digital twin service for things (#855) -- Fix Redis event naming (#996) -- NOISSUE - Add a Browse endpoint in opcua-adapter (#988) -- NOISSUE - Add Redis ES Username/Pass for VerneMQ (#991) -- MF-982 - Add error when connecting empty channels or things (#985) - -## 0.10.0 - 17. DEC 2019. -### Features -- MF-932 - User API keys (#941) -- NOISSUE - Use opcua server timestamp in opcua-adapter messages (#980) -- Simplify CI script (#979) -- NOISSUE - Add opcua-adapter conn route-map, use ServerURI and NodeID (#975) -- Move docs to a separate repo (#976) -- NOISSUE - Support multiple types values in opcua-adapter (#973) -- Migrate from dep to go modules (#971) -- NOISSUE - Add Node IdentifierType config in opcua-adapter (#967) -- NOISSUE - Remove messages limit in influxdb-reader (#968) -- MF-898 - Add bulk connect to CLI and SDK (#956) -- MF-538 - Improve logging and API errors (#866) -- NOISSUE - Remove Elm UI (#953) -- MF-898 - Add bulk connections endpoint (#948) -- MF-898 - Change thing's service to use bulk connect (#946) -- MF-898 - Add transactions to postgres connect (#940) -- Add missing user service tests (#945) -- Remove Normalizer service from compose (#937) -- MF-919 - Magistrala message updates (#924) -- NOISSUE - Remove ARM multi-arch images (#929) -- MF-906 - Change single creation endpoints to use bulk service calls (#927) -- MF-922 - Add UpdateUser endpoint (#923) -- MF-780 - Use Normalizer as a lib (#915) -- NOISSUE - Switch to grpcbox for VerneMQ (#914) -- Change channels to chs (#918) -- MF-484 - Add bulk provisioning for things and channels (#889) -- MF-899 - Update README and official docs (#910) -- NOISSUE - Fix Redis envars (#903) -- Add disconnect on gen_server terminate() (#913) -- MF-890 - Add OPC-UA docs (#904) -- NOISSUE - Update Protobuf version (#902) -- MF-886 - Add OPC-UA adapter (#878) -- MF-532 - Password reset (#873) -- MF-785 - Change CanAccess to CanAccessByKey (#894) -- NOISSUE - Add MQTT UserName check on register and InstanceId in Redis (#884) -- Add MQTT troubleshooting section (#882) -- MF-875 - Add tracing to official documentation (#877) -- MF-788 - Remove date and minimize copyright comments (#876) -- MF-787 - Add tags to user, thing, and channel spans (#869) -- Update docker-compose version for addons (#874) -- MF-859 - Channels metadata search (#867) -- MF-858 Users metadata (#861) -- NOISSUE - Simplify MQTT benchmarking tool (#852) -- NOISSUE - Upgrade Go version to 1.13 in container images (#868) -- MF-820 - Fetch messages for a particular device (#843) -- Update gorilla websocket version (#865) -- NOISSUE - Update aedes version and fix Dockerfile (#863) -- NOISSUE - Search by metadata (#849) -- MF-846 - Install python in docker build for aedes mqtt image (#860) -- NOISSUE - Clean NginX files, move .gitignores to dirs (#853) -- NOISSUE - Add docker-compose for MQTT cluster (#841) -- Add debug logs to the WS adapter (#848) -- NOISSUE - Add measuring time from pub to sub (#839) -- NOISSUE - update mqtt prov tool and some refactor (#831) -- NOISSUE - Use Thing ID to update certs data (#827) -- NOISSUE - Improve VerneMQ plugin code, add configurable gRPC pool size (#836) -- NOISSUE - Use gRPC for VerneMQ (#835) -- Switch secure of WS connection according to secure of http connection of UI (#829) -- NOISSUE - Use current hostname instead of localhost for a WebSocket connection in the UI (#826) -- NOISSUE - Improve MQTT benchmarking tools (#828) -- NOISSUE - update mqtt benchmark (#824) -- Add encryption key to env vars table (#823) -- NOISSUE - Add version endpoint to MQTT adapter (#816) -- MF-295 add mqtt benchmark tool (#817) -- update mqtts commands (#815) -- NOISSUE - Support encrypted bootstrap (#796) -- Add config to writers docs (#812) -- NOISSUE - Add VerneMQ support (#809) -- NOISSUE - Add content type as part of MQTT subscription topic (#810) - -### Bugfixes -- Fix MQTT protobuf filename(#981) -- MF-950 - Runtime error in normalizer - CBOR SenML (#974) -- NOISSUE - Fix opcua-adapter events warnings (#965) -- NOISSUE - Fix opcua-adapter events decode (#951) -- Fix subtopic handling in VerneMQ (#962) -- NOISSUE - Fix Update User (#959) -- NOISSUE - Fix make dockers (#957) -- Add dev_ back to make dockers_dev (#955) -- NOISSUE - Fix docs (#952) -- MF-916 - Fix Things and Channels counters (#947) -- MF-942 - Fix email template logic (#944) -- NOISSUE - Fix HTTP header for Things and Channels creation (#939) -- NOISSUE - Fix docker ui image name (#938) -- NOISSUE - Fix lora-adapter (#936) -- NOISSUE - Fix lora creation events (#933) -- Fix doc for ENV vars in README (#920) -- Fix compilation (#911) -- Revert "NOISSUE - Make event sourcing optional (#907)" (#909) -- NOISSUE - Make event sourcing optional (#907) -- NOISSUE - Fix InfluxDB env vars (#908) -- Fix Elm version for ARM Docker images (#905) -- Fix Elm version in Dockerfile (#901) -- NOISSUE - fix security doc (#897) -- NOISSUE - Fix typo in docs and README (#891) -- Fix Nginx mTLS configuration (#885) -- Fix provision tool connect error handling (#879) -- Fix: Correct 404 and Content-Type Issues in MQTT Version Endpoint (#837) -- NOISSUE - Fix proto files in VerneMQ (#834) -- NOISSUE - Fix hackney HTTP request (#833) -- Add socket pool and fix pattern matching (#830) -- Fix typo (#814) - -## 0.9.0 - 19. JUL 2019. -### Features -- Create and push docker manifest for new release from Makefile (#794) -- MF-399 - Add open tracing support (#782) -- MF-783 - Allow access checking by a thing ID (#784) -- NOISSUE - Add authorization HTTP API to things service (#772) -- Remove cli executable from repo (#776) -- NOISSUE - Use .env vars in docker-compose (#770) -- MF-663 - enable nginx port conf from docker env (#769) -- Update docs (#766) -- NOISSUE - Remove installing non-existent package in ci (#758) -- NOISSUE - Add searchable Channels name (#754) -- MF-466 - ARM docker deployment (#756) -- Add missing Websocket.js into docker ui image (#755) -- NOISSUE - Add searchable Things name (#750) -- NOISSUE - Add certificate fields to the Bootstrap service (#752) -- Update grpc and protobuf deps in mqtt adapter (#751) -- MF-742 - Things to support single user scenario (#749) -- MF-732 - Add Postgres reader (#740) -- MF-722 - Change UUID lib (#746) -- Add performance improvement to writer filtering (#744) -- NOISSUE - Update nginx version (#748) -- MF-574 - Add missing environment variables to Cassandra writer (#745) -- NOISSUE - Add compile test to CI (#743) -- MF-708 - Assign Writer(s) to a channel (#737) -- MF-732 - Add PostgreSQL writer (#733) -- NOISSUE - Add readers pagination in SDK (#736) -- Add UI websocket open/close and send/receive (#728) -- MF-707 - Allow custom Thing key (#726) -- MF-525 - Add pagination response to the readers (#729) -- NOISSUE - Rm Things type from lora-adapter (#727) -- skip deleting of persistent volumes by default (#723) -- MF-488 - Remove Thing type (app or device) (#718) -- Remove empty channels check (#720) -- MF-655 Proper usage of docker volumes (#657) -- NOISSUE - Improve UI styling (#719) -- MF-715 - Conflict on updating connection with a valid list of channels (#716) -- MF-711 - Create separate Redis instance for ES (#717) -- NOISSUE - Update event fields naming (#713) -- MF-698 - Add missing info and docs about sys event sourcing (#712) -- MF-549 - Change metadata format from JSON string to JSON object (#706) -- NOISSUE - Replace repeating code by card gen func (#697) -- Update Bootstrap service docker-compose.yml (#700) -- Remove Debug function (#699) -- MF-687 - Add event sourcing to Bootstrap service (#695) -- NOISSUE - Remove debugging message from response of handle error function (#696) -- Add event stream to MQTT adapter for conn status (#692) -- NOISSUE - Improve UI style (#691) -- Update docs structure (#686) -- Use images instead of carousel (#685) -- NOISSUE - Update docs (#683) -- MF-662 - Change menu style (#678) -- MF-651 - X509 Mutual TLS authentication (#676) -- Update Aedes version for MQTT adapter (#677) -- MF-661 - Bootstrap pagination in UI (#672) -- Update subtopics section in documentation (#670) -- Remove default base URL value (#671) - -### Bugfixes -- NOISSUE - Fix Readers logs (#735) -- NOISSUE - Fix Docker for ARM (#760) -- NOISSUE - Fix count when search by name is performed (#767) -- NOISSUE - Typo fix (#777) -- NOISSUE - Fix Postgres logs in Things service (#734) -- Fix CI with fixed plugin versions (#747) -- fix building problems (#741) -- fix docker-compose env (#775) -- Fix MG_THINGS_AUTH_GRPC_PORT in addons' docker-compose files (#781) -- Fix MQTT raw message deserialization (#753) -- fix variant option for manifest annotate (#765) -- fix to makefile for OSX/Darwin (#724) -- Fix .dockerignore file by removing index.html (#725) -- Fix things and channels metadata create and edit & remove thing type (#721) -- Fix Bootstrap service event map keys (#705) -- Fix logging in publish event callback (#694) -- Fix InfluxDB time bug (#689) -- Fix users service to work in offline mode (#795) -- fix mainflux_id parameter in bootstrap swagger (#789) -- Fix offset calculation after deleting thing/channel, not to go to negative offset after deleting last thing/channel (#679) -- Use errors and null packets in authorized pub/sub (#773) -- NOISSUE - Fix CoAP adapter (#779) - - -### Summary -https://github.com/absmach/magistrala/milestone/10?closed=1 - -## 0.8.0 - 20. MAR 2019. -### Features -- MF-571 - Add Env.elm to set custom base URL (#654) -- NOISSUE Added docs about docker-compose config overriding (#653) -- MF-539 - Improve Bootstrap Service documentation (#646) -- MF-596 - Add subtopic to RawMessage (#642) -- NOISSUE - Prevent infinite loop in lora-adapter if Redis init fail (#647) -- Corrected grammar and rephrased a few sentences to read nicely (#641) -- MF-571 - Elm UI (#632) -- MF-552 - Use event sourcing to keep Bootstrap service in sync with Things service (#603) -- MF-540 - Add pagination in API responses for Bootstrap service (#575) -- MF-600 - Handle custom LoRa Server application decoder (#608) -- update docker-compose (#590) -- Update generated code (#602) -- Add generated files check (#601) -- MF-597 - Removed legacy code as not needed anymore (#598) -- NOISSUE - Added normalizer service to run script (#594) -- Changed RawMessage (#587) -- NOISSUE - fix CLI log (#581) -- MF-519 - Refine Message (#567) -- NOISSUE - Add name field for Bootstrap Config (#564) -- Fix non-SenML message routing in normalizer (#573) -- NOISSUE - Update authors list (#569) -- Update lora.md (#568) -- NOISSUE- Improve LoRa doc (#562) -- MF-551 - Add metadata fields to Bootstrap Channels (#563) -- Fix MQTT adapter by setting subscription queue (#561) -- MF-558 - Add MQTT subtopics documentation (#559) -- Fix regexp for SUB (#557) -- Simplify MQTT topipc regexp (#555) -- MF-429 -Enabled MQTT subtopic's (#554) -- Add env var for number of concurrent messages (#545) -- NOISSUE - Update doc and fix empty key bug (#544) -- MF-370 - Simplify and refine CI (#541) -- NOISSUE - Add connection commands to CLI (#542) -- NOISSUE - Refine docs (#537) -- Update licnese year (#533) -- MF-513 - Add Bootstrapping service (#524) -- Add dedicated env vars for event sourcing (#536) -- NOISSUE - Fix docs (#535) -- Add lora doc to getting-started.md (#529) -- MF-483 - Enable channels and devices corresponding lists in backend (#520) -- Add missing components doc to architecture.md (#531) - -### Bugfixes -- MF-639 Split Content-Type header field on semicolon and evaluate all substrings (#644) -- MF-656 - Change bootstrap service port to 8200 (#658) -- Replace crossOrigin with relative path and fix messaging bug (#645) -- MF-579 Things & Channels returns 404 when not found or ID is malformed, not 500 (#633) -- Fix run command in dev guide (#605) -- MF-583 - Correct cmd/mongodb-reader HTTPServer log Info (#584) -- Fix Dusan Maldenovic GitHub (#570) -- Fix CLI docs (#566) -- Fix pagination response for empty page (#547) -- Fix swagger and provisioning docs (#546) -- NOISSUE - Fix event sourcing client on LoRa adapter (#527) -- Fix MQTT adapter scaling issue (#526) -- NOISSUE - Fix subtopic regex and restrict empty subtopic parts (#659) -- Fix missing css in container ui (#638) -- NOISSUE - Fix lora-adapter Object decode (#610) -- NOISSUE - Fix users logs in main.go (#577) -- NOISSUE - Fix normalizer exposed port in docker-compose (#548) - -### Summary -https://github.com/absmach/magistrala/milestone/9?closed=1 - - -## 0.7.0 - 08. DEC 2018. -### Features - -- MF-486 - Add provisioning command to CLI (#487) -- Fix lora-adapter event store handlers (#492) -- NOISSUE - Add LoRa route map validation and fix LoRa messages URL (#491) -- MF-475 - Replace increment ID with UUID (#490) -- MF-166 - Add lora-adapter service (#481) -- NOISSUE - Add Makefile target to clean old imgs (#485) -- MF-473 - Add metadata field to channel (#476) -- Make CoAP ping period configurable (#469) -- Add nginx ingress config to k8s services (#472) -- Add CoAP section in getting-started (#468) -- NOISSUE - Move CLI documentation from getting started guide to separate page (#470) -- NOISSUE - Update Getting Started doc with CLI usage (#465) -- Update CoAP docs with URL example (#463) -- MF-447 - Add event sourcing to things service (#460) -- Add TLS support to CoAP adapter and all readers (#459) -- MF-417 - Implement SDK tests (#438) -- MF-454 - Use message Time field as a time for InfluxDB points (#455) -- NOISSUE - Add .dockerignore to project root (#457) -- Update docker-compose so that every service has debug log level (#453) -- NOISSUE - Add TLS flag for Magistrala services (#452) -- MF-448 - Option for Postgres SSL Mode (#449) -- MF-443 Update project dependencies (#444) -- MF-426 - Add optional MG_CA_CERTS env variable to allow GRPC client to use TLS certs (#430) -- Expose the InfluxDB and Cassandra ports to host (#441) -- MF-374 - Bring back CoAP adapter (#413) - -### Bugfixes -- gRPC Load Balancing between http-adapter and things (#387) -- MF-407 - Values of zero are being omitted (#434) - -### Summary -https://github.com/absmach/magistrala/milestone/8?closed=1 - - -## 0.6.0 - 26. OCT 2018. -### Features - -- Added Go SDK (#357) -- Updated NATS version (#412) -- Added debbug level to MFX logger (#379) -- Added Documentation for readers (#389) -- Added Redis cache to improve performance (#382) - - -## 0.5.1 - 05. SEP 2018. -### Features -- Improve performance by adding Redis cache (#382) - -### Bugfixes -- Mixed up name and type of the things (#375) -- Fix MQTT topic (#380) - - -## 0.5.0 - 28. AUG 2018 -### Features -- InfluxDB Reader (#311) -- Cassandra Reader (#313) -- MongoDB Reader (#344) -- MQTT Persistance via Redis (#328) -- CLI integrated into monorepo (#216) -- Normalizer logging (#333) -- WS swagger doc (#337) -- Payload renamed to Metadata (#343) -- Protobuf files added (#363) -- SPDX headers added (#325) - -### Bugfixes -- Docker network for InfluxDB (#346) -- Vendor correct gRPC version (#340) - -### Summary -https://github.com/absmach/magistrala/milestone/6?closed=1 - - -## 0.4.0 - 01. JUN 2018. -* Integrated MQTT adapter (#165 ) -* Support for storing messages in MongoDB (#237) -* Support for storing messages in InfluxDB (#236) -* Use UUID PKs with auto-incremented values (#269 ) -* Replaced JWT with plain string tokens in things service (#268 ) -* Emit non-SenML messages (#239 ) -* Support for Grafana (#296) -* Added WS Load test (#299 ) - - -## 0.3.0 - 14. MAY 2018. -- CoAP API for message exchange (#186) -- Split `manager` service into `clients` and `users` (#266) -- Replaced ORM with raw SQL (#265) -- Setup Kubernetes (#226, #273) -- Fix docker compose (#274) -- Integrated `dashflux` into monorepo (#258) -- Integrated (*non-compatible*) `mqtt` into monorepo (#260) - - -## 0.2.3 - 24. APR 2018. -- Fix examples in the documentation (#243) -- Add service name in info response (#241) -- Improve code coverage in WS adapter (#242) - - -## 0.2.2 - 23. APR 2018. -- Setup load testing scenarios (#225) - - -## 0.2.1 - 22. APR 2018. -- Fixed `Content-Type` header checking (#238) - -## 0.2.0 - 18. APR 2018 -- Protobuf message serialization (#192) -- Websocket API for exchanging messages (#188) -- Channel & client retrieval paging (#227) -- Service instrumentation (#213) -- `go-kit` based JSON logger (#212) -- Project documentation (#218, #220) -- API tests (#211, #224) - - -## 0.1.2 - 18. MAR 2018. -### Bug fixes - -- Fixed go lint warnings (#189) -- Compose failing startup (#185) -- Added missing service startup messages (#190) diff --git a/vendor/github.com/absmach/magistrala/CONTRIBUTING.md b/vendor/github.com/absmach/magistrala/CONTRIBUTING.md deleted file mode 100644 index 35a196aa..00000000 --- a/vendor/github.com/absmach/magistrala/CONTRIBUTING.md +++ /dev/null @@ -1,87 +0,0 @@ -# Contributing to Magistrala - -The following is a set of guidelines to contribute to Magistrala and its libraries, which are -hosted on the [Abstract Machines Organization](https://github.com/absmach) on GitHub. - -This project adheres to the [Contributor Covenant 1.2](http://contributor-covenant.org/version/1/2/0). -By participating, you are expected to uphold this code. Please report unacceptable behavior to -[abuse@magistrala.com](mailto:abuse@magistrala.com). - -## Reporting issues - -Reporting issues are a great way to contribute to the project. We are perpetually grateful about a well-written, -thorough bug report. - -Before raising a new issue, check [our issue -list](https://github.com/absmach/magistrala/issues) to determine if it already contains the -problem that you are facing. - -A good bug report shouldn't leave others needing to chase you for more information. Please be as detailed as possible. The following questions might serve as a template for writing a detailed -report: - -- What were you trying to achieve? -- What are the expected results? -- What are the received results? -- What are the steps to reproduce the issue? -- In what environment did you encounter the issue? - -## Pull requests - -Good pull requests (e.g. patches, improvements, new features) are a fantastic help. They should -remain focused in scope and avoid unrelated commits. - -**Please ask first** before embarking on any significant pull request (e.g. implementing new features, -refactoring code etc.), otherwise you risk spending a lot of time working on something that the -maintainers might not want to merge into the project. - -Please adhere to the coding conventions used throughout the project. If in doubt, consult the -[Effective Go](https://golang.org/doc/effective_go.html) style guide. - -To contribute to the project, [fork](https://help.github.com/articles/fork-a-repo/) it, -clone your fork repository, and configure the remotes: - -``` -git clone https://github.com//magistrala.git -cd magistrala -git remote add upstream https://github.com/absmach/magistrala.git -``` - -If your cloned repository is behind the upstream commits, then get the latest changes from upstream: - -``` -git checkout master -git pull --rebase upstream main -``` - -Create a new topic branch from `master` using the naming convention `MG-[issue-number]` -to help us keep track of your contribution scope: - -``` -git checkout -b MG-[issue-number] -``` - -Commit your changes in logical chunks. When you are ready to commit, make sure -to write a Good Commit Message™. Consult the [Erlang's contributing guide](https://github.com/erlang/otp/wiki/Writing-good-commit-messages) -if you're unsure of what constitutes a Good Commit Message™. Use [interactive rebase](https://help.github.com/articles/about-git-rebase) -to group your commits into logical units of work before making it public. - -Note that every commit you make must be signed. By signing off your work you indicate that you -are accepting the [Developer Certificate of Origin](https://developercertificate.org/). - -Use your real name (sorry, no pseudonyms or anonymous contributions). If you set your `user.name` -and `user.email` git configs, you can sign your commit automatically with `git commit -s`. - -Locally merge (or rebase) the upstream development branch into your topic branch: - -``` -git pull --rebase upstream main -``` - -Push your topic branch up to your fork: - -``` -git push origin MG-[issue-number] -``` - -[Open a Pull Request](https://help.github.com/articles/using-pull-requests/) with a clear title -and detailed description. diff --git a/vendor/github.com/absmach/magistrala/LICENSE b/vendor/github.com/absmach/magistrala/LICENSE deleted file mode 100644 index 0cb81525..00000000 --- a/vendor/github.com/absmach/magistrala/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015-2020 Magistrala - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/absmach/magistrala/MAINTAINERS b/vendor/github.com/absmach/magistrala/MAINTAINERS deleted file mode 100644 index 8df02cf4..00000000 --- a/vendor/github.com/absmach/magistrala/MAINTAINERS +++ /dev/null @@ -1,30 +0,0 @@ -# Magistrala follows the timeless, highly efficient and totally unfair system -# known as [Benevolent dictator for -# life](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), with -# Drasko DRASKOVIC in the role of BDFL. - -[bdfl] - - [[drasko]] - Name = "Drasko Draskovic" - Email = "draasko.draskovic@abstractmachines.fr" - GitHub = "drasko" - -# However, this role serves only in dead-lock events, or in a special and very rare cases -# when BDFL completely disagrees with the decisions made. -# In the normal flow of events, decisions on the project design are made through discussions, -# most often on the Pull Requests. -# -# Maintainers have the special role in the project in managing and accepting PRs, -# overall leading the project and making design decisions on the maintained subsystems. -# -# A reference list of all maintainers of the Magistrala project. - -# ADD YOURSELF HERE IN ALPHABETICAL ORDER - -[maintainers] - - [[dusan]] - Name = "Dusan Borovcanin" - Email = "dusan.borovcanin@abstractmachines.fr" - GitHub = "dborovcanin" diff --git a/vendor/github.com/absmach/magistrala/Makefile b/vendor/github.com/absmach/magistrala/Makefile deleted file mode 100644 index 9400256a..00000000 --- a/vendor/github.com/absmach/magistrala/Makefile +++ /dev/null @@ -1,249 +0,0 @@ -# Copyright (c) Abstract Machines -# SPDX-License-Identifier: Apache-2.0 - -MG_DOCKER_IMAGE_NAME_PREFIX ?= magistrala -BUILD_DIR = build -SERVICES = auth users things http coap ws lora influxdb-writer influxdb-reader mongodb-writer \ - mongodb-reader cassandra-writer cassandra-reader postgres-writer postgres-reader timescale-writer timescale-reader cli \ - bootstrap opcua twins mqtt provision certs smtp-notifier smpp-notifier -DOCKERS = $(addprefix docker_,$(SERVICES)) -DOCKERS_DEV = $(addprefix docker_dev_,$(SERVICES)) -CGO_ENABLED ?= 0 -GOARCH ?= amd64 -VERSION ?= $(shell git describe --abbrev=0 --tags) -COMMIT ?= $(shell git rev-parse HEAD) -TIME ?= $(shell date +%F_%T) -USER_REPO ?= $(shell git remote get-url origin | sed -e 's/.*\/\([^/]*\)\/\([^/]*\).*/\1_\2/' ) -BRANCH ?= $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null || git describe --tags --abbrev=0 2>/dev/null ) -empty:= -space:= $(empty) $(empty) -# Docker compose project name should follow this guidelines: https://docs.docker.com/compose/reference/#use--p-to-specify-a-project-name -DOCKER_PROJECT ?= $(shell echo $(subst $(space),,$(USER_REPO)_$(BRANCH)) | tr -c -s '[:alnum:][=-=]' '_' | tr '[:upper:]' '[:lower:]') -DOCKER_COMPOSE_COMMANDS_SUPPORTED := up down config -DEFAULT_DOCKER_COMPOSE_COMMAND := up -GRPC_MTLS_CERT_FILES_EXISTS = 0 -DOCKER_PROFILE ?= $(MG_MQTT_BROKER_TYPE)_$(MG_MESSAGE_BROKER_TYPE) -ifneq ($(MG_MESSAGE_BROKER_TYPE),) - MG_MESSAGE_BROKER_TYPE := $(MG_MESSAGE_BROKER_TYPE) -else - MG_MESSAGE_BROKER_TYPE=nats -endif - -ifneq ($(MG_MQTT_BROKER_TYPE),) - MG_MQTT_BROKER_TYPE := $(MG_MQTT_BROKER_TYPE) -else - MG_MQTT_BROKER_TYPE=nats -endif - -ifneq ($(MG_ES_STORE_TYPE),) - MG_ES_STORE_TYPE := $(MG_ES_STORE_TYPE) -else - MG_ES_STORE_TYPE=nats -endif - -define compile_service - CGO_ENABLED=$(CGO_ENABLED) GOOS=$(GOOS) GOARCH=$(GOARCH) GOARM=$(GOARM) \ - go build -tags $(MG_MESSAGE_BROKER_TYPE) --tags $(MG_ES_STORE_TYPE) -ldflags "-s -w \ - -X 'github.com/absmach/magistrala.BuildTime=$(TIME)' \ - -X 'github.com/absmach/magistrala.Version=$(VERSION)' \ - -X 'github.com/absmach/magistrala.Commit=$(COMMIT)'" \ - -o ${BUILD_DIR}/$(1) cmd/$(1)/main.go -endef - -define make_docker - $(eval svc=$(subst docker_,,$(1))) - - docker build \ - --no-cache \ - --build-arg SVC=$(svc) \ - --build-arg GOARCH=$(GOARCH) \ - --build-arg GOARM=$(GOARM) \ - --build-arg VERSION=$(VERSION) \ - --build-arg COMMIT=$(COMMIT) \ - --build-arg TIME=$(TIME) \ - --tag=$(MG_DOCKER_IMAGE_NAME_PREFIX)/$(svc) \ - -f docker/Dockerfile . -endef - -define make_docker_dev - $(eval svc=$(subst docker_dev_,,$(1))) - - docker build \ - --no-cache \ - --build-arg SVC=$(svc) \ - --tag=$(MG_DOCKER_IMAGE_NAME_PREFIX)/$(svc) \ - -f docker/Dockerfile.dev ./build -endef - -ADDON_SERVICES = bootstrap cassandra-reader cassandra-writer certs \ - influxdb-reader influxdb-writer lora-adapter mongodb-reader mongodb-writer \ - opcua-adapter postgres-reader postgres-writer provision smpp-notifier smtp-notifier \ - timescale-reader timescale-writer twins - -EXTERNAL_SERVICES = vault prometheus - -ifneq ($(filter run%,$(firstword $(MAKECMDGOALS))),) - temp_args := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)) - DOCKER_COMPOSE_COMMAND := $(if $(filter $(DOCKER_COMPOSE_COMMANDS_SUPPORTED),$(temp_args)), $(filter $(DOCKER_COMPOSE_COMMANDS_SUPPORTED),$(temp_args)), $(DEFAULT_DOCKER_COMPOSE_COMMAND)) - $(eval $(DOCKER_COMPOSE_COMMAND):;@) -endif - -ifneq ($(filter run_addons%,$(firstword $(MAKECMDGOALS))),) - temp_args := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)) - RUN_ADDON_ARGS := $(if $(filter-out $(DOCKER_COMPOSE_COMMANDS_SUPPORTED),$(temp_args)), $(filter-out $(DOCKER_COMPOSE_COMMANDS_SUPPORTED),$(temp_args)),$(ADDON_SERVICES) $(EXTERNAL_SERVICES)) - $(eval $(RUN_ADDON_ARGS):;@) -endif - -ifneq ("$(wildcard docker/ssl/certs/*-grpc-*)","") -GRPC_MTLS_CERT_FILES_EXISTS = 1 -else -GRPC_MTLS_CERT_FILES_EXISTS = 0 -endif - -FILTERED_SERVICES = $(filter-out $(RUN_ADDON_ARGS), $(SERVICES)) - -all: $(SERVICES) - -.PHONY: all $(SERVICES) dockers dockers_dev latest release run run_addons grpc_mtls_certs check_mtls check_certs - -clean: - rm -rf ${BUILD_DIR} - -cleandocker: - # Stops containers and removes containers, networks, volumes, and images created by up - docker-compose -f docker/docker-compose.yml --profile $(DOCKER_PROFILE) -p $(DOCKER_PROJECT) down --rmi all -v --remove-orphans - -ifdef pv - # Remove unused volumes - docker volume ls -f name=$(MG_DOCKER_IMAGE_NAME_PREFIX) -f dangling=true -q | xargs -r docker volume rm -endif - -install: - cp ${BUILD_DIR}/* $(GOBIN) - -test: - go test -mod=vendor -v -race -count 1 -tags test $(shell go list ./... | grep -v 'vendor\|cmd') - -proto: - protoc -I. --go_out=. --go_opt=paths=source_relative pkg/messaging/*.proto - protoc -I. --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative ./*.proto - -$(FILTERED_SERVICES): - $(call compile_service,$(@)) - -$(DOCKERS): - $(call make_docker,$(@),$(GOARCH)) - -$(DOCKERS_DEV): - $(call make_docker_dev,$(@)) - -dockers: $(DOCKERS) -dockers_dev: $(DOCKERS_DEV) - -define docker_push - for svc in $(SERVICES); do \ - docker push $(MG_DOCKER_IMAGE_NAME_PREFIX)/$$svc:$(1); \ - done -endef - -changelog: - git log $(shell git describe --tags --abbrev=0)..HEAD --pretty=format:"- %s" - -latest: dockers - $(call docker_push,latest) - -release: - $(eval version = $(shell git describe --abbrev=0 --tags)) - git checkout $(version) - $(MAKE) dockers - for svc in $(SERVICES); do \ - docker tag $(MG_DOCKER_IMAGE_NAME_PREFIX)/$$svc $(MG_DOCKER_IMAGE_NAME_PREFIX)/$$svc:$(version); \ - done - $(call docker_push,$(version)) - -rundev: - cd scripts && ./run.sh - -grpc_mtls_certs: - $(MAKE) -C docker/ssl users_grpc_certs things_grpc_certs - -check_tls: -ifeq ($(GRPC_TLS),true) - @unset GRPC_MTLS - @echo "gRPC TLS is enabled" - GRPC_MTLS= -else - @unset GRPC_TLS - GRPC_TLS= -endif - -check_mtls: -ifeq ($(GRPC_MTLS),true) - @unset GRPC_TLS - @echo "gRPC MTLS is enabled" - GRPC_TLS= -else - @unset GRPC_MTLS - GRPC_MTLS= -endif - -check_certs: check_mtls check_tls -ifeq ($(GRPC_MTLS_CERT_FILES_EXISTS),0) -ifeq ($(filter true,$(GRPC_MTLS) $(GRPC_TLS)),true) -ifeq ($(filter $(DEFAULT_DOCKER_COMPOSE_COMMAND),$(DOCKER_COMPOSE_COMMAND)),$(DEFAULT_DOCKER_COMPOSE_COMMAND)) - $(MAKE) -C docker/ssl users_grpc_certs things_grpc_certs -endif -endif -endif - -define edit_docker_config - sed -i "s/MG_MQTT_BROKER_TYPE=.*/MG_MQTT_BROKER_TYPE=$(1)/" docker/.env - sed -i "s/MG_MQTT_BROKER_HEALTH_CHECK=.*/MG_MQTT_BROKER_HEALTH_CHECK=$$\{MG_$(shell echo ${MG_MQTT_BROKER_TYPE} | tr 'a-z' 'A-Z')_HEALTH_CHECK}/" docker/.env - sed -i "s/MG_MQTT_ADAPTER_WS_TARGET_PATH=.*/MG_MQTT_ADAPTER_WS_TARGET_PATH=$$\{MG_$(shell echo ${MG_MQTT_BROKER_TYPE} | tr 'a-z' 'A-Z')_WS_TARGET_PATH}/" docker/.env - sed -i "s/MG_MESSAGE_BROKER_TYPE=.*/MG_MESSAGE_BROKER_TYPE=$(2)/" docker/.env - sed -i "s,file: .*.yml,file: $(2).yml," docker/brokers/docker-compose.yml - sed -i "s,MG_MESSAGE_BROKER_URL=.*,MG_MESSAGE_BROKER_URL=$$\{MG_$(shell echo ${MG_MESSAGE_BROKER_TYPE} | tr 'a-z' 'A-Z')_URL\}," docker/.env - sed -i "s,MG_MQTT_ADAPTER_MQTT_QOS=.*,MG_MQTT_ADAPTER_MQTT_QOS=$$\{MG_$(shell echo ${MG_MQTT_BROKER_TYPE} | tr 'a-z' 'A-Z')_MQTT_QOS\}," docker/.env -endef - -change_config: -ifeq ($(DOCKER_PROFILE),nats_nats) - sed -i "s/- broker/- nats/g" docker/docker-compose.yml - sed -i "s/- rabbitmq/- nats/g" docker/docker-compose.yml - sed -i "s,MG_NATS_URL=.*,MG_NATS_URL=nats://nats:$$\{MG_NATS_PORT}," docker/.env - $(call edit_docker_config,nats,nats) -else ifeq ($(DOCKER_PROFILE),nats_rabbitmq) - sed -i "s/nats/broker/g" docker/docker-compose.yml - sed -i "s,MG_NATS_URL=.*,MG_NATS_URL=nats://nats:$$\{MG_NATS_PORT}," docker/.env - sed -i "s/rabbitmq/broker/g" docker/docker-compose.yml - $(call edit_docker_config,nats,rabbitmq) -else ifeq ($(DOCKER_PROFILE),vernemq_nats) - sed -i "s/nats/broker/g" docker/docker-compose.yml - sed -i "s/rabbitmq/broker/g" docker/docker-compose.yml - sed -i "s,MG_NATS_URL=.*,MG_NATS_URL=nats://broker:$$\{MG_NATS_PORT}," docker/.env - $(call edit_docker_config,vernemq,nats) -else ifeq ($(DOCKER_PROFILE),vernemq_rabbitmq) - sed -i "s/nats/broker/g" docker/docker-compose.yml - sed -i "s/rabbitmq/broker/g" docker/docker-compose.yml - $(call edit_docker_config,vernemq,rabbitmq) -else - $(error Invalid DOCKER_PROFILE $(DOCKER_PROFILE)) -endif - -run: check_certs change_config -ifeq ($(MG_ES_STORE_TYPE), redis) - sed -i "s/MG_ES_STORE_TYPE=.*/MG_ES_STORE_TYPE=redis/" docker/.env - sed -i "s/MG_ES_STORE_URL=.*/MG_ES_STORE_URL=$$\{MG_REDIS_URL}/" docker/.env - docker-compose -f docker/docker-compose.yml --profile $(DOCKER_PROFILE) --profile redis -p $(DOCKER_PROJECT) $(DOCKER_COMPOSE_COMMAND) $(args) -else - sed -i "s,MG_ES_STORE_TYPE=.*,MG_ES_STORE_TYPE=$$\{MG_MESSAGE_BROKER_TYPE}," docker/.env - sed -i "s,MG_ES_STORE_URL=.*,MG_ES_STORE_URL=$$\{MG_$(shell echo ${MG_MESSAGE_BROKER_TYPE} | tr 'a-z' 'A-Z')_URL\}," docker/.env - docker-compose -f docker/docker-compose.yml --profile $(DOCKER_PROFILE) -p $(DOCKER_PROJECT) $(DOCKER_COMPOSE_COMMAND) $(args) -endif - -run_addons: check_certs - $(call change_config) - $(foreach SVC,$(RUN_ADDON_ARGS),$(if $(filter $(SVC),$(ADDON_SERVICES) $(EXTERNAL_SERVICES)),,$(error Invalid Service $(SVC)))) - @for SVC in $(RUN_ADDON_ARGS); do \ - MG_ADDONS_CERTS_PATH_PREFIX="../." docker-compose -f docker/addons/$$SVC/docker-compose.yml -p $(DOCKER_PROJECT) --env-file ./docker/.env $(DOCKER_COMPOSE_COMMAND) $(args) & \ - done diff --git a/vendor/github.com/absmach/magistrala/README.md b/vendor/github.com/absmach/magistrala/README.md deleted file mode 100644 index c80c320a..00000000 --- a/vendor/github.com/absmach/magistrala/README.md +++ /dev/null @@ -1,203 +0,0 @@ -# Magistrala - -[![Build Status](https://mainflux.semaphoreci.com/badges/mainflux/branches/master.svg?style=shields)](https://mainflux.semaphoreci.com/projects/mainflux) -[![go report card][grc-badge]][grc-url] -[![coverage][cov-badge]][cov-url] -[![license][license]](LICENSE) -[![chat][gitter-badge]][gitter] - -![banner][banner] - -Magistrala is modern, scalable, secure, open-source, and patent-free IoT cloud platform written in Go. - -It accepts user and thing (sensor, actuator, application) connections over various network protocols (i.e. HTTP, -MQTT, WebSocket, CoAP), thus making a seamless bridge between them. It is used as the IoT middleware -for building complex IoT solutions. - -For more details, check out the [official documentation][docs]. - -## Features - -- Multi-protocol connectivity and bridging (HTTP, MQTT, WebSocket and CoAP) -- Device management and provisioning (Zero Touch provisioning) -- Mutual TLS Authentication (mTLS) using X.509 Certificates -- Fine-grained access control (policies, ABAC/RBAC) -- Message persistence (Cassandra, InfluxDB, MongoDB and PostgresSQL) -- Platform logging and instrumentation support (Prometheus and OpenTelemetry) -- Event sourcing -- Container-based deployment using [Docker][docker] and [Kubernetes][kubernetes] -- [LoRaWAN][lora] network integration -- [OPC UA](opcua) integration -- Edge [Agent](agent) and [Export](export) services for remote IoT gateway management and edge computing -- SDK -- CLI -- Small memory footprint and fast execution -- Domain-driven design architecture, high-quality code and test coverage - -## Prerequisites - -The following are needed to run Magistrala: - -- [Docker](https://docs.docker.com/install/) (version 20.10) -- [Docker compose](https://docs.docker.com/compose/install/) (version 1.29) - -Developing Magistrala will also require: - -- [Go](https://golang.org/doc/install) (version 1.19.2) -- [Protobuf](https://github.com/protocolbuffers/protobuf#protocol-compiler-installation) (version 3.6.1) - -## Install - -Once the prerequisites are installed, execute the following commands from the project's root: - -```bash -docker-compose -f docker/docker-compose.yml up -``` - -This will bring up the Magistrala docker services and interconnect them. This command can also be executed using the project's included Makefile: - -```bash -make run -``` - -If you want to run services from specific release checkout code from github and make sure that -`MG_RELEASE_TAG` in [.env](.env) is being set to match the release version - -```bash -git checkout tags/ -b -# e.g. `git checkout tags/0.13.0 -b 0.13.0` -``` - -Check that `.env` file contains: - -```bash -MG_RELEASE_TAG= -``` - ->`docker-compose` should be used for development and testing deployments. For production we suggest using [Kubernetes](https://docs.mainflux.io/kubernetes). - -## Usage - -The quickest way to start using Magistrala is via the CLI. The latest version can be downloaded from the [official releases page][rel]. - -It can also be built and used from the project's root directory: - -```bash -make cli -./build/cli version -``` - -Additional details on using the CLI can be found in the [CLI documentation](https://docs.mainflux.io/cli). - -## Documentation - -Official documentation is hosted at [Magistrala official docs page][docs]. Documentation is auto-generated, checkout the instructions on [official docs repository](https://github.com/mainflux/docs): - -If you spot an error or a need for corrections, please let us know - or even better: send us a PR. - -## Authors - -Main architect and BDFL of Magistrala project is [@drasko][drasko]. - -Additionally, [@nmarcetic][nikola] and [@janko-isidorovic][janko] assured -overall architecture and design, while [@manuio][manu] and [@darkodraskovic][darko] -helped with crafting initial implementation and continuously worked on the project evolutions. - -Besides them, Magistrala is constantly improved and actively -developed by [@anovakovic01][alex], [@dusanb94][dusan], [@srados][sava], -[@gsaleh][george], [@blokovi][iva], [@chombium][kole], [@mteodor][mirko] and a large set of contributors. - -Maintainers are listed in [MAINTAINERS](MAINTAINERS) file. - -The Magistrala team would like to give special thanks to [@mijicd][dejan] for his monumental work -on designing and implementing a highly improved and optimized version of the platform, -and [@malidukica][dusanm] for his effort on implementing the initial user interface. - -## Professional Support - -There are many companies offering professional support for the Magistrala system. - -If you need this kind of support, best is to reach out to [@drasko][drasko] directly, and he will point you out to the best-matching support team. - -## Contributing - -Thank you for your interest in Magistrala and the desire to contribute! - -1. Take a look at our [open issues](https://github.com/absmach/magistrala/issues). The [good-first-issue](https://github.com/absmach/magistrala/labels/good-first-issue) label is specifically for issues that are great for getting started. -2. Checkout the [contribution guide](CONTRIBUTING.md) to learn more about our style and conventions. -3. Make your changes compatible to our workflow. - -### We're Hiring - -You like Magistrala and you would like to make it your day job? We're always looking for talented engineers interested in open-source, IoT and distributed systems. If you recognize yourself, reach out to [@drasko][drasko] - he will contact you back. - ->The best way to grab our attention is, of course, by sending PRs :sunglasses:. - -## Community - -- [Google group][forum] -- [Gitter][gitter] -- [Twitter][twitter] - -## License - -[Apache-2.0](LICENSE) - -[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fmainflux%2Fmainflux.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fmainflux%2Fmainflux?ref=badge_large) - -## Data Collection for Magistrala -Magistrala is committed to continuously improving its services and ensuring a seamless experience for its users. To achieve this, we collect certain data from your deployments. Rest assured, this data is collected solely for the purpose of enhancing Magistrala and is not used with any malicious intent. The deployment summary can be found on our [website][callhome]. - -The collected data includes: -- **IP Address** - Used for approximate location information on deployments. -- **Services Used** - To understand which features are popular and prioritize future developments. -- **Last Seen Time** - To ensure the stability and availability of Magistrala. -- **Magistrala Version** - To track the software version and deliver relevant updates. - -We take your privacy and data security seriously. All data collected is handled in accordance with our stringent privacy policies and industry best practices. - -Data collection is on by default and can be disabled by setting the env variable: -`MG_SEND_TELEMETRY=false` - -By utilizing Magistrala, you actively contribute to its improvement. Together, we can build a more robust and efficient IoT platform. Thank you for your trust in Magistrala! - -[banner]: https://github.com/mainflux/docs/blob/master/docs/img/gopherBanner.jpg -[ci-badge]: https://semaphoreci.com/api/v1/absmach/magistrala/branches/master/badge.svg -[ci-url]: https://semaphoreci.com/absmach/magistrala -[docs]: https://docs.mainflux.io -[docker]: https://www.docker.com -[forum]: https://groups.google.com/forum/#!forum/mainflux -[gitter]: https://gitter.im/absmach/magistrala?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge -[gitter-badge]: https://badges.gitter.im/Join%20Chat.svg -[grc-badge]: https://goreportcard.com/badge/github.com/absmach/magistrala -[grc-url]: https://goreportcard.com/report/github.com/absmach/magistrala -[cov-badge]: https://codecov.io/gh/absmach/magistrala/branch/master/graph/badge.svg -[cov-url]: https://codecov.io/gh/absmach/magistrala -[license]: https://img.shields.io/badge/license-Apache%20v2.0-blue.svg -[twitter]: https://twitter.com/mainflux -[lora]: https://lora-alliance.org/ -[opcua]: https://opcfoundation.org/about/opc-technologies/opc-ua/ -[agent]: https://github.com/mainflux/agent -[export]: https://github.com/mainflux/export -[kubernetes]: https://kubernetes.io/ -[rel]: https://github.com/absmach/magistrala/releases -[careers]: https://www.mainflux.com/careers.html -[lf]: https://www.linuxfoundation.org/ -[edgex]: https://www.edgexfoundry.org/ -[company]: https://abstractmachines.fr -[blog]: https://medium.com/abstract-machines-blog -[drasko]: https://github.com/drasko -[nikola]: https://github.com/nmarcetic -[dejan]: https://github.com/mijicd -[manu]: https://github.com/manuIO -[darko]: https://github.com/darkodraskovic -[janko]: https://github.com/janko-isidorovic -[alex]: https://github.com/anovakovic01 -[dusan]: https://github.com/dborovcanin -[sava]: https://github.com/srados -[george]: https://github.com/gesaleh -[iva]: https://github.com/blokovi -[kole]: https://github.com/chombium -[dusanm]: https://github.com/malidukica -[mirko]: https://github.com/mteodor -[callhome]: https://deployments.mainflux.io diff --git a/vendor/github.com/absmach/magistrala/api.go b/vendor/github.com/absmach/magistrala/api.go deleted file mode 100644 index 33e5eaef..00000000 --- a/vendor/github.com/absmach/magistrala/api.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package magistrala - -// Response contains HTTP response specific methods. -type Response interface { - // Code returns HTTP response code. - Code() int - - // Headers returns map of HTTP headers with their values. - Headers() map[string]string - - // Empty indicates if HTTP response has content. - Empty() bool -} diff --git a/vendor/github.com/absmach/magistrala/auth.pb.go b/vendor/github.com/absmach/magistrala/auth.pb.go deleted file mode 100644 index 5f37fa98..00000000 --- a/vendor/github.com/absmach/magistrala/auth.pb.go +++ /dev/null @@ -1,2060 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.31.0 -// protoc v4.24.3 -// source: auth.proto - -package magistrala - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// If a token is not carrying any information itself, the type -// field can be used to determine how to validate the token. -// Also, different tokens can be encoded in different ways. -type Token struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - AccessToken string `protobuf:"bytes,1,opt,name=accessToken,proto3" json:"accessToken,omitempty"` - RefreshToken *string `protobuf:"bytes,2,opt,name=refreshToken,proto3,oneof" json:"refreshToken,omitempty"` - AccessType string `protobuf:"bytes,3,opt,name=accessType,proto3" json:"accessType,omitempty"` -} - -func (x *Token) Reset() { - *x = Token{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Token) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Token) ProtoMessage() {} - -func (x *Token) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Token.ProtoReflect.Descriptor instead. -func (*Token) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{0} -} - -func (x *Token) GetAccessToken() string { - if x != nil { - return x.AccessToken - } - return "" -} - -func (x *Token) GetRefreshToken() string { - if x != nil && x.RefreshToken != nil { - return *x.RefreshToken - } - return "" -} - -func (x *Token) GetAccessType() string { - if x != nil { - return x.AccessType - } - return "" -} - -type IdentityReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` -} - -func (x *IdentityReq) Reset() { - *x = IdentityReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *IdentityReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*IdentityReq) ProtoMessage() {} - -func (x *IdentityReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use IdentityReq.ProtoReflect.Descriptor instead. -func (*IdentityReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{1} -} - -func (x *IdentityReq) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -type IdentityRes struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` -} - -func (x *IdentityRes) Reset() { - *x = IdentityRes{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *IdentityRes) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*IdentityRes) ProtoMessage() {} - -func (x *IdentityRes) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use IdentityRes.ProtoReflect.Descriptor instead. -func (*IdentityRes) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{2} -} - -func (x *IdentityRes) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -type IssueReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Type uint32 `protobuf:"varint,3,opt,name=type,proto3" json:"type,omitempty"` -} - -func (x *IssueReq) Reset() { - *x = IssueReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *IssueReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*IssueReq) ProtoMessage() {} - -func (x *IssueReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use IssueReq.ProtoReflect.Descriptor instead. -func (*IssueReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{3} -} - -func (x *IssueReq) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *IssueReq) GetType() uint32 { - if x != nil { - return x.Type - } - return 0 -} - -type LoginReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Domain string `protobuf:"bytes,3,opt,name=domain,proto3" json:"domain,omitempty"` -} - -func (x *LoginReq) Reset() { - *x = LoginReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *LoginReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*LoginReq) ProtoMessage() {} - -func (x *LoginReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use LoginReq.ProtoReflect.Descriptor instead. -func (*LoginReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{4} -} - -func (x *LoginReq) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *LoginReq) GetDomain() string { - if x != nil { - return x.Domain - } - return "" -} - -type RefreshReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` -} - -func (x *RefreshReq) Reset() { - *x = RefreshReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *RefreshReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RefreshReq) ProtoMessage() {} - -func (x *RefreshReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RefreshReq.ProtoReflect.Descriptor instead. -func (*RefreshReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{5} -} - -func (x *RefreshReq) GetValue() string { - if x != nil { - return x.Value - } - return "" -} - -type AuthorizeReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` // Namespace = Domain - SubjectType string `protobuf:"bytes,2,opt,name=subject_type,json=subjectType,proto3" json:"subject_type,omitempty"` // Thing or User - SubjectKind string `protobuf:"bytes,3,opt,name=subject_kind,json=subjectKind,proto3" json:"subject_kind,omitempty"` // ID or Token - SubjectRelation string `protobuf:"bytes,4,opt,name=subject_relation,json=subjectRelation,proto3" json:"subject_relation,omitempty"` // Subject relation - Subject string `protobuf:"bytes,5,opt,name=subject,proto3" json:"subject,omitempty"` // Subject value (id or token, depending on kind) - Relation string `protobuf:"bytes,6,opt,name=relation,proto3" json:"relation,omitempty"` // Relation to filter - Permission string `protobuf:"bytes,7,opt,name=permission,proto3" json:"permission,omitempty"` // Action - Object string `protobuf:"bytes,8,opt,name=object,proto3" json:"object,omitempty"` // Object ID - ObjectType string `protobuf:"bytes,9,opt,name=object_type,json=objectType,proto3" json:"object_type,omitempty"` // Thing, User, Group -} - -func (x *AuthorizeReq) Reset() { - *x = AuthorizeReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *AuthorizeReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AuthorizeReq) ProtoMessage() {} - -func (x *AuthorizeReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AuthorizeReq.ProtoReflect.Descriptor instead. -func (*AuthorizeReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{6} -} - -func (x *AuthorizeReq) GetNamespace() string { - if x != nil { - return x.Namespace - } - return "" -} - -func (x *AuthorizeReq) GetSubjectType() string { - if x != nil { - return x.SubjectType - } - return "" -} - -func (x *AuthorizeReq) GetSubjectKind() string { - if x != nil { - return x.SubjectKind - } - return "" -} - -func (x *AuthorizeReq) GetSubjectRelation() string { - if x != nil { - return x.SubjectRelation - } - return "" -} - -func (x *AuthorizeReq) GetSubject() string { - if x != nil { - return x.Subject - } - return "" -} - -func (x *AuthorizeReq) GetRelation() string { - if x != nil { - return x.Relation - } - return "" -} - -func (x *AuthorizeReq) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -func (x *AuthorizeReq) GetObject() string { - if x != nil { - return x.Object - } - return "" -} - -func (x *AuthorizeReq) GetObjectType() string { - if x != nil { - return x.ObjectType - } - return "" -} - -type AuthorizeRes struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Authorized bool `protobuf:"varint,1,opt,name=authorized,proto3" json:"authorized,omitempty"` - Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` -} - -func (x *AuthorizeRes) Reset() { - *x = AuthorizeRes{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *AuthorizeRes) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AuthorizeRes) ProtoMessage() {} - -func (x *AuthorizeRes) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[7] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AuthorizeRes.ProtoReflect.Descriptor instead. -func (*AuthorizeRes) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{7} -} - -func (x *AuthorizeRes) GetAuthorized() bool { - if x != nil { - return x.Authorized - } - return false -} - -func (x *AuthorizeRes) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -type AddPolicyReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - SubjectType string `protobuf:"bytes,2,opt,name=subject_type,json=subjectType,proto3" json:"subject_type,omitempty"` - SubjectRelation string `protobuf:"bytes,3,opt,name=subject_relation,json=subjectRelation,proto3" json:"subject_relation,omitempty"` - Subject string `protobuf:"bytes,4,opt,name=subject,proto3" json:"subject,omitempty"` - Relation string `protobuf:"bytes,5,opt,name=relation,proto3" json:"relation,omitempty"` - Permission string `protobuf:"bytes,6,opt,name=permission,proto3" json:"permission,omitempty"` - Object string `protobuf:"bytes,7,opt,name=object,proto3" json:"object,omitempty"` - ObjectType string `protobuf:"bytes,8,opt,name=object_type,json=objectType,proto3" json:"object_type,omitempty"` -} - -func (x *AddPolicyReq) Reset() { - *x = AddPolicyReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *AddPolicyReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AddPolicyReq) ProtoMessage() {} - -func (x *AddPolicyReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[8] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AddPolicyReq.ProtoReflect.Descriptor instead. -func (*AddPolicyReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{8} -} - -func (x *AddPolicyReq) GetNamespace() string { - if x != nil { - return x.Namespace - } - return "" -} - -func (x *AddPolicyReq) GetSubjectType() string { - if x != nil { - return x.SubjectType - } - return "" -} - -func (x *AddPolicyReq) GetSubjectRelation() string { - if x != nil { - return x.SubjectRelation - } - return "" -} - -func (x *AddPolicyReq) GetSubject() string { - if x != nil { - return x.Subject - } - return "" -} - -func (x *AddPolicyReq) GetRelation() string { - if x != nil { - return x.Relation - } - return "" -} - -func (x *AddPolicyReq) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -func (x *AddPolicyReq) GetObject() string { - if x != nil { - return x.Object - } - return "" -} - -func (x *AddPolicyReq) GetObjectType() string { - if x != nil { - return x.ObjectType - } - return "" -} - -type AddPolicyRes struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Authorized bool `protobuf:"varint,1,opt,name=authorized,proto3" json:"authorized,omitempty"` -} - -func (x *AddPolicyRes) Reset() { - *x = AddPolicyRes{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *AddPolicyRes) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AddPolicyRes) ProtoMessage() {} - -func (x *AddPolicyRes) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[9] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AddPolicyRes.ProtoReflect.Descriptor instead. -func (*AddPolicyRes) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{9} -} - -func (x *AddPolicyRes) GetAuthorized() bool { - if x != nil { - return x.Authorized - } - return false -} - -type DeletePolicyReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - SubjectType string `protobuf:"bytes,2,opt,name=subject_type,json=subjectType,proto3" json:"subject_type,omitempty"` - SubjectRelation string `protobuf:"bytes,3,opt,name=subject_relation,json=subjectRelation,proto3" json:"subject_relation,omitempty"` - Subject string `protobuf:"bytes,4,opt,name=subject,proto3" json:"subject,omitempty"` - Relation string `protobuf:"bytes,5,opt,name=relation,proto3" json:"relation,omitempty"` - Permission string `protobuf:"bytes,6,opt,name=permission,proto3" json:"permission,omitempty"` - Object string `protobuf:"bytes,7,opt,name=object,proto3" json:"object,omitempty"` - ObjectType string `protobuf:"bytes,8,opt,name=object_type,json=objectType,proto3" json:"object_type,omitempty"` -} - -func (x *DeletePolicyReq) Reset() { - *x = DeletePolicyReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[10] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *DeletePolicyReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*DeletePolicyReq) ProtoMessage() {} - -func (x *DeletePolicyReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[10] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use DeletePolicyReq.ProtoReflect.Descriptor instead. -func (*DeletePolicyReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{10} -} - -func (x *DeletePolicyReq) GetNamespace() string { - if x != nil { - return x.Namespace - } - return "" -} - -func (x *DeletePolicyReq) GetSubjectType() string { - if x != nil { - return x.SubjectType - } - return "" -} - -func (x *DeletePolicyReq) GetSubjectRelation() string { - if x != nil { - return x.SubjectRelation - } - return "" -} - -func (x *DeletePolicyReq) GetSubject() string { - if x != nil { - return x.Subject - } - return "" -} - -func (x *DeletePolicyReq) GetRelation() string { - if x != nil { - return x.Relation - } - return "" -} - -func (x *DeletePolicyReq) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -func (x *DeletePolicyReq) GetObject() string { - if x != nil { - return x.Object - } - return "" -} - -func (x *DeletePolicyReq) GetObjectType() string { - if x != nil { - return x.ObjectType - } - return "" -} - -type DeletePolicyRes struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Deleted bool `protobuf:"varint,1,opt,name=deleted,proto3" json:"deleted,omitempty"` -} - -func (x *DeletePolicyRes) Reset() { - *x = DeletePolicyRes{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[11] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *DeletePolicyRes) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*DeletePolicyRes) ProtoMessage() {} - -func (x *DeletePolicyRes) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[11] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use DeletePolicyRes.ProtoReflect.Descriptor instead. -func (*DeletePolicyRes) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{11} -} - -func (x *DeletePolicyRes) GetDeleted() bool { - if x != nil { - return x.Deleted - } - return false -} - -type ListObjectsReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - SubjectType string `protobuf:"bytes,2,opt,name=subject_type,json=subjectType,proto3" json:"subject_type,omitempty"` - SubjectRelation string `protobuf:"bytes,3,opt,name=subject_relation,json=subjectRelation,proto3" json:"subject_relation,omitempty"` - Subject string `protobuf:"bytes,4,opt,name=subject,proto3" json:"subject,omitempty"` - Relation string `protobuf:"bytes,5,opt,name=relation,proto3" json:"relation,omitempty"` - Permission string `protobuf:"bytes,6,opt,name=permission,proto3" json:"permission,omitempty"` - Object string `protobuf:"bytes,7,opt,name=object,proto3" json:"object,omitempty"` - ObjectType string `protobuf:"bytes,8,opt,name=object_type,json=objectType,proto3" json:"object_type,omitempty"` - NextPageToken string `protobuf:"bytes,9,opt,name=nextPageToken,proto3" json:"nextPageToken,omitempty"` - Limit int32 `protobuf:"varint,10,opt,name=limit,proto3" json:"limit,omitempty"` -} - -func (x *ListObjectsReq) Reset() { - *x = ListObjectsReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[12] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ListObjectsReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListObjectsReq) ProtoMessage() {} - -func (x *ListObjectsReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[12] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ListObjectsReq.ProtoReflect.Descriptor instead. -func (*ListObjectsReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{12} -} - -func (x *ListObjectsReq) GetNamespace() string { - if x != nil { - return x.Namespace - } - return "" -} - -func (x *ListObjectsReq) GetSubjectType() string { - if x != nil { - return x.SubjectType - } - return "" -} - -func (x *ListObjectsReq) GetSubjectRelation() string { - if x != nil { - return x.SubjectRelation - } - return "" -} - -func (x *ListObjectsReq) GetSubject() string { - if x != nil { - return x.Subject - } - return "" -} - -func (x *ListObjectsReq) GetRelation() string { - if x != nil { - return x.Relation - } - return "" -} - -func (x *ListObjectsReq) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -func (x *ListObjectsReq) GetObject() string { - if x != nil { - return x.Object - } - return "" -} - -func (x *ListObjectsReq) GetObjectType() string { - if x != nil { - return x.ObjectType - } - return "" -} - -func (x *ListObjectsReq) GetNextPageToken() string { - if x != nil { - return x.NextPageToken - } - return "" -} - -func (x *ListObjectsReq) GetLimit() int32 { - if x != nil { - return x.Limit - } - return 0 -} - -type ListObjectsRes struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Policies []string `protobuf:"bytes,1,rep,name=policies,proto3" json:"policies,omitempty"` - NextPageToken string `protobuf:"bytes,2,opt,name=nextPageToken,proto3" json:"nextPageToken,omitempty"` -} - -func (x *ListObjectsRes) Reset() { - *x = ListObjectsRes{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[13] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ListObjectsRes) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListObjectsRes) ProtoMessage() {} - -func (x *ListObjectsRes) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[13] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ListObjectsRes.ProtoReflect.Descriptor instead. -func (*ListObjectsRes) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{13} -} - -func (x *ListObjectsRes) GetPolicies() []string { - if x != nil { - return x.Policies - } - return nil -} - -func (x *ListObjectsRes) GetNextPageToken() string { - if x != nil { - return x.NextPageToken - } - return "" -} - -type CountObjectsReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - SubjectType string `protobuf:"bytes,2,opt,name=subject_type,json=subjectType,proto3" json:"subject_type,omitempty"` - SubjectRelation string `protobuf:"bytes,3,opt,name=subject_relation,json=subjectRelation,proto3" json:"subject_relation,omitempty"` - Subject string `protobuf:"bytes,4,opt,name=subject,proto3" json:"subject,omitempty"` - Relation string `protobuf:"bytes,5,opt,name=relation,proto3" json:"relation,omitempty"` - Permission string `protobuf:"bytes,6,opt,name=permission,proto3" json:"permission,omitempty"` - Object string `protobuf:"bytes,7,opt,name=object,proto3" json:"object,omitempty"` - ObjectType string `protobuf:"bytes,8,opt,name=object_type,json=objectType,proto3" json:"object_type,omitempty"` - NextPageToken string `protobuf:"bytes,9,opt,name=nextPageToken,proto3" json:"nextPageToken,omitempty"` -} - -func (x *CountObjectsReq) Reset() { - *x = CountObjectsReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[14] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CountObjectsReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CountObjectsReq) ProtoMessage() {} - -func (x *CountObjectsReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[14] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CountObjectsReq.ProtoReflect.Descriptor instead. -func (*CountObjectsReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{14} -} - -func (x *CountObjectsReq) GetNamespace() string { - if x != nil { - return x.Namespace - } - return "" -} - -func (x *CountObjectsReq) GetSubjectType() string { - if x != nil { - return x.SubjectType - } - return "" -} - -func (x *CountObjectsReq) GetSubjectRelation() string { - if x != nil { - return x.SubjectRelation - } - return "" -} - -func (x *CountObjectsReq) GetSubject() string { - if x != nil { - return x.Subject - } - return "" -} - -func (x *CountObjectsReq) GetRelation() string { - if x != nil { - return x.Relation - } - return "" -} - -func (x *CountObjectsReq) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -func (x *CountObjectsReq) GetObject() string { - if x != nil { - return x.Object - } - return "" -} - -func (x *CountObjectsReq) GetObjectType() string { - if x != nil { - return x.ObjectType - } - return "" -} - -func (x *CountObjectsReq) GetNextPageToken() string { - if x != nil { - return x.NextPageToken - } - return "" -} - -type CountObjectsRes struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Count int64 `protobuf:"varint,1,opt,name=count,proto3" json:"count,omitempty"` -} - -func (x *CountObjectsRes) Reset() { - *x = CountObjectsRes{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[15] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CountObjectsRes) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CountObjectsRes) ProtoMessage() {} - -func (x *CountObjectsRes) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[15] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CountObjectsRes.ProtoReflect.Descriptor instead. -func (*CountObjectsRes) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{15} -} - -func (x *CountObjectsRes) GetCount() int64 { - if x != nil { - return x.Count - } - return 0 -} - -type ListSubjectsReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - SubjectType string `protobuf:"bytes,2,opt,name=subject_type,json=subjectType,proto3" json:"subject_type,omitempty"` - SubjectRelation string `protobuf:"bytes,3,opt,name=subject_relation,json=subjectRelation,proto3" json:"subject_relation,omitempty"` - Subject string `protobuf:"bytes,4,opt,name=subject,proto3" json:"subject,omitempty"` - Relation string `protobuf:"bytes,5,opt,name=relation,proto3" json:"relation,omitempty"` - Permission string `protobuf:"bytes,6,opt,name=permission,proto3" json:"permission,omitempty"` - Object string `protobuf:"bytes,7,opt,name=object,proto3" json:"object,omitempty"` - ObjectType string `protobuf:"bytes,8,opt,name=object_type,json=objectType,proto3" json:"object_type,omitempty"` - NextPageToken string `protobuf:"bytes,9,opt,name=nextPageToken,proto3" json:"nextPageToken,omitempty"` - Limit int32 `protobuf:"varint,10,opt,name=limit,proto3" json:"limit,omitempty"` -} - -func (x *ListSubjectsReq) Reset() { - *x = ListSubjectsReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[16] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ListSubjectsReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListSubjectsReq) ProtoMessage() {} - -func (x *ListSubjectsReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[16] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ListSubjectsReq.ProtoReflect.Descriptor instead. -func (*ListSubjectsReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{16} -} - -func (x *ListSubjectsReq) GetNamespace() string { - if x != nil { - return x.Namespace - } - return "" -} - -func (x *ListSubjectsReq) GetSubjectType() string { - if x != nil { - return x.SubjectType - } - return "" -} - -func (x *ListSubjectsReq) GetSubjectRelation() string { - if x != nil { - return x.SubjectRelation - } - return "" -} - -func (x *ListSubjectsReq) GetSubject() string { - if x != nil { - return x.Subject - } - return "" -} - -func (x *ListSubjectsReq) GetRelation() string { - if x != nil { - return x.Relation - } - return "" -} - -func (x *ListSubjectsReq) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -func (x *ListSubjectsReq) GetObject() string { - if x != nil { - return x.Object - } - return "" -} - -func (x *ListSubjectsReq) GetObjectType() string { - if x != nil { - return x.ObjectType - } - return "" -} - -func (x *ListSubjectsReq) GetNextPageToken() string { - if x != nil { - return x.NextPageToken - } - return "" -} - -func (x *ListSubjectsReq) GetLimit() int32 { - if x != nil { - return x.Limit - } - return 0 -} - -type ListSubjectsRes struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Policies []string `protobuf:"bytes,1,rep,name=policies,proto3" json:"policies,omitempty"` - NextPageToken string `protobuf:"bytes,2,opt,name=nextPageToken,proto3" json:"nextPageToken,omitempty"` -} - -func (x *ListSubjectsRes) Reset() { - *x = ListSubjectsRes{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[17] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ListSubjectsRes) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListSubjectsRes) ProtoMessage() {} - -func (x *ListSubjectsRes) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[17] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ListSubjectsRes.ProtoReflect.Descriptor instead. -func (*ListSubjectsRes) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{17} -} - -func (x *ListSubjectsRes) GetPolicies() []string { - if x != nil { - return x.Policies - } - return nil -} - -func (x *ListSubjectsRes) GetNextPageToken() string { - if x != nil { - return x.NextPageToken - } - return "" -} - -type CountSubjectsReq struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - SubjectType string `protobuf:"bytes,2,opt,name=subject_type,json=subjectType,proto3" json:"subject_type,omitempty"` - SubjectRelation string `protobuf:"bytes,3,opt,name=subject_relation,json=subjectRelation,proto3" json:"subject_relation,omitempty"` - Subject string `protobuf:"bytes,4,opt,name=subject,proto3" json:"subject,omitempty"` - Relation string `protobuf:"bytes,5,opt,name=relation,proto3" json:"relation,omitempty"` - Permission string `protobuf:"bytes,6,opt,name=permission,proto3" json:"permission,omitempty"` - Object string `protobuf:"bytes,7,opt,name=object,proto3" json:"object,omitempty"` - ObjectType string `protobuf:"bytes,8,opt,name=object_type,json=objectType,proto3" json:"object_type,omitempty"` - NextPageToken string `protobuf:"bytes,9,opt,name=nextPageToken,proto3" json:"nextPageToken,omitempty"` -} - -func (x *CountSubjectsReq) Reset() { - *x = CountSubjectsReq{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[18] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CountSubjectsReq) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CountSubjectsReq) ProtoMessage() {} - -func (x *CountSubjectsReq) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[18] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CountSubjectsReq.ProtoReflect.Descriptor instead. -func (*CountSubjectsReq) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{18} -} - -func (x *CountSubjectsReq) GetNamespace() string { - if x != nil { - return x.Namespace - } - return "" -} - -func (x *CountSubjectsReq) GetSubjectType() string { - if x != nil { - return x.SubjectType - } - return "" -} - -func (x *CountSubjectsReq) GetSubjectRelation() string { - if x != nil { - return x.SubjectRelation - } - return "" -} - -func (x *CountSubjectsReq) GetSubject() string { - if x != nil { - return x.Subject - } - return "" -} - -func (x *CountSubjectsReq) GetRelation() string { - if x != nil { - return x.Relation - } - return "" -} - -func (x *CountSubjectsReq) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -func (x *CountSubjectsReq) GetObject() string { - if x != nil { - return x.Object - } - return "" -} - -func (x *CountSubjectsReq) GetObjectType() string { - if x != nil { - return x.ObjectType - } - return "" -} - -func (x *CountSubjectsReq) GetNextPageToken() string { - if x != nil { - return x.NextPageToken - } - return "" -} - -type CountSubjectsRes struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Count int64 `protobuf:"varint,1,opt,name=count,proto3" json:"count,omitempty"` -} - -func (x *CountSubjectsRes) Reset() { - *x = CountSubjectsRes{} - if protoimpl.UnsafeEnabled { - mi := &file_auth_proto_msgTypes[19] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CountSubjectsRes) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CountSubjectsRes) ProtoMessage() {} - -func (x *CountSubjectsRes) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[19] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CountSubjectsRes.ProtoReflect.Descriptor instead. -func (*CountSubjectsRes) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{19} -} - -func (x *CountSubjectsRes) GetCount() int64 { - if x != nil { - return x.Count - } - return 0 -} - -var File_auth_proto protoreflect.FileDescriptor - -var file_auth_proto_rawDesc = []byte{ - 0x0a, 0x0a, 0x61, 0x75, 0x74, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x6d, 0x61, - 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x22, 0x83, 0x01, 0x0a, 0x05, 0x54, 0x6f, 0x6b, - 0x65, 0x6e, 0x12, 0x20, 0x0a, 0x0b, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x54, 0x6f, 0x6b, 0x65, - 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x54, - 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x27, 0x0a, 0x0c, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, - 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x0c, 0x72, 0x65, - 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x88, 0x01, 0x01, 0x12, 0x1e, 0x0a, - 0x0a, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x54, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x0a, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x54, 0x79, 0x70, 0x65, 0x42, 0x0f, 0x0a, - 0x0d, 0x5f, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x23, - 0x0a, 0x0b, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, - 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, - 0x6b, 0x65, 0x6e, 0x22, 0x1d, 0x0a, 0x0b, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x52, - 0x65, 0x73, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, - 0x69, 0x64, 0x22, 0x2e, 0x0a, 0x08, 0x49, 0x73, 0x73, 0x75, 0x65, 0x52, 0x65, 0x71, 0x12, 0x0e, - 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, - 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x04, 0x74, 0x79, - 0x70, 0x65, 0x22, 0x32, 0x0a, 0x08, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x12, 0x0e, - 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, - 0x0a, 0x06, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, - 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x22, 0x22, 0x0a, 0x0a, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, - 0x68, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xac, 0x02, 0x0a, 0x0c, 0x41, - 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x12, 0x1c, 0x0a, 0x09, 0x6e, - 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, - 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x75, 0x62, - 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x0b, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x21, 0x0a, 0x0c, - 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x6b, 0x69, 0x6e, 0x64, 0x18, 0x03, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x0b, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x4b, 0x69, 0x6e, 0x64, 0x12, - 0x29, 0x0a, 0x10, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x72, 0x65, 0x6c, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x73, 0x75, 0x62, 0x6a, 0x65, - 0x63, 0x74, 0x52, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, - 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x75, 0x62, - 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x07, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, - 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x6f, 0x62, 0x6a, 0x65, - 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x6f, - 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x22, 0x3e, 0x0a, 0x0c, 0x41, 0x75, 0x74, - 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x61, 0x75, 0x74, - 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x61, - 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x22, 0x89, 0x02, 0x0a, 0x0c, 0x41, 0x64, - 0x64, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x52, 0x65, 0x71, 0x12, 0x1c, 0x0a, 0x09, 0x6e, 0x61, - 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, - 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x75, 0x62, 0x6a, - 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, - 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x73, - 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, - 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, - 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, - 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, - 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a, - 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, - 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6f, 0x62, - 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, - 0x79, 0x70, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x6f, 0x62, 0x6a, 0x65, 0x63, - 0x74, 0x54, 0x79, 0x70, 0x65, 0x22, 0x2e, 0x0a, 0x0c, 0x41, 0x64, 0x64, 0x50, 0x6f, 0x6c, 0x69, - 0x63, 0x79, 0x52, 0x65, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, - 0x7a, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x61, 0x75, 0x74, 0x68, 0x6f, - 0x72, 0x69, 0x7a, 0x65, 0x64, 0x22, 0x8c, 0x02, 0x0a, 0x0f, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, - 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x52, 0x65, 0x71, 0x12, 0x1c, 0x0a, 0x09, 0x6e, 0x61, 0x6d, - 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x61, - 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x75, 0x62, 0x6a, 0x65, - 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x73, - 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x73, 0x75, - 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x6c, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, - 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x08, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a, 0x70, - 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x6f, - 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6f, 0x62, 0x6a, - 0x65, 0x63, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, - 0x70, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, - 0x54, 0x79, 0x70, 0x65, 0x22, 0x2b, 0x0a, 0x0f, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x6f, - 0x6c, 0x69, 0x63, 0x79, 0x52, 0x65, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x64, 0x65, 0x6c, 0x65, 0x74, - 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x65, - 0x64, 0x22, 0xc7, 0x02, 0x0a, 0x0e, 0x4c, 0x69, 0x73, 0x74, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, - 0x73, 0x52, 0x65, 0x71, 0x12, 0x1c, 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, - 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, - 0x63, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, - 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, - 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, - 0x5f, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x0f, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, - 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, - 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, - 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x65, 0x72, 0x6d, - 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, - 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1f, - 0x0a, 0x0b, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x08, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x0a, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, - 0x24, 0x0a, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, - 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, - 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x0a, - 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x22, 0x52, 0x0a, 0x0e, 0x4c, - 0x69, 0x73, 0x74, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x73, 0x12, 0x1a, 0x0a, - 0x08, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, - 0x08, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x12, 0x24, 0x0a, 0x0d, 0x6e, 0x65, 0x78, - 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, - 0xb2, 0x02, 0x0a, 0x0f, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, - 0x52, 0x65, 0x71, 0x12, 0x1c, 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, - 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, - 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, - 0x54, 0x79, 0x70, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, - 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, - 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, - 0x18, 0x0a, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x6c, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, 0x6c, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, - 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, - 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, - 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1f, 0x0a, - 0x0b, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x08, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x0a, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x24, - 0x0a, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x18, - 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, - 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x27, 0x0a, 0x0f, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x4f, 0x62, 0x6a, - 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0xc8, 0x02, - 0x0a, 0x0f, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, - 0x71, 0x12, 0x1c, 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, - 0x21, 0x0a, 0x0c, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, - 0x70, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x72, 0x65, - 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x73, 0x75, - 0x62, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, - 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, - 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x6c, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, 0x6c, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, - 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, - 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x07, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x6f, - 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x0a, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x24, 0x0a, 0x0d, - 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x09, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, - 0x65, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, - 0x05, 0x52, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x22, 0x53, 0x0a, 0x0f, 0x4c, 0x69, 0x73, 0x74, - 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x73, 0x12, 0x1a, 0x0a, 0x08, 0x70, - 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x08, 0x70, - 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x12, 0x24, 0x0a, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, - 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, - 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0xb3, 0x02, - 0x0a, 0x10, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, - 0x65, 0x71, 0x12, 0x1c, 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, - 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, - 0x79, 0x70, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x72, - 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x73, - 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, - 0x0a, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x6c, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, 0x6c, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, - 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, - 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x07, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1f, 0x0a, 0x0b, - 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x0a, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x24, 0x0a, - 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x09, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, - 0x6b, 0x65, 0x6e, 0x22, 0x28, 0x0a, 0x10, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x53, 0x75, 0x62, 0x6a, - 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x32, 0x51, 0x0a, - 0x0c, 0x41, 0x75, 0x74, 0x68, 0x7a, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x41, 0x0a, - 0x09, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x12, 0x18, 0x2e, 0x6d, 0x61, 0x67, - 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, - 0x65, 0x52, 0x65, 0x71, 0x1a, 0x18, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, - 0x61, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x22, 0x00, - 0x32, 0x8a, 0x07, 0x0a, 0x0b, 0x41, 0x75, 0x74, 0x68, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, - 0x12, 0x32, 0x0a, 0x05, 0x49, 0x73, 0x73, 0x75, 0x65, 0x12, 0x14, 0x2e, 0x6d, 0x61, 0x67, 0x69, - 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x49, 0x73, 0x73, 0x75, 0x65, 0x52, 0x65, 0x71, 0x1a, - 0x11, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x54, 0x6f, 0x6b, - 0x65, 0x6e, 0x22, 0x00, 0x12, 0x32, 0x0a, 0x05, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x12, 0x14, 0x2e, - 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x4c, 0x6f, 0x67, 0x69, 0x6e, - 0x52, 0x65, 0x71, 0x1a, 0x11, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, - 0x2e, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x00, 0x12, 0x36, 0x0a, 0x07, 0x52, 0x65, 0x66, 0x72, - 0x65, 0x73, 0x68, 0x12, 0x16, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, - 0x2e, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x71, 0x1a, 0x11, 0x2e, 0x6d, 0x61, - 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x00, - 0x12, 0x3e, 0x0a, 0x08, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x79, 0x12, 0x17, 0x2e, 0x6d, - 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, - 0x74, 0x79, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, - 0x6c, 0x61, 0x2e, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x52, 0x65, 0x73, 0x22, 0x00, - 0x12, 0x41, 0x0a, 0x09, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x12, 0x18, 0x2e, - 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x6f, - 0x72, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x1a, 0x18, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, - 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x52, 0x65, - 0x73, 0x22, 0x00, 0x12, 0x41, 0x0a, 0x09, 0x41, 0x64, 0x64, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, - 0x12, 0x18, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x41, 0x64, - 0x64, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x52, 0x65, 0x71, 0x1a, 0x18, 0x2e, 0x6d, 0x61, 0x67, - 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x41, 0x64, 0x64, 0x50, 0x6f, 0x6c, 0x69, 0x63, - 0x79, 0x52, 0x65, 0x73, 0x22, 0x00, 0x12, 0x4a, 0x0a, 0x0c, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, - 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x1b, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, - 0x61, 0x6c, 0x61, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, - 0x52, 0x65, 0x71, 0x1a, 0x1b, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, - 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x52, 0x65, 0x73, - 0x22, 0x00, 0x12, 0x47, 0x0a, 0x0b, 0x4c, 0x69, 0x73, 0x74, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, - 0x73, 0x12, 0x1a, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x4c, - 0x69, 0x73, 0x74, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x71, 0x1a, 0x1a, 0x2e, - 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x4f, - 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x73, 0x22, 0x00, 0x12, 0x4a, 0x0a, 0x0e, 0x4c, - 0x69, 0x73, 0x74, 0x41, 0x6c, 0x6c, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x12, 0x1a, 0x2e, - 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x4f, - 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x71, 0x1a, 0x1a, 0x2e, 0x6d, 0x61, 0x67, 0x69, - 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x4f, 0x62, 0x6a, 0x65, 0x63, - 0x74, 0x73, 0x52, 0x65, 0x73, 0x22, 0x00, 0x12, 0x4a, 0x0a, 0x0c, 0x43, 0x6f, 0x75, 0x6e, 0x74, - 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x12, 0x1b, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, - 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, - 0x73, 0x52, 0x65, 0x71, 0x1a, 0x1b, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, - 0x61, 0x2e, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, - 0x73, 0x22, 0x00, 0x12, 0x4a, 0x0a, 0x0c, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x75, 0x62, 0x6a, 0x65, - 0x63, 0x74, 0x73, 0x12, 0x1b, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, - 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x71, - 0x1a, 0x1b, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x4c, 0x69, - 0x73, 0x74, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x73, 0x22, 0x00, 0x12, - 0x4d, 0x0a, 0x0f, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6c, 0x6c, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, - 0x74, 0x73, 0x12, 0x1b, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, - 0x4c, 0x69, 0x73, 0x74, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x71, 0x1a, - 0x1b, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x4c, 0x69, 0x73, - 0x74, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x73, 0x22, 0x00, 0x12, 0x4d, - 0x0a, 0x0d, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x12, - 0x1c, 0x2e, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x43, 0x6f, 0x75, - 0x6e, 0x74, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x71, 0x1a, 0x1c, 0x2e, - 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x2e, 0x43, 0x6f, 0x75, 0x6e, 0x74, - 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x52, 0x65, 0x73, 0x22, 0x00, 0x42, 0x0e, 0x5a, - 0x0c, 0x2e, 0x2f, 0x6d, 0x61, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x6c, 0x61, 0x62, 0x06, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_auth_proto_rawDescOnce sync.Once - file_auth_proto_rawDescData = file_auth_proto_rawDesc -) - -func file_auth_proto_rawDescGZIP() []byte { - file_auth_proto_rawDescOnce.Do(func() { - file_auth_proto_rawDescData = protoimpl.X.CompressGZIP(file_auth_proto_rawDescData) - }) - return file_auth_proto_rawDescData -} - -var file_auth_proto_msgTypes = make([]protoimpl.MessageInfo, 20) -var file_auth_proto_goTypes = []interface{}{ - (*Token)(nil), // 0: magistrala.Token - (*IdentityReq)(nil), // 1: magistrala.IdentityReq - (*IdentityRes)(nil), // 2: magistrala.IdentityRes - (*IssueReq)(nil), // 3: magistrala.IssueReq - (*LoginReq)(nil), // 4: magistrala.LoginReq - (*RefreshReq)(nil), // 5: magistrala.RefreshReq - (*AuthorizeReq)(nil), // 6: magistrala.AuthorizeReq - (*AuthorizeRes)(nil), // 7: magistrala.AuthorizeRes - (*AddPolicyReq)(nil), // 8: magistrala.AddPolicyReq - (*AddPolicyRes)(nil), // 9: magistrala.AddPolicyRes - (*DeletePolicyReq)(nil), // 10: magistrala.DeletePolicyReq - (*DeletePolicyRes)(nil), // 11: magistrala.DeletePolicyRes - (*ListObjectsReq)(nil), // 12: magistrala.ListObjectsReq - (*ListObjectsRes)(nil), // 13: magistrala.ListObjectsRes - (*CountObjectsReq)(nil), // 14: magistrala.CountObjectsReq - (*CountObjectsRes)(nil), // 15: magistrala.CountObjectsRes - (*ListSubjectsReq)(nil), // 16: magistrala.ListSubjectsReq - (*ListSubjectsRes)(nil), // 17: magistrala.ListSubjectsRes - (*CountSubjectsReq)(nil), // 18: magistrala.CountSubjectsReq - (*CountSubjectsRes)(nil), // 19: magistrala.CountSubjectsRes -} -var file_auth_proto_depIdxs = []int32{ - 6, // 0: magistrala.AuthzService.Authorize:input_type -> magistrala.AuthorizeReq - 3, // 1: magistrala.AuthService.Issue:input_type -> magistrala.IssueReq - 4, // 2: magistrala.AuthService.Login:input_type -> magistrala.LoginReq - 5, // 3: magistrala.AuthService.Refresh:input_type -> magistrala.RefreshReq - 1, // 4: magistrala.AuthService.Identify:input_type -> magistrala.IdentityReq - 6, // 5: magistrala.AuthService.Authorize:input_type -> magistrala.AuthorizeReq - 8, // 6: magistrala.AuthService.AddPolicy:input_type -> magistrala.AddPolicyReq - 10, // 7: magistrala.AuthService.DeletePolicy:input_type -> magistrala.DeletePolicyReq - 12, // 8: magistrala.AuthService.ListObjects:input_type -> magistrala.ListObjectsReq - 12, // 9: magistrala.AuthService.ListAllObjects:input_type -> magistrala.ListObjectsReq - 14, // 10: magistrala.AuthService.CountObjects:input_type -> magistrala.CountObjectsReq - 16, // 11: magistrala.AuthService.ListSubjects:input_type -> magistrala.ListSubjectsReq - 16, // 12: magistrala.AuthService.ListAllSubjects:input_type -> magistrala.ListSubjectsReq - 18, // 13: magistrala.AuthService.CountSubjects:input_type -> magistrala.CountSubjectsReq - 7, // 14: magistrala.AuthzService.Authorize:output_type -> magistrala.AuthorizeRes - 0, // 15: magistrala.AuthService.Issue:output_type -> magistrala.Token - 0, // 16: magistrala.AuthService.Login:output_type -> magistrala.Token - 0, // 17: magistrala.AuthService.Refresh:output_type -> magistrala.Token - 2, // 18: magistrala.AuthService.Identify:output_type -> magistrala.IdentityRes - 7, // 19: magistrala.AuthService.Authorize:output_type -> magistrala.AuthorizeRes - 9, // 20: magistrala.AuthService.AddPolicy:output_type -> magistrala.AddPolicyRes - 11, // 21: magistrala.AuthService.DeletePolicy:output_type -> magistrala.DeletePolicyRes - 13, // 22: magistrala.AuthService.ListObjects:output_type -> magistrala.ListObjectsRes - 13, // 23: magistrala.AuthService.ListAllObjects:output_type -> magistrala.ListObjectsRes - 15, // 24: magistrala.AuthService.CountObjects:output_type -> magistrala.CountObjectsRes - 17, // 25: magistrala.AuthService.ListSubjects:output_type -> magistrala.ListSubjectsRes - 17, // 26: magistrala.AuthService.ListAllSubjects:output_type -> magistrala.ListSubjectsRes - 19, // 27: magistrala.AuthService.CountSubjects:output_type -> magistrala.CountSubjectsRes - 14, // [14:28] is the sub-list for method output_type - 0, // [0:14] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_auth_proto_init() } -func file_auth_proto_init() { - if File_auth_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_auth_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Token); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*IdentityReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*IdentityRes); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*IssueReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*LoginReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*RefreshReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AuthorizeReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AuthorizeRes); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AddPolicyReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AddPolicyRes); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*DeletePolicyReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*DeletePolicyRes); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListObjectsReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListObjectsRes); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CountObjectsReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CountObjectsRes); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSubjectsReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSubjectsRes); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CountSubjectsReq); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_auth_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CountSubjectsRes); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - file_auth_proto_msgTypes[0].OneofWrappers = []interface{}{} - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_auth_proto_rawDesc, - NumEnums: 0, - NumMessages: 20, - NumExtensions: 0, - NumServices: 2, - }, - GoTypes: file_auth_proto_goTypes, - DependencyIndexes: file_auth_proto_depIdxs, - MessageInfos: file_auth_proto_msgTypes, - }.Build() - File_auth_proto = out.File - file_auth_proto_rawDesc = nil - file_auth_proto_goTypes = nil - file_auth_proto_depIdxs = nil -} diff --git a/vendor/github.com/absmach/magistrala/auth.proto b/vendor/github.com/absmach/magistrala/auth.proto deleted file mode 100644 index db97e78a..00000000 --- a/vendor/github.com/absmach/magistrala/auth.proto +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -syntax = "proto3"; - -package magistrala; -option go_package = "./magistrala"; - -// AuthzService is a service that provides authentication and authorization -// functionalities for the things service. -service AuthzService { - // Authorize checks if the subject is authorized to perform - // the action on the object. - rpc Authorize(AuthorizeReq) returns (AuthorizeRes) {} -} - -// AuthService is a service that provides authentication and authorization -// functionalities for the users service. -service AuthService { - rpc Issue(IssueReq) returns (Token) {} - rpc Login(LoginReq) returns (Token) {} - rpc Refresh(RefreshReq) returns (Token) {} - rpc Identify(IdentityReq) returns (IdentityRes) {} - rpc Authorize(AuthorizeReq) returns (AuthorizeRes) {} - rpc AddPolicy(AddPolicyReq) returns (AddPolicyRes) {} - rpc DeletePolicy(DeletePolicyReq) returns (DeletePolicyRes) {} - rpc ListObjects(ListObjectsReq) returns (ListObjectsRes) {} - rpc ListAllObjects(ListObjectsReq) returns (ListObjectsRes) {} - rpc CountObjects(CountObjectsReq) returns (CountObjectsRes) {} - rpc ListSubjects(ListSubjectsReq) returns (ListSubjectsRes) {} - rpc ListAllSubjects(ListSubjectsReq) returns (ListSubjectsRes) {} - rpc CountSubjects(CountSubjectsReq) returns (CountSubjectsRes) {} -} - -// If a token is not carrying any information itself, the type -// field can be used to determine how to validate the token. -// Also, different tokens can be encoded in different ways. -message Token { - string accessToken = 1; - optional string refreshToken = 2; - string accessType = 3; -} - -message IdentityReq { - string token = 1; -} - -message IdentityRes { - string id = 1; -} - -message IssueReq { - string id = 1; - uint32 type = 3; -} - -message LoginReq { - string id = 1; - string domain = 3; -} - -message RefreshReq { string value = 1; } - -message AuthorizeReq { - string namespace = 1; // Namespace = Domain - string subject_type = 2; // Thing or User - string subject_kind = 3; // ID or Token - string subject_relation = 4; // Subject relation - string subject = 5; // Subject value (id or token, depending on kind) - string relation = 6; // Relation to filter - string permission = 7; // Action - string object = 8; // Object ID - string object_type = 9; // Thing, User, Group -} - -message AuthorizeRes { - bool authorized = 1; - string id = 2; -} - -message AddPolicyReq { - string namespace = 1; - string subject_type = 2; - string subject_relation = 3; - string subject = 4; - string relation = 5; - string permission = 6; - string object = 7; - string object_type = 8; -} - -message AddPolicyRes { bool authorized = 1; } - -message DeletePolicyReq { - string namespace = 1; - string subject_type = 2; - string subject_relation = 3; - string subject = 4; - string relation = 5; - string permission = 6; - string object = 7; - string object_type = 8; -} - -message DeletePolicyRes { bool deleted = 1; } - -message ListObjectsReq { - string namespace = 1; - string subject_type = 2; - string subject_relation = 3; - string subject = 4; - string relation = 5; - string permission = 6; - string object = 7; - string object_type = 8; - string nextPageToken = 9; - int32 limit = 10; -} - -message ListObjectsRes { - repeated string policies = 1; - string nextPageToken = 2; -} - -message CountObjectsReq { - string namespace = 1; - string subject_type = 2; - string subject_relation = 3; - string subject = 4; - string relation = 5; - string permission = 6; - string object = 7; - string object_type = 8; - string nextPageToken = 9; -} - -message CountObjectsRes { int64 count = 1; } - -message ListSubjectsReq { - string namespace = 1; - string subject_type = 2; - string subject_relation = 3; - string subject = 4; - string relation = 5; - string permission = 6; - string object = 7; - string object_type = 8; - string nextPageToken = 9; - int32 limit = 10; -} - -message ListSubjectsRes { - repeated string policies = 1; - string nextPageToken = 2; -} - -message CountSubjectsReq { - string namespace = 1; - string subject_type = 2; - string subject_relation = 3; - string subject = 4; - string relation = 5; - string permission = 6; - string object = 7; - string object_type = 8; - string nextPageToken = 9; -} - -message CountSubjectsRes { int64 count = 1; } diff --git a/vendor/github.com/absmach/magistrala/auth_grpc.pb.go b/vendor/github.com/absmach/magistrala/auth_grpc.pb.go deleted file mode 100644 index 270466b0..00000000 --- a/vendor/github.com/absmach/magistrala/auth_grpc.pb.go +++ /dev/null @@ -1,650 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.3.0 -// - protoc v4.24.3 -// source: auth.proto - -package magistrala - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 - -const ( - AuthzService_Authorize_FullMethodName = "/magistrala.AuthzService/Authorize" -) - -// AuthzServiceClient is the client API for AuthzService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type AuthzServiceClient interface { - // Authorize checks if the subject is authorized to perform - // the action on the object. - Authorize(ctx context.Context, in *AuthorizeReq, opts ...grpc.CallOption) (*AuthorizeRes, error) -} - -type authzServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewAuthzServiceClient(cc grpc.ClientConnInterface) AuthzServiceClient { - return &authzServiceClient{cc} -} - -func (c *authzServiceClient) Authorize(ctx context.Context, in *AuthorizeReq, opts ...grpc.CallOption) (*AuthorizeRes, error) { - out := new(AuthorizeRes) - err := c.cc.Invoke(ctx, AuthzService_Authorize_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AuthzServiceServer is the server API for AuthzService service. -// All implementations must embed UnimplementedAuthzServiceServer -// for forward compatibility -type AuthzServiceServer interface { - // Authorize checks if the subject is authorized to perform - // the action on the object. - Authorize(context.Context, *AuthorizeReq) (*AuthorizeRes, error) - mustEmbedUnimplementedAuthzServiceServer() -} - -// UnimplementedAuthzServiceServer must be embedded to have forward compatible implementations. -type UnimplementedAuthzServiceServer struct { -} - -func (UnimplementedAuthzServiceServer) Authorize(context.Context, *AuthorizeReq) (*AuthorizeRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method Authorize not implemented") -} -func (UnimplementedAuthzServiceServer) mustEmbedUnimplementedAuthzServiceServer() {} - -// UnsafeAuthzServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to AuthzServiceServer will -// result in compilation errors. -type UnsafeAuthzServiceServer interface { - mustEmbedUnimplementedAuthzServiceServer() -} - -func RegisterAuthzServiceServer(s grpc.ServiceRegistrar, srv AuthzServiceServer) { - s.RegisterService(&AuthzService_ServiceDesc, srv) -} - -func _AuthzService_Authorize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AuthorizeReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthzServiceServer).Authorize(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthzService_Authorize_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthzServiceServer).Authorize(ctx, req.(*AuthorizeReq)) - } - return interceptor(ctx, in, info, handler) -} - -// AuthzService_ServiceDesc is the grpc.ServiceDesc for AuthzService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var AuthzService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "magistrala.AuthzService", - HandlerType: (*AuthzServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Authorize", - Handler: _AuthzService_Authorize_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "auth.proto", -} - -const ( - AuthService_Issue_FullMethodName = "/magistrala.AuthService/Issue" - AuthService_Login_FullMethodName = "/magistrala.AuthService/Login" - AuthService_Refresh_FullMethodName = "/magistrala.AuthService/Refresh" - AuthService_Identify_FullMethodName = "/magistrala.AuthService/Identify" - AuthService_Authorize_FullMethodName = "/magistrala.AuthService/Authorize" - AuthService_AddPolicy_FullMethodName = "/magistrala.AuthService/AddPolicy" - AuthService_DeletePolicy_FullMethodName = "/magistrala.AuthService/DeletePolicy" - AuthService_ListObjects_FullMethodName = "/magistrala.AuthService/ListObjects" - AuthService_ListAllObjects_FullMethodName = "/magistrala.AuthService/ListAllObjects" - AuthService_CountObjects_FullMethodName = "/magistrala.AuthService/CountObjects" - AuthService_ListSubjects_FullMethodName = "/magistrala.AuthService/ListSubjects" - AuthService_ListAllSubjects_FullMethodName = "/magistrala.AuthService/ListAllSubjects" - AuthService_CountSubjects_FullMethodName = "/magistrala.AuthService/CountSubjects" -) - -// AuthServiceClient is the client API for AuthService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type AuthServiceClient interface { - Issue(ctx context.Context, in *IssueReq, opts ...grpc.CallOption) (*Token, error) - Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*Token, error) - Refresh(ctx context.Context, in *RefreshReq, opts ...grpc.CallOption) (*Token, error) - Identify(ctx context.Context, in *IdentityReq, opts ...grpc.CallOption) (*IdentityRes, error) - Authorize(ctx context.Context, in *AuthorizeReq, opts ...grpc.CallOption) (*AuthorizeRes, error) - AddPolicy(ctx context.Context, in *AddPolicyReq, opts ...grpc.CallOption) (*AddPolicyRes, error) - DeletePolicy(ctx context.Context, in *DeletePolicyReq, opts ...grpc.CallOption) (*DeletePolicyRes, error) - ListObjects(ctx context.Context, in *ListObjectsReq, opts ...grpc.CallOption) (*ListObjectsRes, error) - ListAllObjects(ctx context.Context, in *ListObjectsReq, opts ...grpc.CallOption) (*ListObjectsRes, error) - CountObjects(ctx context.Context, in *CountObjectsReq, opts ...grpc.CallOption) (*CountObjectsRes, error) - ListSubjects(ctx context.Context, in *ListSubjectsReq, opts ...grpc.CallOption) (*ListSubjectsRes, error) - ListAllSubjects(ctx context.Context, in *ListSubjectsReq, opts ...grpc.CallOption) (*ListSubjectsRes, error) - CountSubjects(ctx context.Context, in *CountSubjectsReq, opts ...grpc.CallOption) (*CountSubjectsRes, error) -} - -type authServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewAuthServiceClient(cc grpc.ClientConnInterface) AuthServiceClient { - return &authServiceClient{cc} -} - -func (c *authServiceClient) Issue(ctx context.Context, in *IssueReq, opts ...grpc.CallOption) (*Token, error) { - out := new(Token) - err := c.cc.Invoke(ctx, AuthService_Issue_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*Token, error) { - out := new(Token) - err := c.cc.Invoke(ctx, AuthService_Login_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) Refresh(ctx context.Context, in *RefreshReq, opts ...grpc.CallOption) (*Token, error) { - out := new(Token) - err := c.cc.Invoke(ctx, AuthService_Refresh_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) Identify(ctx context.Context, in *IdentityReq, opts ...grpc.CallOption) (*IdentityRes, error) { - out := new(IdentityRes) - err := c.cc.Invoke(ctx, AuthService_Identify_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) Authorize(ctx context.Context, in *AuthorizeReq, opts ...grpc.CallOption) (*AuthorizeRes, error) { - out := new(AuthorizeRes) - err := c.cc.Invoke(ctx, AuthService_Authorize_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) AddPolicy(ctx context.Context, in *AddPolicyReq, opts ...grpc.CallOption) (*AddPolicyRes, error) { - out := new(AddPolicyRes) - err := c.cc.Invoke(ctx, AuthService_AddPolicy_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) DeletePolicy(ctx context.Context, in *DeletePolicyReq, opts ...grpc.CallOption) (*DeletePolicyRes, error) { - out := new(DeletePolicyRes) - err := c.cc.Invoke(ctx, AuthService_DeletePolicy_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) ListObjects(ctx context.Context, in *ListObjectsReq, opts ...grpc.CallOption) (*ListObjectsRes, error) { - out := new(ListObjectsRes) - err := c.cc.Invoke(ctx, AuthService_ListObjects_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) ListAllObjects(ctx context.Context, in *ListObjectsReq, opts ...grpc.CallOption) (*ListObjectsRes, error) { - out := new(ListObjectsRes) - err := c.cc.Invoke(ctx, AuthService_ListAllObjects_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) CountObjects(ctx context.Context, in *CountObjectsReq, opts ...grpc.CallOption) (*CountObjectsRes, error) { - out := new(CountObjectsRes) - err := c.cc.Invoke(ctx, AuthService_CountObjects_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) ListSubjects(ctx context.Context, in *ListSubjectsReq, opts ...grpc.CallOption) (*ListSubjectsRes, error) { - out := new(ListSubjectsRes) - err := c.cc.Invoke(ctx, AuthService_ListSubjects_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) ListAllSubjects(ctx context.Context, in *ListSubjectsReq, opts ...grpc.CallOption) (*ListSubjectsRes, error) { - out := new(ListSubjectsRes) - err := c.cc.Invoke(ctx, AuthService_ListAllSubjects_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) CountSubjects(ctx context.Context, in *CountSubjectsReq, opts ...grpc.CallOption) (*CountSubjectsRes, error) { - out := new(CountSubjectsRes) - err := c.cc.Invoke(ctx, AuthService_CountSubjects_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AuthServiceServer is the server API for AuthService service. -// All implementations must embed UnimplementedAuthServiceServer -// for forward compatibility -type AuthServiceServer interface { - Issue(context.Context, *IssueReq) (*Token, error) - Login(context.Context, *LoginReq) (*Token, error) - Refresh(context.Context, *RefreshReq) (*Token, error) - Identify(context.Context, *IdentityReq) (*IdentityRes, error) - Authorize(context.Context, *AuthorizeReq) (*AuthorizeRes, error) - AddPolicy(context.Context, *AddPolicyReq) (*AddPolicyRes, error) - DeletePolicy(context.Context, *DeletePolicyReq) (*DeletePolicyRes, error) - ListObjects(context.Context, *ListObjectsReq) (*ListObjectsRes, error) - ListAllObjects(context.Context, *ListObjectsReq) (*ListObjectsRes, error) - CountObjects(context.Context, *CountObjectsReq) (*CountObjectsRes, error) - ListSubjects(context.Context, *ListSubjectsReq) (*ListSubjectsRes, error) - ListAllSubjects(context.Context, *ListSubjectsReq) (*ListSubjectsRes, error) - CountSubjects(context.Context, *CountSubjectsReq) (*CountSubjectsRes, error) - mustEmbedUnimplementedAuthServiceServer() -} - -// UnimplementedAuthServiceServer must be embedded to have forward compatible implementations. -type UnimplementedAuthServiceServer struct { -} - -func (UnimplementedAuthServiceServer) Issue(context.Context, *IssueReq) (*Token, error) { - return nil, status.Errorf(codes.Unimplemented, "method Issue not implemented") -} -func (UnimplementedAuthServiceServer) Login(context.Context, *LoginReq) (*Token, error) { - return nil, status.Errorf(codes.Unimplemented, "method Login not implemented") -} -func (UnimplementedAuthServiceServer) Refresh(context.Context, *RefreshReq) (*Token, error) { - return nil, status.Errorf(codes.Unimplemented, "method Refresh not implemented") -} -func (UnimplementedAuthServiceServer) Identify(context.Context, *IdentityReq) (*IdentityRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method Identify not implemented") -} -func (UnimplementedAuthServiceServer) Authorize(context.Context, *AuthorizeReq) (*AuthorizeRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method Authorize not implemented") -} -func (UnimplementedAuthServiceServer) AddPolicy(context.Context, *AddPolicyReq) (*AddPolicyRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method AddPolicy not implemented") -} -func (UnimplementedAuthServiceServer) DeletePolicy(context.Context, *DeletePolicyReq) (*DeletePolicyRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method DeletePolicy not implemented") -} -func (UnimplementedAuthServiceServer) ListObjects(context.Context, *ListObjectsReq) (*ListObjectsRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method ListObjects not implemented") -} -func (UnimplementedAuthServiceServer) ListAllObjects(context.Context, *ListObjectsReq) (*ListObjectsRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method ListAllObjects not implemented") -} -func (UnimplementedAuthServiceServer) CountObjects(context.Context, *CountObjectsReq) (*CountObjectsRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method CountObjects not implemented") -} -func (UnimplementedAuthServiceServer) ListSubjects(context.Context, *ListSubjectsReq) (*ListSubjectsRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method ListSubjects not implemented") -} -func (UnimplementedAuthServiceServer) ListAllSubjects(context.Context, *ListSubjectsReq) (*ListSubjectsRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method ListAllSubjects not implemented") -} -func (UnimplementedAuthServiceServer) CountSubjects(context.Context, *CountSubjectsReq) (*CountSubjectsRes, error) { - return nil, status.Errorf(codes.Unimplemented, "method CountSubjects not implemented") -} -func (UnimplementedAuthServiceServer) mustEmbedUnimplementedAuthServiceServer() {} - -// UnsafeAuthServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to AuthServiceServer will -// result in compilation errors. -type UnsafeAuthServiceServer interface { - mustEmbedUnimplementedAuthServiceServer() -} - -func RegisterAuthServiceServer(s grpc.ServiceRegistrar, srv AuthServiceServer) { - s.RegisterService(&AuthService_ServiceDesc, srv) -} - -func _AuthService_Issue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(IssueReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).Issue(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_Issue_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).Issue(ctx, req.(*IssueReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(LoginReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).Login(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_Login_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).Login(ctx, req.(*LoginReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_Refresh_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RefreshReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).Refresh(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_Refresh_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).Refresh(ctx, req.(*RefreshReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_Identify_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(IdentityReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).Identify(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_Identify_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).Identify(ctx, req.(*IdentityReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_Authorize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AuthorizeReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).Authorize(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_Authorize_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).Authorize(ctx, req.(*AuthorizeReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_AddPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AddPolicyReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).AddPolicy(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_AddPolicy_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).AddPolicy(ctx, req.(*AddPolicyReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_DeletePolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeletePolicyReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).DeletePolicy(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_DeletePolicy_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).DeletePolicy(ctx, req.(*DeletePolicyReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_ListObjects_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListObjectsReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).ListObjects(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_ListObjects_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).ListObjects(ctx, req.(*ListObjectsReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_ListAllObjects_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListObjectsReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).ListAllObjects(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_ListAllObjects_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).ListAllObjects(ctx, req.(*ListObjectsReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_CountObjects_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CountObjectsReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).CountObjects(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_CountObjects_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).CountObjects(ctx, req.(*CountObjectsReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_ListSubjects_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListSubjectsReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).ListSubjects(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_ListSubjects_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).ListSubjects(ctx, req.(*ListSubjectsReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_ListAllSubjects_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListSubjectsReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).ListAllSubjects(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_ListAllSubjects_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).ListAllSubjects(ctx, req.(*ListSubjectsReq)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_CountSubjects_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CountSubjectsReq) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).CountSubjects(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_CountSubjects_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).CountSubjects(ctx, req.(*CountSubjectsReq)) - } - return interceptor(ctx, in, info, handler) -} - -// AuthService_ServiceDesc is the grpc.ServiceDesc for AuthService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var AuthService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "magistrala.AuthService", - HandlerType: (*AuthServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Issue", - Handler: _AuthService_Issue_Handler, - }, - { - MethodName: "Login", - Handler: _AuthService_Login_Handler, - }, - { - MethodName: "Refresh", - Handler: _AuthService_Refresh_Handler, - }, - { - MethodName: "Identify", - Handler: _AuthService_Identify_Handler, - }, - { - MethodName: "Authorize", - Handler: _AuthService_Authorize_Handler, - }, - { - MethodName: "AddPolicy", - Handler: _AuthService_AddPolicy_Handler, - }, - { - MethodName: "DeletePolicy", - Handler: _AuthService_DeletePolicy_Handler, - }, - { - MethodName: "ListObjects", - Handler: _AuthService_ListObjects_Handler, - }, - { - MethodName: "ListAllObjects", - Handler: _AuthService_ListAllObjects_Handler, - }, - { - MethodName: "CountObjects", - Handler: _AuthService_CountObjects_Handler, - }, - { - MethodName: "ListSubjects", - Handler: _AuthService_ListSubjects_Handler, - }, - { - MethodName: "ListAllSubjects", - Handler: _AuthService_ListAllSubjects_Handler, - }, - { - MethodName: "CountSubjects", - Handler: _AuthService_CountSubjects_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "auth.proto", -} diff --git a/vendor/github.com/absmach/magistrala/bootstrap/README.md b/vendor/github.com/absmach/magistrala/bootstrap/README.md deleted file mode 100644 index c3f71087..00000000 --- a/vendor/github.com/absmach/magistrala/bootstrap/README.md +++ /dev/null @@ -1,125 +0,0 @@ -# BOOTSTRAP SERVICE - -New devices need to be configured properly and connected to the Magistrala. Bootstrap service is used in order to accomplish that. This service provides the following features: - -1. Creating new Magistrala Things -2. Providing basic configuration for the newly created Things -3. Enabling/disabling Things - -Pre-provisioning a new Thing is as simple as sending Configuration data to the Bootstrap service. Once the Thing is online, it sends a request for initial config to Bootstrap service. Bootstrap service provides an API for enabling and disabling Things. Only enabled Things can exchange messages over Magistrala. Bootstrapping does not implicitly enable Things, it has to be done manually. - -In order to bootstrap successfully, the Thing needs to send bootstrapping request to the specific URL, as well as a secret key. This key and URL are pre-provisioned during the manufacturing process. If the Thing is provisioned on the Bootstrap service side, the corresponding configuration will be sent as a response. Otherwise, the Thing will be saved so that it can be provisioned later. - -## Thing Configuration Entity - -Thing Configuration consists of two logical parts: the custom configuration that can be interpreted by the Thing itself and Magistrala-related configuration. Magistrala config contains: - -1. corresponding Magistrala Thing ID -2. corresponding Magistrala Thing key -3. list of the Magistrala channels the Thing is connected to - -> Note: list of channels contains IDs of the Magistrala channels. These channels are _pre-provisioned_ on the Magistrala side and, unlike corresponding Magistrala Thing, Bootstrap service is not able to create Magistrala Channels. - -Enabling and disabling Thing (adding Thing to/from whitelist) is as simple as connecting corresponding Magistrala Thing to the given list of Channels. Configuration keeps _state_ of the Thing: - -| State | What it means | -| -------- | --------------------------------------------- | -| Inactive | Thing is created, but isn't enabled | -| Active | Thing is able to communicate using Magistrala | - -Switching between states `Active` and `Inactive` enables and disables Thing, respectively. - -Thing configuration also contains the so-called `external ID` and `external key`. An external ID is a unique identifier of corresponding Thing. For example, a device MAC address is a good choice for external ID. External key is a secret key that is used for authentication during the bootstrapping procedure. - -## Configuration - -The service is configured using the environment variables presented in the following table. Note that any unset variables will be replaced with their default values. - -| Variable | Description | Default | -| ----------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------- | -| MG_BOOTSTRAP_LOG_LEVEL | Log level for Bootstrap (debug, info, warn, error) | info | -| MG_BOOTSTRAP_DB_HOST | Database host address | localhost | -| MG_BOOTSTRAP_DB_PORT | Database host port | 5432 | -| MG_BOOTSTRAP_DB_USER | Database user | magistrala | -| MG_BOOTSTRAP_DB_PASS | Database password | magistrala | -| MG_BOOTSTRAP_DB_NAME | Name of the database used by the service | bootstrap | -| MG_BOOTSTRAP_DB_SSL_MODE | Database connection SSL mode (disable, require, verify-ca, verify-full) | disable | -| MG_BOOTSTRAP_DB_SSL_CERT | Path to the PEM encoded certificate file | | -| MG_BOOTSTRAP_DB_SSL_KEY | Path to the PEM encoded key file | | -| MG_BOOTSTRAP_DB_SSL_ROOT_CERT | Path to the PEM encoded root certificate file | | -| MG_BOOTSTRAP_ENCRYPT_KEY | Secret key for secure bootstrapping encryption | v7aT0HGxJxt2gULzr3RHwf4WIf6DusPphG5Ftm2bNCWD8mTpyr | -| MG_BOOTSTRAP_HTTP_HOST | Bootstrap service HTTP host | | -| MG_BOOTSTRAP_HTTP_PORT | Bootstrap service HTTP port | 9013 | -| MG_BOOTSTRAP_HTTP_SERVER_CERT | Path to server certificate in pem format | | -| MG_BOOTSTRAP_HTTP_SERVER_KEY | Path to server key in pem format | | -| MG_BOOTSTRAP_EVENT_CONSUMER | Bootstrap service event source consumer name | bootstrap | -| MG_BOOTSTRAP_ES_URL | Bootstrap service event source URL | localhost:6379 | -| MG_BOOTSTRAP_ES_PASS | Bootstrap service event source password | | -| MG_BOOTSTRAP_ES_DB | Bootstrap service event source database | 0 | -| MG_AUTH_GRPC_URL | Users service gRPC URL | localhost:7001 | -| MG_AUTH_GRPC_TIMEOUT | Users service gRPC request timeout in seconds | 1s | -| MG_AUTH_GRPC_CLIENT_TLS | Enable TLS for gRPC client | false | -| MG_AUTH_GRPC_CA_CERTS | CA certificates for gRPC client | | -| MG_THINGS_URL | Base url for Magistrala Things | http://localhost:9000 | -| MG_JAEGER_URL | Jaeger server URL | http://jaeger:14268/api/traces | -| MG_SEND_TELEMETRY | Send telemetry to magistrala call home server | true | -| MG_BOOTSTRAP_INSTANCE_ID | Bootstrap service instance ID | | - -## Deployment - -The service itself is distributed as Docker container. Check the [`boostrap`](https://github.com/absmach/magistrala/blob/master/docker/addons/bootstrap/docker-compose.yml#L32-L56) service section in -docker-compose to see how service is deployed. - -To start the service outside of the container, execute the following shell script: - -```bash -# download the latest version of the service -git clone https://github.com/absmach/magistrala - -cd magistrala - -# compile the service -make bootstrap - -# copy binary to bin -make install - -# set the environment variables and run the service -MG_BOOTSTRAP_LOG_LEVEL=[Bootstrap log level] \ -MG_BOOTSTRAP_ENCRYPT_KEY=[Hex-encoded encryption key used for secure bootstrap] \ -MG_BOOTSTRAP_EVENT_CONSUMER=[Bootstrap service event source consumer name] \ -MG_BOOTSTRAP_ES_URL=[Bootstrap service event source URL] \ -MG_BOOTSTRAP_ES_PASS=[Bootstrap service event source password] \ -MG_BOOTSTRAP_ES_DB=[Bootstrap service event source database] \ -MG_BOOTSTRAP_HTTP_HOST=[Bootstrap service HTTP host] \ -MG_BOOTSTRAP_HTTP_PORT=[Bootstrap service HTTP port] \ -MG_BOOTSTRAP_HTTP_SERVER_CERT=[Path to HTTP server certificate in pem format] \ -MG_BOOTSTRAP_HTTP_SERVER_KEY=[Path to HTTP server key in pem format] \ -MG_BOOTSTRAP_DB_HOST=[Database host address] \ -MG_BOOTSTRAP_DB_PORT=[Database host port] \ -MG_BOOTSTRAP_DB_USER=[Database user] \ -MG_BOOTSTRAP_DB_PASS=[Database password] \ -MG_BOOTSTRAP_DB_NAME=[Name of the database used by the service] \ -MG_BOOTSTRAP_DB_SSL_MODE=[SSL mode to connect to the database with] \ -MG_BOOTSTRAP_DB_SSL_CERT=[Path to the PEM encoded certificate file] \ -MG_BOOTSTRAP_DB_SSL_KEY=[Path to the PEM encoded key file] \ -MG_BOOTSTRAP_DB_SSL_ROOT_CERT=[Path to the PEM encoded root certificate file] \ -MG_AUTH_GRPC_URL=[Users service gRPC URL] \ -MG_AUTH_GRPC_TIMEOUT=[Users service gRPC request timeout in seconds] \ -MG_AUTH_GRPC_CLIENT_TLS=[Boolean value to enable/disable client TLS] \ -MG_AUTH_GRPC_CA_CERT=[Path to trusted CAs in PEM format] \ -MG_THINGS_URL=[Base url for Magistrala Things] \ -MG_JAEGER_URL=[Jaeger server URL] \ -MG_SEND_TELEMETRY=[Send telemetry to magistrala call home server] \ -MG_BOOTSTRAP_INSTANCE_ID=[Bootstrap instance ID] \ -$GOBIN/magistrala-bootstrap -``` - -Setting `MG_BOOTSTRAP_CA_CERTS` expects a file in PEM format of trusted CAs. This will enable TLS against the Users gRPC endpoint trusting only those CAs that are provided. - -## Usage - -For more information about service capabilities and its usage, please check out -the [API documentation](https://api.mainflux.io/?urls.primaryName=bootstrap-openapi.yml). - -[doc]: https://docs.mainflux.io diff --git a/vendor/github.com/absmach/magistrala/bootstrap/configs.go b/vendor/github.com/absmach/magistrala/bootstrap/configs.go deleted file mode 100644 index 63cdcfb7..00000000 --- a/vendor/github.com/absmach/magistrala/bootstrap/configs.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package bootstrap - -import ( - "context" - "time" - - "github.com/absmach/magistrala/pkg/clients" -) - -// Config represents Configuration entity. It wraps information about external entity -// as well as info about corresponding Magistrala entities. -// MGThing represents corresponding Magistrala Thing ID. -// MGKey is key of corresponding Magistrala Thing. -// MGChannels is a list of Magistrala Channels corresponding Magistrala Thing connects to. -type Config struct { - ThingID string `json:"thing_id"` - Owner string `json:"owner,omitempty"` - Name string `json:"name,omitempty"` - ClientCert string `json:"client_cert,omitempty"` - ClientKey string `json:"client_key,omitempty"` - CACert string `json:"ca_cert,omitempty"` - ThingKey string `json:"thing_key"` - Channels []Channel `json:"channels,omitempty"` - ExternalID string `json:"external_id"` - ExternalKey string `json:"external_key"` - Content string `json:"content,omitempty"` - State State `json:"state"` -} - -// Channel represents Magistrala channel corresponding Magistrala Thing is connected to. -type Channel struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Metadata map[string]interface{} `json:"metadata,omitempty"` - Owner string `json:"owner_id"` - Parent string `json:"parent_id,omitempty"` - Description string `json:"description,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at,omitempty"` - UpdatedBy string `json:"updated_by,omitempty"` - Status clients.Status `json:"status"` -} - -// Filter is used for the search filters. -type Filter struct { - FullMatch map[string]string - PartialMatch map[string]string -} - -// ConfigsPage contains page related metadata as well as list of Configs that -// belong to this page. -type ConfigsPage struct { - Total uint64 `json:"total"` - Offset uint64 `json:"offset"` - Limit uint64 `json:"limit"` - Configs []Config `json:"configs"` -} - -// ConfigRepository specifies a Config persistence API. -type ConfigRepository interface { - // Save persists the Config. Successful operation is indicated by non-nil - // error response. - Save(ctx context.Context, cfg Config, chsConnIDs []string) (string, error) - - // RetrieveByID retrieves the Config having the provided identifier, that is owned - // by the specified user. - RetrieveByID(ctx context.Context, owner, id string) (Config, error) - - // RetrieveAll retrieves a subset of Configs that are owned - // by the specific user, with given filter parameters. - RetrieveAll(ctx context.Context, owner string, filter Filter, offset, limit uint64) ConfigsPage - - // RetrieveByExternalID returns Config for given external ID. - RetrieveByExternalID(ctx context.Context, externalID string) (Config, error) - - // Update updates an existing Config. A non-nil error is returned - // to indicate operation failure. - Update(ctx context.Context, cfg Config) error - - // UpdateCerts updates and returns an existing Config certificate and owner. - // A non-nil error is returned to indicate operation failure. - UpdateCert(ctx context.Context, owner, thingID, clientCert, clientKey, caCert string) (Config, error) - - // UpdateConnections updates a list of Channels the Config is connected to - // adding new Channels if needed. - UpdateConnections(ctx context.Context, owner, id string, channels []Channel, connections []string) error - - // Remove removes the Config having the provided identifier, that is owned - // by the specified user. - Remove(ctx context.Context, owner, id string) error - - // ChangeState changes of the Config, that is owned by the specific user. - ChangeState(ctx context.Context, owner, id string, state State) error - - // ListExisting retrieves those channels from the given list that exist in DB. - ListExisting(ctx context.Context, owner string, ids []string) ([]Channel, error) - - // Methods RemoveThing, UpdateChannel, and RemoveChannel are related to - // event sourcing. That's why these methods surpass ownership check. - - // RemoveThing removes Config of the Thing with the given ID. - RemoveThing(ctx context.Context, id string) error - - // UpdateChannel updates channel with the given ID. - UpdateChannel(ctx context.Context, c Channel) error - - // RemoveChannel removes channel with the given ID. - RemoveChannel(ctx context.Context, id string) error - - // DisconnectHandler changes state of the Config when the corresponding Thing is - // disconnected from the Channel. - DisconnectThing(ctx context.Context, channelID, thingID string) error -} diff --git a/vendor/github.com/absmach/magistrala/bootstrap/doc.go b/vendor/github.com/absmach/magistrala/bootstrap/doc.go deleted file mode 100644 index da5866a5..00000000 --- a/vendor/github.com/absmach/magistrala/bootstrap/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Package bootstrap contains the domain concept definitions needed to support -// Magistrala bootstrap service functionality. -package bootstrap diff --git a/vendor/github.com/absmach/magistrala/bootstrap/reader.go b/vendor/github.com/absmach/magistrala/bootstrap/reader.go deleted file mode 100644 index a61a9c71..00000000 --- a/vendor/github.com/absmach/magistrala/bootstrap/reader.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package bootstrap - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "encoding/json" - "io" - "net/http" -) - -// bootstrapRes represent Magistrala Response to the Bootatrap request. -// This is used as a response from ConfigReader and can easily be -// replace with any other response format. -type bootstrapRes struct { - ThingID string `json:"thing_id"` - ThingKey string `json:"thing_key"` - Channels []channelRes `json:"channels"` - Content string `json:"content,omitempty"` - ClientCert string `json:"client_cert,omitempty"` - ClientKey string `json:"client_key,omitempty"` - CACert string `json:"ca_cert,omitempty"` -} - -type channelRes struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Metadata interface{} `json:"metadata,omitempty"` -} - -func (res bootstrapRes) Code() int { - return http.StatusOK -} - -func (res bootstrapRes) Headers() map[string]string { - return map[string]string{} -} - -func (res bootstrapRes) Empty() bool { - return false -} - -type reader struct { - encKey []byte -} - -// NewConfigReader return new reader which is used to generate response -// from the config. -func NewConfigReader(encKey []byte) ConfigReader { - return reader{encKey: encKey} -} - -func (r reader) ReadConfig(cfg Config, secure bool) (interface{}, error) { - var channels []channelRes - for _, ch := range cfg.Channels { - channels = append(channels, channelRes{ID: ch.ID, Name: ch.Name, Metadata: ch.Metadata}) - } - - res := bootstrapRes{ - ThingKey: cfg.ThingKey, - ThingID: cfg.ThingID, - Channels: channels, - Content: cfg.Content, - ClientCert: cfg.ClientCert, - ClientKey: cfg.ClientKey, - CACert: cfg.CACert, - } - if secure { - b, err := json.Marshal(res) - if err != nil { - return nil, err - } - return r.encrypt(b) - } - - return res, nil -} - -func (r reader) encrypt(in []byte) ([]byte, error) { - block, err := aes.NewCipher(r.encKey) - if err != nil { - return nil, err - } - ciphertext := make([]byte, aes.BlockSize+len(in)) - iv := ciphertext[:aes.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - return nil, err - } - stream := cipher.NewCFBEncrypter(block, iv) - stream.XORKeyStream(ciphertext[aes.BlockSize:], in) - return ciphertext, nil -} diff --git a/vendor/github.com/absmach/magistrala/bootstrap/service.go b/vendor/github.com/absmach/magistrala/bootstrap/service.go deleted file mode 100644 index 7900314d..00000000 --- a/vendor/github.com/absmach/magistrala/bootstrap/service.go +++ /dev/null @@ -1,486 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package bootstrap - -import ( - "context" - "crypto/aes" - "crypto/cipher" - "encoding/hex" - "time" - - "github.com/absmach/magistrala" - "github.com/absmach/magistrala/pkg/errors" - mgsdk "github.com/absmach/magistrala/pkg/sdk/go" -) - -var ( - // ErrThings indicates failure to communicate with Magistrala Things service. - // It can be due to networking error or invalid/unauthenticated request. - ErrThings = errors.New("failed to receive response from Things service") - - // ErrExternalKey indicates a non-existent bootstrap configuration for given external key. - ErrExternalKey = errors.New("failed to get bootstrap configuration for given external key") - - // ErrExternalKeySecure indicates error in getting bootstrap configuration for given encrypted external key. - ErrExternalKeySecure = errors.New("failed to get bootstrap configuration for given encrypted external key") - - // ErrBootstrap indicates error in getting bootstrap configuration. - ErrBootstrap = errors.New("failed to read bootstrap configuration") - - errAddBootstrap = errors.New("failed to add bootstrap configuration") - errUpdateConnections = errors.New("failed to update connections") - errRemoveBootstrap = errors.New("failed to remove bootstrap configuration") - errChangeState = errors.New("failed to change state of bootstrap configuration") - errUpdateChannel = errors.New("failed to update channel") - errRemoveConfig = errors.New("failed to remove bootstrap configuration") - errRemoveChannel = errors.New("failed to remove channel") - errCreateThing = errors.New("failed to create thing") - errDisconnectThing = errors.New("failed to disconnect thing") - errCheckChannels = errors.New("failed to check if channels exists") - errConnectionChannels = errors.New("failed to check channels connections") - errThingNotFound = errors.New("failed to find thing") - errUpdateCert = errors.New("failed to update cert") -) - -var _ Service = (*bootstrapService)(nil) - -// Service specifies an API that must be fulfilled by the domain service -// implementation, and all of its decorators (e.g. logging & metrics). -type Service interface { - // Add adds new Thing Config to the user identified by the provided token. - Add(ctx context.Context, token string, cfg Config) (Config, error) - - // View returns Thing Config with given ID belonging to the user identified by the given token. - View(ctx context.Context, token, id string) (Config, error) - - // Update updates editable fields of the provided Config. - Update(ctx context.Context, token string, cfg Config) error - - // UpdateCert updates an existing Config certificate and token. - // A non-nil error is returned to indicate operation failure. - UpdateCert(ctx context.Context, token, thingID, clientCert, clientKey, caCert string) (Config, error) - - // UpdateConnections updates list of Channels related to given Config. - UpdateConnections(ctx context.Context, token, id string, connections []string) error - - // List returns subset of Configs with given search params that belong to the - // user identified by the given token. - List(ctx context.Context, token string, filter Filter, offset, limit uint64) (ConfigsPage, error) - - // Remove removes Config with specified token that belongs to the user identified by the given token. - Remove(ctx context.Context, token, id string) error - - // Bootstrap returns Config to the Thing with provided external ID using external key. - Bootstrap(ctx context.Context, externalKey, externalID string, secure bool) (Config, error) - - // ChangeState changes state of the Thing with given ID and owner. - ChangeState(ctx context.Context, token, id string, state State) error - - // Methods RemoveConfig, UpdateChannel, and RemoveChannel are used as - // handlers for events. That's why these methods surpass ownership check. - - // UpdateChannelHandler updates Channel with data received from an event. - UpdateChannelHandler(ctx context.Context, channel Channel) error - - // RemoveConfigHandler removes Configuration with id received from an event. - RemoveConfigHandler(ctx context.Context, id string) error - - // RemoveChannelHandler removes Channel with id received from an event. - RemoveChannelHandler(ctx context.Context, id string) error - - // DisconnectHandler changes state of the Config when connect/disconnect event occurs. - DisconnectThingHandler(ctx context.Context, channelID, thingID string) error -} - -// ConfigReader is used to parse Config into format which will be encoded -// as a JSON and consumed from the client side. The purpose of this interface -// is to provide convenient way to generate custom configuration response -// based on the specific Config which will be consumed by the client. -type ConfigReader interface { - ReadConfig(Config, bool) (interface{}, error) -} - -type bootstrapService struct { - auth magistrala.AuthServiceClient - configs ConfigRepository - sdk mgsdk.SDK - encKey []byte -} - -// New returns new Bootstrap service. -func New(auth magistrala.AuthServiceClient, configs ConfigRepository, sdk mgsdk.SDK, encKey []byte) Service { - return &bootstrapService{ - configs: configs, - sdk: sdk, - auth: auth, - encKey: encKey, - } -} - -func (bs bootstrapService) Add(ctx context.Context, token string, cfg Config) (Config, error) { - owner, err := bs.identify(ctx, token) - if err != nil { - return Config{}, err - } - - toConnect := bs.toIDList(cfg.Channels) - - // Check if channels exist. This is the way to prevent fetching channels that already exist. - existing, err := bs.configs.ListExisting(ctx, owner, toConnect) - if err != nil { - return Config{}, errors.Wrap(errCheckChannels, err) - } - - cfg.Channels, err = bs.connectionChannels(toConnect, bs.toIDList(existing), token) - - if err != nil { - return Config{}, errors.Wrap(errConnectionChannels, err) - } - - id := cfg.ThingID - mgThing, err := bs.thing(id, token) - if err != nil { - return Config{}, errors.Wrap(errThingNotFound, err) - } - - cfg.ThingID = mgThing.ID - cfg.Owner = owner - cfg.State = Inactive - cfg.ThingKey = mgThing.Credentials.Secret - - saved, err := bs.configs.Save(ctx, cfg, toConnect) - if err != nil { - if id == "" { - if _, errT := bs.sdk.DisableThing(cfg.ThingID, token); errT != nil { - err = errors.Wrap(err, errT) - } - } - return Config{}, errors.Wrap(errAddBootstrap, err) - } - - cfg.ThingID = saved - cfg.Channels = append(cfg.Channels, existing...) - - return cfg, nil -} - -func (bs bootstrapService) View(ctx context.Context, token, id string) (Config, error) { - owner, err := bs.identify(ctx, token) - if err != nil { - return Config{}, err - } - - return bs.configs.RetrieveByID(ctx, owner, id) -} - -func (bs bootstrapService) Update(ctx context.Context, token string, cfg Config) error { - owner, err := bs.identify(ctx, token) - if err != nil { - return err - } - - cfg.Owner = owner - - return bs.configs.Update(ctx, cfg) -} - -func (bs bootstrapService) UpdateCert(ctx context.Context, token, thingID, clientCert, clientKey, caCert string) (Config, error) { - owner, err := bs.identify(ctx, token) - if err != nil { - return Config{}, err - } - cfg, err := bs.configs.UpdateCert(ctx, owner, thingID, clientCert, clientKey, caCert) - if err != nil { - return Config{}, errors.Wrap(errUpdateCert, err) - } - return cfg, nil -} - -func (bs bootstrapService) UpdateConnections(ctx context.Context, token, id string, connections []string) error { - owner, err := bs.identify(ctx, token) - if err != nil { - return err - } - - cfg, err := bs.configs.RetrieveByID(ctx, owner, id) - if err != nil { - return errors.Wrap(errUpdateConnections, err) - } - - add, remove := bs.updateList(cfg, connections) - - // Check if channels exist. This is the way to prevent fetching channels that already exist. - existing, err := bs.configs.ListExisting(ctx, owner, connections) - if err != nil { - return errors.Wrap(errUpdateConnections, err) - } - - channels, err := bs.connectionChannels(connections, bs.toIDList(existing), token) - if err != nil { - return errors.Wrap(errUpdateConnections, err) - } - - cfg.Channels = channels - var connect, disconnect []string - - if cfg.State == Active { - connect = add - disconnect = remove - } - - for _, c := range disconnect { - if err := bs.sdk.DisconnectThing(id, c, token); err != nil { - if errors.Contains(err, errors.ErrNotFound) { - continue - } - return ErrThings - } - } - - for _, c := range connect { - conIDs := mgsdk.Connection{ - ChannelID: c, - ThingID: id, - } - if err := bs.sdk.Connect(conIDs, token); err != nil { - return ErrThings - } - } - - return bs.configs.UpdateConnections(ctx, owner, id, channels, connections) -} - -func (bs bootstrapService) List(ctx context.Context, token string, filter Filter, offset, limit uint64) (ConfigsPage, error) { - owner, err := bs.identify(ctx, token) - if err != nil { - return ConfigsPage{}, err - } - - return bs.configs.RetrieveAll(ctx, owner, filter, offset, limit), nil -} - -func (bs bootstrapService) Remove(ctx context.Context, token, id string) error { - owner, err := bs.identify(ctx, token) - if err != nil { - return err - } - if err := bs.configs.Remove(ctx, owner, id); err != nil { - return errors.Wrap(errRemoveBootstrap, err) - } - return nil -} - -func (bs bootstrapService) Bootstrap(ctx context.Context, externalKey, externalID string, secure bool) (Config, error) { - cfg, err := bs.configs.RetrieveByExternalID(ctx, externalID) - if err != nil { - return cfg, errors.Wrap(ErrBootstrap, err) - } - if secure { - dec, err := bs.dec(externalKey) - if err != nil { - return Config{}, errors.Wrap(ErrExternalKeySecure, err) - } - externalKey = dec - } - if cfg.ExternalKey != externalKey { - return Config{}, ErrExternalKey - } - - return cfg, nil -} - -func (bs bootstrapService) ChangeState(ctx context.Context, token, id string, state State) error { - owner, err := bs.identify(ctx, token) - if err != nil { - return err - } - - cfg, err := bs.configs.RetrieveByID(ctx, owner, id) - if err != nil { - return errors.Wrap(errChangeState, err) - } - - if cfg.State == state { - return nil - } - - switch state { - case Active: - for _, c := range cfg.Channels { - conIDs := mgsdk.Connection{ - ChannelID: c.ID, - ThingID: cfg.ThingID, - } - if err := bs.sdk.Connect(conIDs, token); err != nil { - return ErrThings - } - } - case Inactive: - for _, c := range cfg.Channels { - if err := bs.sdk.DisconnectThing(cfg.ThingID, c.ID, token); err != nil { - if errors.Contains(err, errors.ErrNotFound) { - continue - } - return ErrThings - } - } - } - if err := bs.configs.ChangeState(ctx, owner, id, state); err != nil { - return errors.Wrap(errChangeState, err) - } - return nil -} - -func (bs bootstrapService) UpdateChannelHandler(ctx context.Context, channel Channel) error { - if err := bs.configs.UpdateChannel(ctx, channel); err != nil { - return errors.Wrap(errUpdateChannel, err) - } - return nil -} - -func (bs bootstrapService) RemoveConfigHandler(ctx context.Context, id string) error { - if err := bs.configs.RemoveThing(ctx, id); err != nil { - return errors.Wrap(errRemoveConfig, err) - } - return nil -} - -func (bs bootstrapService) RemoveChannelHandler(ctx context.Context, id string) error { - if err := bs.configs.RemoveChannel(ctx, id); err != nil { - return errors.Wrap(errRemoveChannel, err) - } - return nil -} - -func (bs bootstrapService) DisconnectThingHandler(ctx context.Context, channelID, thingID string) error { - if err := bs.configs.DisconnectThing(ctx, channelID, thingID); err != nil { - return errors.Wrap(errDisconnectThing, err) - } - return nil -} - -func (bs bootstrapService) identify(ctx context.Context, token string) (string, error) { - ctx, cancel := context.WithTimeout(ctx, time.Second) - defer cancel() - - res, err := bs.auth.Identify(ctx, &magistrala.IdentityReq{Token: token}) - if err != nil { - return "", errors.ErrAuthentication - } - - return res.GetId(), nil -} - -// Method thing retrieves Magistrala Thing creating one if an empty ID is passed. -func (bs bootstrapService) thing(id, token string) (mgsdk.Thing, error) { - var thing mgsdk.Thing - var err error - var sdkErr errors.SDKError - - thing.ID = id - if id == "" { - thing, sdkErr = bs.sdk.CreateThing(mgsdk.Thing{}, token) - if err != nil { - return mgsdk.Thing{}, errors.Wrap(errCreateThing, errors.New(sdkErr.Err().Msg())) - } - } - - thing, sdkErr = bs.sdk.Thing(thing.ID, token) - if sdkErr != nil { - err = errors.New(sdkErr.Error()) - if id != "" { - if _, sdkErr2 := bs.sdk.DisableThing(thing.ID, token); sdkErr2 != nil { - err = errors.Wrap(errors.New(sdkErr.Msg()), errors.New(sdkErr2.Msg())) - } - } - return mgsdk.Thing{}, errors.Wrap(ErrThings, err) - } - - return thing, nil -} - -func (bs bootstrapService) connectionChannels(channels, existing []string, token string) ([]Channel, error) { - add := make(map[string]bool, len(channels)) - for _, ch := range channels { - add[ch] = true - } - - for _, ch := range existing { - if add[ch] { - delete(add, ch) - } - } - - var ret []Channel - for id := range add { - ch, err := bs.sdk.Channel(id, token) - if err != nil { - return nil, errors.Wrap(errors.ErrMalformedEntity, err) - } - - ret = append(ret, Channel{ - ID: ch.ID, - Name: ch.Name, - Metadata: ch.Metadata, - }) - } - - return ret, nil -} - -// Method updateList accepts config and channel IDs and returns three lists: -// 1) IDs of Channels to be added -// 2) IDs of Channels to be removed -// 3) IDs of common Channels for these two configs. -func (bs bootstrapService) updateList(cfg Config, connections []string) (add, remove []string) { - disconnect := make(map[string]bool, len(cfg.Channels)) - for _, c := range cfg.Channels { - disconnect[c.ID] = true - } - - for _, c := range connections { - if disconnect[c] { - // Don't disconnect common elements. - delete(disconnect, c) - continue - } - // Connect new elements. - add = append(add, c) - } - - for v := range disconnect { - remove = append(remove, v) - } - - return -} - -func (bs bootstrapService) toIDList(channels []Channel) []string { - var ret []string - for _, ch := range channels { - ret = append(ret, ch.ID) - } - - return ret -} - -func (bs bootstrapService) dec(in string) (string, error) { - ciphertext, err := hex.DecodeString(in) - if err != nil { - return "", err - } - block, err := aes.NewCipher(bs.encKey) - if err != nil { - return "", err - } - if len(ciphertext) < aes.BlockSize { - return "", err - } - iv := ciphertext[:aes.BlockSize] - ciphertext = ciphertext[aes.BlockSize:] - stream := cipher.NewCFBDecrypter(block, iv) - stream.XORKeyStream(ciphertext, ciphertext) - return string(ciphertext), nil -} diff --git a/vendor/github.com/absmach/magistrala/bootstrap/state.go b/vendor/github.com/absmach/magistrala/bootstrap/state.go deleted file mode 100644 index eb058a9b..00000000 --- a/vendor/github.com/absmach/magistrala/bootstrap/state.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package bootstrap - -import "strconv" - -const ( - // Inactive Thing is created, but not able to exchange messages using Magistrala. - Inactive State = iota - // Active Thing is created, configured, and whitelisted. - Active -) - -// State represents corresponding Magistrala Thing state. The possible Config States -// as well as description of what that State represents are given in the table: -// | State | What it means | -// |----------+--------------------------------------------------------------------------------| -// | Inactive | Thing is created, but isn't able to communicate over Magistrala | -// | Active | Thing is able to communicate using Magistrala |. -type State int - -// String returns string representation of State. -func (s State) String() string { - return strconv.Itoa(int(s)) -} diff --git a/vendor/github.com/absmach/magistrala/config.toml b/vendor/github.com/absmach/magistrala/config.toml deleted file mode 100644 index b3159a58..00000000 --- a/vendor/github.com/absmach/magistrala/config.toml +++ /dev/null @@ -1,16 +0,0 @@ -raw_output = "" -user_token = "" - -[filter] - limit = "" - offset = "" - topic = "" - -[remotes] - bootstrap_url = "http://localhost:9013" - certs_url = "http://localhost:9019" - http_adapter_url = "http://localhost/http" - reader_url = "http://localhost:9009" - things_url = "http://localhost:9000" - tls_verification = false - users_url = "http://localhost:9002" diff --git a/vendor/github.com/absmach/magistrala/doc.go b/vendor/github.com/absmach/magistrala/doc.go deleted file mode 100644 index c5b93de6..00000000 --- a/vendor/github.com/absmach/magistrala/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// package magistrala acts as an umbrella package containing multiple different -// microservices and defines all shared domain concepts. -package magistrala diff --git a/vendor/github.com/absmach/magistrala/health.go b/vendor/github.com/absmach/magistrala/health.go deleted file mode 100644 index b7324de7..00000000 --- a/vendor/github.com/absmach/magistrala/health.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package magistrala - -import ( - "encoding/json" - "net/http" -) - -const ( - contentType = "Content-Type" - contentTypeJSON = "application/health+json" - svcStatus = "pass" - description = " service" -) - -var ( - // Version represents the last service git tag in git history. - // It's meant to be set using go build ldflags: - // -ldflags "-X 'github.com/absmach/magistrala.Version=0.0.0'". - Version = "0.0.0" - // Commit represents the service git commit hash. - // It's meant to be set using go build ldflags: - // -ldflags "-X 'github.com/absmach/magistrala.Commit=ffffffff'". - Commit = "ffffffff" - // BuildTime represetns the service build time. - // It's meant to be set using go build ldflags: - // -ldflags "-X 'github.com/absmach/magistrala.BuildTime=1970-01-01_00:00:00'". - BuildTime = "1970-01-01_00:00:00" -) - -// HealthInfo contains version endpoint response. -type HealthInfo struct { - // Status contains service status. - Status string `json:"status"` - - // Version contains current service version. - Version string `json:"version"` - - // Commit represents the git hash commit. - Commit string `json:"commit"` - - // Description contains service description. - Description string `json:"description"` - - // BuildTime contains service build time. - BuildTime string `json:"build_time"` - - // InstanceID contains the ID of the current service instance - InstanceID string `json:"instance_id"` -} - -// Health exposes an HTTP handler for retrieving service health. -func Health(service, instanceID string) http.HandlerFunc { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Add(contentType, contentTypeJSON) - if r.Method != http.MethodGet && r.Method != http.MethodHead { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - res := HealthInfo{ - Status: svcStatus, - Version: Version, - Commit: Commit, - Description: service + description, - BuildTime: BuildTime, - InstanceID: instanceID, - } - - w.WriteHeader(http.StatusOK) - - if err := json.NewEncoder(w).Encode(res); err != nil { - w.WriteHeader(http.StatusInternalServerError) - } - }) -} diff --git a/vendor/github.com/absmach/magistrala/internal/apiutil/errors.go b/vendor/github.com/absmach/magistrala/internal/apiutil/errors.go deleted file mode 100644 index b02c4f37..00000000 --- a/vendor/github.com/absmach/magistrala/internal/apiutil/errors.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package apiutil - -import "github.com/absmach/magistrala/pkg/errors" - -// Errors defined in this file are used by the LoggingErrorEncoder decorator -// to distinguish and log API request validation errors and avoid that service -// errors are logged twice. -var ( - // ErrValidation indicates that an error was returned by the API. - ErrValidation = errors.New("something went wrong with the request") - - // ErrBearerToken indicates missing or invalid bearer user token. - ErrBearerToken = errors.New("missing or invalid bearer user token") - - // ErrBearerKey indicates missing or invalid bearer entity key. - ErrBearerKey = errors.New("missing or invalid bearer entity key") - - // ErrMissingID indicates missing entity ID. - ErrMissingID = errors.New("missing entity id") - - // ErrInvalidAuthKey indicates invalid auth key. - ErrInvalidAuthKey = errors.New("invalid auth key") - - // ErrInvalidIDFormat indicates an invalid ID format. - ErrInvalidIDFormat = errors.New("invalid id format provided") - - // ErrNameSize indicates that name size exceeds the max. - ErrNameSize = errors.New("invalid name size") - - // ErrEmailSize indicates that email size exceeds the max. - ErrEmailSize = errors.New("invalid email size") - - // ErrInvalidStatus indicates an invalid user account status. - ErrInvalidStatus = errors.New("invalid user account status") - - // ErrInvalidRole indicates that an invalid role. - ErrInvalidRole = errors.New("invalid client role") - - // ErrLimitSize indicates that an invalid limit. - ErrLimitSize = errors.New("invalid limit size") - - // ErrOffsetSize indicates an invalid offset. - ErrOffsetSize = errors.New("invalid offset size") - - // ErrInvalidOrder indicates an invalid list order. - ErrInvalidOrder = errors.New("invalid list order provided") - - // ErrInvalidDirection indicates an invalid list direction. - ErrInvalidDirection = errors.New("invalid list direction provided") - - // ErrInvalidMemberKind indicates an invalid member kind. - ErrInvalidMemberKind = errors.New("invalid member kind") - - // ErrEmptyList indicates that entity data is empty. - ErrEmptyList = errors.New("empty list provided") - - // ErrMalformedPolicy indicates that policies are malformed. - ErrMalformedPolicy = errors.New("malfalmormed policy") - - // ErrMissingPolicySub indicates that policies are subject. - ErrMissingPolicySub = errors.New("malfalmormed policy subject") - - // ErrMissingPolicyObj indicates missing policies object. - ErrMissingPolicyObj = errors.New("malfalmormed policy object") - - // ErrMalformedPolicyAct indicates missing policies action. - ErrMalformedPolicyAct = errors.New("malfalmormed policy action") - - // ErrMissingCertData indicates missing cert data (ttl). - ErrMissingCertData = errors.New("missing certificate data") - - // ErrInvalidCertData indicates invalid cert data (ttl). - ErrInvalidCertData = errors.New("invalid certificate data") - - // ErrInvalidTopic indicates an invalid subscription topic. - ErrInvalidTopic = errors.New("invalid Subscription topic") - - // ErrInvalidContact indicates an invalid subscription contract. - ErrInvalidContact = errors.New("invalid Subscription contact") - - // ErrMissingEmail indicates missing email. - ErrMissingEmail = errors.New("missing email") - - // ErrMissingHost indicates missing host. - ErrMissingHost = errors.New("missing host") - - // ErrMissingPass indicates missing password. - ErrMissingPass = errors.New("missing password") - - // ErrMissingConfPass indicates missing conf password. - ErrMissingConfPass = errors.New("missing conf password") - - // ErrInvalidResetPass indicates an invalid reset password. - ErrInvalidResetPass = errors.New("invalid reset password") - - // ErrInvalidComparator indicates an invalid comparator. - ErrInvalidComparator = errors.New("invalid comparator") - - // ErrMissingMemberType indicates missing group member type. - ErrMissingMemberType = errors.New("missing group member type") - - // ErrMissingMemberKind indicates missing group member kind. - ErrMissingMemberKind = errors.New("missing group member kind") - - // ErrMissingRelation indicates missing relation. - ErrMissingRelation = errors.New("missing relation") - - // ErrInvalidAPIKey indicates an invalid API key type. - ErrInvalidAPIKey = errors.New("invalid api key type") - - // ErrMaxLevelExceeded indicates an invalid group level. - ErrMaxLevelExceeded = errors.New("invalid group level (should be lower than 5)") - - // ErrBootstrapState indicates an invalid boostrap state. - ErrBootstrapState = errors.New("invalid bootstrap state") - - // ErrMissingIdentity indicates missing entity Identity. - ErrMissingIdentity = errors.New("missing entity identity") - - // ErrMissingSecret indicates missing secret. - ErrMissingSecret = errors.New("missing secret") - - // ErrMissingOwner indicates missing entity owner. - ErrMissingOwner = errors.New("missing entity owner") - - // ErrMissingPolicyOwner indicated malformed policy owner. - ErrMissingPolicyOwner = errors.New("malformed policy owner") - - // ErrMissingPolicyEntityType indicates malformed policy entity type. - ErrMissingPolicyEntityType = errors.New("malformed or missing entity type") - - // ErrMissingName indicates missing identity name. - ErrMissingName = errors.New("missing identity name") - - // ErrInvalidSecret indicates invalid secret. - ErrInvalidSecret = errors.New("missing secret") - - // ErrInvalidLevel indicates an invalid group level. - ErrInvalidLevel = errors.New("invalid group level (should be between 0 and 5)") - - // ErrNotFoundParam indicates that the parameter was not found in the query. - ErrNotFoundParam = errors.New("parameter not found in the query") - - // ErrInvalidQueryParams indicates invalid query parameters. - ErrInvalidQueryParams = errors.New("invalid query parameters") - - // ErrInvalidVisibilityType indicates invalid visibility type. - ErrInvalidVisibilityType = errors.New("invalid visibility type") - - // ErrUnsupportedContentType indicates unacceptable or lack of Content-Type. - ErrUnsupportedContentType = errors.New("unsupported content type") -) diff --git a/vendor/github.com/absmach/magistrala/internal/apiutil/responses.go b/vendor/github.com/absmach/magistrala/internal/apiutil/responses.go deleted file mode 100644 index 67541c90..00000000 --- a/vendor/github.com/absmach/magistrala/internal/apiutil/responses.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package apiutil - -// ErrorRes represents the HTTP error response body. -type ErrorRes struct { - Err string `json:"error"` - Msg string `json:"message"` -} diff --git a/vendor/github.com/absmach/magistrala/internal/apiutil/token.go b/vendor/github.com/absmach/magistrala/internal/apiutil/token.go deleted file mode 100644 index a6159ca8..00000000 --- a/vendor/github.com/absmach/magistrala/internal/apiutil/token.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package apiutil - -import ( - "net/http" - "strings" -) - -// BearerPrefix represents the token prefix for Bearer authentication scheme. -const BearerPrefix = "Bearer " - -// ThingPrefix represents the key prefix for Thing authentication scheme. -const ThingPrefix = "Thing " - -// ExtractBearerToken returns value of the bearer token. If there is no bearer token - an empty value is returned. -func ExtractBearerToken(r *http.Request) string { - token := r.Header.Get("Authorization") - - if !strings.HasPrefix(token, BearerPrefix) { - return "" - } - - return strings.TrimPrefix(token, BearerPrefix) -} - -// ExtractThingKey returns value of the thing key. If there is no thing key - an empty value is returned. -func ExtractThingKey(r *http.Request) string { - token := r.Header.Get("Authorization") - - if !strings.HasPrefix(token, ThingPrefix) { - return "" - } - - return strings.TrimPrefix(token, ThingPrefix) -} diff --git a/vendor/github.com/absmach/magistrala/internal/apiutil/transport.go b/vendor/github.com/absmach/magistrala/internal/apiutil/transport.go deleted file mode 100644 index 58304592..00000000 --- a/vendor/github.com/absmach/magistrala/internal/apiutil/transport.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package apiutil - -import ( - "context" - "encoding/json" - "net/http" - "strconv" - - "github.com/absmach/magistrala/logger" - "github.com/absmach/magistrala/pkg/errors" - kithttp "github.com/go-kit/kit/transport/http" - "github.com/go-zoo/bone" -) - -// LoggingErrorEncoder is a go-kit error encoder logging decorator. -func LoggingErrorEncoder(logger logger.Logger, enc kithttp.ErrorEncoder) kithttp.ErrorEncoder { - return func(ctx context.Context, err error, w http.ResponseWriter) { - if errors.Contains(err, ErrValidation) { - logger.Error(err.Error()) - } - enc(ctx, err, w) - } -} - -// ReadUintQuery reads the value of uint64 http query parameters for a given key. -func ReadUintQuery(r *http.Request, key string, def uint64) (uint64, error) { - vals := bone.GetQuery(r, key) - if len(vals) > 1 { - return 0, ErrInvalidQueryParams - } - - if len(vals) == 0 { - return def, nil - } - - strval := vals[0] - val, err := strconv.ParseUint(strval, 10, 64) - if err != nil { - return 0, ErrInvalidQueryParams - } - - return val, nil -} - -// ReadStringQuery reads the value of string http query parameters for a given key. -func ReadStringQuery(r *http.Request, key string, def string) (string, error) { - vals := bone.GetQuery(r, key) - if len(vals) > 1 { - return "", ErrInvalidQueryParams - } - - if len(vals) == 0 { - return def, nil - } - - return vals[0], nil -} - -// ReadMetadataQuery reads the value of json http query parameters for a given key. -func ReadMetadataQuery(r *http.Request, key string, def map[string]interface{}) (map[string]interface{}, error) { - vals := bone.GetQuery(r, key) - if len(vals) > 1 { - return nil, ErrInvalidQueryParams - } - - if len(vals) == 0 { - return def, nil - } - - m := make(map[string]interface{}) - err := json.Unmarshal([]byte(vals[0]), &m) - if err != nil { - return nil, errors.Wrap(ErrInvalidQueryParams, err) - } - - return m, nil -} - -// ReadBoolQuery reads boolean query parameters in a given http request. -func ReadBoolQuery(r *http.Request, key string, def bool) (bool, error) { - vals := bone.GetQuery(r, key) - if len(vals) > 1 { - return false, ErrInvalidQueryParams - } - - if len(vals) == 0 { - return def, nil - } - - b, err := strconv.ParseBool(vals[0]) - if err != nil { - return false, ErrInvalidQueryParams - } - - return b, nil -} - -// ReadFloatQuery reads the value of float64 http query parameters for a given key. -func ReadFloatQuery(r *http.Request, key string, def float64) (float64, error) { - vals := bone.GetQuery(r, key) - if len(vals) > 1 { - return 0, ErrInvalidQueryParams - } - - if len(vals) == 0 { - return def, nil - } - - fval := vals[0] - val, err := strconv.ParseFloat(fval, 64) - if err != nil { - return 0, ErrInvalidQueryParams - } - - return val, nil -} - -type number interface { - int64 | float64 | uint16 | uint64 -} - -// ReadNumQuery returns a numeric value. -func ReadNumQuery[N number](r *http.Request, key string, def N) (N, error) { - vals := bone.GetQuery(r, key) - if len(vals) > 1 { - return 0, ErrInvalidQueryParams - } - if len(vals) == 0 { - return def, nil - } - val := vals[0] - - switch any(def).(type) { - case int64: - v, err := strconv.ParseInt(val, 10, 64) - return N(v), err - case uint64: - v, err := strconv.ParseUint(val, 10, 64) - return N(v), err - case uint16: - v, err := strconv.ParseUint(val, 10, 16) - return N(v), err - case float64: - v, err := strconv.ParseFloat(val, 64) - return N(v), err - default: - return def, nil - } -} diff --git a/vendor/github.com/absmach/magistrala/logger/doc.go b/vendor/github.com/absmach/magistrala/logger/doc.go deleted file mode 100644 index 791beb0c..00000000 --- a/vendor/github.com/absmach/magistrala/logger/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Package logger contains logger API definition, wrapper that -// can be used around any other logger. -package logger diff --git a/vendor/github.com/absmach/magistrala/logger/exit.go b/vendor/github.com/absmach/magistrala/logger/exit.go deleted file mode 100644 index ef0c93dc..00000000 --- a/vendor/github.com/absmach/magistrala/logger/exit.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package logger - -import "os" - -// ExitWithError closes the current process with error code. -func ExitWithError(code *int) { - os.Exit(*code) -} diff --git a/vendor/github.com/absmach/magistrala/logger/level.go b/vendor/github.com/absmach/magistrala/logger/level.go deleted file mode 100644 index dfc1812d..00000000 --- a/vendor/github.com/absmach/magistrala/logger/level.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package logger - -import ( - "errors" - "strings" -) - -const ( - // Error level is used when logging errors. - Error Level = iota + 1 - // Warn level is used when logging warnings. - Warn - // Info level is used when logging info data. - Info - // Debug level is used when logging debugging info. - Debug -) - -// ErrInvalidLogLevel indicates an unrecognized log level. -var ErrInvalidLogLevel = errors.New("unrecognized log level") - -// Level represents severity level while logging. -type Level int - -var levels = map[Level]string{ - Error: "error", - Warn: "warn", - Info: "info", - Debug: "debug", -} - -func (lvl Level) String() string { - return levels[lvl] -} - -func (lvl Level) isAllowed(logLevel Level) bool { - return lvl <= logLevel -} - -// UnmarshalText returns log Level for the given string representation. -func (lvl *Level) UnmarshalText(text string) error { - switch strings.ToLower(text) { - case "debug": - *lvl = Debug - case "info": - *lvl = Info - case "warn": - *lvl = Warn - case "error": - *lvl = Error - default: - return ErrInvalidLogLevel - } - return nil -} diff --git a/vendor/github.com/absmach/magistrala/logger/logger.go b/vendor/github.com/absmach/magistrala/logger/logger.go deleted file mode 100644 index af95e658..00000000 --- a/vendor/github.com/absmach/magistrala/logger/logger.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package logger - -import ( - "fmt" - "io" - "os" - "time" - - "github.com/go-kit/log" -) - -// Logger specifies logging API. -type Logger interface { - // Debug logs any object in JSON format on debug level. - Debug(string) - // Info logs any object in JSON format on info level. - Info(string) - // Warn logs any object in JSON format on warning level. - Warn(string) - // Error logs any object in JSON format on error level. - Error(string) - // Fatal logs any object in JSON format on any level and calls os.Exit(1). - Fatal(string) -} - -var _ Logger = (*logger)(nil) - -type logger struct { - kitLogger log.Logger - level Level -} - -// New returns wrapped go kit logger. -func New(out io.Writer, levelText string) (Logger, error) { - var level Level - err := level.UnmarshalText(levelText) - if err != nil { - return nil, fmt.Errorf(`{"level":"error","message":"%s: %s","ts":"%s"}`, err, levelText, time.RFC3339Nano) - } - l := log.NewJSONLogger(log.NewSyncWriter(out)) - l = log.With(l, "ts", log.DefaultTimestampUTC) - return &logger{l, level}, err -} - -func (l logger) Debug(msg string) { - if Debug.isAllowed(l.level) { - _ = l.kitLogger.Log("level", Debug.String(), "message", msg) - } -} - -func (l logger) Info(msg string) { - if Info.isAllowed(l.level) { - _ = l.kitLogger.Log("level", Info.String(), "message", msg) - } -} - -func (l logger) Warn(msg string) { - if Warn.isAllowed(l.level) { - _ = l.kitLogger.Log("level", Warn.String(), "message", msg) - } -} - -func (l logger) Error(msg string) { - if Error.isAllowed(l.level) { - _ = l.kitLogger.Log("level", Error.String(), "message", msg) - } -} - -func (l logger) Fatal(msg string) { - _ = l.kitLogger.Log("fatal", msg) - os.Exit(1) -} diff --git a/vendor/github.com/absmach/magistrala/logger/mock.go b/vendor/github.com/absmach/magistrala/logger/mock.go deleted file mode 100644 index b15e6937..00000000 --- a/vendor/github.com/absmach/magistrala/logger/mock.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package logger - -var _ Logger = (*loggerMock)(nil) - -type loggerMock struct{} - -// NewMock returns wrapped go kit logger mock. -func NewMock() Logger { - return &loggerMock{} -} - -func (l loggerMock) Debug(msg string) { -} - -func (l loggerMock) Info(msg string) { -} - -func (l loggerMock) Warn(msg string) { -} - -func (l loggerMock) Error(msg string) { -} - -func (l loggerMock) Fatal(msg string) { -} diff --git a/vendor/github.com/absmach/magistrala/pkg/clients/clients.go b/vendor/github.com/absmach/magistrala/pkg/clients/clients.go deleted file mode 100644 index a5f94a15..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/clients/clients.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package clients - -import ( - "context" - "fmt" - "regexp" - "strings" - "time" - - "github.com/absmach/magistrala/pkg/errors" - "golang.org/x/net/idna" -) - -const ( - maxLocalLen = 64 - maxDomainLen = 255 - maxTLDLen = 24 // longest TLD currently in existence - - atSeparator = "@" - dotSeparator = "." -) - -var ( - userRegexp = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$") - hostRegexp = regexp.MustCompile(`^[^\s]+\.[^\s]+$`) - userDotRegexp = regexp.MustCompile("(^[.]{1})|([.]{1}$)|([.]{2,})") -) - -// Credentials represent client credentials: its -// "identity" which can be a username, email, generated name; -// and "secret" which can be a password or access token. -type Credentials struct { - Identity string `json:"identity,omitempty"` // username or generated login ID - Secret string `json:"secret,omitempty"` // password or token -} - -// Client represents generic Client. -type Client struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Tags []string `json:"tags,omitempty"` - Owner string `json:"owner,omitempty"` // nullable - Credentials Credentials `json:"credentials,omitempty"` - Metadata Metadata `json:"metadata,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at,omitempty"` - UpdatedBy string `json:"updated_by,omitempty"` - Status Status `json:"status"` // 1 for enabled, 0 for disabled - Role Role `json:"role,omitempty"` // 1 for admin, 0 for normal user -} - -// ClientsPage contains page related metadata as well as list -// of Clients that belong to the page. -type ClientsPage struct { - Page - Clients []Client -} - -// MembersPage contains page related metadata as well as list of members that -// belong to this page. -type MembersPage struct { - Page - Members []Client -} - -// Repository specifies an account persistence API. -type Repository interface { - // RetrieveByID retrieves client by its unique ID. - RetrieveByID(ctx context.Context, id string) (Client, error) - - // RetrieveByIdentity retrieves client by its unique credentials - RetrieveByIdentity(ctx context.Context, identity string) (Client, error) - - // RetrieveAll retrieves all clients. - RetrieveAll(ctx context.Context, pm Page) (ClientsPage, error) - - // RetrieveAllByIDs retrieves for given client IDs . - RetrieveAllByIDs(ctx context.Context, pm Page) (ClientsPage, error) - - // Update updates the client name and metadata. - Update(ctx context.Context, client Client) (Client, error) - - // UpdateTags updates the client tags. - UpdateTags(ctx context.Context, client Client) (Client, error) - - // UpdateIdentity updates identity for client with given id. - UpdateIdentity(ctx context.Context, client Client) (Client, error) - - // UpdateSecret updates secret for client with given identity. - UpdateSecret(ctx context.Context, client Client) (Client, error) - - // UpdateOwner updates owner for client with given id. - UpdateOwner(ctx context.Context, client Client) (Client, error) - - // ChangeStatus changes client status to enabled or disabled - ChangeStatus(ctx context.Context, client Client) (Client, error) -} - -// Validate returns an error if client representation is invalid. -func (u Client) Validate() error { - if !isEmail(u.Credentials.Identity) { - return errors.ErrMalformedEntity - } - return nil -} - -func isEmail(email string) bool { - if email == "" { - return false - } - - es := strings.Split(email, atSeparator) - if len(es) != 2 { - return false - } - local, host := es[0], es[1] - - if local == "" || len(local) > maxLocalLen { - return false - } - - hs := strings.Split(host, dotSeparator) - if len(hs) < 2 { - return false - } - domain, ext := hs[0], hs[1] - - // Check subdomain and validate - if len(hs) > 2 { - if domain == "" { - return false - } - - for i := 1; i < len(hs)-1; i++ { - sub := hs[i] - if sub == "" { - return false - } - domain = fmt.Sprintf("%s.%s", domain, sub) - } - - ext = hs[len(hs)-1] - } - - if domain == "" || len(domain) > maxDomainLen { - return false - } - if ext == "" || len(ext) > maxTLDLen { - return false - } - - punyLocal, err := idna.ToASCII(local) - if err != nil { - return false - } - punyHost, err := idna.ToASCII(host) - if err != nil { - return false - } - - if userDotRegexp.MatchString(punyLocal) || !userRegexp.MatchString(punyLocal) || !hostRegexp.MatchString(punyHost) { - return false - } - - return true -} diff --git a/vendor/github.com/absmach/magistrala/pkg/clients/doc.go b/vendor/github.com/absmach/magistrala/pkg/clients/doc.go deleted file mode 100644 index 3ecfda34..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/clients/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Package clients contains the domain concept definitions needed to support -// Magistrala clients functionality. -package clients diff --git a/vendor/github.com/absmach/magistrala/pkg/clients/errors.go b/vendor/github.com/absmach/magistrala/pkg/clients/errors.go deleted file mode 100644 index 23904374..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/clients/errors.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package clients - -import "errors" - -var ( - // ErrInvalidStatus indicates invalid status. - ErrInvalidStatus = errors.New("invalid client status") - - // ErrEnableClient indicates error in enabling client. - ErrEnableClient = errors.New("failed to enable client") - - // ErrDisableClient indicates error in disabling client. - ErrDisableClient = errors.New("failed to disable client") -) diff --git a/vendor/github.com/absmach/magistrala/pkg/clients/page.go b/vendor/github.com/absmach/magistrala/pkg/clients/page.go deleted file mode 100644 index 0217665b..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/clients/page.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package clients - -// Page contains page metadata that helps navigation. -type Page struct { - Total uint64 `json:"total"` - Offset uint64 `json:"offset"` - Limit uint64 `json:"limit"` - Name string `json:"name,omitempty"` - Order string `json:"order,omitempty"` - Dir string `json:"dir,omitempty"` - Metadata Metadata `json:"metadata,omitempty"` - Owner string `json:"owner,omitempty"` - Tag string `json:"tag,omitempty"` - Permission string `json:"permission,omitempty"` - Status Status `json:"status,omitempty"` - IDs []string `json:"ids,omitempty"` - Identity string `json:"identity,omitempty"` -} diff --git a/vendor/github.com/absmach/magistrala/pkg/clients/roles.go b/vendor/github.com/absmach/magistrala/pkg/clients/roles.go deleted file mode 100644 index 29fdbb02..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/clients/roles.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package clients - -import ( - "encoding/json" - "strings" - - "github.com/absmach/magistrala/internal/apiutil" -) - -// Role represents Client role. -type Role uint8 - -// Possible Client role values. -const ( - UserRole Role = iota - AdminRole -) - -// String representation of the possible role values. -const ( - Admin = "admin" - User = "user" -) - -// String converts client role to string literal. -func (cs Role) String() string { - switch cs { - case AdminRole: - return Admin - case UserRole: - return User - default: - return Unknown - } -} - -// ToRole converts string value to a valid Client role. -func ToRole(status string) (Role, error) { - switch status { - case "", User: - return UserRole, nil - case Admin: - return AdminRole, nil - } - return Role(0), apiutil.ErrInvalidRole -} - -func (r Role) MarshalJSON() ([]byte, error) { - return json.Marshal(r.String()) -} - -func (r *Role) UnmarshalJSON(data []byte) error { - str := strings.Trim(string(data), "\"") - val, err := ToRole(str) - *r = val - return err -} diff --git a/vendor/github.com/absmach/magistrala/pkg/clients/status.go b/vendor/github.com/absmach/magistrala/pkg/clients/status.go deleted file mode 100644 index f32c8ea4..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/clients/status.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package clients - -import ( - "encoding/json" - "errors" - "strings" - - "github.com/absmach/magistrala/internal/apiutil" -) - -// Status represents Client status. -type Status uint8 - -// Possible Client status values. -const ( - // EnabledStatus represents enabled Client. - EnabledStatus Status = iota - // DisabledStatus represents disabled Client. - DisabledStatus - - // AllStatus is used for querying purposes to list clients irrespective - // of their status - both enabled and disabled. It is never stored in the - // database as the actual Client status and should always be the largest - // value in this enumeration. - AllStatus -) - -// String representation of the possible status values. -const ( - Disabled = "disabled" - Enabled = "enabled" - All = "all" - Unknown = "unknown" -) - -// ErrStatusAlreadyAssigned indicated that the client or group has already been assigned the status. -var ErrStatusAlreadyAssigned = errors.New("status already assigned") - -// String converts client/group status to string literal. -func (s Status) String() string { - switch s { - case DisabledStatus: - return Disabled - case EnabledStatus: - return Enabled - case AllStatus: - return All - default: - return Unknown - } -} - -// ToStatus converts string value to a valid Client/Group status. -func ToStatus(status string) (Status, error) { - switch status { - case "", Enabled: - return EnabledStatus, nil - case Disabled: - return DisabledStatus, nil - case All: - return AllStatus, nil - } - return Status(0), apiutil.ErrInvalidStatus -} - -// Custom Marshaller for Client/Groups. -func (s Status) MarshalJSON() ([]byte, error) { - return json.Marshal(s.String()) -} - -// Custom Unmarshaler for Client/Groups. -func (s *Status) UnmarshalJSON(data []byte) error { - str := strings.Trim(string(data), "\"") - val, err := ToStatus(str) - *s = val - return err -} diff --git a/vendor/github.com/absmach/magistrala/pkg/clients/types.go b/vendor/github.com/absmach/magistrala/pkg/clients/types.go deleted file mode 100644 index 779c6f08..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/clients/types.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package clients - -// Metadata represents arbitrary JSON. -type Metadata map[string]interface{} diff --git a/vendor/github.com/absmach/magistrala/pkg/errors/README.md b/vendor/github.com/absmach/magistrala/pkg/errors/README.md deleted file mode 100644 index fc5ba548..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/errors/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Errors - -`errors` package serve to build an arbitrary long error chain in order to capture errors returned from nested service calls. - -`errors` package contains the custom Go `error` interface implementation, `Error`. You use the `Error` interface to **wrap** two errors in a containing error as well as to test recursively if a given error **contains** some other error. diff --git a/vendor/github.com/absmach/magistrala/pkg/errors/doc.go b/vendor/github.com/absmach/magistrala/pkg/errors/doc.go deleted file mode 100644 index ef7a644c..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/errors/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Package errors contains Magistrala errors definitions. -package errors diff --git a/vendor/github.com/absmach/magistrala/pkg/errors/errors.go b/vendor/github.com/absmach/magistrala/pkg/errors/errors.go deleted file mode 100644 index 7f590c9c..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/errors/errors.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package errors - -import ( - "context" - "encoding/json" - "fmt" - "os" - "os/signal" - "syscall" -) - -// Error specifies an API that must be fullfiled by error type. -type Error interface { - // Error implements the error interface. - Error() string - - // Msg returns error message. - Msg() string - - // Err returns wrapped error. - Err() Error - - // MarshalJSON returns a marshaled error. - MarshalJSON() ([]byte, error) -} - -var _ Error = (*customError)(nil) - -// customError represents a Magistrala error. -type customError struct { - msg string - err Error -} - -func (ce *customError) Error() string { - if ce == nil { - return "" - } - if ce.err == nil { - return ce.msg - } - return ce.msg + " : " + ce.err.Error() -} - -func (ce *customError) Msg() string { - return ce.msg -} - -func (ce *customError) Err() Error { - return ce.err -} - -func (ce *customError) MarshalJSON() ([]byte, error) { - var val string - if e := ce.Err(); e != nil { - val = e.Msg() - } - return json.Marshal(&struct { - Err string `json:"error"` - Msg string `json:"message"` - }{ - Err: val, - Msg: ce.Msg(), - }) -} - -// Contains inspects if e2 error is contained in any layer of e1 error. -func Contains(e1 error, e2 error) bool { - if e1 == nil || e2 == nil { - return e2 == e1 - } - ce, ok := e1.(Error) - if ok { - if ce.Msg() == e2.Error() { - return true - } - return Contains(ce.Err(), e2) - } - return e1.Error() == e2.Error() -} - -// Wrap returns an Error that wrap err with wrapper. -func Wrap(wrapper error, err error) error { - if wrapper == nil || err == nil { - return wrapper - } - if w, ok := wrapper.(Error); ok { - return &customError{ - msg: w.Msg(), - err: cast(err), - } - } - return &customError{ - msg: wrapper.Error(), - err: cast(err), - } -} - -// Unwrap returns the wrapper and the error by separating the Wrapper from the error. -func Unwrap(err error) (error, error) { - if ce, ok := err.(Error); ok { - if ce.Err() == nil { - return nil, New(ce.Msg()) - } - return New(ce.Msg()), ce.Err() - } - - return nil, err -} - -func cast(err error) Error { - if err == nil { - return nil - } - if e, ok := err.(Error); ok { - return e - } - return &customError{ - msg: err.Error(), - err: nil, - } -} - -// New returns an Error that formats as the given text. -func New(text string) Error { - return &customError{ - msg: text, - err: nil, - } -} - -func SignalHandler(ctx context.Context) error { - c := make(chan os.Signal, 2) - signal.Notify(c, syscall.SIGINT, syscall.SIGABRT) - select { - case sig := <-c: - return fmt.Errorf("%s", sig) - case <-ctx.Done(): - return nil - } -} diff --git a/vendor/github.com/absmach/magistrala/pkg/errors/sdk_errors.go b/vendor/github.com/absmach/magistrala/pkg/errors/sdk_errors.go deleted file mode 100644 index 884a127c..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/errors/sdk_errors.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package errors - -import ( - "encoding/json" - "fmt" - "io" - "net/http" -) - -type errorRes struct { - Err string `json:"error"` - Msg string `json:"message"` -} - -// Failed to read response body. -var errRespBody = New("failed to read response body") - -// SDKError is an error type for Magistrala SDK. -type SDKError interface { - Error - StatusCode() int -} - -var _ SDKError = (*sdkError)(nil) - -type sdkError struct { - *customError - statusCode int -} - -func (ce *sdkError) Error() string { - if ce == nil { - return "" - } - if ce.customError == nil { - return http.StatusText(ce.statusCode) - } - return fmt.Sprintf("Status: %s: %s", http.StatusText(ce.statusCode), ce.customError.Error()) -} - -func (ce *sdkError) StatusCode() int { - return ce.statusCode -} - -// NewSDKError returns an SDK Error that formats as the given text. -func NewSDKError(err error) SDKError { - if e, ok := err.(Error); ok { - return &sdkError{ - statusCode: 0, - customError: &customError{ - msg: e.Msg(), - err: cast(e.Err()), - }, - } - } - return &sdkError{ - customError: &customError{ - msg: err.Error(), - err: nil, - }, - statusCode: 0, - } -} - -// NewSDKErrorWithStatus returns an SDK Error setting the status code. -func NewSDKErrorWithStatus(err error, statusCode int) SDKError { - if e, ok := err.(Error); ok { - return &sdkError{ - statusCode: statusCode, - customError: &customError{ - msg: e.Msg(), - err: cast(e.Err()), - }, - } - } - return &sdkError{ - statusCode: statusCode, - customError: &customError{ - msg: err.Error(), - err: nil, - }, - } -} - -// CheckError will check the HTTP response status code and matches it with the given status codes. -// Since multiple status codes can be valid, we can pass multiple status codes to the function. -// The function then checks for errors in the HTTP response. -func CheckError(resp *http.Response, expectedStatusCodes ...int) SDKError { - for _, expectedStatusCode := range expectedStatusCodes { - if resp.StatusCode == expectedStatusCode { - return nil - } - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - return NewSDKErrorWithStatus(Wrap(errRespBody, err), resp.StatusCode) - } - var content errorRes - if err := json.Unmarshal(body, &content); err != nil { - return NewSDKErrorWithStatus(err, resp.StatusCode) - } - if content.Err == "" { - return NewSDKErrorWithStatus(New(content.Msg), resp.StatusCode) - } - - return NewSDKErrorWithStatus(Wrap(New(content.Msg), New(content.Err)), resp.StatusCode) -} diff --git a/vendor/github.com/absmach/magistrala/pkg/errors/types.go b/vendor/github.com/absmach/magistrala/pkg/errors/types.go deleted file mode 100644 index ede8e901..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/errors/types.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package errors - -var ( - // ErrAuthentication indicates failure occurred while authenticating the entity. - ErrAuthentication = New("failed to perform authentication over the entity") - - // ErrAuthorization indicates failure occurred while authorizing the entity. - ErrAuthorization = New("failed to perform authorization over the entity") - - // ErrMalformedEntity indicates a malformed entity specification. - ErrMalformedEntity = New("malformed entity specification") - - // ErrNotFound indicates a non-existent entity request. - ErrNotFound = New("entity not found") - - // ErrConflict indicates that entity already exists. - ErrConflict = New("entity already exists") - - // ErrCreateEntity indicates error in creating entity or entities. - ErrCreateEntity = New("failed to create entity in the db") - - // ErrViewEntity indicates error in viewing entity or entities. - ErrViewEntity = New("view entity failed") - - // ErrUpdateEntity indicates error in updating entity or entities. - ErrUpdateEntity = New("update entity failed") - - // ErrRemoveEntity indicates error in removing entity. - ErrRemoveEntity = New("failed to remove entity") - - // ErrScanMetadata indicates problem with metadata in db. - ErrScanMetadata = New("failed to scan metadata in db") - - // ErrWrongSecret indicates a wrong secret was provided. - ErrWrongSecret = New("wrong secret") - - // ErrLogin indicates wrong login credentials. - ErrLogin = New("invalid user id or secret") - - ErrUnsupportedContentType = New("invalid content type") -) diff --git a/vendor/github.com/absmach/magistrala/pkg/messaging/README.md b/vendor/github.com/absmach/magistrala/pkg/messaging/README.md deleted file mode 100644 index f8b07f8e..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/messaging/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Messaging - -`messaging` package defines `Publisher`, `Subscriber` and an aggregate `Pubsub` interface. - -`Subscriber` interface defines methods used to subscribe to a message broker such as MQTT or NATS or RabbitMQ. - -`Publisher` interface defines methods used to publish messages to a message broker such as MQTT or NATS or RabbitMQ. - -`Pubsub` interface is composed of `Publisher` and `Subscriber` interface and can be used to send messages to as well as to receive messages from a message broker. diff --git a/vendor/github.com/absmach/magistrala/pkg/messaging/message.pb.go b/vendor/github.com/absmach/magistrala/pkg/messaging/message.pb.go deleted file mode 100644 index 80a39df9..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/messaging/message.pb.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.31.0 -// protoc v4.24.3 -// source: pkg/messaging/message.proto - -package messaging - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// Message represents a message emitted by the Magistrala adapters layer. -type Message struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Channel string `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` - Subtopic string `protobuf:"bytes,2,opt,name=subtopic,proto3" json:"subtopic,omitempty"` - Publisher string `protobuf:"bytes,3,opt,name=publisher,proto3" json:"publisher,omitempty"` - Protocol string `protobuf:"bytes,4,opt,name=protocol,proto3" json:"protocol,omitempty"` - Payload []byte `protobuf:"bytes,5,opt,name=payload,proto3" json:"payload,omitempty"` - Created int64 `protobuf:"varint,6,opt,name=created,proto3" json:"created,omitempty"` // Unix timestamp in nanoseconds -} - -func (x *Message) Reset() { - *x = Message{} - if protoimpl.UnsafeEnabled { - mi := &file_pkg_messaging_message_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Message) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Message) ProtoMessage() {} - -func (x *Message) ProtoReflect() protoreflect.Message { - mi := &file_pkg_messaging_message_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Message.ProtoReflect.Descriptor instead. -func (*Message) Descriptor() ([]byte, []int) { - return file_pkg_messaging_message_proto_rawDescGZIP(), []int{0} -} - -func (x *Message) GetChannel() string { - if x != nil { - return x.Channel - } - return "" -} - -func (x *Message) GetSubtopic() string { - if x != nil { - return x.Subtopic - } - return "" -} - -func (x *Message) GetPublisher() string { - if x != nil { - return x.Publisher - } - return "" -} - -func (x *Message) GetProtocol() string { - if x != nil { - return x.Protocol - } - return "" -} - -func (x *Message) GetPayload() []byte { - if x != nil { - return x.Payload - } - return nil -} - -func (x *Message) GetCreated() int64 { - if x != nil { - return x.Created - } - return 0 -} - -var File_pkg_messaging_message_proto protoreflect.FileDescriptor - -var file_pkg_messaging_message_proto_rawDesc = []byte{ - 0x0a, 0x1b, 0x70, 0x6b, 0x67, 0x2f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x2f, - 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x09, 0x6d, - 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x22, 0xad, 0x01, 0x0a, 0x07, 0x4d, 0x65, 0x73, - 0x73, 0x61, 0x67, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x1a, - 0x0a, 0x08, 0x73, 0x75, 0x62, 0x74, 0x6f, 0x70, 0x69, 0x63, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x08, 0x73, 0x75, 0x62, 0x74, 0x6f, 0x70, 0x69, 0x63, 0x12, 0x1c, 0x0a, 0x09, 0x70, 0x75, - 0x62, 0x6c, 0x69, 0x73, 0x68, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, - 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x65, 0x72, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, - 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x18, - 0x0a, 0x07, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, - 0x07, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x42, 0x0d, 0x5a, 0x0b, 0x2e, 0x2f, 0x6d, 0x65, - 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_pkg_messaging_message_proto_rawDescOnce sync.Once - file_pkg_messaging_message_proto_rawDescData = file_pkg_messaging_message_proto_rawDesc -) - -func file_pkg_messaging_message_proto_rawDescGZIP() []byte { - file_pkg_messaging_message_proto_rawDescOnce.Do(func() { - file_pkg_messaging_message_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_messaging_message_proto_rawDescData) - }) - return file_pkg_messaging_message_proto_rawDescData -} - -var file_pkg_messaging_message_proto_msgTypes = make([]protoimpl.MessageInfo, 1) -var file_pkg_messaging_message_proto_goTypes = []interface{}{ - (*Message)(nil), // 0: messaging.Message -} -var file_pkg_messaging_message_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_pkg_messaging_message_proto_init() } -func file_pkg_messaging_message_proto_init() { - if File_pkg_messaging_message_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_pkg_messaging_message_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Message); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_pkg_messaging_message_proto_rawDesc, - NumEnums: 0, - NumMessages: 1, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_pkg_messaging_message_proto_goTypes, - DependencyIndexes: file_pkg_messaging_message_proto_depIdxs, - MessageInfos: file_pkg_messaging_message_proto_msgTypes, - }.Build() - File_pkg_messaging_message_proto = out.File - file_pkg_messaging_message_proto_rawDesc = nil - file_pkg_messaging_message_proto_goTypes = nil - file_pkg_messaging_message_proto_depIdxs = nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/messaging/message.proto b/vendor/github.com/absmach/magistrala/pkg/messaging/message.proto deleted file mode 100644 index b37b7d3e..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/messaging/message.proto +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -syntax = "proto3"; -package messaging; - -option go_package = "./messaging"; - -// Message represents a message emitted by the Magistrala adapters layer. -message Message { - string channel = 1; - string subtopic = 2; - string publisher = 3; - string protocol = 4; - bytes payload = 5; - int64 created = 6; // Unix timestamp in nanoseconds -} diff --git a/vendor/github.com/absmach/magistrala/pkg/messaging/pubsub.go b/vendor/github.com/absmach/magistrala/pkg/messaging/pubsub.go deleted file mode 100644 index 8bebadd2..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/messaging/pubsub.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package messaging - -import "context" - -type DeliveryPolicy uint8 - -const ( - // DeliverNewPolicy will only deliver new messages that are sent after the consumer is created. - // This is the default policy. - DeliverNewPolicy DeliveryPolicy = iota - - // DeliverAllPolicy starts delivering messages from the very beginning of a stream. - DeliverAllPolicy -) - -// Publisher specifies message publishing API. -type Publisher interface { - // Publishes message to the stream. - Publish(ctx context.Context, topic string, msg *Message) error - - // Close gracefully closes message publisher's connection. - Close() error -} - -// MessageHandler represents Message handler for Subscriber. -type MessageHandler interface { - // Handle handles messages passed by underlying implementation. - Handle(msg *Message) error - - // Cancel is used for cleanup during unsubscribing and it's optional. - Cancel() error -} - -type SubscriberConfig struct { - ID string - Topic string - Handler MessageHandler - DeliveryPolicy DeliveryPolicy -} - -// Subscriber specifies message subscription API. -type Subscriber interface { - // Subscribe subscribes to the message stream and consumes messages. - Subscribe(ctx context.Context, cfg SubscriberConfig) error - - // Unsubscribe unsubscribes from the message stream and - // stops consuming messages. - Unsubscribe(ctx context.Context, id, topic string) error - - // Close gracefully closes message subscriber's connection. - Close() error -} - -// PubSub represents aggregation interface for publisher and subscriber. -type PubSub interface { - Publisher - Subscriber -} - -// Option represents optional configuration for message broker. -// -// This is used to provide optional configuration parameters to the -// underlying publisher and pubsub implementation so that it can be -// configured to meet the specific needs. -// -// For example, it can be used to set the message prefix so that -// brokers can be used for event sourcing as well as internal message broker. -// Using value of type interface is not recommended but is the most suitable -// for this use case as options should be compiled with respect to the -// underlying broker which can either be RabbitMQ or NATS. -// -// The example below shows how to set the prefix and jetstream stream for NATS. -// -// Example: -// -// broker.NewPublisher(ctx, url, broker.Prefix(eventsPrefix), broker.JSStream(js)) -type Option func(vals interface{}) error diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/README.md b/vendor/github.com/absmach/magistrala/pkg/sdk/go/README.md deleted file mode 100644 index f82f782f..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# Magistrala Go SDK - -Go SDK, a Go driver for Magistrala HTTP API. - -Does both system administration (provisioning) and messaging. - -## Installation - -Import `"github.com/absmach/magistrala/sdk/go"` in your Go package. - -```` -import "github.com/absmach/magistrala/pkg/sdk/go"``` - -Then call SDK Go functions to interact with the system. - -## API Reference - -```go -FUNCTIONS - -func NewMgxSDK(host, port string, tls bool) *MgxSDK - -func (sdk *MgxSDK) Channel(id, token string) (things.Channel, error) - Channel - gets channel by ID - -func (sdk *MgxSDK) Channels(token string) ([]things.Channel, error) - Channels - gets all channels - -func (sdk *MgxSDK) Connect(struct{[]string, []string}, token string) error - Connect - connect things to channels - -func (sdk *MgxSDK) CreateChannel(data, token string) (string, error) - CreateChannel - creates new channel and generates UUID - -func (sdk *MgxSDK) CreateThing(data, token string) (string, error) - CreateThing - creates new thing and generates thing UUID - -func (sdk *MgxSDK) CreateToken(user, pwd string) (string, error) - CreateToken - create user token - -func (sdk *MgxSDK) CreateUser(user, pwd string) error - CreateUser - create user - -func (sdk *MgxSDK) User(pwd string) (user, error) - User - gets user - -func (sdk *MgxSDK) UpdateUser(user, pwd string) error - UpdateUser - update user - -func (sdk *MgxSDK) UpdatePassword(user, pwd string) error - UpdatePassword - update user password - -func (sdk *MgxSDK) DeleteChannel(id, token string) error - DeleteChannel - removes channel - -func (sdk *MgxSDK) DeleteThing(id, token string) error - DeleteThing - removes thing - -func (sdk *MgxSDK) DisconnectThing(thingID, chanID, token string) error - DisconnectThing - connect thing to a channel - -func (sdk *MgxSDK) SendMessage(chanID, msg, token string) error - SendMessage - send message on Magistrala channel - -func (sdk *MgxSDK) SetContentType(ct ContentType) error - SetContentType - set message content type. Available options are SenML - JSON, custom JSON and custom binary (octet-stream). - -func (sdk *MgxSDK) Thing(id, token string) (Thing, error) - Thing - gets thing by ID - -func (sdk *MgxSDK) Things(token string) ([]Thing, error) - Things - gets all things - -func (sdk *MgxSDK) UpdateChannel(channel Channel, token string) error - UpdateChannel - update a channel - -func (sdk *MgxSDK) UpdateThing(thing Thing, token string) error - UpdateThing - updates thing by ID - -func (sdk *MgxSDK) Health() (magistrala.Health, error) - Health - things service health check -```` diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/bootstrap.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/bootstrap.go deleted file mode 100644 index 4c89b147..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/bootstrap.go +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - - "github.com/absmach/magistrala/internal/apiutil" - "github.com/absmach/magistrala/pkg/errors" -) - -const ( - configsEndpoint = "things/configs" - bootstrapEndpoint = "things/bootstrap" - whitelistEndpoint = "things/state" - bootstrapCertsEndpoint = "things/configs/certs" - bootstrapConnEndpoint = "things/configs/connections" - secureEndpoint = "secure" -) - -// BootstrapConfig represents Configuration entity. It wraps information about external entity -// as well as info about corresponding Magistrala entities. -// MGThing represents corresponding Magistrala Thing ID. -// MGKey is key of corresponding Magistrala Thing. -// MGChannels is a list of Magistrala Channels corresponding Magistrala Thing connects to. -type BootstrapConfig struct { - Channels interface{} `json:"channels,omitempty"` - ExternalID string `json:"external_id,omitempty"` - ExternalKey string `json:"external_key,omitempty"` - ThingID string `json:"thing_id,omitempty"` - ThingKey string `json:"thing_key,omitempty"` - Name string `json:"name,omitempty"` - ClientCert string `json:"client_cert,omitempty"` - ClientKey string `json:"client_key,omitempty"` - CACert string `json:"ca_cert,omitempty"` - Content string `json:"content,omitempty"` - State int `json:"state,omitempty"` -} - -func (ts *BootstrapConfig) UnmarshalJSON(data []byte) error { - var rawData map[string]json.RawMessage - if err := json.Unmarshal(data, &rawData); err != nil { - return err - } - - if channelData, ok := rawData["channels"]; ok { - var stringData []string - if err := json.Unmarshal(channelData, &stringData); err == nil { - ts.Channels = stringData - } else { - var channels []Channel - if err := json.Unmarshal(channelData, &channels); err == nil { - ts.Channels = channels - } else { - return fmt.Errorf("unsupported channel data type") - } - } - } - - if err := json.Unmarshal(data, &struct { - ExternalID *string `json:"external_id,omitempty"` - ExternalKey *string `json:"external_key,omitempty"` - ThingID *string `json:"thing_id,omitempty"` - ThingKey *string `json:"thing_key,omitempty"` - Name *string `json:"name,omitempty"` - ClientCert *string `json:"client_cert,omitempty"` - ClientKey *string `json:"client_key,omitempty"` - CACert *string `json:"ca_cert,omitempty"` - Content *string `json:"content,omitempty"` - State *int `json:"state,omitempty"` - }{ - ExternalID: &ts.ExternalID, - ExternalKey: &ts.ExternalKey, - ThingID: &ts.ThingID, - ThingKey: &ts.ThingKey, - Name: &ts.Name, - ClientCert: &ts.ClientCert, - ClientKey: &ts.ClientKey, - CACert: &ts.CACert, - Content: &ts.Content, - State: &ts.State, - }); err != nil { - return err - } - - return nil -} - -func (sdk mgSDK) AddBootstrap(cfg BootstrapConfig, token string) (string, errors.SDKError) { - data, err := json.Marshal(cfg) - if err != nil { - return "", errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s", sdk.bootstrapURL, configsEndpoint) - - headers, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusOK, http.StatusCreated) - if sdkerr != nil { - return "", sdkerr - } - - id := strings.TrimPrefix(headers.Get("Location"), "/things/configs/") - - return id, nil -} - -func (sdk mgSDK) Bootstraps(pm PageMetadata, token string) (BootstrapPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.bootstrapURL, configsEndpoint, pm) - if err != nil { - return BootstrapPage{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return BootstrapPage{}, sdkerr - } - - var bb BootstrapPage - if err = json.Unmarshal(body, &bb); err != nil { - return BootstrapPage{}, errors.NewSDKError(err) - } - - return bb, nil -} - -func (sdk mgSDK) Whitelist(cfg BootstrapConfig, token string) errors.SDKError { - data, err := json.Marshal(BootstrapConfig{State: cfg.State}) - if err != nil { - return errors.NewSDKError(err) - } - - if cfg.ThingID == "" { - return errors.NewSDKError(apiutil.ErrNotFoundParam) - } - - url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, whitelistEndpoint, cfg.ThingID) - - _, _, sdkerr := sdk.processRequest(http.MethodPut, url, token, data, nil, http.StatusCreated, http.StatusOK) - - return sdkerr -} - -func (sdk mgSDK) ViewBootstrap(id, token string) (BootstrapConfig, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, configsEndpoint, id) - - _, body, err := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if err != nil { - return BootstrapConfig{}, err - } - - var bc BootstrapConfig - if err := json.Unmarshal(body, &bc); err != nil { - return BootstrapConfig{}, errors.NewSDKError(err) - } - - return bc, nil -} - -func (sdk mgSDK) UpdateBootstrap(cfg BootstrapConfig, token string) errors.SDKError { - data, err := json.Marshal(cfg) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, configsEndpoint, cfg.ThingID) - - _, _, sdkerr := sdk.processRequest(http.MethodPut, url, token, data, nil, http.StatusOK) - - return sdkerr -} - -func (sdk mgSDK) UpdateBootstrapCerts(id, clientCert, clientKey, ca, token string) (BootstrapConfig, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, bootstrapCertsEndpoint, id) - request := BootstrapConfig{ - ClientCert: clientCert, - ClientKey: clientKey, - CACert: ca, - } - - data, err := json.Marshal(request) - if err != nil { - return BootstrapConfig{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - - var bc BootstrapConfig - if err := json.Unmarshal(body, &bc); err != nil { - return BootstrapConfig{}, errors.NewSDKError(err) - } - - return bc, sdkerr -} - -func (sdk mgSDK) UpdateBootstrapConnection(id string, channels []string, token string) errors.SDKError { - url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, bootstrapConnEndpoint, id) - request := map[string][]string{ - "channels": channels, - } - data, err := json.Marshal(request) - if err != nil { - return errors.NewSDKError(err) - } - - _, _, sdkerr := sdk.processRequest(http.MethodPut, url, token, data, nil, http.StatusOK) - return sdkerr -} - -func (sdk mgSDK) RemoveBootstrap(id, token string) errors.SDKError { - url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, configsEndpoint, id) - - _, _, err := sdk.processRequest(http.MethodDelete, url, token, nil, nil, http.StatusNoContent) - return err -} - -func (sdk mgSDK) Bootstrap(externalID, externalKey string) (BootstrapConfig, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, bootstrapEndpoint, externalID) - - _, body, err := sdk.processRequest(http.MethodGet, url, ThingPrefix+externalKey, nil, nil, http.StatusOK) - if err != nil { - return BootstrapConfig{}, err - } - - var bc BootstrapConfig - if err := json.Unmarshal(body, &bc); err != nil { - return BootstrapConfig{}, errors.NewSDKError(err) - } - - return bc, nil -} - -func (sdk mgSDK) BootstrapSecure(externalID, externalKey string) (BootstrapConfig, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s/%s", sdk.bootstrapURL, bootstrapEndpoint, secureEndpoint, externalID) - - _, body, err := sdk.processRequest(http.MethodGet, url, ThingPrefix+externalKey, nil, nil, http.StatusOK) - if err != nil { - return BootstrapConfig{}, err - } - - var bc BootstrapConfig - if err := json.Unmarshal(body, &bc); err != nil { - return BootstrapConfig{}, errors.NewSDKError(err) - } - - return bc, nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/certs.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/certs.go deleted file mode 100644 index 0932dd4a..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/certs.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/absmach/magistrala/pkg/errors" -) - -const ( - certsEndpoint = "certs" - serialsEndpoint = "serials" -) - -// Cert represents certs data. -type Cert struct { - ThingID string `json:"thing_id,omitempty"` - CertSerial string `json:"cert_serial,omitempty"` - ClientKey string `json:"client_key,omitempty"` - ClientCert string `json:"client_cert,omitempty"` - Expiration time.Time `json:"expiration,omitempty"` -} - -func (sdk mgSDK) IssueCert(thingID, valid, token string) (Cert, errors.SDKError) { - r := certReq{ - ThingID: thingID, - Valid: valid, - } - d, err := json.Marshal(r) - if err != nil { - return Cert{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s", sdk.certsURL, certsEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, d, nil, http.StatusCreated) - if sdkerr != nil { - return Cert{}, sdkerr - } - - var c Cert - if err := json.Unmarshal(body, &c); err != nil { - return Cert{}, errors.NewSDKError(err) - } - - return c, nil -} - -func (sdk mgSDK) ViewCert(id, token string) (Cert, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.certsURL, certsEndpoint, id) - - _, body, err := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if err != nil { - return Cert{}, err - } - - var cert Cert - if err := json.Unmarshal(body, &cert); err != nil { - return Cert{}, errors.NewSDKError(err) - } - - return cert, nil -} - -func (sdk mgSDK) ViewCertByThing(thingID, token string) (CertSerials, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.certsURL, serialsEndpoint, thingID) - - _, body, err := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if err != nil { - return CertSerials{}, err - } - - var cs CertSerials - if err := json.Unmarshal(body, &cs); err != nil { - return CertSerials{}, errors.NewSDKError(err) - } - - return cs, nil -} - -func (sdk mgSDK) RevokeCert(id, token string) (time.Time, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.certsURL, certsEndpoint, id) - - _, body, err := sdk.processRequest(http.MethodDelete, url, token, nil, nil, http.StatusOK) - if err != nil { - return time.Time{}, err - } - - var rcr revokeCertsRes - if err := json.Unmarshal(body, &rcr); err != nil { - return time.Time{}, errors.NewSDKError(err) - } - - return rcr.RevocationTime, nil -} - -type certReq struct { - ThingID string `json:"thing_id"` - Valid string `json:"ttl"` -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/channels.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/channels.go deleted file mode 100644 index 967e35b7..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/channels.go +++ /dev/null @@ -1,294 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/absmach/magistrala/pkg/errors" -) - -const channelsEndpoint = "channels" - -// Channel represents magistrala channel. -type Channel struct { - ID string `json:"id"` - OwnerID string `json:"owner_id,omitempty"` - ParentID string `json:"parent_id,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Metadata Metadata `json:"metadata,omitempty"` - Level int `json:"level,omitempty"` - Path string `json:"path,omitempty"` - Children []*Channel `json:"children,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` - Status string `json:"status,omitempty"` -} - -func (sdk mgSDK) CreateChannel(c Channel, token string) (Channel, errors.SDKError) { - data, err := json.Marshal(c) - if err != nil { - return Channel{}, errors.NewSDKError(err) - } - url := fmt.Sprintf("%s/%s", sdk.thingsURL, channelsEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - if sdkerr != nil { - return Channel{}, sdkerr - } - - c = Channel{} - if err := json.Unmarshal(body, &c); err != nil { - return Channel{}, errors.NewSDKError(err) - } - - return c, nil -} - -func (sdk mgSDK) CreateChannels(chs []Channel, token string) ([]Channel, errors.SDKError) { - data, err := json.Marshal(chs) - if err != nil { - return []Channel{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, channelsEndpoint, "bulk") - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return []Channel{}, sdkerr - } - - var ccr createChannelsRes - if err := json.Unmarshal(body, &ccr); err != nil { - return []Channel{}, errors.NewSDKError(err) - } - - return ccr.Channels, nil -} - -func (sdk mgSDK) Channels(pm PageMetadata, token string) (ChannelsPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.thingsURL, channelsEndpoint, pm) - if err != nil { - return ChannelsPage{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return ChannelsPage{}, sdkerr - } - - var cp ChannelsPage - if err = json.Unmarshal(body, &cp); err != nil { - return ChannelsPage{}, errors.NewSDKError(err) - } - - return cp, nil -} - -func (sdk mgSDK) ChannelsByThing(thingID string, pm PageMetadata, token string) (ChannelsPage, errors.SDKError) { - url, err := sdk.withQueryParams(fmt.Sprintf("%s/things/%s", sdk.thingsURL, thingID), channelsEndpoint, pm) - if err != nil { - return ChannelsPage{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return ChannelsPage{}, sdkerr - } - - var cp ChannelsPage - if err := json.Unmarshal(body, &cp); err != nil { - return ChannelsPage{}, errors.NewSDKError(err) - } - - return cp, nil -} - -func (sdk mgSDK) Channel(id, token string) (Channel, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, channelsEndpoint, id) - - _, body, err := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if err != nil { - return Channel{}, err - } - - var c Channel - if err := json.Unmarshal(body, &c); err != nil { - return Channel{}, errors.NewSDKError(err) - } - - return c, nil -} - -func (sdk mgSDK) UpdateChannel(c Channel, token string) (Channel, errors.SDKError) { - data, err := json.Marshal(c) - if err != nil { - return Channel{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, channelsEndpoint, c.ID) - - _, body, sdkerr := sdk.processRequest(http.MethodPut, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return Channel{}, sdkerr - } - - c = Channel{} - if err := json.Unmarshal(body, &c); err != nil { - return Channel{}, errors.NewSDKError(err) - } - - return c, nil -} - -func (sdk mgSDK) AddUserToChannel(channelID string, req UsersRelationRequest, token string) errors.SDKError { - data, err := json.Marshal(req) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/%s/%s", sdk.thingsURL, channelsEndpoint, channelID, usersEndpoint, assignEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - return sdkerr -} - -func (sdk mgSDK) RemoveUserFromChannel(channelID string, req UsersRelationRequest, token string) errors.SDKError { - data, err := json.Marshal(req) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/%s/%s", sdk.thingsURL, channelsEndpoint, channelID, usersEndpoint, unassignEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusNoContent) - return sdkerr -} - -func (sdk mgSDK) ListChannelUsers(channelID string, pm PageMetadata, token string) (UsersPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.usersURL, fmt.Sprintf("%s/%s/%s", channelsEndpoint, channelID, usersEndpoint), pm) - if err != nil { - return UsersPage{}, errors.NewSDKError(err) - } - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return UsersPage{}, sdkerr - } - up := UsersPage{} - if err := json.Unmarshal(body, &up); err != nil { - return UsersPage{}, errors.NewSDKError(err) - } - - return up, nil -} - -func (sdk mgSDK) AddUserGroupToChannel(channelID string, req UserGroupsRequest, token string) errors.SDKError { - data, err := json.Marshal(req) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/%s/%s", sdk.thingsURL, channelsEndpoint, channelID, groupsEndpoint, assignEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - return sdkerr -} - -func (sdk mgSDK) RemoveUserGroupFromChannel(channelID string, req UserGroupsRequest, token string) errors.SDKError { - data, err := json.Marshal(req) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/%s/%s", sdk.thingsURL, channelsEndpoint, channelID, groupsEndpoint, unassignEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusNoContent) - return sdkerr -} - -func (sdk mgSDK) ListChannelUserGroups(channelID string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.usersURL, fmt.Sprintf("%s/%s/%s", channelsEndpoint, channelID, groupsEndpoint), pm) - if err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return GroupsPage{}, sdkerr - } - gp := GroupsPage{} - if err := json.Unmarshal(body, &gp); err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - - return gp, nil -} - -func (sdk mgSDK) Connect(conn Connection, token string) errors.SDKError { - data, err := json.Marshal(conn) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s", sdk.thingsURL, connectEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - - return sdkerr -} - -func (sdk mgSDK) Disconnect(connIDs Connection, token string) errors.SDKError { - data, err := json.Marshal(connIDs) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s", sdk.thingsURL, disconnectEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusNoContent) - - return sdkerr -} - -func (sdk mgSDK) ConnectThing(thingID, channelID, token string) errors.SDKError { - url := fmt.Sprintf("%s/%s/%s/%s/%s/%s", sdk.thingsURL, channelsEndpoint, channelID, thingsEndpoint, thingID, connectEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, nil, nil, http.StatusCreated) - - return sdkerr -} - -func (sdk mgSDK) DisconnectThing(thingID, channelID, token string) errors.SDKError { - url := fmt.Sprintf("%s/%s/%s/%s/%s/%s", sdk.thingsURL, channelsEndpoint, channelID, thingsEndpoint, thingID, disconnectEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, nil, nil, http.StatusNoContent) - - return sdkerr -} - -func (sdk mgSDK) EnableChannel(id, token string) (Channel, errors.SDKError) { - return sdk.changeChannelStatus(id, enableEndpoint, token) -} - -func (sdk mgSDK) DisableChannel(id, token string) (Channel, errors.SDKError) { - return sdk.changeChannelStatus(id, disableEndpoint, token) -} - -func (sdk mgSDK) changeChannelStatus(id, status, token string) (Channel, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s/%s", sdk.thingsURL, channelsEndpoint, id, status) - - _, body, err := sdk.processRequest(http.MethodPost, url, token, nil, nil, http.StatusOK) - if err != nil { - return Channel{}, err - } - c := Channel{} - if err := json.Unmarshal(body, &c); err != nil { - return Channel{}, errors.NewSDKError(err) - } - - return c, nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/consumers.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/consumers.go deleted file mode 100644 index a360f17c..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/consumers.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - - "github.com/absmach/magistrala/pkg/errors" -) - -const ( - subscriptionEndpoint = "subscriptions" -) - -type Subscription struct { - ID string `json:"id,omitempty"` - OwnerID string `json:"owner_id,omitempty"` - Topic string `json:"topic,omitempty"` - Contact string `json:"contact,omitempty"` -} - -func (sdk mgSDK) CreateSubscription(topic, contact, token string) (string, errors.SDKError) { - sub := Subscription{ - Topic: topic, - Contact: contact, - } - data, err := json.Marshal(sub) - if err != nil { - return "", errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s", sdk.usersURL, subscriptionEndpoint) - - headers, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - if sdkerr != nil { - return "", sdkerr - } - - id := strings.TrimPrefix(headers.Get("Location"), fmt.Sprintf("/%s/", subscriptionEndpoint)) - - return id, nil -} - -func (sdk mgSDK) ListSubscriptions(pm PageMetadata, token string) (SubscriptionPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.usersURL, subscriptionEndpoint, pm) - if err != nil { - return SubscriptionPage{}, errors.NewSDKError(err) - } - - _, body, err := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if err != nil { - return SubscriptionPage{}, errors.NewSDKError(err) - } - - var sp SubscriptionPage - if err := json.Unmarshal(body, &sp); err != nil { - return SubscriptionPage{}, errors.NewSDKError(err) - } - - return sp, nil -} - -func (sdk mgSDK) ViewSubscription(id, token string) (Subscription, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.usersURL, subscriptionEndpoint, id) - - _, body, err := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if err != nil { - return Subscription{}, err - } - - var sub Subscription - if err := json.Unmarshal(body, &sub); err != nil { - return Subscription{}, errors.NewSDKError(err) - } - - return sub, nil -} - -func (sdk mgSDK) DeleteSubscription(id, token string) errors.SDKError { - url := fmt.Sprintf("%s/%s/%s", sdk.usersURL, subscriptionEndpoint, id) - - _, _, err := sdk.processRequest(http.MethodDelete, url, token, nil, nil, http.StatusNoContent) - - return err -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/doc.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/doc.go deleted file mode 100644 index 120f41ea..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Package sdk contains Magistrala SDK. -package sdk diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/groups.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/groups.go deleted file mode 100644 index b9b1fc66..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/groups.go +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/absmach/magistrala/pkg/errors" -) - -const ( - groupsEndpoint = "groups" - MaxLevel = uint64(5) - MinLevel = uint64(1) -) - -// Group represents the group of Clients. -// Indicates a level in tree hierarchy. Root node is level 1. -// Path in a tree consisting of group IDs -// Paths are unique per owner. -type Group struct { - ID string `json:"id"` - OwnerID string `json:"owner_id,omitempty"` - ParentID string `json:"parent_id,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Metadata Metadata `json:"metadata,omitempty"` - Level int `json:"level,omitempty"` - Path string `json:"path,omitempty"` - Children []*Group `json:"children,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` - Status string `json:"status,omitempty"` -} - -func (sdk mgSDK) CreateGroup(g Group, token string) (Group, errors.SDKError) { - data, err := json.Marshal(g) - if err != nil { - return Group{}, errors.NewSDKError(err) - } - url := fmt.Sprintf("%s/%s", sdk.usersURL, groupsEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - if sdkerr != nil { - return Group{}, sdkerr - } - - g = Group{} - if err := json.Unmarshal(body, &g); err != nil { - return Group{}, errors.NewSDKError(err) - } - - return g, nil -} - -func (sdk mgSDK) Groups(pm PageMetadata, token string) (GroupsPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.usersURL, groupsEndpoint, pm) - if err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - - return sdk.getGroups(url, token) -} - -func (sdk mgSDK) Parents(id string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) { - pm.Level = MaxLevel - url, err := sdk.withQueryParams(fmt.Sprintf("%s/%s/%s", sdk.usersURL, groupsEndpoint, id), "parents", pm) - if err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - - return sdk.getGroups(url, token) -} - -func (sdk mgSDK) Children(id string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) { - pm.Level = MaxLevel - url, err := sdk.withQueryParams(fmt.Sprintf("%s/%s/%s", sdk.usersURL, groupsEndpoint, id), "children", pm) - if err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - - return sdk.getGroups(url, token) -} - -func (sdk mgSDK) getGroups(url, token string) (GroupsPage, errors.SDKError) { - _, body, err := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if err != nil { - return GroupsPage{}, err - } - - var tp GroupsPage - if err := json.Unmarshal(body, &tp); err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - - return tp, nil -} - -func (sdk mgSDK) Group(id, token string) (Group, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.usersURL, groupsEndpoint, id) - - _, body, err := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if err != nil { - return Group{}, err - } - - var t Group - if err := json.Unmarshal(body, &t); err != nil { - return Group{}, errors.NewSDKError(err) - } - - return t, nil -} - -func (sdk mgSDK) UpdateGroup(g Group, token string) (Group, errors.SDKError) { - data, err := json.Marshal(g) - if err != nil { - return Group{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s", sdk.usersURL, groupsEndpoint, g.ID) - - _, body, sdkerr := sdk.processRequest(http.MethodPut, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return Group{}, sdkerr - } - - g = Group{} - if err := json.Unmarshal(body, &g); err != nil { - return Group{}, errors.NewSDKError(err) - } - - return g, nil -} - -func (sdk mgSDK) EnableGroup(id, token string) (Group, errors.SDKError) { - return sdk.changeGroupStatus(id, enableEndpoint, token) -} - -func (sdk mgSDK) DisableGroup(id, token string) (Group, errors.SDKError) { - return sdk.changeGroupStatus(id, disableEndpoint, token) -} - -func (sdk mgSDK) AddUserToGroup(groupID string, req UsersRelationRequest, token string) errors.SDKError { - data, err := json.Marshal(req) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/%s/%s", sdk.usersURL, groupsEndpoint, groupID, usersEndpoint, assignEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - return sdkerr -} - -func (sdk mgSDK) RemoveUserFromGroup(groupID string, req UsersRelationRequest, token string) errors.SDKError { - data, err := json.Marshal(req) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/%s/%s", sdk.usersURL, groupsEndpoint, groupID, usersEndpoint, unassignEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusNoContent) - return sdkerr -} - -func (sdk mgSDK) ListGroupUsers(groupID string, pm PageMetadata, token string) (UsersPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.usersURL, fmt.Sprintf("%s/%s/%s", groupsEndpoint, groupID, usersEndpoint), pm) - if err != nil { - return UsersPage{}, errors.NewSDKError(err) - } - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return UsersPage{}, sdkerr - } - up := UsersPage{} - if err := json.Unmarshal(body, &up); err != nil { - return UsersPage{}, errors.NewSDKError(err) - } - - return up, nil -} - -func (sdk mgSDK) ListGroupChannels(groupID string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.thingsURL, fmt.Sprintf("%s/%s/%s", groupsEndpoint, groupID, channelsEndpoint), pm) - if err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return GroupsPage{}, sdkerr - } - gp := GroupsPage{} - if err := json.Unmarshal(body, &gp); err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - - return gp, nil -} - -func (sdk mgSDK) changeGroupStatus(id, status, token string) (Group, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s/%s", sdk.usersURL, groupsEndpoint, id, status) - - _, body, err := sdk.processRequest(http.MethodPost, url, token, nil, nil, http.StatusOK) - if err != nil { - return Group{}, err - } - g := Group{} - if err := json.Unmarshal(body, &g); err != nil { - return Group{}, errors.NewSDKError(err) - } - - return g, nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/health.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/health.go deleted file mode 100644 index 1c732c03..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/health.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - - "github.com/absmach/magistrala/pkg/errors" -) - -// HealthInfo contains version endpoint response. -type HealthInfo struct { - // Status contains service status. - Status string `json:"status"` - - // Version contains current service version. - Version string `json:"version"` - - // Commit represents the git hash commit. - Commit string `json:"commit"` - - // Description contains service description. - Description string `json:"description"` - - // BuildTime contains service build time. - BuildTime string `json:"build_time"` -} - -func (sdk mgSDK) Health(service string) (HealthInfo, errors.SDKError) { - var url string - switch service { - case "things": - url = fmt.Sprintf("%s/health", sdk.thingsURL) - case "users": - url = fmt.Sprintf("%s/health", sdk.usersURL) - case "bootstrap": - url = fmt.Sprintf("%s/health", sdk.bootstrapURL) - case "certs": - url = fmt.Sprintf("%s/health", sdk.certsURL) - case "reader": - url = fmt.Sprintf("%s/health", sdk.readerURL) - case "http-adapter": - url = fmt.Sprintf("%s/health", sdk.httpAdapterURL) - } - - resp, err := sdk.client.Get(url) - if err != nil { - return HealthInfo{}, errors.NewSDKError(err) - } - defer resp.Body.Close() - - if err := errors.CheckError(resp, http.StatusOK); err != nil { - return HealthInfo{}, err - } - - var h HealthInfo - if err := json.NewDecoder(resp.Body).Decode(&h); err != nil { - return HealthInfo{}, errors.NewSDKError(err) - } - - return h, nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/message.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/message.go deleted file mode 100644 index 30f5a633..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/message.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - - "github.com/absmach/magistrala/internal/apiutil" - "github.com/absmach/magistrala/pkg/errors" -) - -const channelParts = 2 - -func (sdk mgSDK) SendMessage(chanName, msg, key string) errors.SDKError { - chanNameParts := strings.SplitN(chanName, ".", channelParts) - chanID := chanNameParts[0] - subtopicPart := "" - if len(chanNameParts) == channelParts { - subtopicPart = fmt.Sprintf("/%s", strings.ReplaceAll(chanNameParts[1], ".", "/")) - } - - url := fmt.Sprintf("%s/channels/%s/messages%s", sdk.httpAdapterURL, chanID, subtopicPart) - - _, _, err := sdk.processRequest(http.MethodPost, url, ThingPrefix+key, []byte(msg), nil, http.StatusAccepted) - - return err -} - -func (sdk mgSDK) ReadMessages(chanName, token string) (MessagesPage, errors.SDKError) { - chanNameParts := strings.SplitN(chanName, ".", channelParts) - chanID := chanNameParts[0] - subtopicPart := "" - if len(chanNameParts) == channelParts { - subtopicPart = fmt.Sprintf("?subtopic=%s", chanNameParts[1]) - } - - url := fmt.Sprintf("%s/channels/%s/messages%s", sdk.readerURL, chanID, subtopicPart) - - header := make(map[string]string) - header["Content-Type"] = string(sdk.msgContentType) - - _, body, err := sdk.processRequest(http.MethodGet, url, token, nil, header, http.StatusOK) - if err != nil { - return MessagesPage{}, err - } - - var mp MessagesPage - if err := json.Unmarshal(body, &mp); err != nil { - return MessagesPage{}, errors.NewSDKError(err) - } - - return mp, nil -} - -func (sdk *mgSDK) SetContentType(ct ContentType) errors.SDKError { - if ct != CTJSON && ct != CTJSONSenML && ct != CTBinary { - return errors.NewSDKError(apiutil.ErrUnsupportedContentType) - } - - sdk.msgContentType = ct - - return nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/metadata.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/metadata.go deleted file mode 100644 index f9b5360b..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -type Metadata map[string]interface{} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/requests.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/requests.go deleted file mode 100644 index 6cd714b8..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/requests.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -// updateClientSecretReq is used to update the client secret. -type updateClientSecretReq struct { - OldSecret string `json:"old_secret,omitempty"` - NewSecret string `json:"new_secret,omitempty"` -} - -type resetPasswordRequestreq struct { - Email string `json:"email"` - Host string `json:"host"` -} - -type resetPasswordReq struct { - Token string `json:"token"` - Password string `json:"password"` - ConfPass string `json:"confirm_password"` -} - -type updateThingSecretReq struct { - Secret string `json:"secret,omitempty"` -} - -// updateClientIdentityReq is used to update the client identity. -type updateClientIdentityReq struct { - token string - id string - Identity string `json:"identity,omitempty"` -} - -// UserPasswordReq contains old and new passwords. -type UserPasswordReq struct { - OldPassword string `json:"old_password,omitempty"` - Password string `json:"password,omitempty"` -} - -// Connection contains thing and channel ID that are connected. -type Connection struct { - ThingID string `json:"thing_id,omitempty"` - ChannelID string `json:"channel_id,omitempty"` -} - -type tokenReq struct { - Identity string `json:"identity"` - Secret string `json:"secret"` -} - -type UsersRelationRequest struct { - Relation string `json:"relation"` - UserIDs []string `json:"user_ids"` -} - -type UserGroupsRequest struct { - UserGroupIDs []string `json:"group_ids"` -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/responses.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/responses.go deleted file mode 100644 index 63d2f095..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/responses.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "time" - - "github.com/absmach/magistrala/pkg/transformers/senml" -) - -type createThingsRes struct { - Things []Thing `json:"things"` -} - -type createChannelsRes struct { - Channels []Channel `json:"channels"` -} - -type pageRes struct { - Total uint64 `json:"total"` - Offset uint64 `json:"offset"` - Limit uint64 `json:"limit"` -} - -// ThingsPage contains list of things in a page with proper metadata. -type ThingsPage struct { - Things []Thing `json:"things"` - pageRes -} - -// ChannelsPage contains list of channels in a page with proper metadata. -type ChannelsPage struct { - Channels []Channel `json:"groups"` - pageRes -} - -// MessagesPage contains list of messages in a page with proper metadata. -type MessagesPage struct { - Messages []senml.Message `json:"messages,omitempty"` - pageRes -} - -type GroupsPage struct { - Groups []Group `json:"groups"` - pageRes -} - -type UsersPage struct { - Users []User `json:"users"` - pageRes -} - -type MembersPage struct { - Members []User `json:"members"` - pageRes -} - -// MembershipsPage contains page related metadata as well as list of memberships that -// belong to this page. -type MembershipsPage struct { - pageRes - Memberships []Group `json:"memberships"` -} - -type revokeCertsRes struct { - RevocationTime time.Time `json:"revocation_time"` -} - -// BoostrapsPage contains list of boostrap configs in a page with proper metadata. -type BootstrapPage struct { - Configs []BootstrapConfig `json:"configs"` - pageRes -} - -type CertSerials struct { - Certs []Cert `json:"certs"` - pageRes -} - -type SubscriptionPage struct { - Subscriptions []Subscription `json:"subscriptions"` - pageRes -} - -type identifyThingResp struct { - ID string `json:"id,omitempty"` -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/sdk.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/sdk.go deleted file mode 100644 index 7fe3f55b..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/sdk.go +++ /dev/null @@ -1,1128 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/absmach/magistrala/pkg/errors" -) - -const ( - // CTJSON represents JSON content type. - CTJSON ContentType = "application/json" - - // CTJSONSenML represents JSON SenML content type. - CTJSONSenML ContentType = "application/senml+json" - - // CTBinary represents binary content type. - CTBinary ContentType = "application/octet-stream" - - // EnabledStatus represents enable status for a client. - EnabledStatus = "enabled" - - // DisabledStatus represents disabled status for a client. - DisabledStatus = "disabled" - - BearerPrefix = "Bearer " - - ThingPrefix = "Thing " -) - -// ContentType represents all possible content types. -type ContentType string - -var _ SDK = (*mgSDK)(nil) - -var ( - // ErrFailedCreation indicates that entity creation failed. - ErrFailedCreation = errors.New("failed to create entity in the db") - - // ErrFailedList indicates that entities list failed. - ErrFailedList = errors.New("failed to list entities") - - // ErrFailedUpdate indicates that entity update failed. - ErrFailedUpdate = errors.New("failed to update entity") - - // ErrFailedFetch indicates that fetching of entity data failed. - ErrFailedFetch = errors.New("failed to fetch entity") - - // ErrFailedRemoval indicates that entity removal failed. - ErrFailedRemoval = errors.New("failed to remove entity") - - // ErrFailedEnable indicates that client enable failed. - ErrFailedEnable = errors.New("failed to enable client") - - // ErrFailedDisable indicates that client disable failed. - ErrFailedDisable = errors.New("failed to disable client") - - ErrInvalidJWT = errors.New("invalid JWT") -) - -type PageMetadata struct { - Total uint64 `json:"total"` - Offset uint64 `json:"offset"` - Limit uint64 `json:"limit"` - Level uint64 `json:"level,omitempty"` - Email string `json:"email,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` - Metadata Metadata `json:"metadata,omitempty"` - Status string `json:"status,omitempty"` - Action string `json:"action,omitempty"` - Subject string `json:"subject,omitempty"` - Object string `json:"object,omitempty"` - Permission string `json:"permission,omitempty"` - Tag string `json:"tag,omitempty"` - Owner string `json:"owner,omitempty"` - SharedBy string `json:"shared_by,omitempty"` - Visibility string `json:"visibility,omitempty"` - OwnerID string `json:"owner_id,omitempty"` - Topic string `json:"topic,omitempty"` - Contact string `json:"contact,omitempty"` - State string `json:"state,omitempty"` -} - -// Credentials represent client credentials: it contains -// "identity" which can be a username, email, generated name; -// and "secret" which can be a password or access token. -type Credentials struct { - Identity string `json:"identity,omitempty"` // username or generated login ID - Secret string `json:"secret,omitempty"` // password or token -} - -// SDK contains Magistrala API. -type SDK interface { - // CreateUser registers magistrala user. - // - // example: - // user := sdk.User{ - // Name: "John Doe", - // Credentials: sdk.Credentials{ - // Identity: "john.doe@example", - // Secret: "12345678", - // }, - // } - // user, _ := sdk.CreateUser(user) - // fmt.Println(user) - CreateUser(user User, token string) (User, errors.SDKError) - - // User returns user object by id. - // - // example: - // user, _ := sdk.User("userID", "token") - // fmt.Println(user) - User(id, token string) (User, errors.SDKError) - - // Users returns list of users. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Name: "John Doe", - // } - // users, _ := sdk.Users(pm, "token") - // fmt.Println(users) - Users(pm PageMetadata, token string) (UsersPage, errors.SDKError) - - // UserProfile returns user logged in. - // - // example: - // user, _ := sdk.UserProfile("token") - // fmt.Println(user) - UserProfile(token string) (User, errors.SDKError) - - // UpdateUser updates existing user. - // - // example: - // user := sdk.User{ - // ID: "userID", - // Name: "John Doe", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // } - // user, _ := sdk.UpdateUser(user, "token") - // fmt.Println(user) - UpdateUser(user User, token string) (User, errors.SDKError) - - // UpdateUserTags updates the user's tags. - // - // example: - // user := sdk.User{ - // ID: "userID", - // Tags: []string{"tag1", "tag2"}, - // } - // user, _ := sdk.UpdateUserTags(user, "token") - // fmt.Println(user) - UpdateUserTags(user User, token string) (User, errors.SDKError) - - // UpdateUserIdentity updates the user's identity - // - // example: - // user := sdk.User{ - // ID: "userID", - // Credentials: sdk.Credentials{ - // Identity: "john.doe@example", - // }, - // } - // user, _ := sdk.UpdateUserIdentity(user, "token") - // fmt.Println(user) - UpdateUserIdentity(user User, token string) (User, errors.SDKError) - - // UpdateUserOwner updates the user's owner. - // - // example: - // user := sdk.User{ - // ID: "userID", - // Owner: "ownerID", - // } - // user, _ := sdk.UpdateUserOwner(user, "token") - // fmt.Println(user) - UpdateUserOwner(user User, token string) (User, errors.SDKError) - - // ResetPasswordRequest sends a password request email to a user. - // - // example: - // err := sdk.ResetPasswordRequest("example@email.com") - // fmt.Println(err) - ResetPasswordRequest(email string) errors.SDKError - - // ResetPassword changes a user's password to the one passed in the argument. - // - // example: - // err := sdk.ResetPassword("password","password","token") - // fmt.Println(err) - ResetPassword(password, confPass, token string) errors.SDKError - - // UpdatePassword updates user password. - // - // example: - // user, _ := sdk.UpdatePassword("oldPass", "newPass", "token") - // fmt.Println(user) - UpdatePassword(oldPass, newPass, token string) (User, errors.SDKError) - - // EnableUser changes the status of the user to enabled. - // - // example: - // user, _ := sdk.EnableUser("userID", "token") - // fmt.Println(user) - EnableUser(id, token string) (User, errors.SDKError) - - // DisableUser changes the status of the user to disabled. - // - // example: - // user, _ := sdk.DisableUser("userID", "token") - // fmt.Println(user) - DisableUser(id, token string) (User, errors.SDKError) - - // CreateToken receives credentials and returns user token. - // - // example: - // user := sdk.User{ - // Credentials: sdk.Credentials{ - // Identity: "john.doe@example", - // Secret: "12345678", - // }, - // } - // token, _ := sdk.CreateToken(user) - // fmt.Println(token) - CreateToken(user User) (Token, errors.SDKError) - - // RefreshToken receives credentials and returns user token. - // - // example: - // token, _ := sdk.RefreshToken("refresh_token") - // fmt.Println(token) - RefreshToken(token string) (Token, errors.SDKError) - - // ListUserChannels list all channels belongs a particular user id. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Permission: "edit", // available Options: "administrator", "delete", edit", "view", "share", "owner", "admin", "editor", "viewer" - // } - // channels, _ := sdk.ListUserChannels("user_id_1", pm, "token") - // fmt.Println(channels) - ListUserChannels(userID string, pm PageMetadata, token string) (ChannelsPage, errors.SDKError) - - // ListUserGroups list all groups belongs a particular user id. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Permission: "edit", // available Options: "administrator", "delete", edit", "view", "share", "owner", "admin", "editor", "viewer" - // } - // groups, _ := sdk.ListUserGroups("user_id_1", pm, "token") - // fmt.Println(channels) - ListUserGroups(userID string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) - - // ListUserThings list all things belongs a particular user id. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Permission: "edit", // available Options: "administrator", "delete", edit", "view", "share", "owner", "admin", "editor", "viewer" - // } - // things, _ := sdk.ListUserThings("user_id_1", pm, "token") - // fmt.Println(things) - ListUserThings(userID string, pm PageMetadata, token string) (ThingsPage, errors.SDKError) - - // CreateThing registers new thing and returns its id. - // - // example: - // thing := sdk.Thing{ - // Name: "My Thing", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // } - // thing, _ := sdk.CreateThing(thing, "token") - // fmt.Println(thing) - CreateThing(thing Thing, token string) (Thing, errors.SDKError) - - // CreateThings registers new things and returns their ids. - // - // example: - // things := []sdk.Thing{ - // { - // Name: "My Thing 1", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // }, - // { - // Name: "My Thing 2", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // }, - // } - // things, _ := sdk.CreateThings(things, "token") - // fmt.Println(things) - CreateThings(things []Thing, token string) ([]Thing, errors.SDKError) - - // Filters things and returns a page result. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Name: "My Thing", - // } - // things, _ := sdk.Things(pm, "token") - // fmt.Println(things) - Things(pm PageMetadata, token string) (ThingsPage, errors.SDKError) - - // ThingsByChannel returns page of things that are connected to specified channel. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Name: "My Thing", - // } - // things, _ := sdk.ThingsByChannel("channelID", pm, "token") - // fmt.Println(things) - ThingsByChannel(chanID string, pm PageMetadata, token string) (ThingsPage, errors.SDKError) - - // Thing returns thing object by id. - // - // example: - // thing, _ := sdk.Thing("thingID", "token") - // fmt.Println(thing) - Thing(id, token string) (Thing, errors.SDKError) - - // UpdateThing updates existing thing. - // - // example: - // thing := sdk.Thing{ - // ID: "thingID", - // Name: "My Thing", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // } - // thing, _ := sdk.UpdateThing(thing, "token") - // fmt.Println(thing) - UpdateThing(thing Thing, token string) (Thing, errors.SDKError) - - // UpdateThingTags updates the client's tags. - // - // example: - // thing := sdk.Thing{ - // ID: "thingID", - // Tags: []string{"tag1", "tag2"}, - // } - // thing, _ := sdk.UpdateThingTags(thing, "token") - // fmt.Println(thing) - UpdateThingTags(thing Thing, token string) (Thing, errors.SDKError) - - // UpdateThingSecret updates the client's secret - // - // example: - // thing, err := sdk.UpdateThingSecret("thingID", "newSecret", "token") - // fmt.Println(thing) - UpdateThingSecret(id, secret, token string) (Thing, errors.SDKError) - - // UpdateThingOwner updates the client's owner. - // - // example: - // thing := sdk.Thing{ - // ID: "thingID", - // Owner: "ownerID", - // } - // thing, _ := sdk.UpdateThingOwner(thing, "token") - // fmt.Println(thing) - UpdateThingOwner(thing Thing, token string) (Thing, errors.SDKError) - - // EnableThing changes client status to enabled. - // - // example: - // thing, _ := sdk.EnableThing("thingID", "token") - // fmt.Println(thing) - EnableThing(id, token string) (Thing, errors.SDKError) - - // DisableThing changes client status to disabled - soft delete. - // - // example: - // thing, _ := sdk.DisableThing("thingID", "token") - // fmt.Println(thing) - DisableThing(id, token string) (Thing, errors.SDKError) - - // IdentifyThing validates thing's key and returns its ID - // - // example: - // id, _ := sdk.IdentifyThing("thingKey") - // fmt.Println(id) - IdentifyThing(key string) (string, errors.SDKError) - - // ShareThing shares thing with other users. - // - // example: - // req := sdk.UsersRelationRequest{ - // Relation: "viewer", // available options: "owner", "admin", "editor", "viewer" - // UserIDs: ["user_id_1", "user_id_2", "user_id_3"] - // } - // err := sdk.ShareThing("thing_id", req, "token") - // fmt.Println(err) - ShareThing(thingID string, req UsersRelationRequest, token string) errors.SDKError - - // UnshareThing unshare a thing with other users. - // - // example: - // req := sdk.UsersRelationRequest{ - // Relation: "viewer", // available options: "owner", "admin", "editor", "viewer" - // UserIDs: ["user_id_1", "user_id_2", "user_id_3"] - // } - // err := sdk.UnshareThing("thing_id", req, "token") - // fmt.Println(err) - UnshareThing(thingID string, req UsersRelationRequest, token string) errors.SDKError - - // ListThingUsers all users in a thing. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Permission: "edit", // available Options: "administrator", "delete", edit", "view", "share", "owner", "admin", "editor", "viewer" - // } - // users, _ := sdk.ListThingUsers("thing_id", pm, "token") - // fmt.Println(users) - ListThingUsers(thingID string, pm PageMetadata, token string) (UsersPage, errors.SDKError) - - // CreateGroup creates new group and returns its id. - // - // example: - // group := sdk.Group{ - // Name: "My Group", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // } - // group, _ := sdk.CreateGroup(group, "token") - // fmt.Println(group) - CreateGroup(group Group, token string) (Group, errors.SDKError) - - // Groups returns page of groups. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Name: "My Group", - // } - // groups, _ := sdk.Groups(pm, "token") - // fmt.Println(groups) - Groups(pm PageMetadata, token string) (GroupsPage, errors.SDKError) - - // Parents returns page of users groups. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Name: "My Group", - // } - // groups, _ := sdk.Parents("groupID", pm, "token") - // fmt.Println(groups) - Parents(id string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) - - // Children returns page of users groups. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Name: "My Group", - // } - // groups, _ := sdk.Children("groupID", pm, "token") - // fmt.Println(groups) - Children(id string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) - - // Group returns users group object by id. - // - // example: - // group, _ := sdk.Group("groupID", "token") - // fmt.Println(group) - Group(id, token string) (Group, errors.SDKError) - - // UpdateGroup updates existing group. - // - // example: - // group := sdk.Group{ - // ID: "groupID", - // Name: "My Group", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // } - // group, _ := sdk.UpdateGroup(group, "token") - // fmt.Println(group) - UpdateGroup(group Group, token string) (Group, errors.SDKError) - - // EnableGroup changes group status to enabled. - // - // example: - // group, _ := sdk.EnableGroup("groupID", "token") - // fmt.Println(group) - EnableGroup(id, token string) (Group, errors.SDKError) - - // DisableGroup changes group status to disabled - soft delete. - // - // example: - // group, _ := sdk.DisableGroup("groupID", "token") - // fmt.Println(group) - DisableGroup(id, token string) (Group, errors.SDKError) - - // AddUserToGroup add user to a group. - // - // example: - // req := sdk.UsersRelationRequest{ - // Relation: "viewer", // available options: "owner", "admin", "editor", "viewer" - // UserIDs: ["user_id_1", "user_id_2", "user_id_3"] - // } - // group, _ := sdk.AddUserToGroup("groupID",req, "token") - // fmt.Println(group) - AddUserToGroup(groupID string, req UsersRelationRequest, token string) errors.SDKError - - // RemoveUserFromGroup remove user from a group. - // - // example: - // req := sdk.UsersRelationRequest{ - // Relation: "viewer", // available options: "owner", "admin", "editor", "viewer" - // UserIDs: ["user_id_1", "user_id_2", "user_id_3"] - // } - // group, _ := sdk.RemoveUserFromGroup("groupID",req, "token") - // fmt.Println(group) - RemoveUserFromGroup(groupID string, req UsersRelationRequest, token string) errors.SDKError - - // ListGroupUsers list all users in the group id . - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Permission: "edit", // available Options: "administrator", "delete", edit", "view", "share", "owner", "admin", "editor", "viewer" - // } - // groups, _ := sdk.ListGroupUsers("groupID", pm, "token") - // fmt.Println(groups) - ListGroupUsers(groupID string, pm PageMetadata, token string) (UsersPage, errors.SDKError) - - // ListGroupChannels list all channels in the group id . - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Permission: "edit", // available Options: "administrator", "delete", edit", "view", "share", "owner", "admin", "editor", "viewer" - // } - // groups, _ := sdk.ListGroupChannels("groupID", pm, "token") - // fmt.Println(groups) - ListGroupChannels(groupID string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) - - // CreateChannel creates new channel and returns its id. - // - // example: - // channel := sdk.Channel{ - // Name: "My Channel", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // } - // channel, _ := sdk.CreateChannel(channel, "token") - // fmt.Println(channel) - CreateChannel(channel Channel, token string) (Channel, errors.SDKError) - - // CreateChannels registers new channels and returns their ids. - // - // example: - // channels := []sdk.Channel{ - // { - // Name: "My Channel 1", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // }, - // { - // Name: "My Channel 2", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // }, - // } - // channels, _ := sdk.CreateChannels(channels, "token") - // fmt.Println(channels) - CreateChannels(channels []Channel, token string) ([]Channel, errors.SDKError) - - // Channels returns page of channels. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Name: "My Channel", - // } - // channels, _ := sdk.Channels(pm, "token") - // fmt.Println(channels) - Channels(pm PageMetadata, token string) (ChannelsPage, errors.SDKError) - - // ChannelsByThing returns page of channels that are connected to specified thing. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Name: "My Channel", - // } - // channels, _ := sdk.ChannelsByThing("thingID", pm, "token") - // fmt.Println(channels) - ChannelsByThing(thingID string, pm PageMetadata, token string) (ChannelsPage, errors.SDKError) - - // Channel returns channel data by id. - // - // example: - // channel, _ := sdk.Channel("channelID", "token") - // fmt.Println(channel) - Channel(id, token string) (Channel, errors.SDKError) - - // UpdateChannel updates existing channel. - // - // example: - // channel := sdk.Channel{ - // ID: "channelID", - // Name: "My Channel", - // Metadata: sdk.Metadata{ - // "key": "value", - // }, - // } - // channel, _ := sdk.UpdateChannel(channel, "token") - // fmt.Println(channel) - UpdateChannel(channel Channel, token string) (Channel, errors.SDKError) - - // EnableChannel changes channel status to enabled. - // - // example: - // channel, _ := sdk.EnableChannel("channelID", "token") - // fmt.Println(channel) - EnableChannel(id, token string) (Channel, errors.SDKError) - - // DisableChannel changes channel status to disabled - soft delete. - // - // example: - // channel, _ := sdk.DisableChannel("channelID", "token") - // fmt.Println(channel) - DisableChannel(id, token string) (Channel, errors.SDKError) - - // AddUserToChannel add user to a channel. - // - // example: - // req := sdk.UsersRelationRequest{ - // Relation: "viewer", // available options: "owner", "admin", "editor", "viewer" - // UserIDs: ["user_id_1", "user_id_2", "user_id_3"] - // } - // err := sdk.AddUserToChannel("channel_id", req, "token") - // fmt.Println(err) - AddUserToChannel(channelID string, req UsersRelationRequest, token string) errors.SDKError - - // RemoveUserFromChannel remove user from a group. - // - // example: - // req := sdk.UsersRelationRequest{ - // Relation: "viewer", // available options: "owner", "admin", "editor", "viewer" - // UserIDs: ["user_id_1", "user_id_2", "user_id_3"] - // } - // err := sdk.RemoveUserFromChannel("channel_id", req, "token") - // fmt.Println(err) - RemoveUserFromChannel(channelID string, req UsersRelationRequest, token string) errors.SDKError - - // ListChannelUsers list all users in a channel . - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Permission: "edit", // available Options: "administrator", "delete", edit", "view", "share", "owner", "admin", "editor", "viewer" - // } - // users, _ := sdk.ListChannelUsers("channel_id", pm, "token") - // fmt.Println(users) - ListChannelUsers(channelID string, pm PageMetadata, token string) (UsersPage, errors.SDKError) - - // AddUserGroupToChannel add user group to a channel. - // - // example: - // req := sdk.UserGroupsRequest{ - // GroupsIDs: ["group_id_1", "group_id_2", "group_id_3"] - // } - // err := sdk.AddUserGroupToChannel("channel_id",req, "token") - // fmt.Println(err) - AddUserGroupToChannel(channelID string, req UserGroupsRequest, token string) errors.SDKError - - // RemoveUserGroupFromChannel remove user group from a channel. - // - // example: - // req := sdk.UserGroupsRequest{ - // GroupsIDs: ["group_id_1", "group_id_2", "group_id_3"] - // } - // err := sdk.RemoveUserGroupFromChannel("channel_id",req, "token") - // fmt.Println(err) - RemoveUserGroupFromChannel(channelID string, req UserGroupsRequest, token string) errors.SDKError - - // ListChannelUserGroups list all user groups in a channel. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // Permission: "view", - // } - // groups, _ := sdk.ListChannelUserGroups("channel_id_1", pm, "token") - // fmt.Println(groups) - ListChannelUserGroups(channelID string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) - - // Connect bulk connects things to channels specified by id. - // - // example: - // conns := sdk.Connection{ - // ChannelID: "channel_id_1", - // ThingID: "thing_id_1", - // } - // err := sdk.Connect(conns, "token") - // fmt.Println(err) - Connect(conns Connection, token string) errors.SDKError - - // Disconnect - // - // example: - // conns := sdk.Connection{ - // ChannelID: "channel_id_1", - // ThingID: "thing_id_1", - // } - // err := sdk.Disconnect(conns, "token") - // fmt.Println(err) - Disconnect(connIDs Connection, token string) errors.SDKError - - // ConnectThing connects thing to specified channel by id. - // - // The `ConnectThing` method calls the `CreateThingPolicy` method under the hood. - // - // example: - // err := sdk.ConnectThing("thingID", "channelID", "token") - // fmt.Println(err) - ConnectThing(thingID, chanID, token string) errors.SDKError - - // DisconnectThing disconnect thing from specified channel by id. - // - // The `DisconnectThing` method calls the `DeleteThingPolicy` method under the hood. - // - // example: - // err := sdk.DisconnectThing("thingID", "channelID", "token") - // fmt.Println(err) - DisconnectThing(thingID, chanID, token string) errors.SDKError - - // SendMessage send message to specified channel. - // - // example: - // msg := '[{"bn":"some-base-name:","bt":1.276020076001e+09, "bu":"A","bver":5, "n":"voltage","u":"V","v":120.1}, {"n":"current","t":-5,"v":1.2}, {"n":"current","t":-4,"v":1.3}]' - // err := sdk.SendMessage("channelID", msg, "thingSecret") - // fmt.Println(err) - SendMessage(chanID, msg, key string) errors.SDKError - - // ReadMessages read messages of specified channel. - // - // example: - // msgs, _ := sdk.ReadMessages("channelID", "token") - // fmt.Println(msgs) - ReadMessages(chanID, token string) (MessagesPage, errors.SDKError) - - // SetContentType sets message content type. - // - // example: - // err := sdk.SetContentType("application/json") - // fmt.Println(err) - SetContentType(ct ContentType) errors.SDKError - - // Health returns service health check. - // - // example: - // health, _ := sdk.Health("service") - // fmt.Println(health) - Health(service string) (HealthInfo, errors.SDKError) - - // AddBootstrap add bootstrap configuration - // - // example: - // cfg := sdk.BootstrapConfig{ - // ThingID: "thingID", - // Name: "bootstrap", - // ExternalID: "externalID", - // ExternalKey: "externalKey", - // Channels: []string{"channel1", "channel2"}, - // } - // id, _ := sdk.AddBootstrap(cfg, "token") - // fmt.Println(id) - AddBootstrap(cfg BootstrapConfig, token string) (string, errors.SDKError) - - // View returns Thing Config with given ID belonging to the user identified by the given token. - // - // example: - // bootstrap, _ := sdk.ViewBootstrap("id", "token") - // fmt.Println(bootstrap) - ViewBootstrap(id, token string) (BootstrapConfig, errors.SDKError) - - // Update updates editable fields of the provided Config. - // - // example: - // cfg := sdk.BootstrapConfig{ - // ThingID: "thingID", - // Name: "bootstrap", - // ExternalID: "externalID", - // ExternalKey: "externalKey", - // Channels: []string{"channel1", "channel2"}, - // } - // err := sdk.UpdateBootstrap(cfg, "token") - // fmt.Println(err) - UpdateBootstrap(cfg BootstrapConfig, token string) errors.SDKError - - // Update bootstrap config certificates. - // - // example: - // err := sdk.UpdateBootstrapCerts("id", "clientCert", "clientKey", "ca", "token") - // fmt.Println(err) - UpdateBootstrapCerts(id string, clientCert, clientKey, ca string, token string) (BootstrapConfig, errors.SDKError) - - // UpdateBootstrapConnection updates connections performs update of the channel list corresponding Thing is connected to. - // - // example: - // err := sdk.UpdateBootstrapConnection("id", []string{"channel1", "channel2"}, "token") - // fmt.Println(err) - UpdateBootstrapConnection(id string, channels []string, token string) errors.SDKError - - // Remove removes Config with specified token that belongs to the user identified by the given token. - // - // example: - // err := sdk.RemoveBootstrap("id", "token") - // fmt.Println(err) - RemoveBootstrap(id, token string) errors.SDKError - - // Bootstrap returns Config to the Thing with provided external ID using external key. - // - // example: - // bootstrap, _ := sdk.Bootstrap("externalID", "externalKey") - // fmt.Println(bootstrap) - Bootstrap(externalID, externalKey string) (BootstrapConfig, errors.SDKError) - - // BootstrapSecure retrieves a configuration with given external ID and encrypted external key. - // - // example: - // bootstrap, _ := sdk.BootstrapSecure("externalID", "externalKey") - // fmt.Println(bootstrap) - BootstrapSecure(externalID, externalKey string) (BootstrapConfig, errors.SDKError) - - // Bootstraps retrieves a list of managed configs. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // } - // bootstraps, _ := sdk.Bootstraps(pm, "token") - // fmt.Println(bootstraps) - Bootstraps(pm PageMetadata, token string) (BootstrapPage, errors.SDKError) - - // Whitelist updates Thing state Config with given ID belonging to the user identified by the given token. - // - // example: - // cfg := sdk.BootstrapConfig{ - // ThingID: "thingID", - // Name: "bootstrap", - // ExternalID: "externalID", - // ExternalKey: "externalKey", - // Channels: []string{"channel1", "channel2"}, - // } - // err := sdk.Whitelist(cfg, "token") - // fmt.Println(err) - Whitelist(cfg BootstrapConfig, token string) errors.SDKError - - // IssueCert issues a certificate for a thing required for mTLS. - // - // example: - // cert, _ := sdk.IssueCert("thingID", "valid", "token") - // fmt.Println(cert) - IssueCert(thingID, valid, token string) (Cert, errors.SDKError) - - // ViewCert returns a certificate given certificate ID - // - // example: - // cert, _ := sdk.ViewCert("certID", "token") - // fmt.Println(cert) - ViewCert(certID, token string) (Cert, errors.SDKError) - - // ViewCertByThing retrieves a list of certificates' serial IDs for a given thing ID. - // - // example: - // cserial, _ := sdk.ViewCertByThing("thingID", "token") - // fmt.Println(cserial) - ViewCertByThing(thingID, token string) (CertSerials, errors.SDKError) - - // RevokeCert revokes certificate for thing with thingID - // - // example: - // tm, _ := sdk.RevokeCert("thingID", "token") - // fmt.Println(tm) - RevokeCert(thingID, token string) (time.Time, errors.SDKError) - - // CreateSubscription creates a new subscription - // - // example: - // subscription, _ := sdk.CreateSubscription("topic", "contact", "token") - // fmt.Println(subscription) - CreateSubscription(topic, contact, token string) (string, errors.SDKError) - - // ListSubscriptions list subscriptions given list parameters. - // - // example: - // pm := sdk.PageMetadata{ - // Offset: 0, - // Limit: 10, - // } - // subscriptions, _ := sdk.ListSubscriptions(pm, "token") - // fmt.Println(subscriptions) - ListSubscriptions(pm PageMetadata, token string) (SubscriptionPage, errors.SDKError) - - // ViewSubscription retrieves a subscription with the provided id. - // - // example: - // subscription, _ := sdk.ViewSubscription("id", "token") - // fmt.Println(subscription) - ViewSubscription(id, token string) (Subscription, errors.SDKError) - - // DeleteSubscription removes a subscription with the provided id. - // - // example: - // err := sdk.DeleteSubscription("id", "token") - // fmt.Println(err) - DeleteSubscription(id, token string) errors.SDKError -} - -type mgSDK struct { - bootstrapURL string - certsURL string - httpAdapterURL string - readerURL string - thingsURL string - usersURL string - HostURL string - - msgContentType ContentType - client *http.Client -} - -// Config contains sdk configuration parameters. -type Config struct { - BootstrapURL string - CertsURL string - HTTPAdapterURL string - ReaderURL string - ThingsURL string - UsersURL string - HostURL string - - MsgContentType ContentType - TLSVerification bool -} - -// NewSDK returns new magistrala SDK instance. -func NewSDK(conf Config) SDK { - return &mgSDK{ - bootstrapURL: conf.BootstrapURL, - certsURL: conf.CertsURL, - httpAdapterURL: conf.HTTPAdapterURL, - readerURL: conf.ReaderURL, - thingsURL: conf.ThingsURL, - usersURL: conf.UsersURL, - HostURL: conf.HostURL, - - msgContentType: conf.MsgContentType, - client: &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: !conf.TLSVerification, - }, - }, - }, - } -} - -// processRequest creates and send a new HTTP request, and checks for errors in the HTTP response. -// It then returns the response headers, the response body, and the associated error(s) (if any). -func (sdk mgSDK) processRequest(method, url, token string, data []byte, headers map[string]string, expectedRespCodes ...int) (http.Header, []byte, errors.SDKError) { - req, err := http.NewRequest(method, url, bytes.NewReader(data)) - if err != nil { - return make(http.Header), []byte{}, errors.NewSDKError(err) - } - - // Sets a default value for the Content-Type. - // Overridden if Content-Type is passed in the headers arguments. - req.Header.Add("Content-Type", string(CTJSON)) - - for key, value := range headers { - req.Header.Add(key, value) - } - - if token != "" { - if !strings.Contains(token, ThingPrefix) { - token = BearerPrefix + token - } - req.Header.Set("Authorization", token) - } - - resp, err := sdk.client.Do(req) - if err != nil { - return make(http.Header), []byte{}, errors.NewSDKError(err) - } - defer resp.Body.Close() - - sdkerr := errors.CheckError(resp, expectedRespCodes...) - if sdkerr != nil { - return make(http.Header), []byte{}, sdkerr - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - return make(http.Header), []byte{}, errors.NewSDKError(err) - } - - return resp.Header, body, nil -} - -func (sdk mgSDK) withQueryParams(baseURL, endpoint string, pm PageMetadata) (string, error) { - q, err := pm.query() - if err != nil { - return "", err - } - - return fmt.Sprintf("%s/%s?%s", baseURL, endpoint, q), nil -} - -func (pm PageMetadata) query() (string, error) { - q := url.Values{} - if pm.Offset != 0 { - q.Add("offset", strconv.FormatUint(pm.Offset, 10)) - } - if pm.Limit != 0 { - q.Add("limit", strconv.FormatUint(pm.Limit, 10)) - } - if pm.Total != 0 { - q.Add("total", strconv.FormatUint(pm.Total, 10)) - } - if pm.Level != 0 { - q.Add("level", strconv.FormatUint(pm.Level, 10)) - } - if pm.Email != "" { - q.Add("email", pm.Email) - } - if pm.Name != "" { - q.Add("name", pm.Name) - } - if pm.Type != "" { - q.Add("type", pm.Type) - } - if pm.Visibility != "" { - q.Add("visibility", pm.Visibility) - } - if pm.Status != "" { - q.Add("status", pm.Status) - } - if pm.Metadata != nil { - md, err := json.Marshal(pm.Metadata) - if err != nil { - return "", errors.NewSDKError(err) - } - q.Add("metadata", string(md)) - } - if pm.Action != "" { - q.Add("action", pm.Action) - } - if pm.Subject != "" { - q.Add("subject", pm.Subject) - } - if pm.Object != "" { - q.Add("object", pm.Object) - } - if pm.Tag != "" { - q.Add("tag", pm.Tag) - } - if pm.Owner != "" { - q.Add("owner", pm.Owner) - } - if pm.SharedBy != "" { - q.Add("shared_by", pm.SharedBy) - } - if pm.Topic != "" { - q.Add("topic", pm.Topic) - } - if pm.Contact != "" { - q.Add("contact", pm.Contact) - } - if pm.State != "" { - q.Add("state", pm.State) - } - - return q.Encode(), nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/things.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/things.go deleted file mode 100644 index 94ac9834..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/things.go +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/absmach/magistrala/pkg/errors" -) - -const ( - thingsEndpoint = "things" - connectEndpoint = "connect" - disconnectEndpoint = "disconnect" - identifyEndpoint = "identify" - shareEndpoint = "share" - unshareEndpoint = "unshare" -) - -// Thing represents magistrala thing. -type Thing struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Credentials Credentials `json:"credentials"` - Tags []string `json:"tags,omitempty"` - Owner string `json:"owner,omitempty"` - Metadata map[string]interface{} `json:"metadata,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` - Status string `json:"status,omitempty"` -} - -func (sdk mgSDK) CreateThing(thing Thing, token string) (Thing, errors.SDKError) { - data, err := json.Marshal(thing) - if err != nil { - return Thing{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s", sdk.thingsURL, thingsEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - if sdkerr != nil { - return Thing{}, sdkerr - } - - thing = Thing{} - if err := json.Unmarshal(body, &thing); err != nil { - return Thing{}, errors.NewSDKError(err) - } - - return thing, nil -} - -func (sdk mgSDK) CreateThings(things []Thing, token string) ([]Thing, errors.SDKError) { - data, err := json.Marshal(things) - if err != nil { - return []Thing{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, thingsEndpoint, "bulk") - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return []Thing{}, sdkerr - } - - var ctr createThingsRes - if err := json.Unmarshal(body, &ctr); err != nil { - return []Thing{}, errors.NewSDKError(err) - } - - return ctr.Things, nil -} - -func (sdk mgSDK) Things(pm PageMetadata, token string) (ThingsPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.thingsURL, thingsEndpoint, pm) - if err != nil { - return ThingsPage{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return ThingsPage{}, sdkerr - } - - var cp ThingsPage - if err := json.Unmarshal(body, &cp); err != nil { - return ThingsPage{}, errors.NewSDKError(err) - } - - return cp, nil -} - -func (sdk mgSDK) ThingsByChannel(chanID string, pm PageMetadata, token string) (ThingsPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.thingsURL, fmt.Sprintf("channels/%s/%s", chanID, thingsEndpoint), pm) - if err != nil { - return ThingsPage{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return ThingsPage{}, sdkerr - } - - var tp ThingsPage - if err := json.Unmarshal(body, &tp); err != nil { - return ThingsPage{}, errors.NewSDKError(err) - } - - return tp, nil -} - -func (sdk mgSDK) Thing(id, token string) (Thing, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, thingsEndpoint, id) - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return Thing{}, sdkerr - } - - var t Thing - if err := json.Unmarshal(body, &t); err != nil { - return Thing{}, errors.NewSDKError(err) - } - - return t, nil -} - -func (sdk mgSDK) UpdateThing(t Thing, token string) (Thing, errors.SDKError) { - data, err := json.Marshal(t) - if err != nil { - return Thing{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, thingsEndpoint, t.ID) - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return Thing{}, sdkerr - } - - t = Thing{} - if err := json.Unmarshal(body, &t); err != nil { - return Thing{}, errors.NewSDKError(err) - } - - return t, nil -} - -func (sdk mgSDK) UpdateThingTags(t Thing, token string) (Thing, errors.SDKError) { - data, err := json.Marshal(t) - if err != nil { - return Thing{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/tags", sdk.thingsURL, thingsEndpoint, t.ID) - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return Thing{}, sdkerr - } - - t = Thing{} - if err := json.Unmarshal(body, &t); err != nil { - return Thing{}, errors.NewSDKError(err) - } - - return t, nil -} - -func (sdk mgSDK) UpdateThingSecret(id, secret, token string) (Thing, errors.SDKError) { - ucsr := updateThingSecretReq{Secret: secret} - - data, err := json.Marshal(ucsr) - if err != nil { - return Thing{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/secret", sdk.thingsURL, thingsEndpoint, id) - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return Thing{}, sdkerr - } - - var t Thing - if err = json.Unmarshal(body, &t); err != nil { - return Thing{}, errors.NewSDKError(err) - } - - return t, nil -} - -func (sdk mgSDK) UpdateThingOwner(t Thing, token string) (Thing, errors.SDKError) { - data, err := json.Marshal(t) - if err != nil { - return Thing{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/owner", sdk.thingsURL, thingsEndpoint, t.ID) - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return Thing{}, sdkerr - } - - t = Thing{} - if err = json.Unmarshal(body, &t); err != nil { - return Thing{}, errors.NewSDKError(err) - } - - return t, nil -} - -func (sdk mgSDK) EnableThing(id, token string) (Thing, errors.SDKError) { - return sdk.changeThingStatus(id, enableEndpoint, token) -} - -func (sdk mgSDK) DisableThing(id, token string) (Thing, errors.SDKError) { - return sdk.changeThingStatus(id, disableEndpoint, token) -} - -func (sdk mgSDK) changeThingStatus(id, status, token string) (Thing, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s/%s", sdk.thingsURL, thingsEndpoint, id, status) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return Thing{}, sdkerr - } - - t := Thing{} - if err := json.Unmarshal(body, &t); err != nil { - return Thing{}, errors.NewSDKError(err) - } - - return t, nil -} - -func (sdk mgSDK) IdentifyThing(key string) (string, errors.SDKError) { - url := fmt.Sprintf("%s/%s", sdk.thingsURL, identifyEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, ThingPrefix+key, nil, nil, http.StatusOK) - if sdkerr != nil { - return "", sdkerr - } - - var i identifyThingResp - if err := json.Unmarshal(body, &i); err != nil { - return "", errors.NewSDKError(err) - } - - return i.ID, nil -} - -func (sdk mgSDK) ShareThing(thingID string, req UsersRelationRequest, token string) errors.SDKError { - data, err := json.Marshal(req) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/%s", sdk.thingsURL, thingsEndpoint, thingID, shareEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - return sdkerr -} - -func (sdk mgSDK) UnshareThing(thingID string, req UsersRelationRequest, token string) errors.SDKError { - data, err := json.Marshal(req) - if err != nil { - return errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/%s", sdk.thingsURL, thingsEndpoint, thingID, unshareEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusNoContent) - return sdkerr -} - -func (sdk mgSDK) ListThingUsers(thingID string, pm PageMetadata, token string) (UsersPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.usersURL, fmt.Sprintf("%s/%s/%s", thingsEndpoint, thingID, usersEndpoint), pm) - if err != nil { - return UsersPage{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return UsersPage{}, sdkerr - } - up := UsersPage{} - if err := json.Unmarshal(body, &up); err != nil { - return UsersPage{}, errors.NewSDKError(err) - } - - return up, nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/tokens.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/tokens.go deleted file mode 100644 index 634f7179..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/tokens.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - - "github.com/absmach/magistrala/pkg/errors" -) - -// Token is used for authentication purposes. -// It contains AccessToken, RefreshToken and AccessExpiry. -type Token struct { - AccessToken string `json:"access_token,omitempty"` - RefreshToken string `json:"refresh_token,omitempty"` - AccessType string `json:"access_type,omitempty"` -} - -func (sdk mgSDK) CreateToken(user User) (Token, errors.SDKError) { - treq := tokenReq{ - Identity: user.Credentials.Identity, - Secret: user.Credentials.Secret, - } - data, err := json.Marshal(treq) - if err != nil { - return Token{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s", sdk.usersURL, usersEndpoint, issueTokenEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, "", data, nil, http.StatusCreated) - if sdkerr != nil { - return Token{}, sdkerr - } - var token Token - if err := json.Unmarshal(body, &token); err != nil { - return Token{}, errors.NewSDKError(err) - } - - return token, nil -} - -func (sdk mgSDK) RefreshToken(token string) (Token, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.usersURL, usersEndpoint, refreshTokenEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, []byte{}, nil, http.StatusCreated) - if sdkerr != nil { - return Token{}, sdkerr - } - - t := Token{} - if err := json.Unmarshal(body, &t); err != nil { - return Token{}, errors.NewSDKError(err) - } - - return t, nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/sdk/go/users.go b/vendor/github.com/absmach/magistrala/pkg/sdk/go/users.go deleted file mode 100644 index 5702dc50..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/sdk/go/users.go +++ /dev/null @@ -1,346 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package sdk - -import ( - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/absmach/magistrala/pkg/errors" -) - -const ( - usersEndpoint = "users" - assignEndpoint = "assign" - unassignEndpoint = "unassign" - enableEndpoint = "enable" - disableEndpoint = "disable" - issueTokenEndpoint = "tokens/issue" - refreshTokenEndpoint = "tokens/refresh" - membersEndpoint = "members" - PasswordResetEndpoint = "password" -) - -// User represents magistrala user its credentials. -type User struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Credentials Credentials `json:"credentials"` - Tags []string `json:"tags,omitempty"` - Owner string `json:"owner,omitempty"` - Metadata Metadata `json:"metadata,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` - Status string `json:"status,omitempty"` - Role string `json:"role,omitempty"` -} - -func (sdk mgSDK) CreateUser(user User, token string) (User, errors.SDKError) { - data, err := json.Marshal(user) - if err != nil { - return User{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s", sdk.usersURL, usersEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, data, nil, http.StatusCreated) - if sdkerr != nil { - return User{}, sdkerr - } - - user = User{} - if err := json.Unmarshal(body, &user); err != nil { - return User{}, errors.NewSDKError(err) - } - - return user, nil -} - -func (sdk mgSDK) Users(pm PageMetadata, token string) (UsersPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.usersURL, usersEndpoint, pm) - if err != nil { - return UsersPage{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return UsersPage{}, sdkerr - } - - var cp UsersPage - if err := json.Unmarshal(body, &cp); err != nil { - return UsersPage{}, errors.NewSDKError(err) - } - - return cp, nil -} - -func (sdk mgSDK) Members(groupID string, meta PageMetadata, token string) (MembersPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.usersURL, fmt.Sprintf("%s/%s/%s", groupsEndpoint, groupID, membersEndpoint), meta) - if err != nil { - return MembersPage{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return MembersPage{}, sdkerr - } - - var mp MembersPage - if err := json.Unmarshal(body, &mp); err != nil { - return MembersPage{}, errors.NewSDKError(err) - } - - return mp, nil -} - -func (sdk mgSDK) User(id, token string) (User, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s", sdk.usersURL, usersEndpoint, id) - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return User{}, sdkerr - } - - var user User - if err := json.Unmarshal(body, &user); err != nil { - return User{}, errors.NewSDKError(err) - } - - return user, nil -} - -func (sdk mgSDK) UserProfile(token string) (User, errors.SDKError) { - url := fmt.Sprintf("%s/%s/profile", sdk.usersURL, usersEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return User{}, sdkerr - } - - var user User - if err := json.Unmarshal(body, &user); err != nil { - return User{}, errors.NewSDKError(err) - } - - return user, nil -} - -func (sdk mgSDK) UpdateUser(user User, token string) (User, errors.SDKError) { - data, err := json.Marshal(user) - if err != nil { - return User{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s", sdk.usersURL, usersEndpoint, user.ID) - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return User{}, sdkerr - } - - user = User{} - if err := json.Unmarshal(body, &user); err != nil { - return User{}, errors.NewSDKError(err) - } - - return user, nil -} - -func (sdk mgSDK) UpdateUserTags(user User, token string) (User, errors.SDKError) { - data, err := json.Marshal(user) - if err != nil { - return User{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/tags", sdk.usersURL, usersEndpoint, user.ID) - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return User{}, sdkerr - } - - user = User{} - if err := json.Unmarshal(body, &user); err != nil { - return User{}, errors.NewSDKError(err) - } - - return user, nil -} - -func (sdk mgSDK) UpdateUserIdentity(user User, token string) (User, errors.SDKError) { - ucir := updateClientIdentityReq{token: token, id: user.ID, Identity: user.Credentials.Identity} - - data, err := json.Marshal(ucir) - if err != nil { - return User{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/identity", sdk.usersURL, usersEndpoint, user.ID) - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return User{}, sdkerr - } - - user = User{} - if err := json.Unmarshal(body, &user); err != nil { - return User{}, errors.NewSDKError(err) - } - - return user, nil -} - -func (sdk mgSDK) ResetPasswordRequest(email string) errors.SDKError { - rpr := resetPasswordRequestreq{Email: email} - - data, err := json.Marshal(rpr) - if err != nil { - return errors.NewSDKError(err) - } - url := fmt.Sprintf("%s/%s/reset-request", sdk.usersURL, PasswordResetEndpoint) - - header := make(map[string]string) - header["Referer"] = sdk.HostURL - - _, _, sdkerr := sdk.processRequest(http.MethodPost, url, "", data, header, http.StatusCreated) - - return sdkerr -} - -func (sdk mgSDK) ResetPassword(password, confPass, token string) errors.SDKError { - rpr := resetPasswordReq{Token: token, Password: password, ConfPass: confPass} - - data, err := json.Marshal(rpr) - if err != nil { - return errors.NewSDKError(err) - } - url := fmt.Sprintf("%s/%s/reset", sdk.usersURL, PasswordResetEndpoint) - - _, _, sdkerr := sdk.processRequest(http.MethodPut, url, "", data, nil, http.StatusCreated) - - return sdkerr -} - -func (sdk mgSDK) UpdatePassword(oldPass, newPass, token string) (User, errors.SDKError) { - ucsr := updateClientSecretReq{OldSecret: oldPass, NewSecret: newPass} - - data, err := json.Marshal(ucsr) - if err != nil { - return User{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/secret", sdk.usersURL, usersEndpoint) - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return User{}, sdkerr - } - - var user User - if err = json.Unmarshal(body, &user); err != nil { - return User{}, errors.NewSDKError(err) - } - - return user, nil -} - -func (sdk mgSDK) UpdateUserOwner(user User, token string) (User, errors.SDKError) { - data, err := json.Marshal(user) - if err != nil { - return User{}, errors.NewSDKError(err) - } - - url := fmt.Sprintf("%s/%s/%s/owner", sdk.usersURL, usersEndpoint, user.ID) - - _, body, sdkerr := sdk.processRequest(http.MethodPatch, url, token, data, nil, http.StatusOK) - if sdkerr != nil { - return User{}, sdkerr - } - - user = User{} - if err = json.Unmarshal(body, &user); err != nil { - return User{}, errors.NewSDKError(err) - } - - return user, nil -} - -func (sdk mgSDK) ListUserChannels(userID string, pm PageMetadata, token string) (ChannelsPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.thingsURL, fmt.Sprintf("%s/%s/%s", usersEndpoint, userID, channelsEndpoint), pm) - if err != nil { - return ChannelsPage{}, errors.NewSDKError(err) - } - - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return ChannelsPage{}, sdkerr - } - cp := ChannelsPage{} - if err := json.Unmarshal(body, &cp); err != nil { - return ChannelsPage{}, errors.NewSDKError(err) - } - - return cp, nil -} - -func (sdk mgSDK) ListUserGroups(userID string, pm PageMetadata, token string) (GroupsPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.usersURL, fmt.Sprintf("%s/%s/%s", usersEndpoint, userID, groupsEndpoint), pm) - if err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return GroupsPage{}, sdkerr - } - gp := GroupsPage{} - if err := json.Unmarshal(body, &gp); err != nil { - return GroupsPage{}, errors.NewSDKError(err) - } - - return gp, nil -} - -func (sdk mgSDK) ListUserThings(userID string, pm PageMetadata, token string) (ThingsPage, errors.SDKError) { - url, err := sdk.withQueryParams(sdk.thingsURL, fmt.Sprintf("%s/%s/%s", usersEndpoint, userID, thingsEndpoint), pm) - if err != nil { - return ThingsPage{}, errors.NewSDKError(err) - } - _, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return ThingsPage{}, sdkerr - } - tp := ThingsPage{} - if err := json.Unmarshal(body, &tp); err != nil { - return ThingsPage{}, errors.NewSDKError(err) - } - - return tp, nil -} - -func (sdk mgSDK) EnableUser(id, token string) (User, errors.SDKError) { - return sdk.changeClientStatus(token, id, enableEndpoint) -} - -func (sdk mgSDK) DisableUser(id, token string) (User, errors.SDKError) { - return sdk.changeClientStatus(token, id, disableEndpoint) -} - -func (sdk mgSDK) changeClientStatus(token, id, status string) (User, errors.SDKError) { - url := fmt.Sprintf("%s/%s/%s/%s", sdk.usersURL, usersEndpoint, id, status) - - _, body, sdkerr := sdk.processRequest(http.MethodPost, url, token, nil, nil, http.StatusOK) - if sdkerr != nil { - return User{}, sdkerr - } - - user := User{} - if err := json.Unmarshal(body, &user); err != nil { - return User{}, errors.NewSDKError(err) - } - - return user, nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/transformers/README.md b/vendor/github.com/absmach/magistrala/pkg/transformers/README.md deleted file mode 100644 index 44a21202..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/transformers/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Message Transformers - -A transformer service consumes events published by Magistrala adapters (such as MQTT and HTTP adapters) and transforms them to an arbitrary message format. A transformer can be imported as a standalone package and used for message transformation on the consumer side. - -Magistrala [SenML transformer](transformer) is an example of Transformer service for SenML messages. - -Magistrala [writers](writers) are using a standalone SenML transformer to preprocess messages before storing them. - -[transformers]: https://github.com/absmach/magistrala/tree/master/transformers/senml -[writers]: https://github.com/absmach/magistrala/tree/master/writers diff --git a/vendor/github.com/absmach/magistrala/pkg/transformers/doc.go b/vendor/github.com/absmach/magistrala/pkg/transformers/doc.go deleted file mode 100644 index 80050df3..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/transformers/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Package transformers contains the domain concept definitions needed to -// support Magistrala transformer services functionality. -package transformers diff --git a/vendor/github.com/absmach/magistrala/pkg/transformers/senml/README.md b/vendor/github.com/absmach/magistrala/pkg/transformers/senml/README.md deleted file mode 100644 index d5dbd00e..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/transformers/senml/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# SenML Message Transformer - -SenML Transformer provides Message Transformer for SenML messages. -It supports JSON and CBOR content types - To transform Magistrala Message successfully, the payload must be either JSON or CBOR encoded SenML message. diff --git a/vendor/github.com/absmach/magistrala/pkg/transformers/senml/doc.go b/vendor/github.com/absmach/magistrala/pkg/transformers/senml/doc.go deleted file mode 100644 index 04234dd4..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/transformers/senml/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Package senml contains SenML transformer. -package senml diff --git a/vendor/github.com/absmach/magistrala/pkg/transformers/senml/message.go b/vendor/github.com/absmach/magistrala/pkg/transformers/senml/message.go deleted file mode 100644 index 4a88ae6d..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/transformers/senml/message.go +++ /dev/null @@ -1,18 +0,0 @@ -package senml - -// Message represents a resolved (normalized) SenML record. -type Message struct { - Channel string `json:"channel,omitempty" db:"channel" bson:"channel"` - Subtopic string `json:"subtopic,omitempty" db:"subtopic" bson:"subtopic,omitempty"` - Publisher string `json:"publisher,omitempty" db:"publisher" bson:"publisher"` - Protocol string `json:"protocol,omitempty" db:"protocol" bson:"protocol"` - Name string `json:"name,omitempty" db:"name" bson:"name,omitempty"` - Unit string `json:"unit,omitempty" db:"unit" bson:"unit,omitempty"` - Time float64 `json:"time,omitempty" db:"time" bson:"time,omitempty"` - UpdateTime float64 `json:"update_time,omitempty" db:"update_time" bson:"update_time,omitempty"` - Value *float64 `json:"value,omitempty" db:"value" bson:"value,omitempty"` - StringValue *string `json:"string_value,omitempty" db:"string_value" bson:"string_value,omitempty"` - DataValue *string `json:"data_value,omitempty" db:"data_value" bson:"data_value,omitempty"` - BoolValue *bool `json:"bool_value,omitempty" db:"bool_value" bson:"bool_value,omitempty"` - Sum *float64 `json:"sum,omitempty" db:"sum" bson:"sum,omitempty"` -} diff --git a/vendor/github.com/absmach/magistrala/pkg/transformers/senml/transformer.go b/vendor/github.com/absmach/magistrala/pkg/transformers/senml/transformer.go deleted file mode 100644 index f3fe1355..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/transformers/senml/transformer.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package senml - -import ( - "github.com/absmach/magistrala/pkg/errors" - "github.com/absmach/magistrala/pkg/messaging" - "github.com/absmach/magistrala/pkg/transformers" - "github.com/mainflux/senml" -) - -const ( - // JSON represents SenML in JSON format content type. - JSON = "application/senml+json" - // CBOR represents SenML in CBOR format content type. - CBOR = "application/senml+cbor" -) - -var ( - errDecode = errors.New("failed to decode senml") - errNormalize = errors.New("failed to normalize senml") -) - -var formats = map[string]senml.Format{ - JSON: senml.JSON, - CBOR: senml.CBOR, -} - -type transformer struct { - format senml.Format -} - -// New returns transformer service implementation for SenML messages. -func New(contentFormat string) transformers.Transformer { - format, ok := formats[contentFormat] - if !ok { - format = formats[JSON] - } - - return transformer{ - format: format, - } -} - -func (t transformer) Transform(msg *messaging.Message) (interface{}, error) { - raw, err := senml.Decode(msg.Payload, t.format) - if err != nil { - return nil, errors.Wrap(errDecode, err) - } - - normalized, err := senml.Normalize(raw) - if err != nil { - return nil, errors.Wrap(errNormalize, err) - } - - msgs := make([]Message, len(normalized.Records)) - for i, v := range normalized.Records { - // Use reception timestamp if SenML messsage Time is missing - t := v.Time - if t == 0 { - // Convert the Unix timestamp in nanoseconds to float64 - t = float64(msg.Created) / float64(1e9) - } - - msgs[i] = Message{ - Channel: msg.Channel, - Subtopic: msg.Subtopic, - Publisher: msg.Publisher, - Protocol: msg.Protocol, - Name: v.Name, - Unit: v.Unit, - Time: t, - UpdateTime: v.UpdateTime, - Value: v.Value, - BoolValue: v.BoolValue, - DataValue: v.DataValue, - StringValue: v.StringValue, - Sum: v.Sum, - } - } - - return msgs, nil -} diff --git a/vendor/github.com/absmach/magistrala/pkg/transformers/transformer.go b/vendor/github.com/absmach/magistrala/pkg/transformers/transformer.go deleted file mode 100644 index 60797f57..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/transformers/transformer.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package transformers - -import "github.com/absmach/magistrala/pkg/messaging" - -// Transformer specifies API form Message transformer. -type Transformer interface { - // Transform Magistrala message to any other format. - Transform(msg *messaging.Message) (interface{}, error) -} diff --git a/vendor/github.com/absmach/magistrala/pkg/uuid/README.md b/vendor/github.com/absmach/magistrala/pkg/uuid/README.md deleted file mode 100644 index e19a38f2..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/uuid/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# UUID identity provider - -The UUID identity provider generates a random, universally unique identifier (UUID), unique for all practical purposes. diff --git a/vendor/github.com/absmach/magistrala/pkg/uuid/doc.go b/vendor/github.com/absmach/magistrala/pkg/uuid/doc.go deleted file mode 100644 index 8cabc606..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/uuid/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Package uuid contains UUID generator. -package uuid diff --git a/vendor/github.com/absmach/magistrala/pkg/uuid/mock.go b/vendor/github.com/absmach/magistrala/pkg/uuid/mock.go deleted file mode 100644 index 6bcb1269..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/uuid/mock.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package uuid - -import ( - "fmt" - "sync" - - "github.com/absmach/magistrala" -) - -// Prefix represents the prefix used to generate UUID mocks. -const Prefix = "123e4567-e89b-12d3-a456-" - -var _ magistrala.IDProvider = (*uuidProviderMock)(nil) - -type uuidProviderMock struct { - mu sync.Mutex - counter int -} - -func (up *uuidProviderMock) ID() (string, error) { - up.mu.Lock() - defer up.mu.Unlock() - - up.counter++ - return fmt.Sprintf("%s%012d", Prefix, up.counter), nil -} - -// NewMock creates "mirror" uuid provider, i.e. generated -// token will hold value provided by the caller. -func NewMock() magistrala.IDProvider { - return &uuidProviderMock{} -} diff --git a/vendor/github.com/absmach/magistrala/pkg/uuid/uuid.go b/vendor/github.com/absmach/magistrala/pkg/uuid/uuid.go deleted file mode 100644 index 9a78d870..00000000 --- a/vendor/github.com/absmach/magistrala/pkg/uuid/uuid.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -// Package uuid provides a UUID identity provider. -package uuid - -import ( - "github.com/absmach/magistrala" - "github.com/absmach/magistrala/pkg/errors" - "github.com/gofrs/uuid" -) - -// ErrGeneratingID indicates error in generating UUID. -var ErrGeneratingID = errors.New("failed to generate uuid") - -var _ magistrala.IDProvider = (*uuidProvider)(nil) - -type uuidProvider struct{} - -// New instantiates a UUID provider. -func New() magistrala.IDProvider { - return &uuidProvider{} -} - -func (up *uuidProvider) ID() (string, error) { - id, err := uuid.NewV4() - if err != nil { - return "", errors.Wrap(ErrGeneratingID, err) - } - - return id.String(), nil -} diff --git a/vendor/github.com/absmach/magistrala/uuid.go b/vendor/github.com/absmach/magistrala/uuid.go deleted file mode 100644 index 11c00a40..00000000 --- a/vendor/github.com/absmach/magistrala/uuid.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Magistrala -// SPDX-License-Identifier: Apache-2.0 - -package magistrala - -// IDProvider specifies an API for generating unique identifiers. -type IDProvider interface { - // ID generates the unique identifier. - ID() (string, error) -} diff --git a/vendor/github.com/beorn7/perks/LICENSE b/vendor/github.com/beorn7/perks/LICENSE deleted file mode 100644 index 339177be..00000000 --- a/vendor/github.com/beorn7/perks/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (C) 2013 Blake Mizerany - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/beorn7/perks/quantile/exampledata.txt b/vendor/github.com/beorn7/perks/quantile/exampledata.txt deleted file mode 100644 index 1602287d..00000000 --- a/vendor/github.com/beorn7/perks/quantile/exampledata.txt +++ /dev/null @@ -1,2388 +0,0 @@ -8 -5 -26 -12 -5 -235 -13 -6 -28 -30 -3 -3 -3 -3 -5 -2 -33 -7 -2 -4 -7 -12 -14 -5 -8 -3 -10 -4 -5 -3 -6 -6 -209 -20 -3 -10 -14 -3 -4 -6 -8 -5 -11 -7 -3 -2 -3 -3 -212 -5 -222 -4 -10 -10 -5 -6 -3 -8 -3 -10 -254 -220 -2 -3 -5 -24 -5 -4 -222 -7 -3 -3 -223 -8 -15 -12 -14 -14 -3 -2 -2 -3 -13 -3 -11 -4 -4 -6 -5 -7 -13 -5 -3 -5 -2 -5 -3 -5 -2 -7 -15 -17 -14 -3 -6 -6 -3 -17 -5 -4 -7 -6 -4 -4 -8 -6 -8 -3 -9 -3 -6 -3 -4 -5 -3 -3 -660 -4 -6 -10 -3 -6 -3 -2 -5 -13 -2 -4 -4 -10 -4 -8 -4 -3 -7 -9 -9 -3 -10 -37 -3 -13 -4 -12 -3 -6 -10 -8 -5 -21 -2 -3 -8 -3 -2 -3 -3 -4 -12 -2 -4 -8 -8 -4 -3 -2 -20 -1 -6 -32 -2 -11 -6 -18 -3 -8 -11 -3 -212 -3 -4 -2 -6 -7 -12 -11 -3 -2 -16 -10 -6 -4 -6 -3 -2 -7 -3 -2 -2 -2 -2 -5 -6 -4 -3 -10 -3 -4 -6 -5 -3 -4 -4 -5 -6 -4 -3 -4 -4 -5 -7 -5 -5 -3 -2 -7 -2 -4 -12 -4 -5 -6 -2 -4 -4 -8 -4 -15 -13 -7 -16 -5 -3 -23 -5 -5 -7 -3 -2 -9 -8 -7 -5 -8 -11 -4 -10 -76 -4 -47 -4 -3 -2 -7 -4 -2 -3 -37 -10 -4 -2 -20 -5 -4 -4 -10 -10 -4 -3 -7 -23 -240 -7 -13 -5 -5 -3 -3 -2 -5 -4 -2 -8 -7 -19 -2 -23 -8 -7 -2 -5 -3 -8 -3 -8 -13 -5 -5 -5 -2 -3 -23 -4 -9 -8 -4 -3 -3 -5 -220 -2 -3 -4 -6 -14 -3 -53 -6 -2 -5 -18 -6 -3 -219 -6 -5 -2 -5 -3 -6 -5 -15 -4 -3 -17 -3 -2 -4 -7 -2 -3 -3 -4 -4 -3 -2 -664 -6 -3 -23 -5 -5 -16 -5 -8 -2 -4 -2 -24 -12 -3 -2 -3 -5 -8 -3 -5 -4 -3 -14 -3 -5 -8 -2 -3 -7 -9 -4 -2 -3 -6 -8 -4 -3 -4 -6 -5 -3 -3 -6 -3 -19 -4 -4 -6 -3 -6 -3 -5 -22 -5 -4 -4 -3 -8 -11 -4 -9 -7 -6 -13 -4 -4 -4 -6 -17 -9 -3 -3 -3 -4 -3 -221 -5 -11 -3 -4 -2 -12 -6 -3 -5 -7 -5 -7 -4 -9 -7 -14 -37 -19 -217 -16 -3 -5 -2 -2 -7 -19 -7 -6 -7 -4 -24 -5 -11 -4 -7 -7 -9 -13 -3 -4 -3 -6 -28 -4 -4 -5 -5 -2 -5 -6 -4 -4 -6 -10 -5 -4 -3 -2 -3 -3 -6 -5 -5 -4 -3 -2 -3 -7 -4 -6 -18 -16 -8 -16 -4 -5 -8 -6 -9 -13 -1545 -6 -215 -6 -5 -6 -3 -45 -31 -5 -2 -2 -4 -3 -3 -2 -5 -4 -3 -5 -7 -7 -4 -5 -8 -5 -4 -749 -2 -31 -9 -11 -2 -11 -5 -4 -4 -7 -9 -11 -4 -5 -4 -7 -3 -4 -6 -2 -15 -3 -4 -3 -4 -3 -5 -2 -13 -5 -5 -3 -3 -23 -4 -4 -5 -7 -4 -13 -2 -4 -3 -4 -2 -6 -2 -7 -3 -5 -5 -3 -29 -5 -4 -4 -3 -10 -2 -3 -79 -16 -6 -6 -7 -7 -3 -5 -5 -7 -4 -3 -7 -9 -5 -6 -5 -9 -6 -3 -6 -4 -17 -2 -10 -9 -3 -6 -2 -3 -21 -22 -5 -11 -4 -2 -17 -2 -224 -2 -14 -3 -4 -4 -2 -4 -4 -4 -4 -5 -3 -4 -4 -10 -2 -6 -3 -3 -5 -7 -2 -7 -5 -6 -3 -218 -2 -2 -5 -2 -6 -3 -5 -222 -14 -6 -33 -3 -2 -5 -3 -3 -3 -9 -5 -3 -3 -2 -7 -4 -3 -4 -3 -5 -6 -5 -26 -4 -13 -9 -7 -3 -221 -3 -3 -4 -4 -4 -4 -2 -18 -5 -3 -7 -9 -6 -8 -3 -10 -3 -11 -9 -5 -4 -17 -5 -5 -6 -6 -3 -2 -4 -12 -17 -6 -7 -218 -4 -2 -4 -10 -3 -5 -15 -3 -9 -4 -3 -3 -6 -29 -3 -3 -4 -5 -5 -3 -8 -5 -6 -6 -7 -5 -3 -5 -3 -29 -2 -31 -5 -15 -24 -16 -5 -207 -4 -3 -3 -2 -15 -4 -4 -13 -5 -5 -4 -6 -10 -2 -7 -8 -4 -6 -20 -5 -3 -4 -3 -12 -12 -5 -17 -7 -3 -3 -3 -6 -10 -3 -5 -25 -80 -4 -9 -3 -2 -11 -3 -3 -2 -3 -8 -7 -5 -5 -19 -5 -3 -3 -12 -11 -2 -6 -5 -5 -5 -3 -3 -3 -4 -209 -14 -3 -2 -5 -19 -4 -4 -3 -4 -14 -5 -6 -4 -13 -9 -7 -4 -7 -10 -2 -9 -5 -7 -2 -8 -4 -6 -5 -5 -222 -8 -7 -12 -5 -216 -3 -4 -4 -6 -3 -14 -8 -7 -13 -4 -3 -3 -3 -3 -17 -5 -4 -3 -33 -6 -6 -33 -7 -5 -3 -8 -7 -5 -2 -9 -4 -2 -233 -24 -7 -4 -8 -10 -3 -4 -15 -2 -16 -3 -3 -13 -12 -7 -5 -4 -207 -4 -2 -4 -27 -15 -2 -5 -2 -25 -6 -5 -5 -6 -13 -6 -18 -6 -4 -12 -225 -10 -7 -5 -2 -2 -11 -4 -14 -21 -8 -10 -3 -5 -4 -232 -2 -5 -5 -3 -7 -17 -11 -6 -6 -23 -4 -6 -3 -5 -4 -2 -17 -3 -6 -5 -8 -3 -2 -2 -14 -9 -4 -4 -2 -5 -5 -3 -7 -6 -12 -6 -10 -3 -6 -2 -2 -19 -5 -4 -4 -9 -2 -4 -13 -3 -5 -6 -3 -6 -5 -4 -9 -6 -3 -5 -7 -3 -6 -6 -4 -3 -10 -6 -3 -221 -3 -5 -3 -6 -4 -8 -5 -3 -6 -4 -4 -2 -54 -5 -6 -11 -3 -3 -4 -4 -4 -3 -7 -3 -11 -11 -7 -10 -6 -13 -223 -213 -15 -231 -7 -3 -7 -228 -2 -3 -4 -4 -5 -6 -7 -4 -13 -3 -4 -5 -3 -6 -4 -6 -7 -2 -4 -3 -4 -3 -3 -6 -3 -7 -3 -5 -18 -5 -6 -8 -10 -3 -3 -3 -2 -4 -2 -4 -4 -5 -6 -6 -4 -10 -13 -3 -12 -5 -12 -16 -8 -4 -19 -11 -2 -4 -5 -6 -8 -5 -6 -4 -18 -10 -4 -2 -216 -6 -6 -6 -2 -4 -12 -8 -3 -11 -5 -6 -14 -5 -3 -13 -4 -5 -4 -5 -3 -28 -6 -3 -7 -219 -3 -9 -7 -3 -10 -6 -3 -4 -19 -5 -7 -11 -6 -15 -19 -4 -13 -11 -3 -7 -5 -10 -2 -8 -11 -2 -6 -4 -6 -24 -6 -3 -3 -3 -3 -6 -18 -4 -11 -4 -2 -5 -10 -8 -3 -9 -5 -3 -4 -5 -6 -2 -5 -7 -4 -4 -14 -6 -4 -4 -5 -5 -7 -2 -4 -3 -7 -3 -3 -6 -4 -5 -4 -4 -4 -3 -3 -3 -3 -8 -14 -2 -3 -5 -3 -2 -4 -5 -3 -7 -3 -3 -18 -3 -4 -4 -5 -7 -3 -3 -3 -13 -5 -4 -8 -211 -5 -5 -3 -5 -2 -5 -4 -2 -655 -6 -3 -5 -11 -2 -5 -3 -12 -9 -15 -11 -5 -12 -217 -2 -6 -17 -3 -3 -207 -5 -5 -4 -5 -9 -3 -2 -8 -5 -4 -3 -2 -5 -12 -4 -14 -5 -4 -2 -13 -5 -8 -4 -225 -4 -3 -4 -5 -4 -3 -3 -6 -23 -9 -2 -6 -7 -233 -4 -4 -6 -18 -3 -4 -6 -3 -4 -4 -2 -3 -7 -4 -13 -227 -4 -3 -5 -4 -2 -12 -9 -17 -3 -7 -14 -6 -4 -5 -21 -4 -8 -9 -2 -9 -25 -16 -3 -6 -4 -7 -8 -5 -2 -3 -5 -4 -3 -3 -5 -3 -3 -3 -2 -3 -19 -2 -4 -3 -4 -2 -3 -4 -4 -2 -4 -3 -3 -3 -2 -6 -3 -17 -5 -6 -4 -3 -13 -5 -3 -3 -3 -4 -9 -4 -2 -14 -12 -4 -5 -24 -4 -3 -37 -12 -11 -21 -3 -4 -3 -13 -4 -2 -3 -15 -4 -11 -4 -4 -3 -8 -3 -4 -4 -12 -8 -5 -3 -3 -4 -2 -220 -3 -5 -223 -3 -3 -3 -10 -3 -15 -4 -241 -9 -7 -3 -6 -6 -23 -4 -13 -7 -3 -4 -7 -4 -9 -3 -3 -4 -10 -5 -5 -1 -5 -24 -2 -4 -5 -5 -6 -14 -3 -8 -2 -3 -5 -13 -13 -3 -5 -2 -3 -15 -3 -4 -2 -10 -4 -4 -4 -5 -5 -3 -5 -3 -4 -7 -4 -27 -3 -6 -4 -15 -3 -5 -6 -6 -5 -4 -8 -3 -9 -2 -6 -3 -4 -3 -7 -4 -18 -3 -11 -3 -3 -8 -9 -7 -24 -3 -219 -7 -10 -4 -5 -9 -12 -2 -5 -4 -4 -4 -3 -3 -19 -5 -8 -16 -8 -6 -22 -3 -23 -3 -242 -9 -4 -3 -3 -5 -7 -3 -3 -5 -8 -3 -7 -5 -14 -8 -10 -3 -4 -3 -7 -4 -6 -7 -4 -10 -4 -3 -11 -3 -7 -10 -3 -13 -6 -8 -12 -10 -5 -7 -9 -3 -4 -7 -7 -10 -8 -30 -9 -19 -4 -3 -19 -15 -4 -13 -3 -215 -223 -4 -7 -4 -8 -17 -16 -3 -7 -6 -5 -5 -4 -12 -3 -7 -4 -4 -13 -4 -5 -2 -5 -6 -5 -6 -6 -7 -10 -18 -23 -9 -3 -3 -6 -5 -2 -4 -2 -7 -3 -3 -2 -5 -5 -14 -10 -224 -6 -3 -4 -3 -7 -5 -9 -3 -6 -4 -2 -5 -11 -4 -3 -3 -2 -8 -4 -7 -4 -10 -7 -3 -3 -18 -18 -17 -3 -3 -3 -4 -5 -3 -3 -4 -12 -7 -3 -11 -13 -5 -4 -7 -13 -5 -4 -11 -3 -12 -3 -6 -4 -4 -21 -4 -6 -9 -5 -3 -10 -8 -4 -6 -4 -4 -6 -5 -4 -8 -6 -4 -6 -4 -4 -5 -9 -6 -3 -4 -2 -9 -3 -18 -2 -4 -3 -13 -3 -6 -6 -8 -7 -9 -3 -2 -16 -3 -4 -6 -3 -2 -33 -22 -14 -4 -9 -12 -4 -5 -6 -3 -23 -9 -4 -3 -5 -5 -3 -4 -5 -3 -5 -3 -10 -4 -5 -5 -8 -4 -4 -6 -8 -5 -4 -3 -4 -6 -3 -3 -3 -5 -9 -12 -6 -5 -9 -3 -5 -3 -2 -2 -2 -18 -3 -2 -21 -2 -5 -4 -6 -4 -5 -10 -3 -9 -3 -2 -10 -7 -3 -6 -6 -4 -4 -8 -12 -7 -3 -7 -3 -3 -9 -3 -4 -5 -4 -4 -5 -5 -10 -15 -4 -4 -14 -6 -227 -3 -14 -5 -216 -22 -5 -4 -2 -2 -6 -3 -4 -2 -9 -9 -4 -3 -28 -13 -11 -4 -5 -3 -3 -2 -3 -3 -5 -3 -4 -3 -5 -23 -26 -3 -4 -5 -6 -4 -6 -3 -5 -5 -3 -4 -3 -2 -2 -2 -7 -14 -3 -6 -7 -17 -2 -2 -15 -14 -16 -4 -6 -7 -13 -6 -4 -5 -6 -16 -3 -3 -28 -3 -6 -15 -3 -9 -2 -4 -6 -3 -3 -22 -4 -12 -6 -7 -2 -5 -4 -10 -3 -16 -6 -9 -2 -5 -12 -7 -5 -5 -5 -5 -2 -11 -9 -17 -4 -3 -11 -7 -3 -5 -15 -4 -3 -4 -211 -8 -7 -5 -4 -7 -6 -7 -6 -3 -6 -5 -6 -5 -3 -4 -4 -26 -4 -6 -10 -4 -4 -3 -2 -3 -3 -4 -5 -9 -3 -9 -4 -4 -5 -5 -8 -2 -4 -2 -3 -8 -4 -11 -19 -5 -8 -6 -3 -5 -6 -12 -3 -2 -4 -16 -12 -3 -4 -4 -8 -6 -5 -6 -6 -219 -8 -222 -6 -16 -3 -13 -19 -5 -4 -3 -11 -6 -10 -4 -7 -7 -12 -5 -3 -3 -5 -6 -10 -3 -8 -2 -5 -4 -7 -2 -4 -4 -2 -12 -9 -6 -4 -2 -40 -2 -4 -10 -4 -223 -4 -2 -20 -6 -7 -24 -5 -4 -5 -2 -20 -16 -6 -5 -13 -2 -3 -3 -19 -3 -2 -4 -5 -6 -7 -11 -12 -5 -6 -7 -7 -3 -5 -3 -5 -3 -14 -3 -4 -4 -2 -11 -1 -7 -3 -9 -6 -11 -12 -5 -8 -6 -221 -4 -2 -12 -4 -3 -15 -4 -5 -226 -7 -218 -7 -5 -4 -5 -18 -4 -5 -9 -4 -4 -2 -9 -18 -18 -9 -5 -6 -6 -3 -3 -7 -3 -5 -4 -4 -4 -12 -3 -6 -31 -5 -4 -7 -3 -6 -5 -6 -5 -11 -2 -2 -11 -11 -6 -7 -5 -8 -7 -10 -5 -23 -7 -4 -3 -5 -34 -2 -5 -23 -7 -3 -6 -8 -4 -4 -4 -2 -5 -3 -8 -5 -4 -8 -25 -2 -3 -17 -8 -3 -4 -8 -7 -3 -15 -6 -5 -7 -21 -9 -5 -6 -6 -5 -3 -2 -3 -10 -3 -6 -3 -14 -7 -4 -4 -8 -7 -8 -2 -6 -12 -4 -213 -6 -5 -21 -8 -2 -5 -23 -3 -11 -2 -3 -6 -25 -2 -3 -6 -7 -6 -6 -4 -4 -6 -3 -17 -9 -7 -6 -4 -3 -10 -7 -2 -3 -3 -3 -11 -8 -3 -7 -6 -4 -14 -36 -3 -4 -3 -3 -22 -13 -21 -4 -2 -7 -4 -4 -17 -15 -3 -7 -11 -2 -4 -7 -6 -209 -6 -3 -2 -2 -24 -4 -9 -4 -3 -3 -3 -29 -2 -2 -4 -3 -3 -5 -4 -6 -3 -3 -2 -4 diff --git a/vendor/github.com/beorn7/perks/quantile/stream.go b/vendor/github.com/beorn7/perks/quantile/stream.go deleted file mode 100644 index d7d14f8e..00000000 --- a/vendor/github.com/beorn7/perks/quantile/stream.go +++ /dev/null @@ -1,316 +0,0 @@ -// Package quantile computes approximate quantiles over an unbounded data -// stream within low memory and CPU bounds. -// -// A small amount of accuracy is traded to achieve the above properties. -// -// Multiple streams can be merged before calling Query to generate a single set -// of results. This is meaningful when the streams represent the same type of -// data. See Merge and Samples. -// -// For more detailed information about the algorithm used, see: -// -// Effective Computation of Biased Quantiles over Data Streams -// -// http://www.cs.rutgers.edu/~muthu/bquant.pdf -package quantile - -import ( - "math" - "sort" -) - -// Sample holds an observed value and meta information for compression. JSON -// tags have been added for convenience. -type Sample struct { - Value float64 `json:",string"` - Width float64 `json:",string"` - Delta float64 `json:",string"` -} - -// Samples represents a slice of samples. It implements sort.Interface. -type Samples []Sample - -func (a Samples) Len() int { return len(a) } -func (a Samples) Less(i, j int) bool { return a[i].Value < a[j].Value } -func (a Samples) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -type invariant func(s *stream, r float64) float64 - -// NewLowBiased returns an initialized Stream for low-biased quantiles -// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but -// error guarantees can still be given even for the lower ranks of the data -// distribution. -// -// The provided epsilon is a relative error, i.e. the true quantile of a value -// returned by a query is guaranteed to be within (1±Epsilon)*Quantile. -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error -// properties. -func NewLowBiased(epsilon float64) *Stream { - ƒ := func(s *stream, r float64) float64 { - return 2 * epsilon * r - } - return newStream(ƒ) -} - -// NewHighBiased returns an initialized Stream for high-biased quantiles -// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but -// error guarantees can still be given even for the higher ranks of the data -// distribution. -// -// The provided epsilon is a relative error, i.e. the true quantile of a value -// returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile). -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error -// properties. -func NewHighBiased(epsilon float64) *Stream { - ƒ := func(s *stream, r float64) float64 { - return 2 * epsilon * (s.n - r) - } - return newStream(ƒ) -} - -// NewTargeted returns an initialized Stream concerned with a particular set of -// quantile values that are supplied a priori. Knowing these a priori reduces -// space and computation time. The targets map maps the desired quantiles to -// their absolute errors, i.e. the true quantile of a value returned by a query -// is guaranteed to be within (Quantile±Epsilon). -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties. -func NewTargeted(targetMap map[float64]float64) *Stream { - // Convert map to slice to avoid slow iterations on a map. - // ƒ is called on the hot path, so converting the map to a slice - // beforehand results in significant CPU savings. - targets := targetMapToSlice(targetMap) - - ƒ := func(s *stream, r float64) float64 { - var m = math.MaxFloat64 - var f float64 - for _, t := range targets { - if t.quantile*s.n <= r { - f = (2 * t.epsilon * r) / t.quantile - } else { - f = (2 * t.epsilon * (s.n - r)) / (1 - t.quantile) - } - if f < m { - m = f - } - } - return m - } - return newStream(ƒ) -} - -type target struct { - quantile float64 - epsilon float64 -} - -func targetMapToSlice(targetMap map[float64]float64) []target { - targets := make([]target, 0, len(targetMap)) - - for quantile, epsilon := range targetMap { - t := target{ - quantile: quantile, - epsilon: epsilon, - } - targets = append(targets, t) - } - - return targets -} - -// Stream computes quantiles for a stream of float64s. It is not thread-safe by -// design. Take care when using across multiple goroutines. -type Stream struct { - *stream - b Samples - sorted bool -} - -func newStream(ƒ invariant) *Stream { - x := &stream{ƒ: ƒ} - return &Stream{x, make(Samples, 0, 500), true} -} - -// Insert inserts v into the stream. -func (s *Stream) Insert(v float64) { - s.insert(Sample{Value: v, Width: 1}) -} - -func (s *Stream) insert(sample Sample) { - s.b = append(s.b, sample) - s.sorted = false - if len(s.b) == cap(s.b) { - s.flush() - } -} - -// Query returns the computed qth percentiles value. If s was created with -// NewTargeted, and q is not in the set of quantiles provided a priori, Query -// will return an unspecified result. -func (s *Stream) Query(q float64) float64 { - if !s.flushed() { - // Fast path when there hasn't been enough data for a flush; - // this also yields better accuracy for small sets of data. - l := len(s.b) - if l == 0 { - return 0 - } - i := int(math.Ceil(float64(l) * q)) - if i > 0 { - i -= 1 - } - s.maybeSort() - return s.b[i].Value - } - s.flush() - return s.stream.query(q) -} - -// Merge merges samples into the underlying streams samples. This is handy when -// merging multiple streams from separate threads, database shards, etc. -// -// ATTENTION: This method is broken and does not yield correct results. The -// underlying algorithm is not capable of merging streams correctly. -func (s *Stream) Merge(samples Samples) { - sort.Sort(samples) - s.stream.merge(samples) -} - -// Reset reinitializes and clears the list reusing the samples buffer memory. -func (s *Stream) Reset() { - s.stream.reset() - s.b = s.b[:0] -} - -// Samples returns stream samples held by s. -func (s *Stream) Samples() Samples { - if !s.flushed() { - return s.b - } - s.flush() - return s.stream.samples() -} - -// Count returns the total number of samples observed in the stream -// since initialization. -func (s *Stream) Count() int { - return len(s.b) + s.stream.count() -} - -func (s *Stream) flush() { - s.maybeSort() - s.stream.merge(s.b) - s.b = s.b[:0] -} - -func (s *Stream) maybeSort() { - if !s.sorted { - s.sorted = true - sort.Sort(s.b) - } -} - -func (s *Stream) flushed() bool { - return len(s.stream.l) > 0 -} - -type stream struct { - n float64 - l []Sample - ƒ invariant -} - -func (s *stream) reset() { - s.l = s.l[:0] - s.n = 0 -} - -func (s *stream) insert(v float64) { - s.merge(Samples{{v, 1, 0}}) -} - -func (s *stream) merge(samples Samples) { - // TODO(beorn7): This tries to merge not only individual samples, but - // whole summaries. The paper doesn't mention merging summaries at - // all. Unittests show that the merging is inaccurate. Find out how to - // do merges properly. - var r float64 - i := 0 - for _, sample := range samples { - for ; i < len(s.l); i++ { - c := s.l[i] - if c.Value > sample.Value { - // Insert at position i. - s.l = append(s.l, Sample{}) - copy(s.l[i+1:], s.l[i:]) - s.l[i] = Sample{ - sample.Value, - sample.Width, - math.Max(sample.Delta, math.Floor(s.ƒ(s, r))-1), - // TODO(beorn7): How to calculate delta correctly? - } - i++ - goto inserted - } - r += c.Width - } - s.l = append(s.l, Sample{sample.Value, sample.Width, 0}) - i++ - inserted: - s.n += sample.Width - r += sample.Width - } - s.compress() -} - -func (s *stream) count() int { - return int(s.n) -} - -func (s *stream) query(q float64) float64 { - t := math.Ceil(q * s.n) - t += math.Ceil(s.ƒ(s, t) / 2) - p := s.l[0] - var r float64 - for _, c := range s.l[1:] { - r += p.Width - if r+c.Width+c.Delta > t { - return p.Value - } - p = c - } - return p.Value -} - -func (s *stream) compress() { - if len(s.l) < 2 { - return - } - x := s.l[len(s.l)-1] - xi := len(s.l) - 1 - r := s.n - 1 - x.Width - - for i := len(s.l) - 2; i >= 0; i-- { - c := s.l[i] - if c.Width+x.Width+x.Delta <= s.ƒ(s, r) { - x.Width += c.Width - s.l[xi] = x - // Remove element at i. - copy(s.l[i:], s.l[i+1:]) - s.l = s.l[:len(s.l)-1] - xi -= 1 - } else { - x = c - xi = i - } - r -= c.Width - } -} - -func (s *stream) samples() Samples { - samples := make(Samples, len(s.l)) - copy(samples, s.l) - return samples -} diff --git a/vendor/github.com/caarlos0/env/v9/.gitignore b/vendor/github.com/caarlos0/env/v9/.gitignore deleted file mode 100644 index ca6a0ff8..00000000 --- a/vendor/github.com/caarlos0/env/v9/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -coverage.txt -bin -card.png -dist diff --git a/vendor/github.com/caarlos0/env/v9/.golangci.yml b/vendor/github.com/caarlos0/env/v9/.golangci.yml deleted file mode 100644 index ff791f86..00000000 --- a/vendor/github.com/caarlos0/env/v9/.golangci.yml +++ /dev/null @@ -1,8 +0,0 @@ -linters: - enable: - - thelper - - gofumpt - - tparallel - - unconvert - - unparam - - wastedassign diff --git a/vendor/github.com/caarlos0/env/v9/.goreleaser.yml b/vendor/github.com/caarlos0/env/v9/.goreleaser.yml deleted file mode 100644 index 4688983c..00000000 --- a/vendor/github.com/caarlos0/env/v9/.goreleaser.yml +++ /dev/null @@ -1,3 +0,0 @@ -includes: - - from_url: - url: https://raw.githubusercontent.com/caarlos0/.goreleaserfiles/main/lib.yml diff --git a/vendor/github.com/caarlos0/env/v9/.mailmap b/vendor/github.com/caarlos0/env/v9/.mailmap deleted file mode 100644 index eeeee601..00000000 --- a/vendor/github.com/caarlos0/env/v9/.mailmap +++ /dev/null @@ -1,7 +0,0 @@ -Carlos Alexandro Becker Carlos A Becker -Carlos Alexandro Becker Carlos A Becker -Carlos Alexandro Becker Carlos Alexandro Becker -Carlos Alexandro Becker Carlos Alexandro Becker -Carlos Alexandro Becker Carlos Becker -dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com> -actions-user github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> diff --git a/vendor/github.com/caarlos0/env/v9/LICENSE.md b/vendor/github.com/caarlos0/env/v9/LICENSE.md deleted file mode 100644 index 3a59b6b3..00000000 --- a/vendor/github.com/caarlos0/env/v9/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-2022 Carlos Alexandro Becker - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/caarlos0/env/v9/Makefile b/vendor/github.com/caarlos0/env/v9/Makefile deleted file mode 100644 index da8595fb..00000000 --- a/vendor/github.com/caarlos0/env/v9/Makefile +++ /dev/null @@ -1,37 +0,0 @@ -SOURCE_FILES?=./... -TEST_PATTERN?=. - -export GO111MODULE := on - -setup: - go mod tidy -.PHONY: setup - -build: - go build -.PHONY: build - -test: - go test -v -failfast -race -coverpkg=./... -covermode=atomic -coverprofile=coverage.txt $(SOURCE_FILES) -run $(TEST_PATTERN) -timeout=2m -.PHONY: test - -cover: test - go tool cover -html=coverage.txt -.PHONY: cover - -fmt: - gofumpt -w -l . -.PHONY: fmt - -lint: - golangci-lint run ./... -.PHONY: lint - -ci: build test -.PHONY: ci - -card: - wget -O card.png -c "https://og.caarlos0.dev/**env**: parse envs to structs.png?theme=light&md=1&fontSize=100px&images=https://github.com/caarlos0.png" -.PHONY: card - -.DEFAULT_GOAL := ci diff --git a/vendor/github.com/caarlos0/env/v9/README.md b/vendor/github.com/caarlos0/env/v9/README.md deleted file mode 100644 index 9e4cd7af..00000000 --- a/vendor/github.com/caarlos0/env/v9/README.md +++ /dev/null @@ -1,577 +0,0 @@ -# env - -[![Build Status](https://img.shields.io/github/actions/workflow/status/caarlos0/env/build.yml?branch=main&style=for-the-badge)](https://github.com/caarlos0/env/actions?workflow=build) -[![Coverage Status](https://img.shields.io/codecov/c/gh/caarlos0/env.svg?logo=codecov&style=for-the-badge)](https://codecov.io/gh/caarlos0/env) -[![](http://img.shields.io/badge/godoc-reference-5272B4.svg?style=for-the-badge)](https://pkg.go.dev/github.com/caarlos0/env/v9) - -A simple and zero-dependencies library to parse environment variables into -`struct`s. - -## Example - -Get the module with: - -```sh -go get github.com/caarlos0/env/v9 -``` - -The usage looks like this: - -```go -package main - -import ( - "fmt" - "time" - - "github.com/caarlos0/env/v9" -) - -type config struct { - Home string `env:"HOME"` - Port int `env:"PORT" envDefault:"3000"` - Password string `env:"PASSWORD,unset"` - IsProduction bool `env:"PRODUCTION"` - Hosts []string `env:"HOSTS" envSeparator:":"` - Duration time.Duration `env:"DURATION"` - TempFolder string `env:"TEMP_FOLDER,expand" envDefault:"${HOME}/tmp"` -} - -func main() { - cfg := config{} - if err := env.Parse(&cfg); err != nil { - fmt.Printf("%+v\n", err) - } - - fmt.Printf("%+v\n", cfg) -} -``` - -You can run it like this: - -```sh -$ PRODUCTION=true HOSTS="host1:host2:host3" DURATION=1s go run main.go -{Home:/your/home Port:3000 IsProduction:true Hosts:[host1 host2 host3] Duration:1s} -``` - -## Caveats - -> **Warning** -> -> **This is important!** - -- _Unexported fields_ are **ignored** - -## Supported types and defaults - -Out of the box all built-in types are supported, plus a few others that -are commonly used. - -Complete list: - -- `string` -- `bool` -- `int` -- `int8` -- `int16` -- `int32` -- `int64` -- `uint` -- `uint8` -- `uint16` -- `uint32` -- `uint64` -- `float32` -- `float64` -- `time.Duration` -- `encoding.TextUnmarshaler` -- `url.URL` - -Pointers, slices and slices of pointers, and maps of those types are also -supported. - -You can also use/define a [custom parser func](#custom-parser-funcs) for any -other type you want. - -You can also use custom keys and values in your maps, as long as you provide a -parser function for them. - -If you set the `envDefault` tag for something, this value will be used in the -case of absence of it in the environment. - -By default, slice types will split the environment value on `,`; you can change -this behavior by setting the `envSeparator` tag. - -## Custom Parser Funcs - -If you have a type that is not supported out of the box by the lib, you are able -to use (or define) and pass custom parsers (and their associated `reflect.Type`) -to the `env.ParseWithOptions()` function. - -In addition to accepting a struct pointer (same as `Parse()`), this function -also accepts a `Options{}`, and you can set your custom parsers in the `FuncMap` -field. - -If you add a custom parser for, say `Foo`, it will also be used to parse -`*Foo` and `[]Foo` types. - -Check the examples in the [go doc](http://pkg.go.dev/github.com/caarlos0/env/v9) -for more info. - -### A note about `TextUnmarshaler` and `time.Time` - -Env supports by default anything that implements the `TextUnmarshaler` interface. -That includes things like `time.Time` for example. -The upside is that depending on the format you need, you don't need to change -anything. -The downside is that if you do need time in another format, you'll need to -create your own type. - -Its fairly straightforward: - -```go -type MyTime time.Time - -func (t *MyTime) UnmarshalText(text []byte) error { - tt, err := time.Parse("2006-01-02", string(text)) - *t = MyTime(tt) - return err -} - -type Config struct { - SomeTime MyTime `env:"SOME_TIME"` -} -``` - -And then you can parse `Config` with `env.Parse`. - -## Required fields - -The `env` tag option `required` (e.g., `env:"tagKey,required"`) can be added to -ensure that some environment variable is set. In the example above, an error is -returned if the `config` struct is changed to: - -```go -type config struct { - SecretKey string `env:"SECRET_KEY,required"` -} -``` - -> **Warning** -> -> Note that being set is not the same as being empty. -> If the variable is set, but empty, the field will have its type's default -> value. -> This also means that custom parser funcs will not be invoked. - -## Expand vars - -If you set the `expand` option, environment variables (either in `${var}` or -`$var` format) in the string will be replaced according with the actual value -of the variable. For example: - -```go -type config struct { - SecretKey string `env:"SECRET_KEY,expand"` -} -``` - -This also works with `envDefault`. - -## Not Empty fields - -While `required` demands the environment variable to be set, it doesn't check -its value. If you want to make sure the environment is set and not empty, you -need to use the `notEmpty` tag option instead (`env:"SOME_ENV,notEmpty"`). - -Example: - -```go -type config struct { - SecretKey string `env:"SECRET_KEY,notEmpty"` -} -``` - -## Unset environment variable after reading it - -The `env` tag option `unset` (e.g., `env:"tagKey,unset"`) can be added -to ensure that some environment variable is unset after reading it. - -Example: - -```go -type config struct { - SecretKey string `env:"SECRET_KEY,unset"` -} -``` - -## From file - -The `env` tag option `file` (e.g., `env:"tagKey,file"`) can be added -in order to indicate that the value of the variable shall be loaded from a -file. -The path of that file is given by the environment variable associated with it: - -```go -package main - -import ( - "fmt" - "time" - "github.com/caarlos0/env/v9" -) - -type config struct { - Secret string `env:"SECRET,file"` - Password string `env:"PASSWORD,file" envDefault:"/tmp/password"` - Certificate string `env:"CERTIFICATE,file,expand" envDefault:"${CERTIFICATE_FILE}"` -} - -func main() { - cfg := config{} - if err := env.Parse(&cfg); err != nil { - fmt.Printf("%+v\n", err) - } - - fmt.Printf("%+v\n", cfg) -} -``` - -```sh -$ echo qwerty > /tmp/secret -$ echo dvorak > /tmp/password -$ echo coleman > /tmp/certificate - -$ SECRET=/tmp/secret \ - CERTIFICATE_FILE=/tmp/certificate \ - go run main.go -{Secret:qwerty Password:dvorak Certificate:coleman} -``` - -## Options - -### Use field names as environment variables by default - -If you don't want to set the `env` tag on every field, you can use the -`UseFieldNameByDefault` option. - -It will use the field name as environment variable name. - -Here's an example: - -```go -package main - -import ( - "fmt" - "log" - - "github.com/caarlos0/env/v9" -) - -type Config struct { - Username string // will use $USERNAME - Password string // will use $PASSWORD - UserFullName string // will use $USER_FULL_NAME -} - -func main() { - cfg := &Config{} - opts := env.Options{UseFieldNameByDefault: true} - - // Load env vars. - if err := env.ParseWithOptions(cfg, opts); err != nil { - log.Fatal(err) - } - - // Print the loaded data. - fmt.Printf("%+v\n", cfg) -} -``` - -### Environment - -By setting the `Options.Environment` map you can tell `Parse` to add those -`keys` and `values` as `env` vars before parsing is done. -These `envs` are stored in the map and never actually set by `os.Setenv`. -This option effectively makes `env` ignore the OS environment variables: only -the ones provided in the option are used. - -This can make your testing scenarios a bit more clean and easy to handle. - -```go -package main - -import ( - "fmt" - "log" - - "github.com/caarlos0/env/v9" -) - -type Config struct { - Password string `env:"PASSWORD"` -} - -func main() { - cfg := &Config{} - opts := env.Options{Environment: map[string]string{ - "PASSWORD": "MY_PASSWORD", - }} - - // Load env vars. - if err := env.ParseWithOptions(cfg, opts); err != nil { - log.Fatal(err) - } - - // Print the loaded data. - fmt.Printf("%+v\n", cfg) -} -``` - -### Changing default tag name - -You can change what tag name to use for setting the env vars by setting the -`Options.TagName` variable. - -For example - -```go -package main - -import ( - "fmt" - "log" - - "github.com/caarlos0/env/v9" -) - -type Config struct { - Password string `json:"PASSWORD"` -} - -func main() { - cfg := &Config{} - opts := env.Options{TagName: "json"} - - // Load env vars. - if err := env.ParseWithOptions(cfg, opts); err != nil { - log.Fatal(err) - } - - // Print the loaded data. - fmt.Printf("%+v\n", cfg) -} -``` - -### Prefixes - -You can prefix sub-structs env tags, as well as a whole `env.Parse` call. - -Here's an example flexing it a bit: - -```go -package main - -import ( - "fmt" - "log" - - "github.com/caarlos0/env/v9" -) - -type Config struct { - Home string `env:"HOME"` -} - -type ComplexConfig struct { - Foo Config `envPrefix:"FOO_"` - Clean Config - Bar Config `envPrefix:"BAR_"` - Blah string `env:"BLAH"` -} - -func main() { - cfg := &ComplexConfig{} - opts := env.Options{ - Prefix: "T_", - Environment: map[string]string{ - "T_FOO_HOME": "/foo", - "T_BAR_HOME": "/bar", - "T_BLAH": "blahhh", - "T_HOME": "/clean", - }, - } - - // Load env vars. - if err := env.ParseWithOptions(cfg, opts); err != nil { - log.Fatal(err) - } - - // Print the loaded data. - fmt.Printf("%+v\n", cfg) -} -``` - -### On set hooks - -You might want to listen to value sets and, for example, log something or do -some other kind of logic. -You can do this by passing a `OnSet` option: - -```go -package main - -import ( - "fmt" - "log" - - "github.com/caarlos0/env/v9" -) - -type Config struct { - Username string `env:"USERNAME" envDefault:"admin"` - Password string `env:"PASSWORD"` -} - -func main() { - cfg := &Config{} - opts := env.Options{ - OnSet: func(tag string, value interface{}, isDefault bool) { - fmt.Printf("Set %s to %v (default? %v)\n", tag, value, isDefault) - }, - } - - // Load env vars. - if err := env.ParseWithOptions(cfg, opts); err != nil { - log.Fatal(err) - } - - // Print the loaded data. - fmt.Printf("%+v\n", cfg) -} -``` - -## Making all fields to required - -You can make all fields that don't have a default value be required by setting -the `RequiredIfNoDef: true` in the `Options`. - -For example - -```go -package main - -import ( - "fmt" - "log" - - "github.com/caarlos0/env/v9" -) - -type Config struct { - Username string `env:"USERNAME" envDefault:"admin"` - Password string `env:"PASSWORD"` -} - -func main() { - cfg := &Config{} - opts := env.Options{RequiredIfNoDef: true} - - // Load env vars. - if err := env.ParseWithOptions(cfg, opts); err != nil { - log.Fatal(err) - } - - // Print the loaded data. - fmt.Printf("%+v\n", cfg) -} -``` - -## Defaults from code - -You may define default value also in code, by initialising the config data -before it's filled by `env.Parse`. -Default values defined as struct tags will overwrite existing values during -Parse. - -```go -package main - -import ( - "fmt" - "log" - - "github.com/caarlos0/env/v9" -) - -type Config struct { - Username string `env:"USERNAME" envDefault:"admin"` - Password string `env:"PASSWORD"` -} - -func main() { - var cfg = Config{ - Username: "test", - Password: "123456", - } - - if err := env.Parse(&cfg); err != nil { - fmt.Println("failed:", err) - } - - fmt.Printf("%+v", cfg) // {Username:admin Password:123456} -} -``` - -## Error handling - -You can handle the errors the library throws like so: - -```go -package main - -import ( - "fmt" - "log" - - "github.com/caarlos0/env/v9" -) - -type Config struct { - Username string `env:"USERNAME" envDefault:"admin"` - Password string `env:"PASSWORD"` -} - -func main() { - var cfg Config - err := env.Parse(&cfg) - if e, ok := err.(*env.AggregateError); ok { - for _, er := range e.Errors { - switch v := er.(type) { - case env.ParseError: - // handle it - case env.NotStructPtrError: - // handle it - case env.NoParserError: - // handle it - case env.NoSupportedTagOptionError: - // handle it - default: - fmt.Printf("Unknown error type %v", v) - } - } - } - - fmt.Printf("%+v", cfg) // {Username:admin Password:123456} -} -``` - -> **Info** -> -> If you want to check if an specific error is in the chain, you can also use -> `errors.Is()`. - -## Stargazers over time - -[![Stargazers over time](https://starchart.cc/caarlos0/env.svg)](https://starchart.cc/caarlos0/env) diff --git a/vendor/github.com/caarlos0/env/v9/env.go b/vendor/github.com/caarlos0/env/v9/env.go deleted file mode 100644 index be8ee537..00000000 --- a/vendor/github.com/caarlos0/env/v9/env.go +++ /dev/null @@ -1,520 +0,0 @@ -package env - -import ( - "encoding" - "fmt" - "net/url" - "os" - "reflect" - "strconv" - "strings" - "time" - "unicode" -) - -// nolint: gochecknoglobals -var ( - defaultBuiltInParsers = map[reflect.Kind]ParserFunc{ - reflect.Bool: func(v string) (interface{}, error) { - return strconv.ParseBool(v) - }, - reflect.String: func(v string) (interface{}, error) { - return v, nil - }, - reflect.Int: func(v string) (interface{}, error) { - i, err := strconv.ParseInt(v, 10, 32) - return int(i), err - }, - reflect.Int16: func(v string) (interface{}, error) { - i, err := strconv.ParseInt(v, 10, 16) - return int16(i), err - }, - reflect.Int32: func(v string) (interface{}, error) { - i, err := strconv.ParseInt(v, 10, 32) - return int32(i), err - }, - reflect.Int64: func(v string) (interface{}, error) { - return strconv.ParseInt(v, 10, 64) - }, - reflect.Int8: func(v string) (interface{}, error) { - i, err := strconv.ParseInt(v, 10, 8) - return int8(i), err - }, - reflect.Uint: func(v string) (interface{}, error) { - i, err := strconv.ParseUint(v, 10, 32) - return uint(i), err - }, - reflect.Uint16: func(v string) (interface{}, error) { - i, err := strconv.ParseUint(v, 10, 16) - return uint16(i), err - }, - reflect.Uint32: func(v string) (interface{}, error) { - i, err := strconv.ParseUint(v, 10, 32) - return uint32(i), err - }, - reflect.Uint64: func(v string) (interface{}, error) { - i, err := strconv.ParseUint(v, 10, 64) - return i, err - }, - reflect.Uint8: func(v string) (interface{}, error) { - i, err := strconv.ParseUint(v, 10, 8) - return uint8(i), err - }, - reflect.Float64: func(v string) (interface{}, error) { - return strconv.ParseFloat(v, 64) - }, - reflect.Float32: func(v string) (interface{}, error) { - f, err := strconv.ParseFloat(v, 32) - return float32(f), err - }, - } -) - -func defaultTypeParsers() map[reflect.Type]ParserFunc { - return map[reflect.Type]ParserFunc{ - reflect.TypeOf(url.URL{}): func(v string) (interface{}, error) { - u, err := url.Parse(v) - if err != nil { - return nil, newParseValueError("unable to parse URL", err) - } - return *u, nil - }, - reflect.TypeOf(time.Nanosecond): func(v string) (interface{}, error) { - s, err := time.ParseDuration(v) - if err != nil { - return nil, newParseValueError("unable to parse duration", err) - } - return s, err - }, - } -} - -// ParserFunc defines the signature of a function that can be used within `CustomParsers`. -type ParserFunc func(v string) (interface{}, error) - -// OnSetFn is a hook that can be run when a value is set. -type OnSetFn func(tag string, value interface{}, isDefault bool) - -// Options for the parser. -type Options struct { - // Environment keys and values that will be accessible for the service. - Environment map[string]string - - // TagName specifies another tagname to use rather than the default env. - TagName string - - // RequiredIfNoDef automatically sets all env as required if they do not - // declare 'envDefault'. - RequiredIfNoDef bool - - // OnSet allows to run a function when a value is set. - OnSet OnSetFn - - // Prefix define a prefix for each key. - Prefix string - - // UseFieldNameByDefault defines whether or not env should use the field - // name by default if the `env` key is missing. - UseFieldNameByDefault bool - - // Custom parse functions for different types. - FuncMap map[reflect.Type]ParserFunc -} - -func defaultOptions() Options { - return Options{ - TagName: "env", - Environment: toMap(os.Environ()), - FuncMap: defaultTypeParsers(), - } -} - -func customOptions(opt Options) Options { - defOpts := defaultOptions() - if opt.TagName == "" { - opt.TagName = defOpts.TagName - } - if opt.Environment == nil { - opt.Environment = defOpts.Environment - } - if opt.FuncMap == nil { - opt.FuncMap = map[reflect.Type]ParserFunc{} - } - for k, v := range defOpts.FuncMap { - opt.FuncMap[k] = v - } - return opt -} - -func optionsWithEnvPrefix(field reflect.StructField, opts Options) Options { - return Options{ - Environment: opts.Environment, - TagName: opts.TagName, - RequiredIfNoDef: opts.RequiredIfNoDef, - OnSet: opts.OnSet, - Prefix: opts.Prefix + field.Tag.Get("envPrefix"), - UseFieldNameByDefault: opts.UseFieldNameByDefault, - FuncMap: opts.FuncMap, - } -} - -// Parse parses a struct containing `env` tags and loads its values from -// environment variables. -func Parse(v interface{}) error { - return parseInternal(v, defaultOptions()) -} - -// Parse parses a struct containing `env` tags and loads its values from -// environment variables. -func ParseWithOptions(v interface{}, opts Options) error { - return parseInternal(v, customOptions(opts)) -} - -func parseInternal(v interface{}, opts Options) error { - ptrRef := reflect.ValueOf(v) - if ptrRef.Kind() != reflect.Ptr { - return newAggregateError(NotStructPtrError{}) - } - ref := ptrRef.Elem() - if ref.Kind() != reflect.Struct { - return newAggregateError(NotStructPtrError{}) - } - return doParse(ref, opts) -} - -func doParse(ref reflect.Value, opts Options) error { - refType := ref.Type() - - var agrErr AggregateError - - for i := 0; i < refType.NumField(); i++ { - refField := ref.Field(i) - refTypeField := refType.Field(i) - - if err := doParseField(refField, refTypeField, opts); err != nil { - if val, ok := err.(AggregateError); ok { - agrErr.Errors = append(agrErr.Errors, val.Errors...) - } else { - agrErr.Errors = append(agrErr.Errors, err) - } - } - } - - if len(agrErr.Errors) == 0 { - return nil - } - - return agrErr -} - -func doParseField(refField reflect.Value, refTypeField reflect.StructField, opts Options) error { - if !refField.CanSet() { - return nil - } - if reflect.Ptr == refField.Kind() && !refField.IsNil() { - return parseInternal(refField.Interface(), optionsWithEnvPrefix(refTypeField, opts)) - } - if reflect.Struct == refField.Kind() && refField.CanAddr() && refField.Type().Name() == "" { - return parseInternal(refField.Addr().Interface(), optionsWithEnvPrefix(refTypeField, opts)) - } - value, err := get(refTypeField, opts) - if err != nil { - return err - } - - if value != "" { - return set(refField, refTypeField, value, opts.FuncMap) - } - - if reflect.Struct == refField.Kind() { - return doParse(refField, optionsWithEnvPrefix(refTypeField, opts)) - } - - return nil -} - -const underscore rune = '_' - -func toEnvName(input string) string { - var output []rune - for i, c := range input { - if i > 0 && output[i-1] != underscore && c != underscore && unicode.ToUpper(c) == c { - output = append(output, underscore) - } - output = append(output, unicode.ToUpper(c)) - } - return string(output) -} - -func get(field reflect.StructField, opts Options) (val string, err error) { - var exists bool - var isDefault bool - var loadFile bool - var unset bool - var notEmpty bool - var expand bool - - required := opts.RequiredIfNoDef - ownKey, tags := parseKeyForOption(field.Tag.Get(opts.TagName)) - if ownKey == "" && opts.UseFieldNameByDefault { - ownKey = toEnvName(field.Name) - } - - for _, tag := range tags { - switch tag { - case "": - continue - case "file": - loadFile = true - case "required": - required = true - case "unset": - unset = true - case "notEmpty": - notEmpty = true - case "expand": - expand = true - default: - return "", newNoSupportedTagOptionError(tag) - } - } - - prefix := opts.Prefix - key := prefix + ownKey - defaultValue, defExists := field.Tag.Lookup("envDefault") - val, exists, isDefault = getOr(key, defaultValue, defExists, opts.Environment) - - if expand { - val = os.ExpandEnv(val) - } - - if unset { - defer os.Unsetenv(key) - } - - if required && !exists && len(ownKey) > 0 { - return "", newEnvVarIsNotSet(key) - } - - if notEmpty && val == "" { - return "", newEmptyEnvVarError(key) - } - - if loadFile && val != "" { - filename := val - val, err = getFromFile(filename) - if err != nil { - return "", newLoadFileContentError(filename, key, err) - } - } - - if opts.OnSet != nil { - if ownKey != "" { - opts.OnSet(key, val, isDefault) - } - } - return val, err -} - -// split the env tag's key into the expected key and desired option, if any. -func parseKeyForOption(key string) (string, []string) { - opts := strings.Split(key, ",") - return opts[0], opts[1:] -} - -func getFromFile(filename string) (value string, err error) { - b, err := os.ReadFile(filename) - return string(b), err -} - -func getOr(key, defaultValue string, defExists bool, envs map[string]string) (string, bool, bool) { - value, exists := envs[key] - switch { - case (!exists || key == "") && defExists: - return defaultValue, true, true - case exists && value == "" && defExists: - return defaultValue, true, true - case !exists: - return "", false, false - } - - return value, true, false -} - -func set(field reflect.Value, sf reflect.StructField, value string, funcMap map[reflect.Type]ParserFunc) error { - if tm := asTextUnmarshaler(field); tm != nil { - if err := tm.UnmarshalText([]byte(value)); err != nil { - return newParseError(sf, err) - } - return nil - } - - typee := sf.Type - fieldee := field - if typee.Kind() == reflect.Ptr { - typee = typee.Elem() - fieldee = field.Elem() - } - - parserFunc, ok := funcMap[typee] - if ok { - val, err := parserFunc(value) - if err != nil { - return newParseError(sf, err) - } - - fieldee.Set(reflect.ValueOf(val)) - return nil - } - - parserFunc, ok = defaultBuiltInParsers[typee.Kind()] - if ok { - val, err := parserFunc(value) - if err != nil { - return newParseError(sf, err) - } - - fieldee.Set(reflect.ValueOf(val).Convert(typee)) - return nil - } - - switch field.Kind() { - case reflect.Slice: - return handleSlice(field, value, sf, funcMap) - case reflect.Map: - return handleMap(field, value, sf, funcMap) - } - - return newNoParserError(sf) -} - -func handleSlice(field reflect.Value, value string, sf reflect.StructField, funcMap map[reflect.Type]ParserFunc) error { - separator := sf.Tag.Get("envSeparator") - if separator == "" { - separator = "," - } - parts := strings.Split(value, separator) - - typee := sf.Type.Elem() - if typee.Kind() == reflect.Ptr { - typee = typee.Elem() - } - - if _, ok := reflect.New(typee).Interface().(encoding.TextUnmarshaler); ok { - return parseTextUnmarshalers(field, parts, sf) - } - - parserFunc, ok := funcMap[typee] - if !ok { - parserFunc, ok = defaultBuiltInParsers[typee.Kind()] - if !ok { - return newNoParserError(sf) - } - } - - result := reflect.MakeSlice(sf.Type, 0, len(parts)) - for _, part := range parts { - r, err := parserFunc(part) - if err != nil { - return newParseError(sf, err) - } - v := reflect.ValueOf(r).Convert(typee) - if sf.Type.Elem().Kind() == reflect.Ptr { - v = reflect.New(typee) - v.Elem().Set(reflect.ValueOf(r).Convert(typee)) - } - result = reflect.Append(result, v) - } - field.Set(result) - return nil -} - -func handleMap(field reflect.Value, value string, sf reflect.StructField, funcMap map[reflect.Type]ParserFunc) error { - keyType := sf.Type.Key() - keyParserFunc, ok := funcMap[keyType] - if !ok { - keyParserFunc, ok = defaultBuiltInParsers[keyType.Kind()] - if !ok { - return newNoParserError(sf) - } - } - - elemType := sf.Type.Elem() - elemParserFunc, ok := funcMap[elemType] - if !ok { - elemParserFunc, ok = defaultBuiltInParsers[elemType.Kind()] - if !ok { - return newNoParserError(sf) - } - } - - separator := sf.Tag.Get("envSeparator") - if separator == "" { - separator = "," - } - - result := reflect.MakeMap(sf.Type) - for _, part := range strings.Split(value, separator) { - pairs := strings.Split(part, ":") - if len(pairs) != 2 { - return newParseError(sf, fmt.Errorf(`%q should be in "key:value" format`, part)) - } - - key, err := keyParserFunc(pairs[0]) - if err != nil { - return newParseError(sf, err) - } - - elem, err := elemParserFunc(pairs[1]) - if err != nil { - return newParseError(sf, err) - } - - result.SetMapIndex(reflect.ValueOf(key).Convert(keyType), reflect.ValueOf(elem).Convert(elemType)) - } - - field.Set(result) - return nil -} - -func asTextUnmarshaler(field reflect.Value) encoding.TextUnmarshaler { - if reflect.Ptr == field.Kind() { - if field.IsNil() { - field.Set(reflect.New(field.Type().Elem())) - } - } else if field.CanAddr() { - field = field.Addr() - } - - tm, ok := field.Interface().(encoding.TextUnmarshaler) - if !ok { - return nil - } - return tm -} - -func parseTextUnmarshalers(field reflect.Value, data []string, sf reflect.StructField) error { - s := len(data) - elemType := field.Type().Elem() - slice := reflect.MakeSlice(reflect.SliceOf(elemType), s, s) - for i, v := range data { - sv := slice.Index(i) - kind := sv.Kind() - if kind == reflect.Ptr { - sv = reflect.New(elemType.Elem()) - } else { - sv = sv.Addr() - } - tm := sv.Interface().(encoding.TextUnmarshaler) - if err := tm.UnmarshalText([]byte(v)); err != nil { - return newParseError(sf, err) - } - if kind == reflect.Ptr { - slice.Index(i).Set(sv) - } - } - - field.Set(slice) - - return nil -} diff --git a/vendor/github.com/caarlos0/env/v9/env_tomap.go b/vendor/github.com/caarlos0/env/v9/env_tomap.go deleted file mode 100644 index aece2ae9..00000000 --- a/vendor/github.com/caarlos0/env/v9/env_tomap.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build !windows - -package env - -import "strings" - -func toMap(env []string) map[string]string { - r := map[string]string{} - for _, e := range env { - p := strings.SplitN(e, "=", 2) - if len(p) == 2 { - r[p[0]] = p[1] - } - } - return r -} diff --git a/vendor/github.com/caarlos0/env/v9/env_tomap_windows.go b/vendor/github.com/caarlos0/env/v9/env_tomap_windows.go deleted file mode 100644 index 04ce66f5..00000000 --- a/vendor/github.com/caarlos0/env/v9/env_tomap_windows.go +++ /dev/null @@ -1,29 +0,0 @@ -//go:build windows - -package env - -import "strings" - -func toMap(env []string) map[string]string { - r := map[string]string{} - for _, e := range env { - p := strings.SplitN(e, "=", 2) - - // On Windows, environment variables can start with '='. If so, Split at next character. - // See env_windows.go in the Go source: https://github.com/golang/go/blob/master/src/syscall/env_windows.go#L58 - prefixEqualSign := false - if len(e) > 0 && e[0] == '=' { - e = e[1:] - prefixEqualSign = true - } - p = strings.SplitN(e, "=", 2) - if prefixEqualSign { - p[0] = "=" + p[0] - } - - if len(p) == 2 { - r[p[0]] = p[1] - } - } - return r -} diff --git a/vendor/github.com/caarlos0/env/v9/error.go b/vendor/github.com/caarlos0/env/v9/error.go deleted file mode 100644 index 156ca3ec..00000000 --- a/vendor/github.com/caarlos0/env/v9/error.go +++ /dev/null @@ -1,164 +0,0 @@ -package env - -import ( - "fmt" - "reflect" - "strings" -) - -// An aggregated error wrapper to combine gathered errors. This allows either to display all errors or convert them individually -// List of the available errors -// ParseError -// NotStructPtrError -// NoParserError -// NoSupportedTagOptionError -// EnvVarIsNotSetError -// EmptyEnvVarError -// LoadFileContentError -// ParseValueError -type AggregateError struct { - Errors []error -} - -func newAggregateError(initErr error) error { - return AggregateError{ - []error{ - initErr, - }, - } -} - -func (e AggregateError) Error() string { - var sb strings.Builder - - sb.WriteString("env:") - - for _, err := range e.Errors { - sb.WriteString(fmt.Sprintf(" %v;", err.Error())) - } - - return strings.TrimRight(sb.String(), ";") -} - -// Is conforms with errors.Is. -func (e AggregateError) Is(err error) bool { - for _, ie := range e.Errors { - if reflect.TypeOf(ie) == reflect.TypeOf(err) { - return true - } - } - return false -} - -// The error occurs when it's impossible to convert the value for given type. -type ParseError struct { - Name string - Type reflect.Type - Err error -} - -func newParseError(sf reflect.StructField, err error) error { - return ParseError{sf.Name, sf.Type, err} -} - -func (e ParseError) Error() string { - return fmt.Sprintf(`parse error on field "%s" of type "%s": %v`, e.Name, e.Type, e.Err) -} - -// The error occurs when pass something that is not a pointer to a Struct to Parse -type NotStructPtrError struct{} - -func (e NotStructPtrError) Error() string { - return "expected a pointer to a Struct" -} - -// This error occurs when there is no parser provided for given type -// Supported types and defaults: https://github.com/caarlos0/env#supported-types-and-defaults -// How to create a custom parser: https://github.com/caarlos0/env#custom-parser-funcs -type NoParserError struct { - Name string - Type reflect.Type -} - -func newNoParserError(sf reflect.StructField) error { - return NoParserError{sf.Name, sf.Type} -} - -func (e NoParserError) Error() string { - return fmt.Sprintf(`no parser found for field "%s" of type "%s"`, e.Name, e.Type) -} - -// This error occurs when the given tag is not supported -// In-built supported tags: "", "file", "required", "unset", "notEmpty", "expand", "envDefault", "envSeparator" -// How to create a custom tag: https://github.com/caarlos0/env#changing-default-tag-name -type NoSupportedTagOptionError struct { - Tag string -} - -func newNoSupportedTagOptionError(tag string) error { - return NoSupportedTagOptionError{tag} -} - -func (e NoSupportedTagOptionError) Error() string { - return fmt.Sprintf("tag option %q not supported", e.Tag) -} - -// This error occurs when the required variable is not set -// Read about required fields: https://github.com/caarlos0/env#required-fields -type EnvVarIsNotSetError struct { - Key string -} - -func newEnvVarIsNotSet(key string) error { - return EnvVarIsNotSetError{key} -} - -func (e EnvVarIsNotSetError) Error() string { - return fmt.Sprintf(`required environment variable %q is not set`, e.Key) -} - -// This error occurs when the variable which must be not empty is existing but has an empty value -// Read about not empty fields: https://github.com/caarlos0/env#not-empty-fields -type EmptyEnvVarError struct { - Key string -} - -func newEmptyEnvVarError(key string) error { - return EmptyEnvVarError{key} -} - -func (e EmptyEnvVarError) Error() string { - return fmt.Sprintf("environment variable %q should not be empty", e.Key) -} - -// This error occurs when it's impossible to load the value from the file -// Read about From file feature: https://github.com/caarlos0/env#from-file -type LoadFileContentError struct { - Filename string - Key string - Err error -} - -func newLoadFileContentError(filename, key string, err error) error { - return LoadFileContentError{filename, key, err} -} - -func (e LoadFileContentError) Error() string { - return fmt.Sprintf(`could not load content of file "%s" from variable %s: %v`, e.Filename, e.Key, e.Err) -} - -// This error occurs when it's impossible to convert value using given parser -// Supported types and defaults: https://github.com/caarlos0/env#supported-types-and-defaults -// How to create a custom parser: https://github.com/caarlos0/env#custom-parser-funcs -type ParseValueError struct { - Msg string - Err error -} - -func newParseValueError(message string, err error) error { - return ParseValueError{message, err} -} - -func (e ParseValueError) Error() string { - return fmt.Sprintf("%s: %v", e.Msg, e.Err) -} diff --git a/vendor/github.com/cespare/xxhash/v2/LICENSE.txt b/vendor/github.com/cespare/xxhash/v2/LICENSE.txt deleted file mode 100644 index 24b53065..00000000 --- a/vendor/github.com/cespare/xxhash/v2/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2016 Caleb Spare - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/cespare/xxhash/v2/README.md b/vendor/github.com/cespare/xxhash/v2/README.md deleted file mode 100644 index 8bf0e5b7..00000000 --- a/vendor/github.com/cespare/xxhash/v2/README.md +++ /dev/null @@ -1,72 +0,0 @@ -# xxhash - -[![Go Reference](https://pkg.go.dev/badge/github.com/cespare/xxhash/v2.svg)](https://pkg.go.dev/github.com/cespare/xxhash/v2) -[![Test](https://github.com/cespare/xxhash/actions/workflows/test.yml/badge.svg)](https://github.com/cespare/xxhash/actions/workflows/test.yml) - -xxhash is a Go implementation of the 64-bit [xxHash] algorithm, XXH64. This is a -high-quality hashing algorithm that is much faster than anything in the Go -standard library. - -This package provides a straightforward API: - -``` -func Sum64(b []byte) uint64 -func Sum64String(s string) uint64 -type Digest struct{ ... } - func New() *Digest -``` - -The `Digest` type implements hash.Hash64. Its key methods are: - -``` -func (*Digest) Write([]byte) (int, error) -func (*Digest) WriteString(string) (int, error) -func (*Digest) Sum64() uint64 -``` - -The package is written with optimized pure Go and also contains even faster -assembly implementations for amd64 and arm64. If desired, the `purego` build tag -opts into using the Go code even on those architectures. - -[xxHash]: http://cyan4973.github.io/xxHash/ - -## Compatibility - -This package is in a module and the latest code is in version 2 of the module. -You need a version of Go with at least "minimal module compatibility" to use -github.com/cespare/xxhash/v2: - -* 1.9.7+ for Go 1.9 -* 1.10.3+ for Go 1.10 -* Go 1.11 or later - -I recommend using the latest release of Go. - -## Benchmarks - -Here are some quick benchmarks comparing the pure-Go and assembly -implementations of Sum64. - -| input size | purego | asm | -| ---------- | --------- | --------- | -| 4 B | 1.3 GB/s | 1.2 GB/s | -| 16 B | 2.9 GB/s | 3.5 GB/s | -| 100 B | 6.9 GB/s | 8.1 GB/s | -| 4 KB | 11.7 GB/s | 16.7 GB/s | -| 10 MB | 12.0 GB/s | 17.3 GB/s | - -These numbers were generated on Ubuntu 20.04 with an Intel Xeon Platinum 8252C -CPU using the following commands under Go 1.19.2: - -``` -benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') -benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') -``` - -## Projects using this package - -- [InfluxDB](https://github.com/influxdata/influxdb) -- [Prometheus](https://github.com/prometheus/prometheus) -- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics) -- [FreeCache](https://github.com/coocood/freecache) -- [FastCache](https://github.com/VictoriaMetrics/fastcache) diff --git a/vendor/github.com/cespare/xxhash/v2/testall.sh b/vendor/github.com/cespare/xxhash/v2/testall.sh deleted file mode 100644 index 94b9c443..00000000 --- a/vendor/github.com/cespare/xxhash/v2/testall.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -set -eu -o pipefail - -# Small convenience script for running the tests with various combinations of -# arch/tags. This assumes we're running on amd64 and have qemu available. - -go test ./... -go test -tags purego ./... -GOARCH=arm64 go test -GOARCH=arm64 go test -tags purego diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash.go b/vendor/github.com/cespare/xxhash/v2/xxhash.go deleted file mode 100644 index a9e0d45c..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash.go +++ /dev/null @@ -1,228 +0,0 @@ -// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described -// at http://cyan4973.github.io/xxHash/. -package xxhash - -import ( - "encoding/binary" - "errors" - "math/bits" -) - -const ( - prime1 uint64 = 11400714785074694791 - prime2 uint64 = 14029467366897019727 - prime3 uint64 = 1609587929392839161 - prime4 uint64 = 9650029242287828579 - prime5 uint64 = 2870177450012600261 -) - -// Store the primes in an array as well. -// -// The consts are used when possible in Go code to avoid MOVs but we need a -// contiguous array of the assembly code. -var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5} - -// Digest implements hash.Hash64. -type Digest struct { - v1 uint64 - v2 uint64 - v3 uint64 - v4 uint64 - total uint64 - mem [32]byte - n int // how much of mem is used -} - -// New creates a new Digest that computes the 64-bit xxHash algorithm. -func New() *Digest { - var d Digest - d.Reset() - return &d -} - -// Reset clears the Digest's state so that it can be reused. -func (d *Digest) Reset() { - d.v1 = primes[0] + prime2 - d.v2 = prime2 - d.v3 = 0 - d.v4 = -primes[0] - d.total = 0 - d.n = 0 -} - -// Size always returns 8 bytes. -func (d *Digest) Size() int { return 8 } - -// BlockSize always returns 32 bytes. -func (d *Digest) BlockSize() int { return 32 } - -// Write adds more data to d. It always returns len(b), nil. -func (d *Digest) Write(b []byte) (n int, err error) { - n = len(b) - d.total += uint64(n) - - memleft := d.mem[d.n&(len(d.mem)-1):] - - if d.n+n < 32 { - // This new data doesn't even fill the current block. - copy(memleft, b) - d.n += n - return - } - - if d.n > 0 { - // Finish off the partial block. - c := copy(memleft, b) - d.v1 = round(d.v1, u64(d.mem[0:8])) - d.v2 = round(d.v2, u64(d.mem[8:16])) - d.v3 = round(d.v3, u64(d.mem[16:24])) - d.v4 = round(d.v4, u64(d.mem[24:32])) - b = b[c:] - d.n = 0 - } - - if len(b) >= 32 { - // One or more full blocks left. - nw := writeBlocks(d, b) - b = b[nw:] - } - - // Store any remaining partial block. - copy(d.mem[:], b) - d.n = len(b) - - return -} - -// Sum appends the current hash to b and returns the resulting slice. -func (d *Digest) Sum(b []byte) []byte { - s := d.Sum64() - return append( - b, - byte(s>>56), - byte(s>>48), - byte(s>>40), - byte(s>>32), - byte(s>>24), - byte(s>>16), - byte(s>>8), - byte(s), - ) -} - -// Sum64 returns the current hash. -func (d *Digest) Sum64() uint64 { - var h uint64 - - if d.total >= 32 { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = d.v3 + prime5 - } - - h += d.total - - b := d.mem[:d.n&(len(d.mem)-1)] - for ; len(b) >= 8; b = b[8:] { - k1 := round(0, u64(b[:8])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if len(b) >= 4 { - h ^= uint64(u32(b[:4])) * prime1 - h = rol23(h)*prime2 + prime3 - b = b[4:] - } - for ; len(b) > 0; b = b[1:] { - h ^= uint64(b[0]) * prime5 - h = rol11(h) * prime1 - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -const ( - magic = "xxh\x06" - marshaledSize = len(magic) + 8*5 + 32 -) - -// MarshalBinary implements the encoding.BinaryMarshaler interface. -func (d *Digest) MarshalBinary() ([]byte, error) { - b := make([]byte, 0, marshaledSize) - b = append(b, magic...) - b = appendUint64(b, d.v1) - b = appendUint64(b, d.v2) - b = appendUint64(b, d.v3) - b = appendUint64(b, d.v4) - b = appendUint64(b, d.total) - b = append(b, d.mem[:d.n]...) - b = b[:len(b)+len(d.mem)-d.n] - return b, nil -} - -// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. -func (d *Digest) UnmarshalBinary(b []byte) error { - if len(b) < len(magic) || string(b[:len(magic)]) != magic { - return errors.New("xxhash: invalid hash state identifier") - } - if len(b) != marshaledSize { - return errors.New("xxhash: invalid hash state size") - } - b = b[len(magic):] - b, d.v1 = consumeUint64(b) - b, d.v2 = consumeUint64(b) - b, d.v3 = consumeUint64(b) - b, d.v4 = consumeUint64(b) - b, d.total = consumeUint64(b) - copy(d.mem[:], b) - d.n = int(d.total % uint64(len(d.mem))) - return nil -} - -func appendUint64(b []byte, x uint64) []byte { - var a [8]byte - binary.LittleEndian.PutUint64(a[:], x) - return append(b, a[:]...) -} - -func consumeUint64(b []byte) ([]byte, uint64) { - x := u64(b) - return b[8:], x -} - -func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } -func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } - -func round(acc, input uint64) uint64 { - acc += input * prime2 - acc = rol31(acc) - acc *= prime1 - return acc -} - -func mergeRound(acc, val uint64) uint64 { - val = round(0, val) - acc ^= val - acc = acc*prime1 + prime4 - return acc -} - -func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) } -func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) } -func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) } -func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) } -func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) } -func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) } -func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) } -func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) } diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s b/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s deleted file mode 100644 index 3e8b1325..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s +++ /dev/null @@ -1,209 +0,0 @@ -//go:build !appengine && gc && !purego -// +build !appengine -// +build gc -// +build !purego - -#include "textflag.h" - -// Registers: -#define h AX -#define d AX -#define p SI // pointer to advance through b -#define n DX -#define end BX // loop end -#define v1 R8 -#define v2 R9 -#define v3 R10 -#define v4 R11 -#define x R12 -#define prime1 R13 -#define prime2 R14 -#define prime4 DI - -#define round(acc, x) \ - IMULQ prime2, x \ - ADDQ x, acc \ - ROLQ $31, acc \ - IMULQ prime1, acc - -// round0 performs the operation x = round(0, x). -#define round0(x) \ - IMULQ prime2, x \ - ROLQ $31, x \ - IMULQ prime1, x - -// mergeRound applies a merge round on the two registers acc and x. -// It assumes that prime1, prime2, and prime4 have been loaded. -#define mergeRound(acc, x) \ - round0(x) \ - XORQ x, acc \ - IMULQ prime1, acc \ - ADDQ prime4, acc - -// blockLoop processes as many 32-byte blocks as possible, -// updating v1, v2, v3, and v4. It assumes that there is at least one block -// to process. -#define blockLoop() \ -loop: \ - MOVQ +0(p), x \ - round(v1, x) \ - MOVQ +8(p), x \ - round(v2, x) \ - MOVQ +16(p), x \ - round(v3, x) \ - MOVQ +24(p), x \ - round(v4, x) \ - ADDQ $32, p \ - CMPQ p, end \ - JLE loop - -// func Sum64(b []byte) uint64 -TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 - // Load fixed primes. - MOVQ ·primes+0(SB), prime1 - MOVQ ·primes+8(SB), prime2 - MOVQ ·primes+24(SB), prime4 - - // Load slice. - MOVQ b_base+0(FP), p - MOVQ b_len+8(FP), n - LEAQ (p)(n*1), end - - // The first loop limit will be len(b)-32. - SUBQ $32, end - - // Check whether we have at least one block. - CMPQ n, $32 - JLT noBlocks - - // Set up initial state (v1, v2, v3, v4). - MOVQ prime1, v1 - ADDQ prime2, v1 - MOVQ prime2, v2 - XORQ v3, v3 - XORQ v4, v4 - SUBQ prime1, v4 - - blockLoop() - - MOVQ v1, h - ROLQ $1, h - MOVQ v2, x - ROLQ $7, x - ADDQ x, h - MOVQ v3, x - ROLQ $12, x - ADDQ x, h - MOVQ v4, x - ROLQ $18, x - ADDQ x, h - - mergeRound(h, v1) - mergeRound(h, v2) - mergeRound(h, v3) - mergeRound(h, v4) - - JMP afterBlocks - -noBlocks: - MOVQ ·primes+32(SB), h - -afterBlocks: - ADDQ n, h - - ADDQ $24, end - CMPQ p, end - JG try4 - -loop8: - MOVQ (p), x - ADDQ $8, p - round0(x) - XORQ x, h - ROLQ $27, h - IMULQ prime1, h - ADDQ prime4, h - - CMPQ p, end - JLE loop8 - -try4: - ADDQ $4, end - CMPQ p, end - JG try1 - - MOVL (p), x - ADDQ $4, p - IMULQ prime1, x - XORQ x, h - - ROLQ $23, h - IMULQ prime2, h - ADDQ ·primes+16(SB), h - -try1: - ADDQ $4, end - CMPQ p, end - JGE finalize - -loop1: - MOVBQZX (p), x - ADDQ $1, p - IMULQ ·primes+32(SB), x - XORQ x, h - ROLQ $11, h - IMULQ prime1, h - - CMPQ p, end - JL loop1 - -finalize: - MOVQ h, x - SHRQ $33, x - XORQ x, h - IMULQ prime2, h - MOVQ h, x - SHRQ $29, x - XORQ x, h - IMULQ ·primes+16(SB), h - MOVQ h, x - SHRQ $32, x - XORQ x, h - - MOVQ h, ret+24(FP) - RET - -// func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 - // Load fixed primes needed for round. - MOVQ ·primes+0(SB), prime1 - MOVQ ·primes+8(SB), prime2 - - // Load slice. - MOVQ b_base+8(FP), p - MOVQ b_len+16(FP), n - LEAQ (p)(n*1), end - SUBQ $32, end - - // Load vN from d. - MOVQ s+0(FP), d - MOVQ 0(d), v1 - MOVQ 8(d), v2 - MOVQ 16(d), v3 - MOVQ 24(d), v4 - - // We don't need to check the loop condition here; this function is - // always called with at least one block of data to process. - blockLoop() - - // Copy vN back to d. - MOVQ v1, 0(d) - MOVQ v2, 8(d) - MOVQ v3, 16(d) - MOVQ v4, 24(d) - - // The number of bytes written is p minus the old base pointer. - SUBQ b_base+8(FP), p - MOVQ p, ret+32(FP) - - RET diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s b/vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s deleted file mode 100644 index 7e3145a2..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s +++ /dev/null @@ -1,183 +0,0 @@ -//go:build !appengine && gc && !purego -// +build !appengine -// +build gc -// +build !purego - -#include "textflag.h" - -// Registers: -#define digest R1 -#define h R2 // return value -#define p R3 // input pointer -#define n R4 // input length -#define nblocks R5 // n / 32 -#define prime1 R7 -#define prime2 R8 -#define prime3 R9 -#define prime4 R10 -#define prime5 R11 -#define v1 R12 -#define v2 R13 -#define v3 R14 -#define v4 R15 -#define x1 R20 -#define x2 R21 -#define x3 R22 -#define x4 R23 - -#define round(acc, x) \ - MADD prime2, acc, x, acc \ - ROR $64-31, acc \ - MUL prime1, acc - -// round0 performs the operation x = round(0, x). -#define round0(x) \ - MUL prime2, x \ - ROR $64-31, x \ - MUL prime1, x - -#define mergeRound(acc, x) \ - round0(x) \ - EOR x, acc \ - MADD acc, prime4, prime1, acc - -// blockLoop processes as many 32-byte blocks as possible, -// updating v1, v2, v3, and v4. It assumes that n >= 32. -#define blockLoop() \ - LSR $5, n, nblocks \ - PCALIGN $16 \ - loop: \ - LDP.P 16(p), (x1, x2) \ - LDP.P 16(p), (x3, x4) \ - round(v1, x1) \ - round(v2, x2) \ - round(v3, x3) \ - round(v4, x4) \ - SUB $1, nblocks \ - CBNZ nblocks, loop - -// func Sum64(b []byte) uint64 -TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 - LDP b_base+0(FP), (p, n) - - LDP ·primes+0(SB), (prime1, prime2) - LDP ·primes+16(SB), (prime3, prime4) - MOVD ·primes+32(SB), prime5 - - CMP $32, n - CSEL LT, prime5, ZR, h // if n < 32 { h = prime5 } else { h = 0 } - BLT afterLoop - - ADD prime1, prime2, v1 - MOVD prime2, v2 - MOVD $0, v3 - NEG prime1, v4 - - blockLoop() - - ROR $64-1, v1, x1 - ROR $64-7, v2, x2 - ADD x1, x2 - ROR $64-12, v3, x3 - ROR $64-18, v4, x4 - ADD x3, x4 - ADD x2, x4, h - - mergeRound(h, v1) - mergeRound(h, v2) - mergeRound(h, v3) - mergeRound(h, v4) - -afterLoop: - ADD n, h - - TBZ $4, n, try8 - LDP.P 16(p), (x1, x2) - - round0(x1) - - // NOTE: here and below, sequencing the EOR after the ROR (using a - // rotated register) is worth a small but measurable speedup for small - // inputs. - ROR $64-27, h - EOR x1 @> 64-27, h, h - MADD h, prime4, prime1, h - - round0(x2) - ROR $64-27, h - EOR x2 @> 64-27, h, h - MADD h, prime4, prime1, h - -try8: - TBZ $3, n, try4 - MOVD.P 8(p), x1 - - round0(x1) - ROR $64-27, h - EOR x1 @> 64-27, h, h - MADD h, prime4, prime1, h - -try4: - TBZ $2, n, try2 - MOVWU.P 4(p), x2 - - MUL prime1, x2 - ROR $64-23, h - EOR x2 @> 64-23, h, h - MADD h, prime3, prime2, h - -try2: - TBZ $1, n, try1 - MOVHU.P 2(p), x3 - AND $255, x3, x1 - LSR $8, x3, x2 - - MUL prime5, x1 - ROR $64-11, h - EOR x1 @> 64-11, h, h - MUL prime1, h - - MUL prime5, x2 - ROR $64-11, h - EOR x2 @> 64-11, h, h - MUL prime1, h - -try1: - TBZ $0, n, finalize - MOVBU (p), x4 - - MUL prime5, x4 - ROR $64-11, h - EOR x4 @> 64-11, h, h - MUL prime1, h - -finalize: - EOR h >> 33, h - MUL prime2, h - EOR h >> 29, h - MUL prime3, h - EOR h >> 32, h - - MOVD h, ret+24(FP) - RET - -// func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 - LDP ·primes+0(SB), (prime1, prime2) - - // Load state. Assume v[1-4] are stored contiguously. - MOVD d+0(FP), digest - LDP 0(digest), (v1, v2) - LDP 16(digest), (v3, v4) - - LDP b_base+8(FP), (p, n) - - blockLoop() - - // Store updated state. - STP (v1, v2), 0(digest) - STP (v3, v4), 16(digest) - - BIC $31, n - MOVD n, ret+32(FP) - RET diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_asm.go b/vendor/github.com/cespare/xxhash/v2/xxhash_asm.go deleted file mode 100644 index 9216e0a4..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_asm.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build (amd64 || arm64) && !appengine && gc && !purego -// +build amd64 arm64 -// +build !appengine -// +build gc -// +build !purego - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b. -// -//go:noescape -func Sum64(b []byte) uint64 - -//go:noescape -func writeBlocks(d *Digest, b []byte) int diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_other.go b/vendor/github.com/cespare/xxhash/v2/xxhash_other.go deleted file mode 100644 index 26df13bb..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_other.go +++ /dev/null @@ -1,76 +0,0 @@ -//go:build (!amd64 && !arm64) || appengine || !gc || purego -// +build !amd64,!arm64 appengine !gc purego - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b. -func Sum64(b []byte) uint64 { - // A simpler version would be - // d := New() - // d.Write(b) - // return d.Sum64() - // but this is faster, particularly for small inputs. - - n := len(b) - var h uint64 - - if n >= 32 { - v1 := primes[0] + prime2 - v2 := prime2 - v3 := uint64(0) - v4 := -primes[0] - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = prime5 - } - - h += uint64(n) - - for ; len(b) >= 8; b = b[8:] { - k1 := round(0, u64(b[:8])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if len(b) >= 4 { - h ^= uint64(u32(b[:4])) * prime1 - h = rol23(h)*prime2 + prime3 - b = b[4:] - } - for ; len(b) > 0; b = b[1:] { - h ^= uint64(b[0]) * prime5 - h = rol11(h) * prime1 - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -func writeBlocks(d *Digest, b []byte) int { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - n := len(b) - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4 - return n - len(b) -} diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go b/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go deleted file mode 100644 index e86f1b5f..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build appengine -// +build appengine - -// This file contains the safe implementations of otherwise unsafe-using code. - -package xxhash - -// Sum64String computes the 64-bit xxHash digest of s. -func Sum64String(s string) uint64 { - return Sum64([]byte(s)) -} - -// WriteString adds more data to d. It always returns len(s), nil. -func (d *Digest) WriteString(s string) (n int, err error) { - return d.Write([]byte(s)) -} diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go b/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go deleted file mode 100644 index 1c1638fd..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go +++ /dev/null @@ -1,58 +0,0 @@ -//go:build !appengine -// +build !appengine - -// This file encapsulates usage of unsafe. -// xxhash_safe.go contains the safe implementations. - -package xxhash - -import ( - "unsafe" -) - -// In the future it's possible that compiler optimizations will make these -// XxxString functions unnecessary by realizing that calls such as -// Sum64([]byte(s)) don't need to copy s. See https://go.dev/issue/2205. -// If that happens, even if we keep these functions they can be replaced with -// the trivial safe code. - -// NOTE: The usual way of doing an unsafe string-to-[]byte conversion is: -// -// var b []byte -// bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) -// bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data -// bh.Len = len(s) -// bh.Cap = len(s) -// -// Unfortunately, as of Go 1.15.3 the inliner's cost model assigns a high enough -// weight to this sequence of expressions that any function that uses it will -// not be inlined. Instead, the functions below use a different unsafe -// conversion designed to minimize the inliner weight and allow both to be -// inlined. There is also a test (TestInlining) which verifies that these are -// inlined. -// -// See https://github.com/golang/go/issues/42739 for discussion. - -// Sum64String computes the 64-bit xxHash digest of s. -// It may be faster than Sum64([]byte(s)) by avoiding a copy. -func Sum64String(s string) uint64 { - b := *(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)})) - return Sum64(b) -} - -// WriteString adds more data to d. It always returns len(s), nil. -// It may be faster than Write([]byte(s)) by avoiding a copy. -func (d *Digest) WriteString(s string) (n int, err error) { - d.Write(*(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)}))) - // d.Write always returns len(s), nil. - // Ignoring the return output and returning these fixed values buys a - // savings of 6 in the inliner's cost model. - return len(s), nil -} - -// sliceHeader is similar to reflect.SliceHeader, but it assumes that the layout -// of the first two words is the same as the layout of a string. -type sliceHeader struct { - s string - cap int -} diff --git a/vendor/github.com/creack/pty/.gitignore b/vendor/github.com/creack/pty/.gitignore deleted file mode 100644 index 1f0a99f2..00000000 --- a/vendor/github.com/creack/pty/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -[568].out -_go* -_test* -_obj diff --git a/vendor/github.com/creack/pty/Dockerfile.golang b/vendor/github.com/creack/pty/Dockerfile.golang deleted file mode 100644 index 2ee82a3a..00000000 --- a/vendor/github.com/creack/pty/Dockerfile.golang +++ /dev/null @@ -1,17 +0,0 @@ -ARG GOVERSION=1.14 -FROM golang:${GOVERSION} - -# Set base env. -ARG GOOS=linux -ARG GOARCH=amd64 -ENV GOOS=${GOOS} GOARCH=${GOARCH} CGO_ENABLED=0 GOFLAGS='-v -ldflags=-s -ldflags=-w' - -# Pre compile the stdlib for 386/arm (32bits). -RUN go build -a std - -# Add the code to the image. -WORKDIR pty -ADD . . - -# Build the lib. -RUN go build diff --git a/vendor/github.com/creack/pty/Dockerfile.riscv b/vendor/github.com/creack/pty/Dockerfile.riscv deleted file mode 100644 index 7a30c94d..00000000 --- a/vendor/github.com/creack/pty/Dockerfile.riscv +++ /dev/null @@ -1,23 +0,0 @@ -# NOTE: Using 1.13 as a base to build the RISCV compiler, the resulting version is based on go1.6. -FROM golang:1.13 - -# Clone and complie a riscv compatible version of the go compiler. -RUN git clone https://review.gerrithub.io/riscv/riscv-go /riscv-go -# riscvdev branch HEAD as of 2019-06-29. -RUN cd /riscv-go && git checkout 04885fddd096d09d4450726064d06dd107e374bf -ENV PATH=/riscv-go/misc/riscv:/riscv-go/bin:$PATH -RUN cd /riscv-go/src && GOROOT_BOOTSTRAP=$(go env GOROOT) ./make.bash -ENV GOROOT=/riscv-go - -# Set the base env. -ENV GOOS=linux GOARCH=riscv CGO_ENABLED=0 GOFLAGS='-v -ldflags=-s -ldflags=-w' - -# Pre compile the stdlib. -RUN go build -a std - -# Add the code to the image. -WORKDIR pty -ADD . . - -# Build the lib. -RUN go build diff --git a/vendor/github.com/creack/pty/LICENSE b/vendor/github.com/creack/pty/LICENSE deleted file mode 100644 index 6b7558b6..00000000 --- a/vendor/github.com/creack/pty/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2011 Keith Rarick - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, -sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall -be included in all copies or substantial portions of the -Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY -KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE -WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS -OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/creack/pty/README.md b/vendor/github.com/creack/pty/README.md deleted file mode 100644 index a4fe7670..00000000 --- a/vendor/github.com/creack/pty/README.md +++ /dev/null @@ -1,107 +0,0 @@ -# pty - -Pty is a Go package for using unix pseudo-terminals. - -## Install - -```sh -go get github.com/creack/pty -``` - -## Examples - -Note that those examples are for demonstration purpose only, to showcase how to use the library. They are not meant to be used in any kind of production environment. - -### Command - -```go -package main - -import ( - "io" - "os" - "os/exec" - - "github.com/creack/pty" -) - -func main() { - c := exec.Command("grep", "--color=auto", "bar") - f, err := pty.Start(c) - if err != nil { - panic(err) - } - - go func() { - f.Write([]byte("foo\n")) - f.Write([]byte("bar\n")) - f.Write([]byte("baz\n")) - f.Write([]byte{4}) // EOT - }() - io.Copy(os.Stdout, f) -} -``` - -### Shell - -```go -package main - -import ( - "io" - "log" - "os" - "os/exec" - "os/signal" - "syscall" - - "github.com/creack/pty" - "golang.org/x/term" -) - -func test() error { - // Create arbitrary command. - c := exec.Command("bash") - - // Start the command with a pty. - ptmx, err := pty.Start(c) - if err != nil { - return err - } - // Make sure to close the pty at the end. - defer func() { _ = ptmx.Close() }() // Best effort. - - // Handle pty size. - ch := make(chan os.Signal, 1) - signal.Notify(ch, syscall.SIGWINCH) - go func() { - for range ch { - if err := pty.InheritSize(os.Stdin, ptmx); err != nil { - log.Printf("error resizing pty: %s", err) - } - } - }() - ch <- syscall.SIGWINCH // Initial resize. - defer func() { signal.Stop(ch); close(ch) }() // Cleanup signals when done. - - // Set stdin in raw mode. - oldState, err := term.MakeRaw(int(os.Stdin.Fd())) - if err != nil { - panic(err) - } - defer func() { _ = term.Restore(int(os.Stdin.Fd()), oldState) }() // Best effort. - - // Copy stdin to the pty and the pty to stdout. - // NOTE: The goroutine will keep reading until the next keystroke before returning. - go func() { _, _ = io.Copy(ptmx, os.Stdin) }() - _, _ = io.Copy(os.Stdout, ptmx) - - return nil -} - -func main() { - if err := test(); err != nil { - log.Fatal(err) - } -} -``` diff --git a/vendor/github.com/creack/pty/asm_solaris_amd64.s b/vendor/github.com/creack/pty/asm_solaris_amd64.s deleted file mode 100644 index 7fbef8ee..00000000 --- a/vendor/github.com/creack/pty/asm_solaris_amd64.s +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build gc -//+build gc - -#include "textflag.h" - -// -// System calls for amd64, Solaris are implemented in runtime/syscall_solaris.go -// - -TEXT ·sysvicall6(SB),NOSPLIT,$0-88 - JMP syscall·sysvicall6(SB) - -TEXT ·rawSysvicall6(SB),NOSPLIT,$0-88 - JMP syscall·rawSysvicall6(SB) diff --git a/vendor/github.com/creack/pty/doc.go b/vendor/github.com/creack/pty/doc.go deleted file mode 100644 index 3c8b3244..00000000 --- a/vendor/github.com/creack/pty/doc.go +++ /dev/null @@ -1,16 +0,0 @@ -// Package pty provides functions for working with Unix terminals. -package pty - -import ( - "errors" - "os" -) - -// ErrUnsupported is returned if a function is not -// available on the current platform. -var ErrUnsupported = errors.New("unsupported") - -// Open a pty and its corresponding tty. -func Open() (pty, tty *os.File, err error) { - return open() -} diff --git a/vendor/github.com/creack/pty/ioctl.go b/vendor/github.com/creack/pty/ioctl.go deleted file mode 100644 index 3cabedd9..00000000 --- a/vendor/github.com/creack/pty/ioctl.go +++ /dev/null @@ -1,19 +0,0 @@ -//go:build !windows && !solaris && !aix -// +build !windows,!solaris,!aix - -package pty - -import "syscall" - -const ( - TIOCGWINSZ = syscall.TIOCGWINSZ - TIOCSWINSZ = syscall.TIOCSWINSZ -) - -func ioctl(fd, cmd, ptr uintptr) error { - _, _, e := syscall.Syscall(syscall.SYS_IOCTL, fd, cmd, ptr) - if e != 0 { - return e - } - return nil -} diff --git a/vendor/github.com/creack/pty/ioctl_bsd.go b/vendor/github.com/creack/pty/ioctl_bsd.go deleted file mode 100644 index db3bf845..00000000 --- a/vendor/github.com/creack/pty/ioctl_bsd.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build darwin || dragonfly || freebsd || netbsd || openbsd -// +build darwin dragonfly freebsd netbsd openbsd - -package pty - -// from -const ( - _IOC_VOID uintptr = 0x20000000 - _IOC_OUT uintptr = 0x40000000 - _IOC_IN uintptr = 0x80000000 - _IOC_IN_OUT uintptr = _IOC_OUT | _IOC_IN - _IOC_DIRMASK = _IOC_VOID | _IOC_OUT | _IOC_IN - - _IOC_PARAM_SHIFT = 13 - _IOC_PARAM_MASK = (1 << _IOC_PARAM_SHIFT) - 1 -) - -func _IOC_PARM_LEN(ioctl uintptr) uintptr { - return (ioctl >> 16) & _IOC_PARAM_MASK -} - -func _IOC(inout uintptr, group byte, ioctl_num uintptr, param_len uintptr) uintptr { - return inout | (param_len&_IOC_PARAM_MASK)<<16 | uintptr(group)<<8 | ioctl_num -} - -func _IO(group byte, ioctl_num uintptr) uintptr { - return _IOC(_IOC_VOID, group, ioctl_num, 0) -} - -func _IOR(group byte, ioctl_num uintptr, param_len uintptr) uintptr { - return _IOC(_IOC_OUT, group, ioctl_num, param_len) -} - -func _IOW(group byte, ioctl_num uintptr, param_len uintptr) uintptr { - return _IOC(_IOC_IN, group, ioctl_num, param_len) -} - -func _IOWR(group byte, ioctl_num uintptr, param_len uintptr) uintptr { - return _IOC(_IOC_IN_OUT, group, ioctl_num, param_len) -} diff --git a/vendor/github.com/creack/pty/ioctl_solaris.go b/vendor/github.com/creack/pty/ioctl_solaris.go deleted file mode 100644 index bff22dad..00000000 --- a/vendor/github.com/creack/pty/ioctl_solaris.go +++ /dev/null @@ -1,48 +0,0 @@ -//go:build solaris -// +build solaris - -package pty - -import ( - "syscall" - "unsafe" -) - -//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" -//go:linkname procioctl libc_ioctl -var procioctl uintptr - -const ( - // see /usr/include/sys/stropts.h - I_PUSH = uintptr((int32('S')<<8 | 002)) - I_STR = uintptr((int32('S')<<8 | 010)) - I_FIND = uintptr((int32('S')<<8 | 013)) - - // see /usr/include/sys/ptms.h - ISPTM = (int32('P') << 8) | 1 - UNLKPT = (int32('P') << 8) | 2 - PTSSTTY = (int32('P') << 8) | 3 - ZONEPT = (int32('P') << 8) | 4 - OWNERPT = (int32('P') << 8) | 5 - - // see /usr/include/sys/termios.h - TIOCSWINSZ = (uint32('T') << 8) | 103 - TIOCGWINSZ = (uint32('T') << 8) | 104 -) - -type strioctl struct { - icCmd int32 - icTimeout int32 - icLen int32 - icDP unsafe.Pointer -} - -// Defined in asm_solaris_amd64.s. -func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) - -func ioctl(fd, cmd, ptr uintptr) error { - if _, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procioctl)), 3, fd, cmd, ptr, 0, 0, 0); errno != 0 { - return errno - } - return nil -} diff --git a/vendor/github.com/creack/pty/ioctl_unsupported.go b/vendor/github.com/creack/pty/ioctl_unsupported.go deleted file mode 100644 index 2449a27e..00000000 --- a/vendor/github.com/creack/pty/ioctl_unsupported.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build aix -// +build aix - -package pty - -const ( - TIOCGWINSZ = 0 - TIOCSWINSZ = 0 -) - -func ioctl(fd, cmd, ptr uintptr) error { - return ErrUnsupported -} diff --git a/vendor/github.com/creack/pty/mktypes.bash b/vendor/github.com/creack/pty/mktypes.bash deleted file mode 100644 index 7f71bda6..00000000 --- a/vendor/github.com/creack/pty/mktypes.bash +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env bash - -GOOSARCH="${GOOS}_${GOARCH}" -case "$GOOSARCH" in -_* | *_ | _) - echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 - exit 1 - ;; -esac - -GODEFS="go tool cgo -godefs" - -$GODEFS types.go |gofmt > ztypes_$GOARCH.go - -case $GOOS in -freebsd|dragonfly|netbsd|openbsd) - $GODEFS types_$GOOS.go |gofmt > ztypes_$GOOSARCH.go - ;; -esac diff --git a/vendor/github.com/creack/pty/pty_darwin.go b/vendor/github.com/creack/pty/pty_darwin.go deleted file mode 100644 index 9bdd71d0..00000000 --- a/vendor/github.com/creack/pty/pty_darwin.go +++ /dev/null @@ -1,68 +0,0 @@ -//go:build darwin -// +build darwin - -package pty - -import ( - "errors" - "os" - "syscall" - "unsafe" -) - -func open() (pty, tty *os.File, err error) { - pFD, err := syscall.Open("/dev/ptmx", syscall.O_RDWR|syscall.O_CLOEXEC, 0) - if err != nil { - return nil, nil, err - } - p := os.NewFile(uintptr(pFD), "/dev/ptmx") - // In case of error after this point, make sure we close the ptmx fd. - defer func() { - if err != nil { - _ = p.Close() // Best effort. - } - }() - - sname, err := ptsname(p) - if err != nil { - return nil, nil, err - } - - if err := grantpt(p); err != nil { - return nil, nil, err - } - - if err := unlockpt(p); err != nil { - return nil, nil, err - } - - t, err := os.OpenFile(sname, os.O_RDWR|syscall.O_NOCTTY, 0) - if err != nil { - return nil, nil, err - } - return p, t, nil -} - -func ptsname(f *os.File) (string, error) { - n := make([]byte, _IOC_PARM_LEN(syscall.TIOCPTYGNAME)) - - err := ioctl(f.Fd(), syscall.TIOCPTYGNAME, uintptr(unsafe.Pointer(&n[0]))) - if err != nil { - return "", err - } - - for i, c := range n { - if c == 0 { - return string(n[:i]), nil - } - } - return "", errors.New("TIOCPTYGNAME string not NUL-terminated") -} - -func grantpt(f *os.File) error { - return ioctl(f.Fd(), syscall.TIOCPTYGRANT, 0) -} - -func unlockpt(f *os.File) error { - return ioctl(f.Fd(), syscall.TIOCPTYUNLK, 0) -} diff --git a/vendor/github.com/creack/pty/pty_dragonfly.go b/vendor/github.com/creack/pty/pty_dragonfly.go deleted file mode 100644 index aa916aad..00000000 --- a/vendor/github.com/creack/pty/pty_dragonfly.go +++ /dev/null @@ -1,83 +0,0 @@ -//go:build dragonfly -// +build dragonfly - -package pty - -import ( - "errors" - "os" - "strings" - "syscall" - "unsafe" -) - -// same code as pty_darwin.go -func open() (pty, tty *os.File, err error) { - p, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0) - if err != nil { - return nil, nil, err - } - // In case of error after this point, make sure we close the ptmx fd. - defer func() { - if err != nil { - _ = p.Close() // Best effort. - } - }() - - sname, err := ptsname(p) - if err != nil { - return nil, nil, err - } - - if err := grantpt(p); err != nil { - return nil, nil, err - } - - if err := unlockpt(p); err != nil { - return nil, nil, err - } - - t, err := os.OpenFile(sname, os.O_RDWR, 0) - if err != nil { - return nil, nil, err - } - return p, t, nil -} - -func grantpt(f *os.File) error { - _, err := isptmaster(f.Fd()) - return err -} - -func unlockpt(f *os.File) error { - _, err := isptmaster(f.Fd()) - return err -} - -func isptmaster(fd uintptr) (bool, error) { - err := ioctl(fd, syscall.TIOCISPTMASTER, 0) - return err == nil, err -} - -var ( - emptyFiodgnameArg fiodgnameArg - ioctl_FIODNAME = _IOW('f', 120, unsafe.Sizeof(emptyFiodgnameArg)) -) - -func ptsname(f *os.File) (string, error) { - name := make([]byte, _C_SPECNAMELEN) - fa := fiodgnameArg{Name: (*byte)(unsafe.Pointer(&name[0])), Len: _C_SPECNAMELEN, Pad_cgo_0: [4]byte{0, 0, 0, 0}} - - err := ioctl(f.Fd(), ioctl_FIODNAME, uintptr(unsafe.Pointer(&fa))) - if err != nil { - return "", err - } - - for i, c := range name { - if c == 0 { - s := "/dev/" + string(name[:i]) - return strings.Replace(s, "ptm", "pts", -1), nil - } - } - return "", errors.New("TIOCPTYGNAME string not NUL-terminated") -} diff --git a/vendor/github.com/creack/pty/pty_freebsd.go b/vendor/github.com/creack/pty/pty_freebsd.go deleted file mode 100644 index bcd3b6f9..00000000 --- a/vendor/github.com/creack/pty/pty_freebsd.go +++ /dev/null @@ -1,81 +0,0 @@ -//go:build freebsd -// +build freebsd - -package pty - -import ( - "errors" - "os" - "syscall" - "unsafe" -) - -func posixOpenpt(oflag int) (fd int, err error) { - r0, _, e1 := syscall.Syscall(syscall.SYS_POSIX_OPENPT, uintptr(oflag), 0, 0) - fd = int(r0) - if e1 != 0 { - err = e1 - } - return fd, err -} - -func open() (pty, tty *os.File, err error) { - fd, err := posixOpenpt(syscall.O_RDWR | syscall.O_CLOEXEC) - if err != nil { - return nil, nil, err - } - p := os.NewFile(uintptr(fd), "/dev/pts") - // In case of error after this point, make sure we close the pts fd. - defer func() { - if err != nil { - _ = p.Close() // Best effort. - } - }() - - sname, err := ptsname(p) - if err != nil { - return nil, nil, err - } - - t, err := os.OpenFile("/dev/"+sname, os.O_RDWR, 0) - if err != nil { - return nil, nil, err - } - return p, t, nil -} - -func isptmaster(fd uintptr) (bool, error) { - err := ioctl(fd, syscall.TIOCPTMASTER, 0) - return err == nil, err -} - -var ( - emptyFiodgnameArg fiodgnameArg - ioctlFIODGNAME = _IOW('f', 120, unsafe.Sizeof(emptyFiodgnameArg)) -) - -func ptsname(f *os.File) (string, error) { - master, err := isptmaster(f.Fd()) - if err != nil { - return "", err - } - if !master { - return "", syscall.EINVAL - } - - const n = _C_SPECNAMELEN + 1 - var ( - buf = make([]byte, n) - arg = fiodgnameArg{Len: n, Buf: (*byte)(unsafe.Pointer(&buf[0]))} - ) - if err := ioctl(f.Fd(), ioctlFIODGNAME, uintptr(unsafe.Pointer(&arg))); err != nil { - return "", err - } - - for i, c := range buf { - if c == 0 { - return string(buf[:i]), nil - } - } - return "", errors.New("FIODGNAME string not NUL-terminated") -} diff --git a/vendor/github.com/creack/pty/pty_linux.go b/vendor/github.com/creack/pty/pty_linux.go deleted file mode 100644 index a3b368f5..00000000 --- a/vendor/github.com/creack/pty/pty_linux.go +++ /dev/null @@ -1,54 +0,0 @@ -//go:build linux -// +build linux - -package pty - -import ( - "os" - "strconv" - "syscall" - "unsafe" -) - -func open() (pty, tty *os.File, err error) { - p, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0) - if err != nil { - return nil, nil, err - } - // In case of error after this point, make sure we close the ptmx fd. - defer func() { - if err != nil { - _ = p.Close() // Best effort. - } - }() - - sname, err := ptsname(p) - if err != nil { - return nil, nil, err - } - - if err := unlockpt(p); err != nil { - return nil, nil, err - } - - t, err := os.OpenFile(sname, os.O_RDWR|syscall.O_NOCTTY, 0) //nolint:gosec // Expected Open from a variable. - if err != nil { - return nil, nil, err - } - return p, t, nil -} - -func ptsname(f *os.File) (string, error) { - var n _C_uint - err := ioctl(f.Fd(), syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n))) //nolint:gosec // Expected unsafe pointer for Syscall call. - if err != nil { - return "", err - } - return "/dev/pts/" + strconv.Itoa(int(n)), nil -} - -func unlockpt(f *os.File) error { - var u _C_int - // use TIOCSPTLCK with a pointer to zero to clear the lock - return ioctl(f.Fd(), syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&u))) //nolint:gosec // Expected unsafe pointer for Syscall call. -} diff --git a/vendor/github.com/creack/pty/pty_netbsd.go b/vendor/github.com/creack/pty/pty_netbsd.go deleted file mode 100644 index 2b20d944..00000000 --- a/vendor/github.com/creack/pty/pty_netbsd.go +++ /dev/null @@ -1,69 +0,0 @@ -//go:build netbsd -// +build netbsd - -package pty - -import ( - "errors" - "os" - "syscall" - "unsafe" -) - -func open() (pty, tty *os.File, err error) { - p, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0) - if err != nil { - return nil, nil, err - } - // In case of error after this point, make sure we close the ptmx fd. - defer func() { - if err != nil { - _ = p.Close() // Best effort. - } - }() - - sname, err := ptsname(p) - if err != nil { - return nil, nil, err - } - - if err := grantpt(p); err != nil { - return nil, nil, err - } - - // In NetBSD unlockpt() does nothing, so it isn't called here. - - t, err := os.OpenFile(sname, os.O_RDWR|syscall.O_NOCTTY, 0) - if err != nil { - return nil, nil, err - } - return p, t, nil -} - -func ptsname(f *os.File) (string, error) { - /* - * from ptsname(3): The ptsname() function is equivalent to: - * struct ptmget pm; - * ioctl(fd, TIOCPTSNAME, &pm) == -1 ? NULL : pm.sn; - */ - var ptm ptmget - if err := ioctl(f.Fd(), uintptr(ioctl_TIOCPTSNAME), uintptr(unsafe.Pointer(&ptm))); err != nil { - return "", err - } - name := make([]byte, len(ptm.Sn)) - for i, c := range ptm.Sn { - name[i] = byte(c) - if c == 0 { - return string(name[:i]), nil - } - } - return "", errors.New("TIOCPTSNAME string not NUL-terminated") -} - -func grantpt(f *os.File) error { - /* - * from grantpt(3): Calling grantpt() is equivalent to: - * ioctl(fd, TIOCGRANTPT, 0); - */ - return ioctl(f.Fd(), uintptr(ioctl_TIOCGRANTPT), 0) -} diff --git a/vendor/github.com/creack/pty/pty_openbsd.go b/vendor/github.com/creack/pty/pty_openbsd.go deleted file mode 100644 index 031367a8..00000000 --- a/vendor/github.com/creack/pty/pty_openbsd.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build openbsd -// +build openbsd - -package pty - -import ( - "os" - "syscall" - "unsafe" -) - -func open() (pty, tty *os.File, err error) { - /* - * from ptm(4): - * The PTMGET command allocates a free pseudo terminal, changes its - * ownership to the caller, revokes the access privileges for all previous - * users, opens the file descriptors for the pty and tty devices and - * returns them to the caller in struct ptmget. - */ - - p, err := os.OpenFile("/dev/ptm", os.O_RDWR|syscall.O_CLOEXEC, 0) - if err != nil { - return nil, nil, err - } - defer p.Close() - - var ptm ptmget - if err := ioctl(p.Fd(), uintptr(ioctl_PTMGET), uintptr(unsafe.Pointer(&ptm))); err != nil { - return nil, nil, err - } - - pty = os.NewFile(uintptr(ptm.Cfd), "/dev/ptm") - tty = os.NewFile(uintptr(ptm.Sfd), "/dev/ptm") - - return pty, tty, nil -} diff --git a/vendor/github.com/creack/pty/pty_solaris.go b/vendor/github.com/creack/pty/pty_solaris.go deleted file mode 100644 index 37f933e6..00000000 --- a/vendor/github.com/creack/pty/pty_solaris.go +++ /dev/null @@ -1,152 +0,0 @@ -//go:build solaris -// +build solaris - -package pty - -/* based on: -http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libc/port/gen/pt.c -*/ - -import ( - "errors" - "os" - "strconv" - "syscall" - "unsafe" -) - -func open() (pty, tty *os.File, err error) { - ptmxfd, err := syscall.Open("/dev/ptmx", syscall.O_RDWR|syscall.O_NOCTTY, 0) - if err != nil { - return nil, nil, err - } - p := os.NewFile(uintptr(ptmxfd), "/dev/ptmx") - // In case of error after this point, make sure we close the ptmx fd. - defer func() { - if err != nil { - _ = p.Close() // Best effort. - } - }() - - sname, err := ptsname(p) - if err != nil { - return nil, nil, err - } - - if err := grantpt(p); err != nil { - return nil, nil, err - } - - if err := unlockpt(p); err != nil { - return nil, nil, err - } - - ptsfd, err := syscall.Open(sname, os.O_RDWR|syscall.O_NOCTTY, 0) - if err != nil { - return nil, nil, err - } - t := os.NewFile(uintptr(ptsfd), sname) - - // In case of error after this point, make sure we close the pts fd. - defer func() { - if err != nil { - _ = t.Close() // Best effort. - } - }() - - // pushing terminal driver STREAMS modules as per pts(7) - for _, mod := range []string{"ptem", "ldterm", "ttcompat"} { - if err := streamsPush(t, mod); err != nil { - return nil, nil, err - } - } - - return p, t, nil -} - -func ptsname(f *os.File) (string, error) { - dev, err := ptsdev(f.Fd()) - if err != nil { - return "", err - } - fn := "/dev/pts/" + strconv.FormatInt(int64(dev), 10) - - if err := syscall.Access(fn, 0); err != nil { - return "", err - } - return fn, nil -} - -func unlockpt(f *os.File) error { - istr := strioctl{ - icCmd: UNLKPT, - icTimeout: 0, - icLen: 0, - icDP: nil, - } - return ioctl(f.Fd(), I_STR, uintptr(unsafe.Pointer(&istr))) -} - -func minor(x uint64) uint64 { return x & 0377 } - -func ptsdev(fd uintptr) (uint64, error) { - istr := strioctl{ - icCmd: ISPTM, - icTimeout: 0, - icLen: 0, - icDP: nil, - } - - if err := ioctl(fd, I_STR, uintptr(unsafe.Pointer(&istr))); err != nil { - return 0, err - } - var status syscall.Stat_t - if err := syscall.Fstat(int(fd), &status); err != nil { - return 0, err - } - return uint64(minor(status.Rdev)), nil -} - -type ptOwn struct { - rUID int32 - rGID int32 -} - -func grantpt(f *os.File) error { - if _, err := ptsdev(f.Fd()); err != nil { - return err - } - pto := ptOwn{ - rUID: int32(os.Getuid()), - // XXX should first attempt to get gid of DEFAULT_TTY_GROUP="tty" - rGID: int32(os.Getgid()), - } - istr := strioctl{ - icCmd: OWNERPT, - icTimeout: 0, - icLen: int32(unsafe.Sizeof(strioctl{})), - icDP: unsafe.Pointer(&pto), - } - if err := ioctl(f.Fd(), I_STR, uintptr(unsafe.Pointer(&istr))); err != nil { - return errors.New("access denied") - } - return nil -} - -// streamsPush pushes STREAMS modules if not already done so. -func streamsPush(f *os.File, mod string) error { - buf := []byte(mod) - - // XXX I_FIND is not returning an error when the module - // is already pushed even though truss reports a return - // value of 1. A bug in the Go Solaris syscall interface? - // XXX without this we are at risk of the issue - // https://www.illumos.org/issues/9042 - // but since we are not using libc or XPG4.2, we should not be - // double-pushing modules - - if err := ioctl(f.Fd(), I_FIND, uintptr(unsafe.Pointer(&buf[0]))); err != nil { - return nil - } - return ioctl(f.Fd(), I_PUSH, uintptr(unsafe.Pointer(&buf[0]))) -} diff --git a/vendor/github.com/creack/pty/pty_unsupported.go b/vendor/github.com/creack/pty/pty_unsupported.go deleted file mode 100644 index c771020f..00000000 --- a/vendor/github.com/creack/pty/pty_unsupported.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build !linux && !darwin && !freebsd && !dragonfly && !netbsd && !openbsd && !solaris -// +build !linux,!darwin,!freebsd,!dragonfly,!netbsd,!openbsd,!solaris - -package pty - -import ( - "os" -) - -func open() (pty, tty *os.File, err error) { - return nil, nil, ErrUnsupported -} diff --git a/vendor/github.com/creack/pty/run.go b/vendor/github.com/creack/pty/run.go deleted file mode 100644 index 47553662..00000000 --- a/vendor/github.com/creack/pty/run.go +++ /dev/null @@ -1,57 +0,0 @@ -package pty - -import ( - "os" - "os/exec" - "syscall" -) - -// Start assigns a pseudo-terminal tty os.File to c.Stdin, c.Stdout, -// and c.Stderr, calls c.Start, and returns the File of the tty's -// corresponding pty. -// -// Starts the process in a new session and sets the controlling terminal. -func Start(cmd *exec.Cmd) (*os.File, error) { - return StartWithSize(cmd, nil) -} - -// StartWithAttrs assigns a pseudo-terminal tty os.File to c.Stdin, c.Stdout, -// and c.Stderr, calls c.Start, and returns the File of the tty's -// corresponding pty. -// -// This will resize the pty to the specified size before starting the command if a size is provided. -// The `attrs` parameter overrides the one set in c.SysProcAttr. -// -// This should generally not be needed. Used in some edge cases where it is needed to create a pty -// without a controlling terminal. -func StartWithAttrs(c *exec.Cmd, sz *Winsize, attrs *syscall.SysProcAttr) (*os.File, error) { - pty, tty, err := Open() - if err != nil { - return nil, err - } - defer func() { _ = tty.Close() }() // Best effort. - - if sz != nil { - if err := Setsize(pty, sz); err != nil { - _ = pty.Close() // Best effort. - return nil, err - } - } - if c.Stdout == nil { - c.Stdout = tty - } - if c.Stderr == nil { - c.Stderr = tty - } - if c.Stdin == nil { - c.Stdin = tty - } - - c.SysProcAttr = attrs - - if err := c.Start(); err != nil { - _ = pty.Close() // Best effort. - return nil, err - } - return pty, err -} diff --git a/vendor/github.com/creack/pty/start.go b/vendor/github.com/creack/pty/start.go deleted file mode 100644 index 9b51635f..00000000 --- a/vendor/github.com/creack/pty/start.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build !windows -// +build !windows - -package pty - -import ( - "os" - "os/exec" - "syscall" -) - -// StartWithSize assigns a pseudo-terminal tty os.File to c.Stdin, c.Stdout, -// and c.Stderr, calls c.Start, and returns the File of the tty's -// corresponding pty. -// -// This will resize the pty to the specified size before starting the command. -// Starts the process in a new session and sets the controlling terminal. -func StartWithSize(cmd *exec.Cmd, ws *Winsize) (*os.File, error) { - if cmd.SysProcAttr == nil { - cmd.SysProcAttr = &syscall.SysProcAttr{} - } - cmd.SysProcAttr.Setsid = true - cmd.SysProcAttr.Setctty = true - return StartWithAttrs(cmd, ws, cmd.SysProcAttr) -} diff --git a/vendor/github.com/creack/pty/start_windows.go b/vendor/github.com/creack/pty/start_windows.go deleted file mode 100644 index 7e9530ba..00000000 --- a/vendor/github.com/creack/pty/start_windows.go +++ /dev/null @@ -1,19 +0,0 @@ -//go:build windows -// +build windows - -package pty - -import ( - "os" - "os/exec" -) - -// StartWithSize assigns a pseudo-terminal tty os.File to c.Stdin, c.Stdout, -// and c.Stderr, calls c.Start, and returns the File of the tty's -// corresponding pty. -// -// This will resize the pty to the specified size before starting the command. -// Starts the process in a new session and sets the controlling terminal. -func StartWithSize(cmd *exec.Cmd, ws *Winsize) (*os.File, error) { - return nil, ErrUnsupported -} diff --git a/vendor/github.com/creack/pty/test_crosscompile.sh b/vendor/github.com/creack/pty/test_crosscompile.sh deleted file mode 100644 index 47e8b106..00000000 --- a/vendor/github.com/creack/pty/test_crosscompile.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env sh - -# Test script checking that all expected os/arch compile properly. -# Does not actually test the logic, just the compilation so we make sure we don't break code depending on the lib. - -echo2() { - echo $@ >&2 -} - -trap end 0 -end() { - [ "$?" = 0 ] && echo2 "Pass." || (echo2 "Fail."; exit 1) -} - -cross() { - os=$1 - shift - echo2 "Build for $os." - for arch in $@; do - echo2 " - $os/$arch" - GOOS=$os GOARCH=$arch go build - done - echo2 -} - -set -e - -cross linux amd64 386 arm arm64 ppc64 ppc64le s390x mips mipsle mips64 mips64le -cross darwin amd64 arm64 -cross freebsd amd64 386 arm arm64 -cross netbsd amd64 386 arm arm64 -cross openbsd amd64 386 arm arm64 -cross dragonfly amd64 -cross solaris amd64 - -# Not expected to work but should still compile. -cross windows amd64 386 arm - -# TODO: Fix compilation error on openbsd/arm. -# TODO: Merge the solaris PR. - -# Some os/arch require a different compiler. Run in docker. -if ! hash docker; then - # If docker is not present, stop here. - return -fi - -echo2 "Build for linux." -echo2 " - linux/riscv" -docker build -t creack-pty-test -f Dockerfile.riscv . - -# Golang dropped support for darwin 32bits since go1.15. Make sure the lib still compile with go1.14 on those archs. -echo2 "Build for darwin (32bits)." -echo2 " - darwin/386" -docker build -t creack-pty-test -f Dockerfile.golang --build-arg=GOVERSION=1.14 --build-arg=GOOS=darwin --build-arg=GOARCH=386 . -echo2 " - darwin/arm" -docker build -t creack-pty-test -f Dockerfile.golang --build-arg=GOVERSION=1.14 --build-arg=GOOS=darwin --build-arg=GOARCH=arm . - -# Run a single test for an old go version. Would be best with go1.0, but not available on Dockerhub. -# Using 1.6 as it is the base version for the RISCV compiler. -# Would also be better to run all the tests, not just one, need to refactor this file to allow for specifc archs per version. -echo2 "Build for linux - go1.6." -echo2 " - linux/amd64" -docker build -t creack-pty-test -f Dockerfile.golang --build-arg=GOVERSION=1.6 --build-arg=GOOS=linux --build-arg=GOARCH=amd64 . diff --git a/vendor/github.com/creack/pty/winsize.go b/vendor/github.com/creack/pty/winsize.go deleted file mode 100644 index 57323f40..00000000 --- a/vendor/github.com/creack/pty/winsize.go +++ /dev/null @@ -1,27 +0,0 @@ -package pty - -import "os" - -// InheritSize applies the terminal size of pty to tty. This should be run -// in a signal handler for syscall.SIGWINCH to automatically resize the tty when -// the pty receives a window size change notification. -func InheritSize(pty, tty *os.File) error { - size, err := GetsizeFull(pty) - if err != nil { - return err - } - if err := Setsize(tty, size); err != nil { - return err - } - return nil -} - -// Getsize returns the number of rows (lines) and cols (positions -// in each line) in terminal t. -func Getsize(t *os.File) (rows, cols int, err error) { - ws, err := GetsizeFull(t) - if err != nil { - return 0, 0, err - } - return int(ws.Rows), int(ws.Cols), nil -} diff --git a/vendor/github.com/creack/pty/winsize_unix.go b/vendor/github.com/creack/pty/winsize_unix.go deleted file mode 100644 index 5d99c3dd..00000000 --- a/vendor/github.com/creack/pty/winsize_unix.go +++ /dev/null @@ -1,35 +0,0 @@ -//go:build !windows -// +build !windows - -package pty - -import ( - "os" - "syscall" - "unsafe" -) - -// Winsize describes the terminal size. -type Winsize struct { - Rows uint16 // ws_row: Number of rows (in cells) - Cols uint16 // ws_col: Number of columns (in cells) - X uint16 // ws_xpixel: Width in pixels - Y uint16 // ws_ypixel: Height in pixels -} - -// Setsize resizes t to s. -func Setsize(t *os.File, ws *Winsize) error { - //nolint:gosec // Expected unsafe pointer for Syscall call. - return ioctl(t.Fd(), syscall.TIOCSWINSZ, uintptr(unsafe.Pointer(ws))) -} - -// GetsizeFull returns the full terminal size description. -func GetsizeFull(t *os.File) (size *Winsize, err error) { - var ws Winsize - - //nolint:gosec // Expected unsafe pointer for Syscall call. - if err := ioctl(t.Fd(), syscall.TIOCGWINSZ, uintptr(unsafe.Pointer(&ws))); err != nil { - return nil, err - } - return &ws, nil -} diff --git a/vendor/github.com/creack/pty/winsize_unsupported.go b/vendor/github.com/creack/pty/winsize_unsupported.go deleted file mode 100644 index 0d210993..00000000 --- a/vendor/github.com/creack/pty/winsize_unsupported.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build windows -// +build windows - -package pty - -import ( - "os" -) - -// Winsize is a dummy struct to enable compilation on unsupported platforms. -type Winsize struct { - Rows, Cols, X, Y uint16 -} - -// Setsize resizes t to s. -func Setsize(*os.File, *Winsize) error { - return ErrUnsupported -} - -// GetsizeFull returns the full terminal size description. -func GetsizeFull(*os.File) (*Winsize, error) { - return nil, ErrUnsupported -} diff --git a/vendor/github.com/creack/pty/ztypes_386.go b/vendor/github.com/creack/pty/ztypes_386.go deleted file mode 100644 index d126f4aa..00000000 --- a/vendor/github.com/creack/pty/ztypes_386.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build 386 -// +build 386 - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/creack/pty/ztypes_amd64.go b/vendor/github.com/creack/pty/ztypes_amd64.go deleted file mode 100644 index 6c4a7677..00000000 --- a/vendor/github.com/creack/pty/ztypes_amd64.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build amd64 -// +build amd64 - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/creack/pty/ztypes_arm.go b/vendor/github.com/creack/pty/ztypes_arm.go deleted file mode 100644 index de6fe160..00000000 --- a/vendor/github.com/creack/pty/ztypes_arm.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build arm -// +build arm - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/creack/pty/ztypes_arm64.go b/vendor/github.com/creack/pty/ztypes_arm64.go deleted file mode 100644 index c4f315ca..00000000 --- a/vendor/github.com/creack/pty/ztypes_arm64.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build arm64 -// +build arm64 - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/creack/pty/ztypes_dragonfly_amd64.go b/vendor/github.com/creack/pty/ztypes_dragonfly_amd64.go deleted file mode 100644 index 183c4214..00000000 --- a/vendor/github.com/creack/pty/ztypes_dragonfly_amd64.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build amd64 && dragonfly -// +build amd64,dragonfly - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_dragonfly.go - -package pty - -const ( - _C_SPECNAMELEN = 0x3f -) - -type fiodgnameArg struct { - Name *byte - Len uint32 - Pad_cgo_0 [4]byte -} diff --git a/vendor/github.com/creack/pty/ztypes_freebsd_386.go b/vendor/github.com/creack/pty/ztypes_freebsd_386.go deleted file mode 100644 index d80dbf71..00000000 --- a/vendor/github.com/creack/pty/ztypes_freebsd_386.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build 386 && freebsd -// +build 386,freebsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_freebsd.go - -package pty - -const ( - _C_SPECNAMELEN = 0x3f -) - -type fiodgnameArg struct { - Len int32 - Buf *byte -} diff --git a/vendor/github.com/creack/pty/ztypes_freebsd_amd64.go b/vendor/github.com/creack/pty/ztypes_freebsd_amd64.go deleted file mode 100644 index bfab4e45..00000000 --- a/vendor/github.com/creack/pty/ztypes_freebsd_amd64.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build amd64 && freebsd -// +build amd64,freebsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_freebsd.go - -package pty - -const ( - _C_SPECNAMELEN = 0x3f -) - -type fiodgnameArg struct { - Len int32 - Pad_cgo_0 [4]byte - Buf *byte -} diff --git a/vendor/github.com/creack/pty/ztypes_freebsd_arm.go b/vendor/github.com/creack/pty/ztypes_freebsd_arm.go deleted file mode 100644 index 3a8aeae3..00000000 --- a/vendor/github.com/creack/pty/ztypes_freebsd_arm.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build arm && freebsd -// +build arm,freebsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_freebsd.go - -package pty - -const ( - _C_SPECNAMELEN = 0x3f -) - -type fiodgnameArg struct { - Len int32 - Buf *byte -} diff --git a/vendor/github.com/creack/pty/ztypes_freebsd_arm64.go b/vendor/github.com/creack/pty/ztypes_freebsd_arm64.go deleted file mode 100644 index a8392491..00000000 --- a/vendor/github.com/creack/pty/ztypes_freebsd_arm64.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build arm64 && freebsd -// +build arm64,freebsd - -// Code generated by cmd/cgo -godefs; DO NOT EDIT. -// cgo -godefs types_freebsd.go - -package pty - -const ( - _C_SPECNAMELEN = 0xff -) - -type fiodgnameArg struct { - Len int32 - Buf *byte -} diff --git a/vendor/github.com/creack/pty/ztypes_freebsd_ppc64.go b/vendor/github.com/creack/pty/ztypes_freebsd_ppc64.go deleted file mode 100644 index 5fa102fc..00000000 --- a/vendor/github.com/creack/pty/ztypes_freebsd_ppc64.go +++ /dev/null @@ -1,14 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_freebsd.go - -package pty - -const ( - _C_SPECNAMELEN = 0x3f -) - -type fiodgnameArg struct { - Len int32 - Pad_cgo_0 [4]byte - Buf *byte -} diff --git a/vendor/github.com/creack/pty/ztypes_loong64.go b/vendor/github.com/creack/pty/ztypes_loong64.go deleted file mode 100644 index 3beb5c17..00000000 --- a/vendor/github.com/creack/pty/ztypes_loong64.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build loong64 -// +build loong64 - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/creack/pty/ztypes_mipsx.go b/vendor/github.com/creack/pty/ztypes_mipsx.go deleted file mode 100644 index 28127797..00000000 --- a/vendor/github.com/creack/pty/ztypes_mipsx.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build (mips || mipsle || mips64 || mips64le) && linux -// +build mips mipsle mips64 mips64le -// +build linux - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/creack/pty/ztypes_netbsd_32bit_int.go b/vendor/github.com/creack/pty/ztypes_netbsd_32bit_int.go deleted file mode 100644 index 2ab7c455..00000000 --- a/vendor/github.com/creack/pty/ztypes_netbsd_32bit_int.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build (386 || amd64 || arm || arm64) && netbsd -// +build 386 amd64 arm arm64 -// +build netbsd - -package pty - -type ptmget struct { - Cfd int32 - Sfd int32 - Cn [1024]int8 - Sn [1024]int8 -} - -var ( - ioctl_TIOCPTSNAME = 0x48087448 - ioctl_TIOCGRANTPT = 0x20007447 -) diff --git a/vendor/github.com/creack/pty/ztypes_openbsd_32bit_int.go b/vendor/github.com/creack/pty/ztypes_openbsd_32bit_int.go deleted file mode 100644 index 1eb09481..00000000 --- a/vendor/github.com/creack/pty/ztypes_openbsd_32bit_int.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build (386 || amd64 || arm || arm64 || mips64) && openbsd -// +build 386 amd64 arm arm64 mips64 -// +build openbsd - -package pty - -type ptmget struct { - Cfd int32 - Sfd int32 - Cn [16]int8 - Sn [16]int8 -} - -var ioctl_PTMGET = 0x40287401 diff --git a/vendor/github.com/creack/pty/ztypes_ppc64.go b/vendor/github.com/creack/pty/ztypes_ppc64.go deleted file mode 100644 index bbb3da83..00000000 --- a/vendor/github.com/creack/pty/ztypes_ppc64.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build ppc64 -// +build ppc64 - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/creack/pty/ztypes_ppc64le.go b/vendor/github.com/creack/pty/ztypes_ppc64le.go deleted file mode 100644 index 8a4fac3e..00000000 --- a/vendor/github.com/creack/pty/ztypes_ppc64le.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build ppc64le -// +build ppc64le - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/creack/pty/ztypes_riscvx.go b/vendor/github.com/creack/pty/ztypes_riscvx.go deleted file mode 100644 index dc5da905..00000000 --- a/vendor/github.com/creack/pty/ztypes_riscvx.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build riscv || riscv64 -// +build riscv riscv64 - -// Code generated by cmd/cgo -godefs; DO NOT EDIT. -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/creack/pty/ztypes_s390x.go b/vendor/github.com/creack/pty/ztypes_s390x.go deleted file mode 100644 index 3433be7c..00000000 --- a/vendor/github.com/creack/pty/ztypes_s390x.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build s390x -// +build s390x - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types.go - -package pty - -type ( - _C_int int32 - _C_uint uint32 -) diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore b/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore deleted file mode 100644 index 47bb0de4..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore +++ /dev/null @@ -1,36 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -*.msg -*.lok - -samples/trivial -samples/trivial2 -samples/sample -samples/reconnect -samples/ssl -samples/custom_store -samples/simple -samples/stdinpub -samples/stdoutsub -samples/routing \ No newline at end of file diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md b/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md deleted file mode 100644 index 9791dc60..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md +++ /dev/null @@ -1,56 +0,0 @@ -Contributing to Paho -==================== - -Thanks for your interest in this project. - -Project description: --------------------- - -The Paho project has been created to provide scalable open-source implementations of open and standard messaging protocols aimed at new, existing, and emerging applications for Machine-to-Machine (M2M) and Internet of Things (IoT). -Paho reflects the inherent physical and cost constraints of device connectivity. Its objectives include effective levels of decoupling between devices and applications, designed to keep markets open and encourage the rapid growth of scalable Web and Enterprise middleware and applications. Paho is being kicked off with MQTT publish/subscribe client implementations for use on embedded platforms, along with corresponding server support as determined by the community. - -- https://projects.eclipse.org/projects/technology.paho - -Developer resources: --------------------- - -Information regarding source code management, builds, coding standards, and more. - -- https://projects.eclipse.org/projects/technology.paho/developer - -Contributor License Agreement: ------------------------------- - -Before your contribution can be accepted by the project, you need to create and electronically sign the Eclipse Foundation Contributor License Agreement (CLA). - -- http://www.eclipse.org/legal/CLA.php - -Contributing Code: ------------------- - -The Go client is developed in Github, see their documentation on the process of forking and pull requests; https://help.github.com/categories/collaborating-on-projects-using-pull-requests/ - -Git commit messages should follow the style described here; - -http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html - -Contact: --------- - -Contact the project developers via the project's "dev" list. - -- https://dev.eclipse.org/mailman/listinfo/paho-dev - -Search for bugs: ----------------- - -This project uses Github issues to track ongoing development and issues. - -- https://github.com/eclipse/paho.mqtt.golang/issues - -Create a new bug: ------------------ - -Be sure to search for existing bugs before you create another one. Remember that contributions are always welcome! - -- https://github.com/eclipse/paho.mqtt.golang/issues diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE b/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE deleted file mode 100644 index f55c3953..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE +++ /dev/null @@ -1,294 +0,0 @@ -Eclipse Public License - v 2.0 (EPL-2.0) - -This program and the accompanying materials -are made available under the terms of the Eclipse Public License v2.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - https://www.eclipse.org/legal/epl-2.0/ -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -For an explanation of what dual-licensing means to you, see: -https://www.eclipse.org/legal/eplfaq.php#DUALLIC - -**** -The epl-2.0 is copied below in order to pass the pkg.go.dev license check (https://pkg.go.dev/license-policy). -**** -Eclipse Public License - v 2.0 - - THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE - PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION - OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - - a) in the case of the initial Contributor, the initial content - Distributed under this Agreement, and - - b) in the case of each subsequent Contributor: - i) changes to the Program, and - ii) additions to the Program; - where such changes and/or additions to the Program originate from - and are Distributed by that particular Contributor. A Contribution - "originates" from a Contributor if it was added to the Program by - such Contributor itself or anyone acting on such Contributor's behalf. - Contributions do not include changes or additions to the Program that - are not Modified Works. - -"Contributor" means any person or entity that Distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which -are necessarily infringed by the use or sale of its Contribution alone -or when combined with the Program. - -"Program" means the Contributions Distributed in accordance with this -Agreement. - -"Recipient" means anyone who receives the Program under this Agreement -or any Secondary License (as applicable), including Contributors. - -"Derivative Works" shall mean any work, whether in Source Code or other -form, that is based on (or derived from) the Program and for which the -editorial revisions, annotations, elaborations, or other modifications -represent, as a whole, an original work of authorship. - -"Modified Works" shall mean any work in Source Code or other form that -results from an addition to, deletion from, or modification of the -contents of the Program, including, for purposes of clarity any new file -in Source Code form that contains any contents of the Program. Modified -Works shall not include works that contain only declarations, -interfaces, types, classes, structures, or files of the Program solely -in each case in order to link to, bind by name, or subclass the Program -or Modified Works thereof. - -"Distribute" means the acts of a) distributing or b) making available -in any manner that enables the transfer of a copy. - -"Source Code" means the form of a Program preferred for making -modifications, including but not limited to software source code, -documentation source, and configuration files. - -"Secondary License" means either the GNU General Public License, -Version 2.0, or any later versions of that license, including any -exceptions or additional permissions as identified by the initial -Contributor. - -2. GRANT OF RIGHTS - - a) Subject to the terms of this Agreement, each Contributor hereby - grants Recipient a non-exclusive, worldwide, royalty-free copyright - license to reproduce, prepare Derivative Works of, publicly display, - publicly perform, Distribute and sublicense the Contribution of such - Contributor, if any, and such Derivative Works. - - b) Subject to the terms of this Agreement, each Contributor hereby - grants Recipient a non-exclusive, worldwide, royalty-free patent - license under Licensed Patents to make, use, sell, offer to sell, - import and otherwise transfer the Contribution of such Contributor, - if any, in Source Code or other form. This patent license shall - apply to the combination of the Contribution and the Program if, at - the time the Contribution is added by the Contributor, such addition - of the Contribution causes such combination to be covered by the - Licensed Patents. The patent license shall not apply to any other - combinations which include the Contribution. No hardware per se is - licensed hereunder. - - c) Recipient understands that although each Contributor grants the - licenses to its Contributions set forth herein, no assurances are - provided by any Contributor that the Program does not infringe the - patent or other intellectual property rights of any other entity. - Each Contributor disclaims any liability to Recipient for claims - brought by any other entity based on infringement of intellectual - property rights or otherwise. As a condition to exercising the - rights and licenses granted hereunder, each Recipient hereby - assumes sole responsibility to secure any other intellectual - property rights needed, if any. For example, if a third party - patent license is required to allow Recipient to Distribute the - Program, it is Recipient's responsibility to acquire that license - before distributing the Program. - - d) Each Contributor represents that to its knowledge it has - sufficient copyright rights in its Contribution, if any, to grant - the copyright license set forth in this Agreement. - - e) Notwithstanding the terms of any Secondary License, no - Contributor makes additional grants to any Recipient (other than - those set forth in this Agreement) as a result of such Recipient's - receipt of the Program under the terms of a Secondary License - (if permitted under the terms of Section 3). - -3. REQUIREMENTS - -3.1 If a Contributor Distributes the Program in any form, then: - - a) the Program must also be made available as Source Code, in - accordance with section 3.2, and the Contributor must accompany - the Program with a statement that the Source Code for the Program - is available under this Agreement, and informs Recipients how to - obtain it in a reasonable manner on or through a medium customarily - used for software exchange; and - - b) the Contributor may Distribute the Program under a license - different than this Agreement, provided that such license: - i) effectively disclaims on behalf of all other Contributors all - warranties and conditions, express and implied, including - warranties or conditions of title and non-infringement, and - implied warranties or conditions of merchantability and fitness - for a particular purpose; - - ii) effectively excludes on behalf of all other Contributors all - liability for damages, including direct, indirect, special, - incidental and consequential damages, such as lost profits; - - iii) does not attempt to limit or alter the recipients' rights - in the Source Code under section 3.2; and - - iv) requires any subsequent distribution of the Program by any - party to be under a license that satisfies the requirements - of this section 3. - -3.2 When the Program is Distributed as Source Code: - - a) it must be made available under this Agreement, or if the - Program (i) is combined with other material in a separate file or - files made available under a Secondary License, and (ii) the initial - Contributor attached to the Source Code the notice described in - Exhibit A of this Agreement, then the Program may be made available - under the terms of such Secondary Licenses, and - - b) a copy of this Agreement must be included with each copy of - the Program. - -3.3 Contributors may not remove or alter any copyright, patent, -trademark, attribution notices, disclaimers of warranty, or limitations -of liability ("notices") contained within the Program from any copy of -the Program which they Distribute, provided that Contributors may add -their own appropriate notices. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities -with respect to end users, business partners and the like. While this -license is intended to facilitate the commercial use of the Program, -the Contributor who includes the Program in a commercial product -offering should do so in a manner which does not create potential -liability for other Contributors. Therefore, if a Contributor includes -the Program in a commercial product offering, such Contributor -("Commercial Contributor") hereby agrees to defend and indemnify every -other Contributor ("Indemnified Contributor") against any losses, -damages and costs (collectively "Losses") arising from claims, lawsuits -and other legal actions brought by a third party against the Indemnified -Contributor to the extent caused by the acts or omissions of such -Commercial Contributor in connection with its distribution of the Program -in a commercial product offering. The obligations in this section do not -apply to any claims or Losses relating to any actual or alleged -intellectual property infringement. In order to qualify, an Indemnified -Contributor must: a) promptly notify the Commercial Contributor in -writing of such claim, and b) allow the Commercial Contributor to control, -and cooperate with the Commercial Contributor in, the defense and any -related settlement negotiations. The Indemnified Contributor may -participate in any such claim at its own expense. - -For example, a Contributor might include the Program in a commercial -product offering, Product X. That Contributor is then a Commercial -Contributor. If that Commercial Contributor then makes performance -claims, or offers warranties related to Product X, those performance -claims and warranties are such Commercial Contributor's responsibility -alone. Under this section, the Commercial Contributor would have to -defend claims against the other Contributors related to those performance -claims and warranties, and if a court requires any other Contributor to -pay any damages as a result, the Commercial Contributor must pay -those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT -PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" -BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR -IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF -TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR -PURPOSE. Each Recipient is solely responsible for determining the -appropriateness of using and distributing the Program and assumes all -risks associated with its exercise of rights under this Agreement, -including but not limited to the risks and costs of program errors, -compliance with applicable laws, damage to or loss of data, programs -or equipment, and unavailability or interruption of operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT -PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS -SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST -PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE -EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of -the remainder of the terms of this Agreement, and without further -action by the parties hereto, such provision shall be reformed to the -minimum extent necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity -(including a cross-claim or counterclaim in a lawsuit) alleging that the -Program itself (excluding combinations of the Program with other software -or hardware) infringes such Recipient's patent(s), then such Recipient's -rights granted under Section 2(b) shall terminate as of the date such -litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it -fails to comply with any of the material terms or conditions of this -Agreement and does not cure such failure in a reasonable period of -time after becoming aware of such noncompliance. If all Recipient's -rights under this Agreement terminate, Recipient agrees to cease use -and distribution of the Program as soon as reasonably practicable. -However, Recipient's obligations under this Agreement and any licenses -granted by Recipient relating to the Program shall continue and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, -but in order to avoid inconsistency the Agreement is copyrighted and -may only be modified in the following manner. The Agreement Steward -reserves the right to publish new versions (including revisions) of -this Agreement from time to time. No one other than the Agreement -Steward has the right to modify this Agreement. The Eclipse Foundation -is the initial Agreement Steward. The Eclipse Foundation may assign the -responsibility to serve as the Agreement Steward to a suitable separate -entity. Each new version of the Agreement will be given a distinguishing -version number. The Program (including Contributions) may always be -Distributed subject to the version of the Agreement under which it was -received. In addition, after a new version of the Agreement is published, -Contributor may elect to Distribute the Program (including its -Contributions) under the new version. - -Except as expressly stated in Sections 2(a) and 2(b) above, Recipient -receives no rights or licenses to the intellectual property of any -Contributor under this Agreement, whether expressly, by implication, -estoppel or otherwise. All rights in the Program not expressly granted -under this Agreement are reserved. Nothing in this Agreement is intended -to be enforceable by any entity that is not a Contributor or Recipient. -No third-party beneficiary rights are created under this Agreement. - -Exhibit A - Form of Secondary Licenses Notice - -"This Source Code may also be made available under the following -Secondary Licenses when the conditions for such availability set forth -in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), -version(s), and exceptions or additional permissions here}." - - Simply including a copy of this Agreement, including this Exhibit A - is not sufficient to license the Source Code under Secondary Licenses. - - If it is not possible or desirable to put the notice in a particular - file, then You may include the notice in a location (such as a LICENSE - file in a relevant directory) where a recipient would be likely to - look for such a notice. - - You may add additional accurate notices of copyright ownership. diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/NOTICE.md b/vendor/github.com/eclipse/paho.mqtt.golang/NOTICE.md deleted file mode 100644 index 10c4a1cd..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/NOTICE.md +++ /dev/null @@ -1,77 +0,0 @@ -# Notices for paho.mqtt.golang - -This content is produced and maintained by the Eclipse Paho project. - - * Project home: https://www.eclipse.org/paho/ - -Note that a [separate mqtt v5 client](https://github.com/eclipse/paho.golang) also exists (this is a full rewrite -and deliberately incompatible with this library). - -## Trademarks - -Eclipse Mosquitto trademarks of the Eclipse Foundation. Eclipse, and the -Eclipse Logo are registered trademarks of the Eclipse Foundation. - -Paho is a trademark of the Eclipse Foundation. Eclipse, and the Eclipse Logo are -registered trademarks of the Eclipse Foundation. - -## Copyright - -All content is the property of the respective authors or their employers. -For more information regarding authorship of content, please consult the -listed source code repository logs. - -## Declared Project Licenses - -This program and the accompanying materials are made available under the terms of the -Eclipse Public License v2.0 and Eclipse Distribution License v1.0 which accompany this -distribution. - -The Eclipse Public License is available at -https://www.eclipse.org/legal/epl-2.0/ -and the Eclipse Distribution License is available at -http://www.eclipse.org/org/documents/edl-v10.php. - -For an explanation of what dual-licensing means to you, see: -https://www.eclipse.org/legal/eplfaq.php#DUALLIC - -SPDX-License-Identifier: EPL-2.0 or BSD-3-Clause - -## Source Code - -The project maintains the following source code repositories: - - * https://github.com/eclipse/paho.mqtt.golang - -## Third-party Content - -This project makes use of the follow third party projects. - -Go Programming Language and Standard Library - -* License: BSD-style license (https://golang.org/LICENSE) -* Project: https://golang.org/ - -Go Networking - -* License: BSD 3-Clause style license and patent grant. -* Project: https://cs.opensource.google/go/x/net - -Go Sync - -* License: BSD 3-Clause style license and patent grant. -* Project: https://cs.opensource.google/go/x/sync/ - -Gorilla Websockets v1.4.2 - -* License: BSD 2-Clause "Simplified" License -* Project: https://github.com/gorilla/websocket - -## Cryptography - -Content may contain encryption software. The country in which you are currently -may have restrictions on the import, possession, and use, and/or re-export to -another country, of encryption software. BEFORE using any encryption software, -please check the country's laws, regulations and policies concerning the import, -possession, or use, and re-export of encryption software, to see if this is -permitted. \ No newline at end of file diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/README.md b/vendor/github.com/eclipse/paho.mqtt.golang/README.md deleted file mode 100644 index 21ed96f3..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/README.md +++ /dev/null @@ -1,198 +0,0 @@ - -[![PkgGoDev](https://pkg.go.dev/badge/github.com/eclipse/paho.mqtt.golang)](https://pkg.go.dev/github.com/eclipse/paho.mqtt.golang) -[![Go Report Card](https://goreportcard.com/badge/github.com/eclipse/paho.mqtt.golang)](https://goreportcard.com/report/github.com/eclipse/paho.mqtt.golang) - -Eclipse Paho MQTT Go client -=========================== - - -This repository contains the source code for the [Eclipse Paho](https://eclipse.org/paho) MQTT 3.1/3.11 Go client library. - -This code builds a library which enable applications to connect to an [MQTT](https://mqtt.org) broker to publish -messages, and to subscribe to topics and receive published messages. - -This library supports a fully asynchronous mode of operation. - -A client supporting MQTT V5 is [also available](https://github.com/eclipse/paho.golang). - -Installation and Build ----------------------- - -The process depends upon whether you are using [modules](https://golang.org/ref/mod) (recommended) or `GOPATH`. - -#### Modules - -If you are using [modules](https://blog.golang.org/using-go-modules) then `import "github.com/eclipse/paho.mqtt.golang"` -and start using it. The necessary packages will be download automatically when you run `go build`. - -Note that the latest release will be downloaded and changes may have been made since the release. If you have -encountered an issue, or wish to try the latest code for another reason, then run -`go get github.com/eclipse/paho.mqtt.golang@master` to get the latest commit. - -#### GOPATH - -Installation is as easy as: - -``` -go get github.com/eclipse/paho.mqtt.golang -``` - -The client depends on Google's [proxy](https://godoc.org/golang.org/x/net/proxy) package and the -[websockets](https://godoc.org/github.com/gorilla/websocket) package, also easily installed with the commands: - -``` -go get github.com/gorilla/websocket -go get golang.org/x/net/proxy -``` - - -Usage and API -------------- - -Detailed API documentation is available by using to godoc tool, or can be browsed online -using the [pkg.go.dev](https://pkg.go.dev/github.com/eclipse/paho.mqtt.golang) service. - -Samples are available in the `cmd` directory for reference. - -Note: - -The library also supports using MQTT over websockets by using the `ws://` (unsecure) or `wss://` (secure) prefix in the -URI. If the client is running behind a corporate http/https proxy then the following environment variables `HTTP_PROXY`, -`HTTPS_PROXY` and `NO_PROXY` are taken into account when establishing the connection. - -Troubleshooting ---------------- - -If you are new to MQTT and your application is not working as expected reviewing the -[MQTT specification](https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html), which this library implements, -is a good first step. [MQTT.org](https://mqtt.org) has some [good resources](https://mqtt.org/getting-started/) that answer many -common questions. - -### Error Handling - -The asynchronous nature of this library makes it easy to forget to check for errors. Consider using a go routine to -log these: - -```go -t := client.Publish("topic", qos, retained, msg) -go func() { - _ = t.Wait() // Can also use '<-t.Done()' in releases > 1.2.0 - if t.Error() != nil { - log.Error(t.Error()) // Use your preferred logging technique (or just fmt.Printf) - } -}() -``` - -### Logging - -If you are encountering issues then enabling logging, both within this library and on your broker, is a good way to -begin troubleshooting. This library can produce various levels of log by assigning the logging endpoints, ERROR, -CRITICAL, WARN and DEBUG. For example: - -```go -func main() { - mqtt.ERROR = log.New(os.Stdout, "[ERROR] ", 0) - mqtt.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0) - mqtt.WARN = log.New(os.Stdout, "[WARN] ", 0) - mqtt.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0) - - // Connect, Subscribe, Publish etc.. -} -``` - -### Common Problems - -* Seemingly random disconnections may be caused by another client connecting to the broker with the same client -identifier; this is as per the [spec](https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc384800405). -* Unless ordered delivery of messages is essential (and you have configured your broker to support this e.g. - `max_inflight_messages=1` in mosquitto) then set `ClientOptions.SetOrderMatters(false)`. Doing so will avoid the - below issue (deadlocks due to blocking message handlers). -* A `MessageHandler` (called when a new message is received) must not block (unless - `ClientOptions.SetOrderMatters(false)` set). If you wish to perform a long-running task, or publish a message, then - please use a go routine (blocking in the handler is a common cause of unexpected `pingresp -not received, disconnecting` errors). -* When QOS1+ subscriptions have been created previously and you connect with `CleanSession` set to false it is possible -that the broker will deliver retained messages before `Subscribe` can be called. To process these messages either -configure a handler with `AddRoute` or set a `DefaultPublishHandler`. If there is no handler (or `DefaultPublishHandler`) -then inbound messages will not be acknowledged. Adding a handler (even if it's `opts.SetDefaultPublishHandler(func(mqtt.Client, mqtt.Message) {})`) -is highly recommended to avoid inadvertently hitting inflight message limits. -* Loss of network connectivity may not be detected immediately. If this is an issue then consider setting -`ClientOptions.KeepAlive` (sends regular messages to check the link is active). -* Reusing a `Client` is not completely safe. After calling `Disconnect` please create a new Client (`NewClient()`) rather -than attempting to reuse the existing one (note that features such as `SetAutoReconnect` mean this is rarely necessary). -* Brokers offer many configuration options; some settings may lead to unexpected results. -* Publish tokens will complete if the connection is lost and re-established using the default -options.SetAutoReconnect(true) functionality (token.Error() will return nil). Attempts will be made to re-deliver the -message but there is currently no easy way know when such messages are delivered. - -If using Mosquitto then there are a range of fairly common issues: -* `listener` - By default [Mosquitto v2+](https://mosquitto.org/documentation/migrating-to-2-0/) listens on loopback -interfaces only (meaning it will only accept connections made from the computer its running on). -* `max_inflight_messages` - Unless this is set to 1 mosquitto does not guarantee ordered delivery of messages. -* `max_queued_messages` / `max_queued_bytes` - These impose limits on the number/size of queued messages. The defaults -may lead to messages being silently dropped. -* `persistence` - Defaults to false (messages will not survive a broker restart) -* `max_keepalive` - defaults to 65535 and, from version 2.0.12, `SetKeepAlive(0)` will result in a rejected connection -by default. - -Reporting bugs --------------- - -Please report bugs by raising issues for this project in github https://github.com/eclipse/paho.mqtt.golang/issues - -A limited number of contributors monitor the issues section so if you have a general question please see the -resources in the [more information](#more-information) section for help. - -We welcome bug reports, but it is important they are actionable. A significant percentage of issues reported are not -resolved due to a lack of information. If we cannot replicate the problem then it is unlikely we will be able to fix it. -The information required will vary from issue to issue but almost all bug reports would be expected to include: - -* Which version of the package you are using (tag or commit - this should be in your `go.mod` file) -* A full, clear, description of the problem (detail what you are expecting vs what actually happens). -* Configuration information (code showing how you connect, please include all references to `ClientOption`) -* Broker details (name and version). - -If at all possible please also include: -* Details of your attempts to resolve the issue (what have you tried, what worked, what did not). -* A [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Providing an example -is the best way to demonstrate the issue you are facing; it is important this includes all relevant information -(including broker configuration). Docker (see `cmd/docker`) makes it relatively simple to provide a working end-to-end -example. -* Broker logs covering the period the issue occurred. -* [Application Logs](#logging) covering the period the issue occurred. Unless you have isolated the root cause of the -issue please include a link to a full log (including data from well before the problem arose). - -It is important to remember that this library does not stand alone; it communicates with a broker and any issues you are -seeing may be due to: - -* Bugs in your code. -* Bugs in this library. -* The broker configuration. -* Bugs in the broker. -* Issues with whatever you are communicating with. - -When submitting an issue, please ensure that you provide sufficient details to enable us to eliminate causes outside of -this library. - -Contributing ------------- - -We welcome pull requests but before your contribution can be accepted by the project, you need to create and -electronically sign the Eclipse Contributor Agreement (ECA) and sign off on the Eclipse Foundation Certificate of Origin. - -More information is available in the -[Eclipse Development Resources](http://wiki.eclipse.org/Development_Resources/Contributing_via_Git); please take special -note of the requirement that the commit record contain a "Signed-off-by" entry. - -More information ----------------- - -[Stack Overflow](https://stackoverflow.com/questions/tagged/mqtt+go) has a range questions/answers covering a range of -common issues (both relating to use of this library and MQTT in general). This is the best place to ask general questions -(including those relating to the use of this library). - -Discussion of the Paho clients takes place on the [Eclipse paho-dev mailing list](https://dev.eclipse.org/mailman/listinfo/paho-dev). - -General questions about the MQTT protocol are discussed in the [MQTT Google Group](https://groups.google.com/forum/?hl=en-US&fromgroups#!forum/mqtt). - -There is much more information available via the [MQTT community site](http://mqtt.org). diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/backoff.go b/vendor/github.com/eclipse/paho.mqtt.golang/backoff.go deleted file mode 100644 index 8ee06f69..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/backoff.go +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Matt Brittan - * Daichi Tomaru - */ - -package mqtt - -import ( - "sync" - "time" -) - -// Controller for sleep with backoff when the client attempts reconnection -// It has statuses for each situations cause reconnection. -type backoffController struct { - sync.RWMutex - statusMap map[string]*backoffStatus -} - -type backoffStatus struct { - lastSleepPeriod time.Duration - lastErrorTime time.Time -} - -func newBackoffController() *backoffController { - return &backoffController{ - statusMap: map[string]*backoffStatus{}, - } -} - -// Calculate next sleep period from the specified parameters. -// Returned values are next sleep period and whether the error situation is continual. -// If connection errors continuouslly occurs, its sleep period is exponentially increased. -// Also if there is a lot of time between last and this error, sleep period is initialized. -func (b *backoffController) getBackoffSleepTime( - situation string, initSleepPeriod time.Duration, maxSleepPeriod time.Duration, processTime time.Duration, skipFirst bool, -) (time.Duration, bool) { - // Decide first sleep time if the situation is not continual. - var firstProcess = func(status *backoffStatus, init time.Duration, skip bool) (time.Duration, bool) { - if skip { - status.lastSleepPeriod = 0 - return 0, false - } - status.lastSleepPeriod = init - return init, false - } - - // Prioritize maxSleep. - if initSleepPeriod > maxSleepPeriod { - initSleepPeriod = maxSleepPeriod - } - b.Lock() - defer b.Unlock() - - status, exist := b.statusMap[situation] - if !exist { - b.statusMap[situation] = &backoffStatus{initSleepPeriod, time.Now()} - return firstProcess(b.statusMap[situation], initSleepPeriod, skipFirst) - } - - oldTime := status.lastErrorTime - status.lastErrorTime = time.Now() - - // When there is a lot of time between last and this error, sleep period is initialized. - if status.lastErrorTime.Sub(oldTime) > (processTime * 2 + status.lastSleepPeriod) { - return firstProcess(status, initSleepPeriod, skipFirst) - } - - if status.lastSleepPeriod == 0 { - status.lastSleepPeriod = initSleepPeriod - return initSleepPeriod, true - } - - if nextSleepPeriod := status.lastSleepPeriod * 2; nextSleepPeriod <= maxSleepPeriod { - status.lastSleepPeriod = nextSleepPeriod - } else { - status.lastSleepPeriod = maxSleepPeriod - } - - return status.lastSleepPeriod, true -} - -// Execute sleep the time returned from getBackoffSleepTime. -func (b *backoffController) sleepWithBackoff( - situation string, initSleepPeriod time.Duration, maxSleepPeriod time.Duration, processTime time.Duration, skipFirst bool, -) (time.Duration, bool) { - sleep, isFirst := b.getBackoffSleepTime(situation, initSleepPeriod, maxSleepPeriod, processTime, skipFirst) - if sleep != 0 { - time.Sleep(sleep) - } - return sleep, isFirst -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/client.go b/vendor/github.com/eclipse/paho.mqtt.golang/client.go deleted file mode 100644 index 9fe349e6..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/client.go +++ /dev/null @@ -1,1240 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - * Matt Brittan - */ - -// Portions copyright © 2018 TIBCO Software Inc. - -// Package mqtt provides an MQTT v3.1.1 client library. -package mqtt - -import ( - "bytes" - "context" - "errors" - "fmt" - "net" - "strings" - "sync" - "sync/atomic" - "time" - - "golang.org/x/sync/semaphore" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -// Client is the interface definition for a Client as used by this -// library, the interface is primarily to allow mocking tests. -// -// It is an MQTT v3.1.1 client for communicating -// with an MQTT server using non-blocking methods that allow work -// to be done in the background. -// An application may connect to an MQTT server using: -// -// A plain TCP socket (e.g. mqtt://test.mosquitto.org:1833) -// A secure SSL/TLS socket (e.g. tls://test.mosquitto.org:8883) -// A websocket (e.g ws://test.mosquitto.org:8080 or wss://test.mosquitto.org:8081) -// Something else (using `options.CustomOpenConnectionFn`) -// -// To enable ensured message delivery at Quality of Service (QoS) levels -// described in the MQTT spec, a message persistence mechanism must be -// used. This is done by providing a type which implements the Store -// interface. For convenience, FileStore and MemoryStore are provided -// implementations that should be sufficient for most use cases. More -// information can be found in their respective documentation. -// Numerous connection options may be specified by configuring a -// and then supplying a ClientOptions type. -// Implementations of Client must be safe for concurrent use by multiple -// goroutines -type Client interface { - // IsConnected returns a bool signifying whether - // the client is connected or not. - IsConnected() bool - // IsConnectionOpen return a bool signifying whether the client has an active - // connection to mqtt broker, i.e not in disconnected or reconnect mode - IsConnectionOpen() bool - // Connect will create a connection to the message broker, by default - // it will attempt to connect at v3.1.1 and auto retry at v3.1 if that - // fails - Connect() Token - // Disconnect will end the connection with the server, but not before waiting - // the specified number of milliseconds to wait for existing work to be - // completed. - Disconnect(quiesce uint) - // Publish will publish a message with the specified QoS and content - // to the specified topic. - // Returns a token to track delivery of the message to the broker - Publish(topic string, qos byte, retained bool, payload interface{}) Token - // Subscribe starts a new subscription. Provide a MessageHandler to be executed when - // a message is published on the topic provided, or nil for the default handler. - // - // If options.OrderMatters is true (the default) then callback must not block or - // call functions within this package that may block (e.g. Publish) other than in - // a new go routine. - // callback must be safe for concurrent use by multiple goroutines. - Subscribe(topic string, qos byte, callback MessageHandler) Token - // SubscribeMultiple starts a new subscription for multiple topics. Provide a MessageHandler to - // be executed when a message is published on one of the topics provided, or nil for the - // default handler. - // - // If options.OrderMatters is true (the default) then callback must not block or - // call functions within this package that may block (e.g. Publish) other than in - // a new go routine. - // callback must be safe for concurrent use by multiple goroutines. - SubscribeMultiple(filters map[string]byte, callback MessageHandler) Token - // Unsubscribe will end the subscription from each of the topics provided. - // Messages published to those topics from other clients will no longer be - // received. - Unsubscribe(topics ...string) Token - // AddRoute allows you to add a handler for messages on a specific topic - // without making a subscription. For example having a different handler - // for parts of a wildcard subscription or for receiving retained messages - // upon connection (before Sub scribe can be processed). - // - // If options.OrderMatters is true (the default) then callback must not block or - // call functions within this package that may block (e.g. Publish) other than in - // a new go routine. - // callback must be safe for concurrent use by multiple goroutines. - AddRoute(topic string, callback MessageHandler) - // OptionsReader returns a ClientOptionsReader which is a copy of the clientoptions - // in use by the client. - OptionsReader() ClientOptionsReader -} - -// client implements the Client interface -// clients are safe for concurrent use by multiple -// goroutines -type client struct { - lastSent atomic.Value // time.Time - the last time a packet was successfully sent to network - lastReceived atomic.Value // time.Time - the last time a packet was successfully received from network - pingOutstanding int32 // set to 1 if a ping has been sent but response not ret received - - status connectionStatus // see constants in status.go for values - - messageIds // effectively a map from message id to token completor - - obound chan *PacketAndToken // outgoing publish packet - oboundP chan *PacketAndToken // outgoing 'priority' packet (anything other than publish) - msgRouter *router // routes topics to handlers - persist Store - options ClientOptions - optionsMu sync.Mutex // Protects the options in a few limited cases where needed for testing - - conn net.Conn // the network connection, must only be set with connMu locked (only used when starting/stopping workers) - connMu sync.Mutex // mutex for the connection (again only used in two functions) - - stop chan struct{} // Closed to request that workers stop - workers sync.WaitGroup // used to wait for workers to complete (ping, keepalive, errwatch, resume) - commsStopped chan struct{} // closed when the comms routines have stopped (kept running until after workers have closed to avoid deadlocks) - - backoff *backoffController -} - -// NewClient will create an MQTT v3.1.1 client with all of the options specified -// in the provided ClientOptions. The client must have the Connect method called -// on it before it may be used. This is to make sure resources (such as a net -// connection) are created before the application is actually ready. -func NewClient(o *ClientOptions) Client { - c := &client{} - c.options = *o - - if c.options.Store == nil { - c.options.Store = NewMemoryStore() - } - switch c.options.ProtocolVersion { - case 3, 4: - c.options.protocolVersionExplicit = true - case 0x83, 0x84: - c.options.protocolVersionExplicit = true - default: - c.options.ProtocolVersion = 4 - c.options.protocolVersionExplicit = false - } - c.persist = c.options.Store - c.messageIds = messageIds{index: make(map[uint16]tokenCompletor)} - c.msgRouter = newRouter() - c.msgRouter.setDefaultHandler(c.options.DefaultPublishHandler) - c.obound = make(chan *PacketAndToken) - c.oboundP = make(chan *PacketAndToken) - c.backoff = newBackoffController() - return c -} - -// AddRoute allows you to add a handler for messages on a specific topic -// without making a subscription. For example having a different handler -// for parts of a wildcard subscription -// -// If options.OrderMatters is true (the default) then callback must not block or -// call functions within this package that may block (e.g. Publish) other than in -// a new go routine. -// callback must be safe for concurrent use by multiple goroutines. -func (c *client) AddRoute(topic string, callback MessageHandler) { - if callback != nil { - c.msgRouter.addRoute(topic, callback) - } -} - -// IsConnected returns a bool signifying whether -// the client is connected or not. -// connected means that the connection is up now OR it will -// be established/reestablished automatically when possible -// Warning: The connection status may change at any time so use this with care! -func (c *client) IsConnected() bool { - // This will need to change if additional statuses are added - s, r := c.status.ConnectionStatusRetry() - switch { - case s == connected: - return true - case c.options.ConnectRetry && s == connecting: - return true - case c.options.AutoReconnect: - return s == reconnecting || (s == disconnecting && r) // r indicates we will reconnect - default: - return false - } -} - -// IsConnectionOpen return a bool signifying whether the client has an active -// connection to mqtt broker, i.e. not in disconnected or reconnect mode -// Warning: The connection status may change at any time so use this with care! -func (c *client) IsConnectionOpen() bool { - return c.status.ConnectionStatus() == connected -} - -// ErrNotConnected is the error returned from function calls that are -// made when the client is not connected to a broker -var ErrNotConnected = errors.New("not Connected") - -// Connect will create a connection to the message broker, by default -// it will attempt to connect at v3.1.1 and auto retry at v3.1 if that -// fails -// Note: If using QOS1+ and CleanSession=false it is advisable to add -// routes (or a DefaultPublishHandler) prior to calling Connect() -// because queued messages may be delivered immediately post connection -func (c *client) Connect() Token { - t := newToken(packets.Connect).(*ConnectToken) - DEBUG.Println(CLI, "Connect()") - - connectionUp, err := c.status.Connecting() - if err != nil { - if err == errAlreadyConnectedOrReconnecting && c.options.AutoReconnect { - // When reconnection is active we don't consider calls tro Connect to ba an error (mainly for compatability) - WARN.Println(CLI, "Connect() called but not disconnected") - t.returnCode = packets.Accepted - t.flowComplete() - return t - } - ERROR.Println(CLI, err) // CONNECT should never be called unless we are disconnected - t.setError(err) - return t - } - - c.persist.Open() - if c.options.ConnectRetry { - c.reserveStoredPublishIDs() // Reserve IDs to allow publishing before connect complete - } - - go func() { - if len(c.options.Servers) == 0 { - t.setError(fmt.Errorf("no servers defined to connect to")) - if err := connectionUp(false); err != nil { - ERROR.Println(CLI, err.Error()) - } - return - } - - RETRYCONN: - var conn net.Conn - var rc byte - var err error - conn, rc, t.sessionPresent, err = c.attemptConnection() - if err != nil { - if c.options.ConnectRetry { - DEBUG.Println(CLI, "Connect failed, sleeping for", int(c.options.ConnectRetryInterval.Seconds()), "seconds and will then retry, error:", err.Error()) - time.Sleep(c.options.ConnectRetryInterval) - - if c.status.ConnectionStatus() == connecting { // Possible connection aborted elsewhere - goto RETRYCONN - } - } - ERROR.Println(CLI, "Failed to connect to a broker") - c.persist.Close() - t.returnCode = rc - t.setError(err) - if err := connectionUp(false); err != nil { - ERROR.Println(CLI, err.Error()) - } - return - } - inboundFromStore := make(chan packets.ControlPacket) // there may be some inbound comms packets in the store that are awaiting processing - if c.startCommsWorkers(conn, connectionUp, inboundFromStore) { // note that this takes care of updating the status (to connected or disconnected) - // Take care of any messages in the store - if !c.options.CleanSession { - c.resume(c.options.ResumeSubs, inboundFromStore) - } else { - c.persist.Reset() - } - } else { // Note: With the new status subsystem this should only happen if Disconnect called simultaneously with the above - WARN.Println(CLI, "Connect() called but connection established in another goroutine") - } - - close(inboundFromStore) - t.flowComplete() - DEBUG.Println(CLI, "exit startClient") - }() - return t -} - -// internal function used to reconnect the client when it loses its connection -// The connection status MUST be reconnecting prior to calling this function (via call to status.connectionLost) -func (c *client) reconnect(connectionUp connCompletedFn) { - DEBUG.Println(CLI, "enter reconnect") - var ( - initSleep = 1 * time.Second - conn net.Conn - ) - - // If the reason of connection lost is same as the before one, sleep timer is set before attempting connection is started. - // Sleep time is exponentially increased as the same situation continues - if slp, isContinual := c.backoff.sleepWithBackoff("connectionLost", initSleep, c.options.MaxReconnectInterval, 3 * time.Second, true); isContinual { - DEBUG.Println(CLI, "Detect continual connection lost after reconnect, slept for", int(slp.Seconds()), "seconds") - } - - for { - if nil != c.options.OnReconnecting { - c.options.OnReconnecting(c, &c.options) - } - var err error - conn, _, _, err = c.attemptConnection() - if err == nil { - break - } - sleep, _ := c.backoff.sleepWithBackoff("attemptReconnection", initSleep, c.options.MaxReconnectInterval, c.options.ConnectTimeout, false) - DEBUG.Println(CLI, "Reconnect failed, slept for", int(sleep.Seconds()), "seconds:", err) - - if c.status.ConnectionStatus() != reconnecting { // Disconnect may have been called - if err := connectionUp(false); err != nil { // Should always return an error - ERROR.Println(CLI, err.Error()) - } - DEBUG.Println(CLI, "Client moved to disconnected state while reconnecting, abandoning reconnect") - return - } - } - - inboundFromStore := make(chan packets.ControlPacket) // there may be some inbound comms packets in the store that are awaiting processing - if c.startCommsWorkers(conn, connectionUp, inboundFromStore) { // note that this takes care of updating the status (to connected or disconnected) - c.resume(c.options.ResumeSubs, inboundFromStore) - } - close(inboundFromStore) -} - -// attemptConnection makes a single attempt to connect to each of the brokers -// the protocol version to use is passed in (as c.options.ProtocolVersion) -// Note: Does not set c.conn in order to minimise race conditions -// Returns: -// net.Conn - Connected network connection -// byte - Return code (packets.Accepted indicates a successful connection). -// bool - SessionPresent flag from the connect ack (only valid if packets.Accepted) -// err - Error (err != nil guarantees that conn has been set to active connection). -func (c *client) attemptConnection() (net.Conn, byte, bool, error) { - protocolVersion := c.options.ProtocolVersion - var ( - sessionPresent bool - conn net.Conn - err error - rc byte - ) - - c.optionsMu.Lock() // Protect c.options.Servers so that servers can be added in test cases - brokers := c.options.Servers - c.optionsMu.Unlock() - for _, broker := range brokers { - cm := newConnectMsgFromOptions(&c.options, broker) - DEBUG.Println(CLI, "about to write new connect msg") - CONN: - tlsCfg := c.options.TLSConfig - if c.options.OnConnectAttempt != nil { - DEBUG.Println(CLI, "using custom onConnectAttempt handler...") - tlsCfg = c.options.OnConnectAttempt(broker, c.options.TLSConfig) - } - connDeadline := time.Now().Add(c.options.ConnectTimeout) // Time by which connection must be established - dialer := c.options.Dialer - if dialer == nil { // - WARN.Println(CLI, "dialer was nil, using default") - dialer = &net.Dialer{Timeout: 30 * time.Second} - } - // Start by opening the network connection (tcp, tls, ws) etc - if c.options.CustomOpenConnectionFn != nil { - conn, err = c.options.CustomOpenConnectionFn(broker, c.options) - } else { - conn, err = openConnection(broker, tlsCfg, c.options.ConnectTimeout, c.options.HTTPHeaders, c.options.WebsocketOptions, dialer) - } - if err != nil { - ERROR.Println(CLI, err.Error()) - WARN.Println(CLI, "failed to connect to broker, trying next") - rc = packets.ErrNetworkError - continue - } - DEBUG.Println(CLI, "socket connected to broker") - - // Now we perform the MQTT connection handshake ensuring that it does not exceed the timeout - if err := conn.SetDeadline(connDeadline); err != nil { - ERROR.Println(CLI, "set deadline for handshake ", err) - } - - // Now we perform the MQTT connection handshake - rc, sessionPresent, err = connectMQTT(conn, cm, protocolVersion) - if rc == packets.Accepted { - if err := conn.SetDeadline(time.Time{}); err != nil { - ERROR.Println(CLI, "reset deadline following handshake ", err) - } - break // successfully connected - } - - // We may have to attempt the connection with MQTT 3.1 - _ = conn.Close() - - if !c.options.protocolVersionExplicit && protocolVersion == 4 { // try falling back to 3.1? - DEBUG.Println(CLI, "Trying reconnect using MQTT 3.1 protocol") - protocolVersion = 3 - goto CONN - } - if c.options.protocolVersionExplicit { // to maintain logging from previous version - ERROR.Println(CLI, "Connecting to", broker, "CONNACK was not CONN_ACCEPTED, but rather", packets.ConnackReturnCodes[rc]) - } - } - // If the connection was successful we set member variable and lock in the protocol version for future connection attempts (and users) - if rc == packets.Accepted { - c.options.ProtocolVersion = protocolVersion - c.options.protocolVersionExplicit = true - } else { - // Maintain same error format as used previously - if rc != packets.ErrNetworkError { // mqtt error - err = packets.ConnErrors[rc] - } else { // network error (if this occurred in ConnectMQTT then err will be nil) - err = fmt.Errorf("%s : %s", packets.ConnErrors[rc], err) - } - } - return conn, rc, sessionPresent, err -} - -// Disconnect will end the connection with the server, but not before waiting -// the specified number of milliseconds to wait for existing work to be -// completed. -// WARNING: `Disconnect` may return before all activities (goroutines) have completed. This means that -// reusing the `client` may lead to panics. If you want to reconnect when the connection drops then use -// `SetAutoReconnect` and/or `SetConnectRetry`options instead of implementing this yourself. -func (c *client) Disconnect(quiesce uint) { - done := make(chan struct{}) // Simplest way to ensure quiesce is always honoured - go func() { - defer close(done) - disDone, err := c.status.Disconnecting() - if err != nil { - // Status has been set to disconnecting, but we had to wait for something else to complete - WARN.Println(CLI, err.Error()) - return - } - defer func() { - c.disconnect() // Force disconnection - disDone() // Update status - }() - DEBUG.Println(CLI, "disconnecting") - dm := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket) - dt := newToken(packets.Disconnect) - select { - case c.oboundP <- &PacketAndToken{p: dm, t: dt}: - // wait for work to finish, or quiesce time consumed - DEBUG.Println(CLI, "calling WaitTimeout") - dt.WaitTimeout(time.Duration(quiesce) * time.Millisecond) - DEBUG.Println(CLI, "WaitTimeout done") - // Below code causes a potential data race. Following status refactor it should no longer be required - // but leaving in as need to check code further. - // case <-c.commsStopped: - // WARN.Println("Disconnect packet could not be sent because comms stopped") - case <-time.After(time.Duration(quiesce) * time.Millisecond): - WARN.Println("Disconnect packet not sent due to timeout") - } - }() - - // Return when done or after timeout expires (would like to change but this maintains compatibility) - delay := time.NewTimer(time.Duration(quiesce) * time.Millisecond) - select { - case <-done: - if !delay.Stop() { - <-delay.C - } - case <-delay.C: - } -} - -// forceDisconnect will end the connection with the mqtt broker immediately (used for tests only) -func (c *client) forceDisconnect() { - disDone, err := c.status.Disconnecting() - if err != nil { - // Possible that we are not actually connected - WARN.Println(CLI, err.Error()) - return - } - DEBUG.Println(CLI, "forcefully disconnecting") - c.disconnect() - disDone() -} - -// disconnect cleans up after a final disconnection (user requested so no auto reconnection) -func (c *client) disconnect() { - done := c.stopCommsWorkers() - if done != nil { - <-done // Wait until the disconnect is complete (to limit chance that another connection will be started) - DEBUG.Println(CLI, "forcefully disconnecting") - c.messageIds.cleanUp() - DEBUG.Println(CLI, "disconnected") - c.persist.Close() - } -} - -// internalConnLost cleanup when connection is lost or an error occurs -// Note: This function will not block -func (c *client) internalConnLost(whyConnLost error) { - // It is possible that internalConnLost will be called multiple times simultaneously - // (including after sending a DisconnectPacket) as such we only do cleanup etc if the - // routines were actually running and are not being disconnected at users request - DEBUG.Println(CLI, "internalConnLost called") - disDone, err := c.status.ConnectionLost(c.options.AutoReconnect && c.status.ConnectionStatus() > connecting) - if err != nil { - if err == errConnLossWhileDisconnecting || err == errAlreadyHandlingConnectionLoss { - return // Loss of connection is expected or already being handled - } - ERROR.Println(CLI, fmt.Sprintf("internalConnLost unexpected status: %s", err.Error())) - return - } - - // c.stopCommsWorker returns a channel that is closed when the operation completes. This was required prior - // to the implementation of proper status management but has been left in place, for now, to minimise change - stopDone := c.stopCommsWorkers() - // stopDone was required in previous versions because there was no connectionLost status (and there were - // issues with status handling). This code has been left in place for the time being just in case the new - // status handling contains bugs (refactoring required at some point). - if stopDone == nil { // stopDone will be nil if workers already in the process of stopping or stopped - ERROR.Println(CLI, "internalConnLost stopDone unexpectedly nil - BUG BUG") - // Cannot really do anything other than leave things disconnected - if _, err = disDone(false); err != nil { // Safest option - cannot leave status as connectionLost - ERROR.Println(CLI, fmt.Sprintf("internalConnLost failed to set status to disconnected (stopDone): %s", err.Error())) - } - return - } - - // It may take a while for the disconnection to complete whatever called us needs to exit cleanly so finnish in goRoutine - go func() { - DEBUG.Println(CLI, "internalConnLost waiting on workers") - <-stopDone - DEBUG.Println(CLI, "internalConnLost workers stopped") - - reConnDone, err := disDone(true) - if err != nil { - ERROR.Println(CLI, "failure whilst reporting completion of disconnect", err) - } else if reConnDone == nil { // Should never happen - ERROR.Println(CLI, "BUG BUG BUG reconnection function is nil", err) - } - - reconnect := err == nil && reConnDone != nil - - if c.options.CleanSession && !reconnect { - c.messageIds.cleanUp() // completes PUB/SUB/UNSUB tokens - } else if !c.options.ResumeSubs { - c.messageIds.cleanUpSubscribe() // completes SUB/UNSUB tokens - } - if reconnect { - go c.reconnect(reConnDone) // Will set connection status to reconnecting - } - if c.options.OnConnectionLost != nil { - go c.options.OnConnectionLost(c, whyConnLost) - } - DEBUG.Println(CLI, "internalConnLost complete") - }() -} - -// startCommsWorkers is called when the connection is up. -// It starts off the routines needed to process incoming and outgoing messages. -// Returns true if the comms workers were started (i.e. successful connection) -// connectionUp(true) will be called once everything is up; connectionUp(false) will be called on failure -func (c *client) startCommsWorkers(conn net.Conn, connectionUp connCompletedFn, inboundFromStore <-chan packets.ControlPacket) bool { - DEBUG.Println(CLI, "startCommsWorkers called") - c.connMu.Lock() - defer c.connMu.Unlock() - if c.conn != nil { // Should never happen due to new status handling; leaving in for safety for the time being - WARN.Println(CLI, "startCommsWorkers called when commsworkers already running BUG BUG") - _ = conn.Close() // No use for the new network connection - if err := connectionUp(false); err != nil { - ERROR.Println(CLI, err.Error()) - } - return false - } - c.conn = conn // Store the connection - - c.stop = make(chan struct{}) - if c.options.KeepAlive != 0 { - atomic.StoreInt32(&c.pingOutstanding, 0) - c.lastReceived.Store(time.Now()) - c.lastSent.Store(time.Now()) - c.workers.Add(1) - go keepalive(c, conn) - } - - // matchAndDispatch will process messages received from the network. It may generate acknowledgements - // It will complete when incomingPubChan is closed and will close ackOut prior to exiting - incomingPubChan := make(chan *packets.PublishPacket) - c.workers.Add(1) // Done will be called when ackOut is closed - ackOut := c.msgRouter.matchAndDispatch(incomingPubChan, c.options.Order, c) - - // The connection is now ready for use (we spin up a few go routines below). It is possible that - // Disconnect has been called in the interim... - if err := connectionUp(true); err != nil { - DEBUG.Println(CLI, err) - close(c.stop) // Tidy up anything we have already started - close(incomingPubChan) - c.workers.Wait() - c.conn.Close() - c.conn = nil - return false - } - DEBUG.Println(CLI, "client is connected/reconnected") - if c.options.OnConnect != nil { - go c.options.OnConnect(c) - } - - // c.oboundP and c.obound need to stay active for the life of the client because, depending upon the options, - // messages may be published while the client is disconnected (they will block unless in a goroutine). However - // to keep the comms routines clean we want to shutdown the input messages it uses so create out own channels - // and copy data across. - commsobound := make(chan *PacketAndToken) // outgoing publish packets - commsoboundP := make(chan *PacketAndToken) // outgoing 'priority' packet - c.workers.Add(1) - go func() { - defer c.workers.Done() - for { - select { - case msg := <-c.oboundP: - commsoboundP <- msg - case msg := <-c.obound: - commsobound <- msg - case msg, ok := <-ackOut: - if !ok { - ackOut = nil // ignore channel going forward - c.workers.Done() // matchAndDispatch has completed - continue // await next message - } - commsoboundP <- msg - case <-c.stop: - // Attempt to transmit any outstanding acknowledgements (this may well fail but should work if this is a clean disconnect) - if ackOut != nil { - for msg := range ackOut { - commsoboundP <- msg - } - c.workers.Done() // matchAndDispatch has completed - } - close(commsoboundP) // Nothing sending to these channels anymore so close them and allow comms routines to exit - close(commsobound) - DEBUG.Println(CLI, "startCommsWorkers output redirector finished") - return - } - } - }() - - commsIncomingPub, commsErrors := startComms(c.conn, c, inboundFromStore, commsoboundP, commsobound) - c.commsStopped = make(chan struct{}) - go func() { - for { - if commsIncomingPub == nil && commsErrors == nil { - break - } - select { - case pub, ok := <-commsIncomingPub: - if !ok { - // Incoming comms has shutdown - close(incomingPubChan) // stop the router - commsIncomingPub = nil - continue - } - // Care is needed here because an error elsewhere could trigger a deadlock - sendPubLoop: - for { - select { - case incomingPubChan <- pub: - break sendPubLoop - case err, ok := <-commsErrors: - if !ok { // commsErrors has been closed so we can ignore it - commsErrors = nil - continue - } - ERROR.Println(CLI, "Connect comms goroutine - error triggered during send Pub", err) - c.internalConnLost(err) // no harm in calling this if the connection is already down (or shutdown is in progress) - continue - } - } - case err, ok := <-commsErrors: - if !ok { - commsErrors = nil - continue - } - ERROR.Println(CLI, "Connect comms goroutine - error triggered", err) - c.internalConnLost(err) // no harm in calling this if the connection is already down (or shutdown is in progress) - continue - } - } - DEBUG.Println(CLI, "incoming comms goroutine done") - close(c.commsStopped) - }() - DEBUG.Println(CLI, "startCommsWorkers done") - return true -} - -// stopWorkersAndComms - Cleanly shuts down worker go routines (including the comms routines) and waits until everything has stopped -// Returns nil if workers did not need to be stopped; otherwise returns a channel which will be closed when the stop is complete -// Note: This may block so run as a go routine if calling from any of the comms routines -// Note2: It should be possible to simplify this now that the new status management code is in place. -func (c *client) stopCommsWorkers() chan struct{} { - DEBUG.Println(CLI, "stopCommsWorkers called") - // It is possible that this function will be called multiple times simultaneously due to the way things get shutdown - c.connMu.Lock() - if c.conn == nil { - DEBUG.Println(CLI, "stopCommsWorkers done (not running)") - c.connMu.Unlock() - return nil - } - - // It is important that everything is stopped in the correct order to avoid deadlocks. The main issue here is - // the router because it both receives incoming publish messages and also sends outgoing acknowledgements. To - // avoid issues we signal the workers to stop and close the connection (it is probably already closed but - // there is no harm in being sure). We can then wait for the workers to finnish before closing outbound comms - // channels which will allow the comms routines to exit. - - // We stop all non-comms related workers first (ping, keepalive, errwatch, resume etc) so they don't get blocked waiting on comms - close(c.stop) // Signal for workers to stop - c.conn.Close() // Possible that this is already closed but no harm in closing again - c.conn = nil // Important that this is the only place that this is set to nil - c.connMu.Unlock() // As the connection is now nil we can unlock the mu (allowing subsequent calls to exit immediately) - - doneChan := make(chan struct{}) - - go func() { - DEBUG.Println(CLI, "stopCommsWorkers waiting for workers") - c.workers.Wait() - - // Stopping the workers will allow the comms routines to exit; we wait for these to complete - DEBUG.Println(CLI, "stopCommsWorkers waiting for comms") - <-c.commsStopped // wait for comms routine to stop - - DEBUG.Println(CLI, "stopCommsWorkers done") - close(doneChan) - }() - return doneChan -} - -// Publish will publish a message with the specified QoS and content -// to the specified topic. -// Returns a token to track delivery of the message to the broker -func (c *client) Publish(topic string, qos byte, retained bool, payload interface{}) Token { - token := newToken(packets.Publish).(*PublishToken) - DEBUG.Println(CLI, "enter Publish") - switch { - case !c.IsConnected(): - token.setError(ErrNotConnected) - return token - case c.status.ConnectionStatus() == reconnecting && qos == 0: - // message written to store and will be sent when connection comes up - token.flowComplete() - return token - } - pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pub.Qos = qos - pub.TopicName = topic - pub.Retain = retained - switch p := payload.(type) { - case string: - pub.Payload = []byte(p) - case []byte: - pub.Payload = p - case bytes.Buffer: - pub.Payload = p.Bytes() - default: - token.setError(fmt.Errorf("unknown payload type")) - return token - } - - if pub.Qos != 0 && pub.MessageID == 0 { - mID := c.getID(token) - if mID == 0 { - token.setError(fmt.Errorf("no message IDs available")) - return token - } - pub.MessageID = mID - token.messageID = mID - } - persistOutbound(c.persist, pub) - switch c.status.ConnectionStatus() { - case connecting: - DEBUG.Println(CLI, "storing publish message (connecting), topic:", topic) - case reconnecting: - DEBUG.Println(CLI, "storing publish message (reconnecting), topic:", topic) - case disconnecting: - DEBUG.Println(CLI, "storing publish message (disconnecting), topic:", topic) - default: - DEBUG.Println(CLI, "sending publish message, topic:", topic) - publishWaitTimeout := c.options.WriteTimeout - if publishWaitTimeout == 0 { - publishWaitTimeout = time.Second * 30 - } - select { - case c.obound <- &PacketAndToken{p: pub, t: token}: - case <-time.After(publishWaitTimeout): - token.setError(errors.New("publish was broken by timeout")) - } - } - return token -} - -// Subscribe starts a new subscription. Provide a MessageHandler to be executed when -// a message is published on the topic provided. -// -// If options.OrderMatters is true (the default) then callback must not block or -// call functions within this package that may block (e.g. Publish) other than in -// a new go routine. -// callback must be safe for concurrent use by multiple goroutines. -func (c *client) Subscribe(topic string, qos byte, callback MessageHandler) Token { - token := newToken(packets.Subscribe).(*SubscribeToken) - DEBUG.Println(CLI, "enter Subscribe") - if !c.IsConnected() { - token.setError(ErrNotConnected) - return token - } - if !c.IsConnectionOpen() { - switch { - case !c.options.ResumeSubs: - // if not connected and resumeSubs not set this sub will be thrown away - token.setError(fmt.Errorf("not currently connected and ResumeSubs not set")) - return token - case c.options.CleanSession && c.status.ConnectionStatus() == reconnecting: - // if reconnecting and cleanSession is true this sub will be thrown away - token.setError(fmt.Errorf("reconnecting state and cleansession is true")) - return token - } - } - sub := packets.NewControlPacket(packets.Subscribe).(*packets.SubscribePacket) - if err := validateTopicAndQos(topic, qos); err != nil { - token.setError(err) - return token - } - sub.Topics = append(sub.Topics, topic) - sub.Qoss = append(sub.Qoss, qos) - - if strings.HasPrefix(topic, "$share/") { - topic = strings.Join(strings.Split(topic, "/")[2:], "/") - } - - if strings.HasPrefix(topic, "$queue/") { - topic = strings.TrimPrefix(topic, "$queue/") - } - - if callback != nil { - c.msgRouter.addRoute(topic, callback) - } - - token.subs = append(token.subs, topic) - - if sub.MessageID == 0 { - mID := c.getID(token) - if mID == 0 { - token.setError(fmt.Errorf("no message IDs available")) - return token - } - sub.MessageID = mID - token.messageID = mID - } - DEBUG.Println(CLI, sub.String()) - - if c.options.ResumeSubs { // Only persist if we need this to resume subs after a disconnection - persistOutbound(c.persist, sub) - } - switch c.status.ConnectionStatus() { - case connecting: - DEBUG.Println(CLI, "storing subscribe message (connecting), topic:", topic) - case reconnecting: - DEBUG.Println(CLI, "storing subscribe message (reconnecting), topic:", topic) - case disconnecting: - DEBUG.Println(CLI, "storing subscribe message (disconnecting), topic:", topic) - default: - DEBUG.Println(CLI, "sending subscribe message, topic:", topic) - subscribeWaitTimeout := c.options.WriteTimeout - if subscribeWaitTimeout == 0 { - subscribeWaitTimeout = time.Second * 30 - } - select { - case c.oboundP <- &PacketAndToken{p: sub, t: token}: - case <-time.After(subscribeWaitTimeout): - token.setError(errors.New("subscribe was broken by timeout")) - } - } - DEBUG.Println(CLI, "exit Subscribe") - return token -} - -// SubscribeMultiple starts a new subscription for multiple topics. Provide a MessageHandler to -// be executed when a message is published on one of the topics provided. -// -// If options.OrderMatters is true (the default) then callback must not block or -// call functions within this package that may block (e.g. Publish) other than in -// a new go routine. -// callback must be safe for concurrent use by multiple goroutines. -func (c *client) SubscribeMultiple(filters map[string]byte, callback MessageHandler) Token { - var err error - token := newToken(packets.Subscribe).(*SubscribeToken) - DEBUG.Println(CLI, "enter SubscribeMultiple") - if !c.IsConnected() { - token.setError(ErrNotConnected) - return token - } - if !c.IsConnectionOpen() { - switch { - case !c.options.ResumeSubs: - // if not connected and resumesubs not set this sub will be thrown away - token.setError(fmt.Errorf("not currently connected and ResumeSubs not set")) - return token - case c.options.CleanSession && c.status.ConnectionStatus() == reconnecting: - // if reconnecting and cleanSession is true this sub will be thrown away - token.setError(fmt.Errorf("reconnecting state and cleansession is true")) - return token - } - } - sub := packets.NewControlPacket(packets.Subscribe).(*packets.SubscribePacket) - if sub.Topics, sub.Qoss, err = validateSubscribeMap(filters); err != nil { - token.setError(err) - return token - } - - if callback != nil { - for topic := range filters { - c.msgRouter.addRoute(topic, callback) - } - } - token.subs = make([]string, len(sub.Topics)) - copy(token.subs, sub.Topics) - - if sub.MessageID == 0 { - mID := c.getID(token) - if mID == 0 { - token.setError(fmt.Errorf("no message IDs available")) - return token - } - sub.MessageID = mID - token.messageID = mID - } - if c.options.ResumeSubs { // Only persist if we need this to resume subs after a disconnection - persistOutbound(c.persist, sub) - } - switch c.status.ConnectionStatus() { - case connecting: - DEBUG.Println(CLI, "storing subscribe message (connecting), topics:", sub.Topics) - case reconnecting: - DEBUG.Println(CLI, "storing subscribe message (reconnecting), topics:", sub.Topics) - case disconnecting: - DEBUG.Println(CLI, "storing subscribe message (disconnecting), topics:", sub.Topics) - default: - DEBUG.Println(CLI, "sending subscribe message, topics:", sub.Topics) - subscribeWaitTimeout := c.options.WriteTimeout - if subscribeWaitTimeout == 0 { - subscribeWaitTimeout = time.Second * 30 - } - select { - case c.oboundP <- &PacketAndToken{p: sub, t: token}: - case <-time.After(subscribeWaitTimeout): - token.setError(errors.New("subscribe was broken by timeout")) - } - } - DEBUG.Println(CLI, "exit SubscribeMultiple") - return token -} - -// reserveStoredPublishIDs reserves the ids for publish packets in the persistent store to ensure these are not duplicated -func (c *client) reserveStoredPublishIDs() { - // The resume function sets the stored id for publish packets only (some other packets - // will get new ids in net code). This means that the only keys we need to ensure are - // unique are the publish ones (and these will completed/replaced in resume() ) - if !c.options.CleanSession { - storedKeys := c.persist.All() - for _, key := range storedKeys { - packet := c.persist.Get(key) - if packet == nil { - continue - } - switch packet.(type) { - case *packets.PublishPacket: - details := packet.Details() - token := &PlaceHolderToken{id: details.MessageID} - c.claimID(token, details.MessageID) - } - } - } -} - -// Load all stored messages and resend them -// Call this to ensure QOS > 1,2 even after an application crash -// Note: This function will exit if c.stop is closed (this allows the shutdown to proceed avoiding a potential deadlock) -// other than that it does not return until all messages in the store have been sent (connect() does not complete its -// token before this completes) -func (c *client) resume(subscription bool, ibound chan packets.ControlPacket) { - DEBUG.Println(STR, "enter Resume") - - // Prior to sending a message getSemaphore will be called and once sent releaseSemaphore will be called - // with the token (so semaphore can be released when ACK received if applicable). - // Using a weighted semaphore rather than channels because this retains ordering - getSemaphore := func() {} // Default = do nothing - releaseSemaphore := func(_ *PublishToken) {} // Default = do nothing - var sem *semaphore.Weighted - if c.options.MaxResumePubInFlight > 0 { - sem = semaphore.NewWeighted(int64(c.options.MaxResumePubInFlight)) - ctx, cancel := context.WithCancel(context.Background()) // Context needed for semaphore - defer cancel() // ensure context gets cancelled - - go func() { - select { - case <-c.stop: // Request to stop (due to comm error etc) - cancel() - case <-ctx.Done(): // resume completed normally - } - }() - - getSemaphore = func() { sem.Acquire(ctx, 1) } - releaseSemaphore = func(token *PublishToken) { // Note: If token never completes then resume() may stall (will still exit on ctx.Done()) - go func() { - select { - case <-token.Done(): - case <-ctx.Done(): - } - sem.Release(1) - }() - } - } - - storedKeys := c.persist.All() - for _, key := range storedKeys { - packet := c.persist.Get(key) - if packet == nil { - DEBUG.Println(STR, fmt.Sprintf("resume found NIL packet (%s)", key)) - continue - } - details := packet.Details() - if isKeyOutbound(key) { - switch p := packet.(type) { - case *packets.SubscribePacket: - if subscription { - DEBUG.Println(STR, fmt.Sprintf("loaded pending subscribe (%d)", details.MessageID)) - subPacket := packet.(*packets.SubscribePacket) - token := newToken(packets.Subscribe).(*SubscribeToken) - token.messageID = details.MessageID - token.subs = append(token.subs, subPacket.Topics...) - c.claimID(token, details.MessageID) - select { - case c.oboundP <- &PacketAndToken{p: packet, t: token}: - case <-c.stop: - DEBUG.Println(STR, "resume exiting due to stop") - return - } - } else { - c.persist.Del(key) // Unsubscribe packets should not be retained following a reconnect - } - case *packets.UnsubscribePacket: - if subscription { - DEBUG.Println(STR, fmt.Sprintf("loaded pending unsubscribe (%d)", details.MessageID)) - token := newToken(packets.Unsubscribe).(*UnsubscribeToken) - select { - case c.oboundP <- &PacketAndToken{p: packet, t: token}: - case <-c.stop: - DEBUG.Println(STR, "resume exiting due to stop") - return - } - } else { - c.persist.Del(key) // Unsubscribe packets should not be retained following a reconnect - } - case *packets.PubrelPacket: - DEBUG.Println(STR, fmt.Sprintf("loaded pending pubrel (%d)", details.MessageID)) - select { - case c.oboundP <- &PacketAndToken{p: packet, t: nil}: - case <-c.stop: - DEBUG.Println(STR, "resume exiting due to stop") - return - } - case *packets.PublishPacket: - // spec: If the DUP flag is set to 0, it indicates that this is the first occasion that the Client or - // Server has attempted to send this MQTT PUBLISH Packet. If the DUP flag is set to 1, it indicates that - // this might be re-delivery of an earlier attempt to send the Packet. - // - // If the message is in the store than an attempt at delivery has been made (note that the message may - // never have made it onto the wire but tracking that would be complicated!). - if p.Qos != 0 { // spec: The DUP flag MUST be set to 0 for all QoS 0 messages - p.Dup = true - } - token := newToken(packets.Publish).(*PublishToken) - token.messageID = details.MessageID - c.claimID(token, details.MessageID) - DEBUG.Println(STR, fmt.Sprintf("loaded pending publish (%d)", details.MessageID)) - DEBUG.Println(STR, details) - getSemaphore() - select { - case c.obound <- &PacketAndToken{p: p, t: token}: - case <-c.stop: - DEBUG.Println(STR, "resume exiting due to stop") - return - } - releaseSemaphore(token) // If limiting simultaneous messages then we need to know when message is acknowledged - default: - ERROR.Println(STR, fmt.Sprintf("invalid message type (inbound - %T) in store (discarded)", packet)) - c.persist.Del(key) - } - } else { - switch packet.(type) { - case *packets.PubrelPacket: - DEBUG.Println(STR, fmt.Sprintf("loaded pending incomming (%d)", details.MessageID)) - select { - case ibound <- packet: - case <-c.stop: - DEBUG.Println(STR, "resume exiting due to stop (ibound <- packet)") - return - } - default: - ERROR.Println(STR, fmt.Sprintf("invalid message type (%T) in store (discarded)", packet)) - c.persist.Del(key) - } - } - } - DEBUG.Println(STR, "exit resume") -} - -// Unsubscribe will end the subscription from each of the topics provided. -// Messages published to those topics from other clients will no longer be -// received. -func (c *client) Unsubscribe(topics ...string) Token { - token := newToken(packets.Unsubscribe).(*UnsubscribeToken) - DEBUG.Println(CLI, "enter Unsubscribe") - if !c.IsConnected() { - token.setError(ErrNotConnected) - return token - } - if !c.IsConnectionOpen() { - switch { - case !c.options.ResumeSubs: - // if not connected and resumeSubs not set this unsub will be thrown away - token.setError(fmt.Errorf("not currently connected and ResumeSubs not set")) - return token - case c.options.CleanSession && c.status.ConnectionStatus() == reconnecting: - // if reconnecting and cleanSession is true this unsub will be thrown away - token.setError(fmt.Errorf("reconnecting state and cleansession is true")) - return token - } - } - unsub := packets.NewControlPacket(packets.Unsubscribe).(*packets.UnsubscribePacket) - unsub.Topics = make([]string, len(topics)) - copy(unsub.Topics, topics) - - if unsub.MessageID == 0 { - mID := c.getID(token) - if mID == 0 { - token.setError(fmt.Errorf("no message IDs available")) - return token - } - unsub.MessageID = mID - token.messageID = mID - } - - if c.options.ResumeSubs { // Only persist if we need this to resume subs after a disconnection - persistOutbound(c.persist, unsub) - } - - switch c.status.ConnectionStatus() { - case connecting: - DEBUG.Println(CLI, "storing unsubscribe message (connecting), topics:", topics) - case reconnecting: - DEBUG.Println(CLI, "storing unsubscribe message (reconnecting), topics:", topics) - case disconnecting: - DEBUG.Println(CLI, "storing unsubscribe message (reconnecting), topics:", topics) - default: - DEBUG.Println(CLI, "sending unsubscribe message, topics:", topics) - subscribeWaitTimeout := c.options.WriteTimeout - if subscribeWaitTimeout == 0 { - subscribeWaitTimeout = time.Second * 30 - } - select { - case c.oboundP <- &PacketAndToken{p: unsub, t: token}: - for _, topic := range topics { - c.msgRouter.deleteRoute(topic) - } - case <-time.After(subscribeWaitTimeout): - token.setError(errors.New("unsubscribe was broken by timeout")) - } - } - - DEBUG.Println(CLI, "exit Unsubscribe") - return token -} - -// OptionsReader returns a ClientOptionsReader which is a copy of the clientoptions -// in use by the client. -func (c *client) OptionsReader() ClientOptionsReader { - r := ClientOptionsReader{options: &c.options} - return r -} - -// DefaultConnectionLostHandler is a definition of a function that simply -// reports to the DEBUG log the reason for the client losing a connection. -func DefaultConnectionLostHandler(client Client, reason error) { - DEBUG.Println("Connection lost:", reason.Error()) -} - -// UpdateLastReceived - Will be called whenever a packet is received off the network -// This is used by the keepalive routine to -func (c *client) UpdateLastReceived() { - if c.options.KeepAlive != 0 { - c.lastReceived.Store(time.Now()) - } -} - -// UpdateLastReceived - Will be called whenever a packet is successfully transmitted to the network -func (c *client) UpdateLastSent() { - if c.options.KeepAlive != 0 { - c.lastSent.Store(time.Now()) - } -} - -// getWriteTimeOut returns the writetimeout (duration to wait when writing to the connection) or 0 if none -func (c *client) getWriteTimeOut() time.Duration { - return c.options.WriteTimeout -} - -// persistOutbound adds the packet to the outbound store -func (c *client) persistOutbound(m packets.ControlPacket) { - persistOutbound(c.persist, m) -} - -// persistInbound adds the packet to the inbound store -func (c *client) persistInbound(m packets.ControlPacket) { - persistInbound(c.persist, m) -} - -// pingRespReceived will be called by the network routines when a ping response is received -func (c *client) pingRespReceived() { - atomic.StoreInt32(&c.pingOutstanding, 0) -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/components.go b/vendor/github.com/eclipse/paho.mqtt.golang/components.go deleted file mode 100644 index 524db031..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/components.go +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -type component string - -// Component names for debug output -const ( - NET component = "[net] " - PNG component = "[pinger] " - CLI component = "[client] " - DEC component = "[decode] " - MES component = "[message] " - STR component = "[store] " - MID component = "[msgids] " - TST component = "[test] " - STA component = "[state] " - ERR component = "[error] " - ROU component = "[router] " -) diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 b/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 deleted file mode 100644 index cf989f14..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 +++ /dev/null @@ -1,15 +0,0 @@ - -Eclipse Distribution License - v 1.0 - -Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/epl-v20 b/vendor/github.com/eclipse/paho.mqtt.golang/epl-v20 deleted file mode 100644 index e55f3446..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/epl-v20 +++ /dev/null @@ -1,277 +0,0 @@ -Eclipse Public License - v 2.0 - - THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE - PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION - OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - - a) in the case of the initial Contributor, the initial content - Distributed under this Agreement, and - - b) in the case of each subsequent Contributor: - i) changes to the Program, and - ii) additions to the Program; - where such changes and/or additions to the Program originate from - and are Distributed by that particular Contributor. A Contribution - "originates" from a Contributor if it was added to the Program by - such Contributor itself or anyone acting on such Contributor's behalf. - Contributions do not include changes or additions to the Program that - are not Modified Works. - -"Contributor" means any person or entity that Distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which -are necessarily infringed by the use or sale of its Contribution alone -or when combined with the Program. - -"Program" means the Contributions Distributed in accordance with this -Agreement. - -"Recipient" means anyone who receives the Program under this Agreement -or any Secondary License (as applicable), including Contributors. - -"Derivative Works" shall mean any work, whether in Source Code or other -form, that is based on (or derived from) the Program and for which the -editorial revisions, annotations, elaborations, or other modifications -represent, as a whole, an original work of authorship. - -"Modified Works" shall mean any work in Source Code or other form that -results from an addition to, deletion from, or modification of the -contents of the Program, including, for purposes of clarity any new file -in Source Code form that contains any contents of the Program. Modified -Works shall not include works that contain only declarations, -interfaces, types, classes, structures, or files of the Program solely -in each case in order to link to, bind by name, or subclass the Program -or Modified Works thereof. - -"Distribute" means the acts of a) distributing or b) making available -in any manner that enables the transfer of a copy. - -"Source Code" means the form of a Program preferred for making -modifications, including but not limited to software source code, -documentation source, and configuration files. - -"Secondary License" means either the GNU General Public License, -Version 2.0, or any later versions of that license, including any -exceptions or additional permissions as identified by the initial -Contributor. - -2. GRANT OF RIGHTS - - a) Subject to the terms of this Agreement, each Contributor hereby - grants Recipient a non-exclusive, worldwide, royalty-free copyright - license to reproduce, prepare Derivative Works of, publicly display, - publicly perform, Distribute and sublicense the Contribution of such - Contributor, if any, and such Derivative Works. - - b) Subject to the terms of this Agreement, each Contributor hereby - grants Recipient a non-exclusive, worldwide, royalty-free patent - license under Licensed Patents to make, use, sell, offer to sell, - import and otherwise transfer the Contribution of such Contributor, - if any, in Source Code or other form. This patent license shall - apply to the combination of the Contribution and the Program if, at - the time the Contribution is added by the Contributor, such addition - of the Contribution causes such combination to be covered by the - Licensed Patents. The patent license shall not apply to any other - combinations which include the Contribution. No hardware per se is - licensed hereunder. - - c) Recipient understands that although each Contributor grants the - licenses to its Contributions set forth herein, no assurances are - provided by any Contributor that the Program does not infringe the - patent or other intellectual property rights of any other entity. - Each Contributor disclaims any liability to Recipient for claims - brought by any other entity based on infringement of intellectual - property rights or otherwise. As a condition to exercising the - rights and licenses granted hereunder, each Recipient hereby - assumes sole responsibility to secure any other intellectual - property rights needed, if any. For example, if a third party - patent license is required to allow Recipient to Distribute the - Program, it is Recipient's responsibility to acquire that license - before distributing the Program. - - d) Each Contributor represents that to its knowledge it has - sufficient copyright rights in its Contribution, if any, to grant - the copyright license set forth in this Agreement. - - e) Notwithstanding the terms of any Secondary License, no - Contributor makes additional grants to any Recipient (other than - those set forth in this Agreement) as a result of such Recipient's - receipt of the Program under the terms of a Secondary License - (if permitted under the terms of Section 3). - -3. REQUIREMENTS - -3.1 If a Contributor Distributes the Program in any form, then: - - a) the Program must also be made available as Source Code, in - accordance with section 3.2, and the Contributor must accompany - the Program with a statement that the Source Code for the Program - is available under this Agreement, and informs Recipients how to - obtain it in a reasonable manner on or through a medium customarily - used for software exchange; and - - b) the Contributor may Distribute the Program under a license - different than this Agreement, provided that such license: - i) effectively disclaims on behalf of all other Contributors all - warranties and conditions, express and implied, including - warranties or conditions of title and non-infringement, and - implied warranties or conditions of merchantability and fitness - for a particular purpose; - - ii) effectively excludes on behalf of all other Contributors all - liability for damages, including direct, indirect, special, - incidental and consequential damages, such as lost profits; - - iii) does not attempt to limit or alter the recipients' rights - in the Source Code under section 3.2; and - - iv) requires any subsequent distribution of the Program by any - party to be under a license that satisfies the requirements - of this section 3. - -3.2 When the Program is Distributed as Source Code: - - a) it must be made available under this Agreement, or if the - Program (i) is combined with other material in a separate file or - files made available under a Secondary License, and (ii) the initial - Contributor attached to the Source Code the notice described in - Exhibit A of this Agreement, then the Program may be made available - under the terms of such Secondary Licenses, and - - b) a copy of this Agreement must be included with each copy of - the Program. - -3.3 Contributors may not remove or alter any copyright, patent, -trademark, attribution notices, disclaimers of warranty, or limitations -of liability ("notices") contained within the Program from any copy of -the Program which they Distribute, provided that Contributors may add -their own appropriate notices. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities -with respect to end users, business partners and the like. While this -license is intended to facilitate the commercial use of the Program, -the Contributor who includes the Program in a commercial product -offering should do so in a manner which does not create potential -liability for other Contributors. Therefore, if a Contributor includes -the Program in a commercial product offering, such Contributor -("Commercial Contributor") hereby agrees to defend and indemnify every -other Contributor ("Indemnified Contributor") against any losses, -damages and costs (collectively "Losses") arising from claims, lawsuits -and other legal actions brought by a third party against the Indemnified -Contributor to the extent caused by the acts or omissions of such -Commercial Contributor in connection with its distribution of the Program -in a commercial product offering. The obligations in this section do not -apply to any claims or Losses relating to any actual or alleged -intellectual property infringement. In order to qualify, an Indemnified -Contributor must: a) promptly notify the Commercial Contributor in -writing of such claim, and b) allow the Commercial Contributor to control, -and cooperate with the Commercial Contributor in, the defense and any -related settlement negotiations. The Indemnified Contributor may -participate in any such claim at its own expense. - -For example, a Contributor might include the Program in a commercial -product offering, Product X. That Contributor is then a Commercial -Contributor. If that Commercial Contributor then makes performance -claims, or offers warranties related to Product X, those performance -claims and warranties are such Commercial Contributor's responsibility -alone. Under this section, the Commercial Contributor would have to -defend claims against the other Contributors related to those performance -claims and warranties, and if a court requires any other Contributor to -pay any damages as a result, the Commercial Contributor must pay -those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT -PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" -BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR -IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF -TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR -PURPOSE. Each Recipient is solely responsible for determining the -appropriateness of using and distributing the Program and assumes all -risks associated with its exercise of rights under this Agreement, -including but not limited to the risks and costs of program errors, -compliance with applicable laws, damage to or loss of data, programs -or equipment, and unavailability or interruption of operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT -PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS -SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST -PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE -EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of -the remainder of the terms of this Agreement, and without further -action by the parties hereto, such provision shall be reformed to the -minimum extent necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity -(including a cross-claim or counterclaim in a lawsuit) alleging that the -Program itself (excluding combinations of the Program with other software -or hardware) infringes such Recipient's patent(s), then such Recipient's -rights granted under Section 2(b) shall terminate as of the date such -litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it -fails to comply with any of the material terms or conditions of this -Agreement and does not cure such failure in a reasonable period of -time after becoming aware of such noncompliance. If all Recipient's -rights under this Agreement terminate, Recipient agrees to cease use -and distribution of the Program as soon as reasonably practicable. -However, Recipient's obligations under this Agreement and any licenses -granted by Recipient relating to the Program shall continue and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, -but in order to avoid inconsistency the Agreement is copyrighted and -may only be modified in the following manner. The Agreement Steward -reserves the right to publish new versions (including revisions) of -this Agreement from time to time. No one other than the Agreement -Steward has the right to modify this Agreement. The Eclipse Foundation -is the initial Agreement Steward. The Eclipse Foundation may assign the -responsibility to serve as the Agreement Steward to a suitable separate -entity. Each new version of the Agreement will be given a distinguishing -version number. The Program (including Contributions) may always be -Distributed subject to the version of the Agreement under which it was -received. In addition, after a new version of the Agreement is published, -Contributor may elect to Distribute the Program (including its -Contributions) under the new version. - -Except as expressly stated in Sections 2(a) and 2(b) above, Recipient -receives no rights or licenses to the intellectual property of any -Contributor under this Agreement, whether expressly, by implication, -estoppel or otherwise. All rights in the Program not expressly granted -under this Agreement are reserved. Nothing in this Agreement is intended -to be enforceable by any entity that is not a Contributor or Recipient. -No third-party beneficiary rights are created under this Agreement. - -Exhibit A - Form of Secondary Licenses Notice - -"This Source Code may also be made available under the following -Secondary Licenses when the conditions for such availability set forth -in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), -version(s), and exceptions or additional permissions here}." - - Simply including a copy of this Agreement, including this Exhibit A - is not sufficient to license the Source Code under Secondary Licenses. - - If it is not possible or desirable to put the notice in a particular - file, then You may include the notice in a location (such as a LICENSE - file in a relevant directory) where a recipient would be likely to - look for such a notice. - - You may add additional accurate notices of copyright ownership. \ No newline at end of file diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go b/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go deleted file mode 100644 index fcfaa12e..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "io/ioutil" - "os" - "path" - "sort" - "sync" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -const ( - msgExt = ".msg" - tmpExt = ".tmp" - corruptExt = ".CORRUPT" -) - -// FileStore implements the store interface using the filesystem to provide -// true persistence, even across client failure. This is designed to use a -// single directory per running client. If you are running multiple clients -// on the same filesystem, you will need to be careful to specify unique -// store directories for each. -type FileStore struct { - sync.RWMutex - directory string - opened bool -} - -// NewFileStore will create a new FileStore which stores its messages in the -// directory provided. -func NewFileStore(directory string) *FileStore { - store := &FileStore{ - directory: directory, - opened: false, - } - return store -} - -// Open will allow the FileStore to be used. -func (store *FileStore) Open() { - store.Lock() - defer store.Unlock() - // if no store directory was specified in ClientOpts, by default use the - // current working directory - if store.directory == "" { - store.directory, _ = os.Getwd() - } - - // if store dir exists, great, otherwise, create it - if !exists(store.directory) { - perms := os.FileMode(0770) - merr := os.MkdirAll(store.directory, perms) - chkerr(merr) - } - store.opened = true - DEBUG.Println(STR, "store is opened at", store.directory) -} - -// Close will disallow the FileStore from being used. -func (store *FileStore) Close() { - store.Lock() - defer store.Unlock() - store.opened = false - DEBUG.Println(STR, "store is closed") -} - -// Put will put a message into the store, associated with the provided -// key value. -func (store *FileStore) Put(key string, m packets.ControlPacket) { - store.Lock() - defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to use file store, but not open") - return - } - full := fullpath(store.directory, key) - write(store.directory, key, m) - if !exists(full) { - ERROR.Println(STR, "file not created:", full) - } -} - -// Get will retrieve a message from the store, the one associated with -// the provided key value. -func (store *FileStore) Get(key string) packets.ControlPacket { - store.RLock() - defer store.RUnlock() - if !store.opened { - ERROR.Println(STR, "trying to use file store, but not open") - return nil - } - filepath := fullpath(store.directory, key) - if !exists(filepath) { - return nil - } - mfile, oerr := os.Open(filepath) - chkerr(oerr) - msg, rerr := packets.ReadPacket(mfile) - chkerr(mfile.Close()) - - // Message was unreadable, return nil - if rerr != nil { - newpath := corruptpath(store.directory, key) - WARN.Println(STR, "corrupted file detected:", rerr.Error(), "archived at:", newpath) - if err := os.Rename(filepath, newpath); err != nil { - ERROR.Println(STR, err) - } - return nil - } - return msg -} - -// All will provide a list of all of the keys associated with messages -// currently residing in the FileStore. -func (store *FileStore) All() []string { - store.RLock() - defer store.RUnlock() - return store.all() -} - -// Del will remove the persisted message associated with the provided -// key from the FileStore. -func (store *FileStore) Del(key string) { - store.Lock() - defer store.Unlock() - store.del(key) -} - -// Reset will remove all persisted messages from the FileStore. -func (store *FileStore) Reset() { - store.Lock() - defer store.Unlock() - WARN.Println(STR, "FileStore Reset") - for _, key := range store.all() { - store.del(key) - } -} - -// lockless -func (store *FileStore) all() []string { - var err error - var keys []string - var files fileInfos - - if !store.opened { - ERROR.Println(STR, "trying to use file store, but not open") - return nil - } - - files, err = ioutil.ReadDir(store.directory) - chkerr(err) - sort.Sort(files) - for _, f := range files { - DEBUG.Println(STR, "file in All():", f.Name()) - name := f.Name() - if len(name) < len(msgExt) || name[len(name)-len(msgExt):] != msgExt { - DEBUG.Println(STR, "skipping file, doesn't have right extension: ", name) - continue - } - key := name[0 : len(name)-4] // remove file extension - keys = append(keys, key) - } - return keys -} - -// lockless -func (store *FileStore) del(key string) { - if !store.opened { - ERROR.Println(STR, "trying to use file store, but not open") - return - } - DEBUG.Println(STR, "store del filepath:", store.directory) - DEBUG.Println(STR, "store delete key:", key) - filepath := fullpath(store.directory, key) - DEBUG.Println(STR, "path of deletion:", filepath) - if !exists(filepath) { - WARN.Println(STR, "store could not delete key:", key) - return - } - rerr := os.Remove(filepath) - chkerr(rerr) - DEBUG.Println(STR, "del msg:", key) - if exists(filepath) { - ERROR.Println(STR, "file not deleted:", filepath) - } -} - -func fullpath(store string, key string) string { - p := path.Join(store, key+msgExt) - return p -} - -func tmppath(store string, key string) string { - p := path.Join(store, key+tmpExt) - return p -} - -func corruptpath(store string, key string) string { - p := path.Join(store, key+corruptExt) - return p -} - -// create file called "X.[messageid].tmp" located in the store -// the contents of the file is the bytes of the message, then -// rename it to "X.[messageid].msg", overwriting any existing -// message with the same id -// X will be 'i' for inbound messages, and O for outbound messages -func write(store, key string, m packets.ControlPacket) { - temppath := tmppath(store, key) - f, err := os.Create(temppath) - chkerr(err) - werr := m.Write(f) - chkerr(werr) - cerr := f.Close() - chkerr(cerr) - rerr := os.Rename(temppath, fullpath(store, key)) - chkerr(rerr) -} - -func exists(file string) bool { - if _, err := os.Stat(file); err != nil { - if os.IsNotExist(err) { - return false - } - chkerr(err) - } - return true -} - -type fileInfos []os.FileInfo - -func (f fileInfos) Len() int { - return len(f) -} - -func (f fileInfos) Swap(i, j int) { - f[i], f[j] = f[j], f[i] -} - -func (f fileInfos) Less(i, j int) bool { - return f[i].ModTime().Before(f[j].ModTime()) -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go b/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go deleted file mode 100644 index e9f80882..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "sync" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -// MemoryStore implements the store interface to provide a "persistence" -// mechanism wholly stored in memory. This is only useful for -// as long as the client instance exists. -type MemoryStore struct { - sync.RWMutex - messages map[string]packets.ControlPacket - opened bool -} - -// NewMemoryStore returns a pointer to a new instance of -// MemoryStore, the instance is not initialized and ready to -// use until Open() has been called on it. -func NewMemoryStore() *MemoryStore { - store := &MemoryStore{ - messages: make(map[string]packets.ControlPacket), - opened: false, - } - return store -} - -// Open initializes a MemoryStore instance. -func (store *MemoryStore) Open() { - store.Lock() - defer store.Unlock() - store.opened = true - DEBUG.Println(STR, "memorystore initialized") -} - -// Put takes a key and a pointer to a Message and stores the -// message. -func (store *MemoryStore) Put(key string, message packets.ControlPacket) { - store.Lock() - defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return - } - store.messages[key] = message -} - -// Get takes a key and looks in the store for a matching Message -// returning either the Message pointer or nil. -func (store *MemoryStore) Get(key string) packets.ControlPacket { - store.RLock() - defer store.RUnlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return nil - } - mid := mIDFromKey(key) - m := store.messages[key] - if m == nil { - CRITICAL.Println(STR, "memorystore get: message", mid, "not found") - } else { - DEBUG.Println(STR, "memorystore get: message", mid, "found") - } - return m -} - -// All returns a slice of strings containing all the keys currently -// in the MemoryStore. -func (store *MemoryStore) All() []string { - store.RLock() - defer store.RUnlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return nil - } - var keys []string - for k := range store.messages { - keys = append(keys, k) - } - return keys -} - -// Del takes a key, searches the MemoryStore and if the key is found -// deletes the Message pointer associated with it. -func (store *MemoryStore) Del(key string) { - store.Lock() - defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return - } - mid := mIDFromKey(key) - m := store.messages[key] - if m == nil { - WARN.Println(STR, "memorystore del: message", mid, "not found") - } else { - delete(store.messages, key) - DEBUG.Println(STR, "memorystore del: message", mid, "was deleted") - } -} - -// Close will disallow modifications to the state of the store. -func (store *MemoryStore) Close() { - store.Lock() - defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to close memory store, but not open") - return - } - store.opened = false - DEBUG.Println(STR, "memorystore closed") -} - -// Reset eliminates all persisted message data in the store. -func (store *MemoryStore) Reset() { - store.Lock() - defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to reset memory store, but not open") - } - store.messages = make(map[string]packets.ControlPacket) - WARN.Println(STR, "memorystore wiped") -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/memstore_ordered.go b/vendor/github.com/eclipse/paho.mqtt.golang/memstore_ordered.go deleted file mode 100644 index 498b82b8..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/memstore_ordered.go +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - * Matt Brittan - */ - -package mqtt - -import ( - "sort" - "sync" - "time" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -// OrderedMemoryStore uses a map internally so the order in which All() returns packets is -// undefined. OrderedMemoryStore resolves this by storing the time the message is added -// and sorting based upon this. - -// storedMessage encapsulates a message and the time it was initially stored -type storedMessage struct { - ts time.Time - msg packets.ControlPacket -} - -// OrderedMemoryStore implements the store interface to provide a "persistence" -// mechanism wholly stored in memory. This is only useful for -// as long as the client instance exists. -type OrderedMemoryStore struct { - sync.RWMutex - messages map[string]storedMessage - opened bool -} - -// NewOrderedMemoryStore returns a pointer to a new instance of -// OrderedMemoryStore, the instance is not initialized and ready to -// use until Open() has been called on it. -func NewOrderedMemoryStore() *OrderedMemoryStore { - store := &OrderedMemoryStore{ - messages: make(map[string]storedMessage), - opened: false, - } - return store -} - -// Open initializes a OrderedMemoryStore instance. -func (store *OrderedMemoryStore) Open() { - store.Lock() - defer store.Unlock() - store.opened = true - DEBUG.Println(STR, "OrderedMemoryStore initialized") -} - -// Put takes a key and a pointer to a Message and stores the -// message. -func (store *OrderedMemoryStore) Put(key string, message packets.ControlPacket) { - store.Lock() - defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return - } - store.messages[key] = storedMessage{ts: time.Now(), msg: message} -} - -// Get takes a key and looks in the store for a matching Message -// returning either the Message pointer or nil. -func (store *OrderedMemoryStore) Get(key string) packets.ControlPacket { - store.RLock() - defer store.RUnlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return nil - } - mid := mIDFromKey(key) - m, ok := store.messages[key] - if !ok || m.msg == nil { - CRITICAL.Println(STR, "OrderedMemoryStore get: message", mid, "not found") - } else { - DEBUG.Println(STR, "OrderedMemoryStore get: message", mid, "found") - } - return m.msg -} - -// All returns a slice of strings containing all the keys currently -// in the OrderedMemoryStore. -func (store *OrderedMemoryStore) All() []string { - store.RLock() - defer store.RUnlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return nil - } - type tsAndKey struct { - ts time.Time - key string - } - - tsKeys := make([]tsAndKey, 0, len(store.messages)) - for k, v := range store.messages { - tsKeys = append(tsKeys, tsAndKey{ts: v.ts, key: k}) - } - sort.Slice(tsKeys, func(a int, b int) bool { return tsKeys[a].ts.Before(tsKeys[b].ts) }) - - keys := make([]string, len(tsKeys)) - for i := range tsKeys { - keys[i] = tsKeys[i].key - } - return keys -} - -// Del takes a key, searches the OrderedMemoryStore and if the key is found -// deletes the Message pointer associated with it. -func (store *OrderedMemoryStore) Del(key string) { - store.Lock() - defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return - } - mid := mIDFromKey(key) - _, ok := store.messages[key] - if !ok { - WARN.Println(STR, "OrderedMemoryStore del: message", mid, "not found") - } else { - delete(store.messages, key) - DEBUG.Println(STR, "OrderedMemoryStore del: message", mid, "was deleted") - } -} - -// Close will disallow modifications to the state of the store. -func (store *OrderedMemoryStore) Close() { - store.Lock() - defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to close memory store, but not open") - return - } - store.opened = false - DEBUG.Println(STR, "OrderedMemoryStore closed") -} - -// Reset eliminates all persisted message data in the store. -func (store *OrderedMemoryStore) Reset() { - store.Lock() - defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to reset memory store, but not open") - } - store.messages = make(map[string]storedMessage) - WARN.Println(STR, "OrderedMemoryStore wiped") -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/message.go b/vendor/github.com/eclipse/paho.mqtt.golang/message.go deleted file mode 100644 index 35b463f8..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/message.go +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "net/url" - "sync" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -// Message defines the externals that a message implementation must support -// these are received messages that are passed to the callbacks, not internal -// messages -type Message interface { - Duplicate() bool - Qos() byte - Retained() bool - Topic() string - MessageID() uint16 - Payload() []byte - Ack() -} - -type message struct { - duplicate bool - qos byte - retained bool - topic string - messageID uint16 - payload []byte - once sync.Once - ack func() -} - -func (m *message) Duplicate() bool { - return m.duplicate -} - -func (m *message) Qos() byte { - return m.qos -} - -func (m *message) Retained() bool { - return m.retained -} - -func (m *message) Topic() string { - return m.topic -} - -func (m *message) MessageID() uint16 { - return m.messageID -} - -func (m *message) Payload() []byte { - return m.payload -} - -func (m *message) Ack() { - m.once.Do(m.ack) -} - -func messageFromPublish(p *packets.PublishPacket, ack func()) Message { - return &message{ - duplicate: p.Dup, - qos: p.Qos, - retained: p.Retain, - topic: p.TopicName, - messageID: p.MessageID, - payload: p.Payload, - ack: ack, - } -} - -func newConnectMsgFromOptions(options *ClientOptions, broker *url.URL) *packets.ConnectPacket { - m := packets.NewControlPacket(packets.Connect).(*packets.ConnectPacket) - - m.CleanSession = options.CleanSession - m.WillFlag = options.WillEnabled - m.WillRetain = options.WillRetained - m.ClientIdentifier = options.ClientID - - if options.WillEnabled { - m.WillQos = options.WillQos - m.WillTopic = options.WillTopic - m.WillMessage = options.WillPayload - } - - username := options.Username - password := options.Password - if broker.User != nil { - username = broker.User.Username() - if pwd, ok := broker.User.Password(); ok { - password = pwd - } - } - if options.CredentialsProvider != nil { - username, password = options.CredentialsProvider() - } - - if username != "" { - m.UsernameFlag = true - m.Username = username - // mustn't have password without user as well - if password != "" { - m.PasswordFlag = true - m.Password = []byte(password) - } - } - - m.Keepalive = uint16(options.KeepAlive) - - return m -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go b/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go deleted file mode 100644 index 04c94bd3..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - * Matt Brittan - */ - -package mqtt - -import ( - "fmt" - "sync" - "time" -) - -// MId is 16 bit message id as specified by the MQTT spec. -// In general, these values should not be depended upon by -// the client application. -type MId uint16 - -type messageIds struct { - mu sync.RWMutex // Named to prevent Mu from being accessible directly via client - index map[uint16]tokenCompletor - - lastIssuedID uint16 // The most recently issued ID. Used so we cycle through ids rather than immediately reusing them (can make debugging easier) -} - -const ( - midMin uint16 = 1 - midMax uint16 = 65535 -) - -// cleanup clears the message ID map; completes all token types and sets error on PUB, SUB and UNSUB tokens. -func (mids *messageIds) cleanUp() { - mids.mu.Lock() - for _, token := range mids.index { - switch token.(type) { - case *PublishToken: - token.setError(fmt.Errorf("connection lost before Publish completed")) - case *SubscribeToken: - token.setError(fmt.Errorf("connection lost before Subscribe completed")) - case *UnsubscribeToken: - token.setError(fmt.Errorf("connection lost before Unsubscribe completed")) - case nil: // should not be any nil entries - continue - } - token.flowComplete() - } - mids.index = make(map[uint16]tokenCompletor) - mids.mu.Unlock() - DEBUG.Println(MID, "cleaned up") -} - -// cleanUpSubscribe removes all SUBSCRIBE and UNSUBSCRIBE tokens (setting error) -// This may be called when the connection is lost, and we will not be resending SUB/UNSUB packets -func (mids *messageIds) cleanUpSubscribe() { - mids.mu.Lock() - for mid, token := range mids.index { - switch token.(type) { - case *SubscribeToken: - token.setError(fmt.Errorf("connection lost before Subscribe completed")) - delete(mids.index, mid) - case *UnsubscribeToken: - token.setError(fmt.Errorf("connection lost before Unsubscribe completed")) - delete(mids.index, mid) - } - } - mids.mu.Unlock() - DEBUG.Println(MID, "cleaned up subs") -} - -func (mids *messageIds) freeID(id uint16) { - mids.mu.Lock() - delete(mids.index, id) - mids.mu.Unlock() -} - -func (mids *messageIds) claimID(token tokenCompletor, id uint16) { - mids.mu.Lock() - defer mids.mu.Unlock() - if _, ok := mids.index[id]; !ok { - mids.index[id] = token - } else { - old := mids.index[id] - old.flowComplete() - mids.index[id] = token - } - if id > mids.lastIssuedID { - mids.lastIssuedID = id - } -} - -// getID will return an available id or 0 if none available -// The id will generally be the previous id + 1 (because this makes tracing messages a bit simpler) -func (mids *messageIds) getID(t tokenCompletor) uint16 { - mids.mu.Lock() - defer mids.mu.Unlock() - i := mids.lastIssuedID // note: the only situation where lastIssuedID is 0 the map will be empty - looped := false // uint16 will loop from 65535->0 - for { - i++ - if i == 0 { // skip 0 because its not a valid id (Control Packets MUST contain a non-zero 16-bit Packet Identifier [MQTT-2.3.1-1]) - i++ - looped = true - } - if _, ok := mids.index[i]; !ok { - mids.index[i] = t - mids.lastIssuedID = i - return i - } - if (looped && i == mids.lastIssuedID) || (mids.lastIssuedID == 0 && i == midMax) { // lastIssuedID will be 0 at startup - return 0 // no free ids - } - } -} - -func (mids *messageIds) getToken(id uint16) tokenCompletor { - mids.mu.RLock() - defer mids.mu.RUnlock() - if token, ok := mids.index[id]; ok { - return token - } - return &DummyToken{id: id} -} - -type DummyToken struct { - id uint16 -} - -// Wait implements the Token Wait method. -func (d *DummyToken) Wait() bool { - return true -} - -// WaitTimeout implements the Token WaitTimeout method. -func (d *DummyToken) WaitTimeout(t time.Duration) bool { - return true -} - -// Done implements the Token Done method. -func (d *DummyToken) Done() <-chan struct{} { - ch := make(chan struct{}) - close(ch) - return ch -} - -func (d *DummyToken) flowComplete() { - ERROR.Printf("A lookup for token %d returned nil\n", d.id) -} - -func (d *DummyToken) Error() error { - return nil -} - -func (d *DummyToken) setError(e error) {} - -// PlaceHolderToken does nothing and was implemented to allow a messageid to be reserved -// it differs from DummyToken in that calling flowComplete does not generate an error (it -// is expected that flowComplete will be called when the token is overwritten with a real token) -type PlaceHolderToken struct { - id uint16 -} - -// Wait implements the Token Wait method. -func (p *PlaceHolderToken) Wait() bool { - return true -} - -// WaitTimeout implements the Token WaitTimeout method. -func (p *PlaceHolderToken) WaitTimeout(t time.Duration) bool { - return true -} - -// Done implements the Token Done method. -func (p *PlaceHolderToken) Done() <-chan struct{} { - ch := make(chan struct{}) - close(ch) - return ch -} - -func (p *PlaceHolderToken) flowComplete() { -} - -func (p *PlaceHolderToken) Error() error { - return nil -} - -func (p *PlaceHolderToken) setError(e error) {} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/net.go b/vendor/github.com/eclipse/paho.mqtt.golang/net.go deleted file mode 100644 index 10cc7dae..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/net.go +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - * Matt Brittan - */ - -package mqtt - -import ( - "errors" - "io" - "net" - "reflect" - "strings" - "sync" - "time" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -const closedNetConnErrorText = "use of closed network connection" // error string for closed conn (https://golang.org/src/net/error_test.go) - -// ConnectMQTT takes a connected net.Conn and performs the initial MQTT handshake. Parameters are: -// conn - Connected net.Conn -// cm - Connect Packet with everything other than the protocol name/version populated (historical reasons) -// protocolVersion - The protocol version to attempt to connect with -// -// Note that, for backward compatibility, ConnectMQTT() suppresses the actual connection error (compare to connectMQTT()). -func ConnectMQTT(conn net.Conn, cm *packets.ConnectPacket, protocolVersion uint) (byte, bool) { - rc, sessionPresent, _ := connectMQTT(conn, cm, protocolVersion) - return rc, sessionPresent -} - -func connectMQTT(conn io.ReadWriter, cm *packets.ConnectPacket, protocolVersion uint) (byte, bool, error) { - switch protocolVersion { - case 3: - DEBUG.Println(CLI, "Using MQTT 3.1 protocol") - cm.ProtocolName = "MQIsdp" - cm.ProtocolVersion = 3 - case 0x83: - DEBUG.Println(CLI, "Using MQTT 3.1b protocol") - cm.ProtocolName = "MQIsdp" - cm.ProtocolVersion = 0x83 - case 0x84: - DEBUG.Println(CLI, "Using MQTT 3.1.1b protocol") - cm.ProtocolName = "MQTT" - cm.ProtocolVersion = 0x84 - default: - DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol") - cm.ProtocolName = "MQTT" - cm.ProtocolVersion = 4 - } - - if err := cm.Write(conn); err != nil { - ERROR.Println(CLI, err) - return packets.ErrNetworkError, false, err - } - - rc, sessionPresent, err := verifyCONNACK(conn) - return rc, sessionPresent, err -} - -// This function is only used for receiving a connack -// when the connection is first started. -// This prevents receiving incoming data while resume -// is in progress if clean session is false. -func verifyCONNACK(conn io.Reader) (byte, bool, error) { - DEBUG.Println(NET, "connect started") - - ca, err := packets.ReadPacket(conn) - if err != nil { - ERROR.Println(NET, "connect got error", err) - return packets.ErrNetworkError, false, err - } - - if ca == nil { - ERROR.Println(NET, "received nil packet") - return packets.ErrNetworkError, false, errors.New("nil CONNACK packet") - } - - msg, ok := ca.(*packets.ConnackPacket) - if !ok { - ERROR.Println(NET, "received msg that was not CONNACK") - return packets.ErrNetworkError, false, errors.New("non-CONNACK first packet received") - } - - DEBUG.Println(NET, "received connack") - return msg.ReturnCode, msg.SessionPresent, nil -} - -// inbound encapsulates the output from startIncoming. -// err - If != nil then an error has occurred -// cp - A control packet received over the network link -type inbound struct { - err error - cp packets.ControlPacket -} - -// startIncoming initiates a goroutine that reads incoming messages off the wire and sends them to the channel (returned). -// If there are any issues with the network connection then the returned channel will be closed and the goroutine will exit -// (so closing the connection will terminate the goroutine) -func startIncoming(conn io.Reader) <-chan inbound { - var err error - var cp packets.ControlPacket - ibound := make(chan inbound) - - DEBUG.Println(NET, "incoming started") - - go func() { - for { - if cp, err = packets.ReadPacket(conn); err != nil { - // We do not want to log the error if it is due to the network connection having been closed - // elsewhere (i.e. after sending DisconnectPacket). Detecting this situation is the subject of - // https://github.com/golang/go/issues/4373 - if !strings.Contains(err.Error(), closedNetConnErrorText) { - ibound <- inbound{err: err} - } - close(ibound) - DEBUG.Println(NET, "incoming complete") - return - } - DEBUG.Println(NET, "startIncoming Received Message") - ibound <- inbound{cp: cp} - } - }() - - return ibound -} - -// incomingComms encapsulates the possible output of the incomingComms routine. If err != nil then an error has occurred and -// the routine will have terminated; otherwise one of the other members should be non-nil -type incomingComms struct { - err error // If non-nil then there has been an error (ignore everything else) - outbound *PacketAndToken // Packet (with token) than needs to be sent out (e.g. an acknowledgement) - incomingPub *packets.PublishPacket // A new publish has been received; this will need to be passed on to our user -} - -// startIncomingComms initiates incoming communications; this includes starting a goroutine to process incoming -// messages. -// Accepts a channel of inbound messages from the store (persisted messages); note this must be closed as soon as -// everything in the store has been sent. -// Returns a channel that will be passed any received packets; this will be closed on a network error (and inboundFromStore closed) -func startIncomingComms(conn io.Reader, - c commsFns, - inboundFromStore <-chan packets.ControlPacket, -) <-chan incomingComms { - ibound := startIncoming(conn) // Start goroutine that reads from network connection - output := make(chan incomingComms) - - DEBUG.Println(NET, "startIncomingComms started") - go func() { - for { - if inboundFromStore == nil && ibound == nil { - close(output) - DEBUG.Println(NET, "startIncomingComms goroutine complete") - return // As soon as ibound is closed we can exit (should have already processed an error) - } - DEBUG.Println(NET, "logic waiting for msg on ibound") - - var msg packets.ControlPacket - var ok bool - select { - case msg, ok = <-inboundFromStore: - if !ok { - DEBUG.Println(NET, "startIncomingComms: inboundFromStore complete") - inboundFromStore = nil // should happen quickly as this is only for persisted messages - continue - } - DEBUG.Println(NET, "startIncomingComms: got msg from store") - case ibMsg, ok := <-ibound: - if !ok { - DEBUG.Println(NET, "startIncomingComms: ibound complete") - ibound = nil - continue - } - DEBUG.Println(NET, "startIncomingComms: got msg on ibound") - // If the inbound comms routine encounters any issues it will send us an error. - if ibMsg.err != nil { - output <- incomingComms{err: ibMsg.err} - continue // Usually the channel will be closed immediately after sending an error but safer that we do not assume this - } - msg = ibMsg.cp - - c.persistInbound(msg) - c.UpdateLastReceived() // Notify keepalive logic that we recently received a packet - } - - switch m := msg.(type) { - case *packets.PingrespPacket: - DEBUG.Println(NET, "startIncomingComms: received pingresp") - c.pingRespReceived() - case *packets.SubackPacket: - DEBUG.Println(NET, "startIncomingComms: received suback, id:", m.MessageID) - token := c.getToken(m.MessageID) - - if t, ok := token.(*SubscribeToken); ok { - DEBUG.Println(NET, "startIncomingComms: granted qoss", m.ReturnCodes) - for i, qos := range m.ReturnCodes { - t.subResult[t.subs[i]] = qos - } - } - - token.flowComplete() - c.freeID(m.MessageID) - case *packets.UnsubackPacket: - DEBUG.Println(NET, "startIncomingComms: received unsuback, id:", m.MessageID) - c.getToken(m.MessageID).flowComplete() - c.freeID(m.MessageID) - case *packets.PublishPacket: - DEBUG.Println(NET, "startIncomingComms: received publish, msgId:", m.MessageID) - output <- incomingComms{incomingPub: m} - case *packets.PubackPacket: - DEBUG.Println(NET, "startIncomingComms: received puback, id:", m.MessageID) - c.getToken(m.MessageID).flowComplete() - c.freeID(m.MessageID) - case *packets.PubrecPacket: - DEBUG.Println(NET, "startIncomingComms: received pubrec, id:", m.MessageID) - prel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket) - prel.MessageID = m.MessageID - output <- incomingComms{outbound: &PacketAndToken{p: prel, t: nil}} - case *packets.PubrelPacket: - DEBUG.Println(NET, "startIncomingComms: received pubrel, id:", m.MessageID) - pc := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket) - pc.MessageID = m.MessageID - c.persistOutbound(pc) - output <- incomingComms{outbound: &PacketAndToken{p: pc, t: nil}} - case *packets.PubcompPacket: - DEBUG.Println(NET, "startIncomingComms: received pubcomp, id:", m.MessageID) - c.getToken(m.MessageID).flowComplete() - c.freeID(m.MessageID) - } - } - }() - return output -} - -// startOutgoingComms initiates a go routine to transmit outgoing packets. -// Pass in an open network connection and channels for outbound messages (including those triggered -// directly from incoming comms). -// Returns a channel that will receive details of any errors (closed when the goroutine exits) -// This function wil only terminate when all input channels are closed -func startOutgoingComms(conn net.Conn, - c commsFns, - oboundp <-chan *PacketAndToken, - obound <-chan *PacketAndToken, - oboundFromIncoming <-chan *PacketAndToken, -) <-chan error { - errChan := make(chan error) - DEBUG.Println(NET, "outgoing started") - - go func() { - for { - DEBUG.Println(NET, "outgoing waiting for an outbound message") - - // This goroutine will only exits when all of the input channels we receive on have been closed. This approach is taken to avoid any - // deadlocks (if the connection goes down there are limited options as to what we can do with anything waiting on us and - // throwing away the packets seems the best option) - if oboundp == nil && obound == nil && oboundFromIncoming == nil { - DEBUG.Println(NET, "outgoing comms stopping") - close(errChan) - return - } - - select { - case pub, ok := <-obound: - if !ok { - obound = nil - continue - } - msg := pub.p.(*packets.PublishPacket) - DEBUG.Println(NET, "obound msg to write", msg.MessageID) - - writeTimeout := c.getWriteTimeOut() - if writeTimeout > 0 { - if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil { - ERROR.Println(NET, "SetWriteDeadline ", err) - } - } - - if err := msg.Write(conn); err != nil { - ERROR.Println(NET, "outgoing obound reporting error ", err) - pub.t.setError(err) - // report error if it's not due to the connection being closed elsewhere - if !strings.Contains(err.Error(), closedNetConnErrorText) { - errChan <- err - } - continue - } - - if writeTimeout > 0 { - // If we successfully wrote, we don't want the timeout to happen during an idle period - // so we reset it to infinite. - if err := conn.SetWriteDeadline(time.Time{}); err != nil { - ERROR.Println(NET, "SetWriteDeadline to 0 ", err) - } - } - - if msg.Qos == 0 { - pub.t.flowComplete() - } - DEBUG.Println(NET, "obound wrote msg, id:", msg.MessageID) - case msg, ok := <-oboundp: - if !ok { - oboundp = nil - continue - } - DEBUG.Println(NET, "obound priority msg to write, type", reflect.TypeOf(msg.p)) - if err := msg.p.Write(conn); err != nil { - ERROR.Println(NET, "outgoing oboundp reporting error ", err) - if msg.t != nil { - msg.t.setError(err) - } - errChan <- err - continue - } - - if _, ok := msg.p.(*packets.DisconnectPacket); ok { - msg.t.(*DisconnectToken).flowComplete() - DEBUG.Println(NET, "outbound wrote disconnect, closing connection") - // As per the MQTT spec "After sending a DISCONNECT Packet the Client MUST close the Network Connection" - // Closing the connection will cause the goroutines to end in sequence (starting with incoming comms) - _ = conn.Close() - } - case msg, ok := <-oboundFromIncoming: // message triggered by an inbound message (PubrecPacket or PubrelPacket) - if !ok { - oboundFromIncoming = nil - continue - } - DEBUG.Println(NET, "obound from incoming msg to write, type", reflect.TypeOf(msg.p), " ID ", msg.p.Details().MessageID) - if err := msg.p.Write(conn); err != nil { - ERROR.Println(NET, "outgoing oboundFromIncoming reporting error", err) - if msg.t != nil { - msg.t.setError(err) - } - errChan <- err - continue - } - } - c.UpdateLastSent() // Record that a packet has been received (for keepalive routine) - } - }() - return errChan -} - -// commsFns provide access to the client state (messageids, requesting disconnection and updating timing) -type commsFns interface { - getToken(id uint16) tokenCompletor // Retrieve the token for the specified messageid (if none then a dummy token must be returned) - freeID(id uint16) // Release the specified messageid (clearing out of any persistent store) - UpdateLastReceived() // Must be called whenever a packet is received - UpdateLastSent() // Must be called whenever a packet is successfully sent - getWriteTimeOut() time.Duration // Return the writetimeout (or 0 if none) - persistOutbound(m packets.ControlPacket) // add the packet to the outbound store - persistInbound(m packets.ControlPacket) // add the packet to the inbound store - pingRespReceived() // Called when a ping response is received -} - -// startComms initiates goroutines that handles communications over the network connection -// Messages will be stored (via commsFns) and deleted from the store as necessary -// It returns two channels: -// -// packets.PublishPacket - Will receive publish packets received over the network. -// Closed when incoming comms routines exit (on shutdown or if network link closed) -// error - Any errors will be sent on this channel. The channel is closed when all comms routines have shut down -// -// Note: The comms routines monitoring oboundp and obound will not shutdown until those channels are both closed. Any messages received between the -// connection being closed and those channels being closed will generate errors (and nothing will be sent). That way the chance of a deadlock is -// minimised. -func startComms(conn net.Conn, // Network connection (must be active) - c commsFns, // getters and setters to enable us to cleanly interact with client - inboundFromStore <-chan packets.ControlPacket, // Inbound packets from the persistence store (should be closed relatively soon after startup) - oboundp <-chan *PacketAndToken, - obound <-chan *PacketAndToken) ( - <-chan *packets.PublishPacket, // Publishpackages received over the network - <-chan error, // Any errors (should generally trigger a disconnect) -) { - // Start inbound comms handler; this needs to be able to transmit messages so we start a go routine to add these to the priority outbound channel - ibound := startIncomingComms(conn, c, inboundFromStore) - outboundFromIncoming := make(chan *PacketAndToken) // Will accept outgoing messages triggered by startIncomingComms (e.g. acknowledgements) - - // Start the outgoing handler. It is important to note that output from startIncomingComms is fed into startOutgoingComms (for ACK's) - oboundErr := startOutgoingComms(conn, c, oboundp, obound, outboundFromIncoming) - DEBUG.Println(NET, "startComms started") - - // Run up go routines to handle the output from the above comms functions - these are handled in separate - // go routines because they can interact (e.g. ibound triggers an ACK to obound which triggers an error) - var wg sync.WaitGroup - wg.Add(2) - - outPublish := make(chan *packets.PublishPacket) - outError := make(chan error) - - // Any messages received get passed to the appropriate channel - go func() { - for ic := range ibound { - if ic.err != nil { - outError <- ic.err - continue - } - if ic.outbound != nil { - outboundFromIncoming <- ic.outbound - continue - } - if ic.incomingPub != nil { - outPublish <- ic.incomingPub - continue - } - ERROR.Println(STR, "startComms received empty incomingComms msg") - } - // Close channels that will not be written to again (allowing other routines to exit) - close(outboundFromIncoming) - close(outPublish) - wg.Done() - }() - - // Any errors will be passed out to our caller - go func() { - for err := range oboundErr { - outError <- err - } - wg.Done() - }() - - // outError is used by both routines so can only be closed when they are both complete - go func() { - wg.Wait() - close(outError) - DEBUG.Println(NET, "startComms closing outError") - }() - - return outPublish, outError -} - -// ackFunc acknowledges a packet -// WARNING the function returned must not be called if the comms routine is shutting down or not running -// (it needs outgoing comms in order to send the acknowledgement). Currently this is only called from -// matchAndDispatch which will be shutdown before the comms are -func ackFunc(oboundP chan *PacketAndToken, persist Store, packet *packets.PublishPacket) func() { - return func() { - switch packet.Qos { - case 2: - pr := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket) - pr.MessageID = packet.MessageID - DEBUG.Println(NET, "putting pubrec msg on obound") - oboundP <- &PacketAndToken{p: pr, t: nil} - DEBUG.Println(NET, "done putting pubrec msg on obound") - case 1: - pa := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket) - pa.MessageID = packet.MessageID - DEBUG.Println(NET, "putting puback msg on obound") - persistOutbound(persist, pa) - oboundP <- &PacketAndToken{p: pa, t: nil} - DEBUG.Println(NET, "done putting puback msg on obound") - case 0: - // do nothing, since there is no need to send an ack packet back - } - } -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/netconn.go b/vendor/github.com/eclipse/paho.mqtt.golang/netconn.go deleted file mode 100644 index f5429e28..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/netconn.go +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - * MAtt Brittan - */ - -package mqtt - -import ( - "crypto/tls" - "errors" - "net" - "net/http" - "net/url" - "os" - "time" - - "golang.org/x/net/proxy" -) - -// -// This just establishes the network connection; once established the type of connection should be irrelevant -// - -// openConnection opens a network connection using the protocol indicated in the URL. -// Does not carry out any MQTT specific handshakes. -func openConnection(uri *url.URL, tlsc *tls.Config, timeout time.Duration, headers http.Header, websocketOptions *WebsocketOptions, dialer *net.Dialer) (net.Conn, error) { - switch uri.Scheme { - case "ws": - dialURI := *uri // #623 - Gorilla Websockets does not accept URL's where uri.User != nil - dialURI.User = nil - conn, err := NewWebsocket(dialURI.String(), nil, timeout, headers, websocketOptions) - return conn, err - case "wss": - dialURI := *uri // #623 - Gorilla Websockets does not accept URL's where uri.User != nil - dialURI.User = nil - conn, err := NewWebsocket(dialURI.String(), tlsc, timeout, headers, websocketOptions) - return conn, err - case "mqtt", "tcp": - allProxy := os.Getenv("all_proxy") - if len(allProxy) == 0 { - conn, err := dialer.Dial("tcp", uri.Host) - if err != nil { - return nil, err - } - return conn, nil - } - proxyDialer := proxy.FromEnvironment() - - conn, err := proxyDialer.Dial("tcp", uri.Host) - if err != nil { - return nil, err - } - return conn, nil - case "unix": - var conn net.Conn - var err error - - // this check is preserved for compatibility with older versions - // which used uri.Host only (it works for local paths, e.g. unix://socket.sock in current dir) - if len(uri.Host) > 0 { - conn, err = dialer.Dial("unix", uri.Host) - } else { - conn, err = dialer.Dial("unix", uri.Path) - } - - if err != nil { - return nil, err - } - return conn, nil - case "ssl", "tls", "mqtts", "mqtt+ssl", "tcps": - allProxy := os.Getenv("all_proxy") - if len(allProxy) == 0 { - conn, err := tls.DialWithDialer(dialer, "tcp", uri.Host, tlsc) - if err != nil { - return nil, err - } - return conn, nil - } - proxyDialer := proxy.FromEnvironment() - conn, err := proxyDialer.Dial("tcp", uri.Host) - if err != nil { - return nil, err - } - - tlsConn := tls.Client(conn, tlsc) - - err = tlsConn.Handshake() - if err != nil { - _ = conn.Close() - return nil, err - } - - return tlsConn, nil - } - return nil, errors.New("unknown protocol") -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/oops.go b/vendor/github.com/eclipse/paho.mqtt.golang/oops.go deleted file mode 100644 index c454aeba..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/oops.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -func chkerr(e error) { - if e != nil { - panic(e) - } -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/options.go b/vendor/github.com/eclipse/paho.mqtt.golang/options.go deleted file mode 100644 index 5aaa7d95..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/options.go +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - * Måns Ansgariusson - */ - -// Portions copyright © 2018 TIBCO Software Inc. - -package mqtt - -import ( - "crypto/tls" - "net" - "net/http" - "net/url" - "strings" - "time" -) - -// CredentialsProvider allows the username and password to be updated -// before reconnecting. It should return the current username and password. -type CredentialsProvider func() (username string, password string) - -// MessageHandler is a callback type which can be set to be -// executed upon the arrival of messages published to topics -// to which the client is subscribed. -type MessageHandler func(Client, Message) - -// ConnectionLostHandler is a callback type which can be set to be -// executed upon an unintended disconnection from the MQTT broker. -// Disconnects caused by calling Disconnect or ForceDisconnect will -// not cause an OnConnectionLost callback to execute. -type ConnectionLostHandler func(Client, error) - -// OnConnectHandler is a callback that is called when the client -// state changes from unconnected/disconnected to connected. Both -// at initial connection and on reconnection -type OnConnectHandler func(Client) - -// ReconnectHandler is invoked prior to reconnecting after -// the initial connection is lost -type ReconnectHandler func(Client, *ClientOptions) - -// ConnectionAttemptHandler is invoked prior to making the initial connection. -type ConnectionAttemptHandler func(broker *url.URL, tlsCfg *tls.Config) *tls.Config - -// OpenConnectionFunc is invoked to establish the underlying network connection -// Its purpose if for custom network transports. -// Does not carry out any MQTT specific handshakes. -type OpenConnectionFunc func(uri *url.URL, options ClientOptions) (net.Conn, error) - -// ClientOptions contains configurable options for an Client. Note that these should be set using the -// relevant methods (e.g. AddBroker) rather than directly. See those functions for information on usage. -// WARNING: Create the below using NewClientOptions unless you have a compelling reason not to. It is easy -// to create a configuration with difficult to trace issues (e.g. Mosquitto 2.0.12+ will reject connections -// with KeepAlive=0 by default). -type ClientOptions struct { - Servers []*url.URL - ClientID string - Username string - Password string - CredentialsProvider CredentialsProvider - CleanSession bool - Order bool - WillEnabled bool - WillTopic string - WillPayload []byte - WillQos byte - WillRetained bool - ProtocolVersion uint - protocolVersionExplicit bool - TLSConfig *tls.Config - KeepAlive int64 // Warning: Some brokers may reject connections with Keepalive = 0. - PingTimeout time.Duration - ConnectTimeout time.Duration - MaxReconnectInterval time.Duration - AutoReconnect bool - ConnectRetryInterval time.Duration - ConnectRetry bool - Store Store - DefaultPublishHandler MessageHandler - OnConnect OnConnectHandler - OnConnectionLost ConnectionLostHandler - OnReconnecting ReconnectHandler - OnConnectAttempt ConnectionAttemptHandler - WriteTimeout time.Duration - MessageChannelDepth uint - ResumeSubs bool - HTTPHeaders http.Header - WebsocketOptions *WebsocketOptions - MaxResumePubInFlight int // // 0 = no limit; otherwise this is the maximum simultaneous messages sent while resuming - Dialer *net.Dialer - CustomOpenConnectionFn OpenConnectionFunc - AutoAckDisabled bool -} - -// NewClientOptions will create a new ClientClientOptions type with some -// default values. -// Port: 1883 -// CleanSession: True -// Order: True (note: it is recommended that this be set to FALSE unless order is important) -// KeepAlive: 30 (seconds) -// ConnectTimeout: 30 (seconds) -// MaxReconnectInterval 10 (minutes) -// AutoReconnect: True -func NewClientOptions() *ClientOptions { - o := &ClientOptions{ - Servers: nil, - ClientID: "", - Username: "", - Password: "", - CleanSession: true, - Order: true, - WillEnabled: false, - WillTopic: "", - WillPayload: nil, - WillQos: 0, - WillRetained: false, - ProtocolVersion: 0, - protocolVersionExplicit: false, - KeepAlive: 30, - PingTimeout: 10 * time.Second, - ConnectTimeout: 30 * time.Second, - MaxReconnectInterval: 10 * time.Minute, - AutoReconnect: true, - ConnectRetryInterval: 30 * time.Second, - ConnectRetry: false, - Store: nil, - OnConnect: nil, - OnConnectionLost: DefaultConnectionLostHandler, - OnConnectAttempt: nil, - WriteTimeout: 0, // 0 represents timeout disabled - ResumeSubs: false, - HTTPHeaders: make(map[string][]string), - WebsocketOptions: &WebsocketOptions{}, - Dialer: &net.Dialer{Timeout: 30 * time.Second}, - CustomOpenConnectionFn: nil, - AutoAckDisabled: false, - } - return o -} - -// AddBroker adds a broker URI to the list of brokers to be used. The format should be -// scheme://host:port -// Where "scheme" is one of "tcp", "ssl", or "ws", "host" is the ip-address (or hostname) -// and "port" is the port on which the broker is accepting connections. -// -// Default values for hostname is "127.0.0.1", for schema is "tcp://". -// -// An example broker URI would look like: tcp://foobar.com:1883 -func (o *ClientOptions) AddBroker(server string) *ClientOptions { - if len(server) > 0 && server[0] == ':' { - server = "127.0.0.1" + server - } - if !strings.Contains(server, "://") { - server = "tcp://" + server - } - brokerURI, err := url.Parse(server) - if err != nil { - ERROR.Println(CLI, "Failed to parse %q broker address: %s", server, err) - return o - } - o.Servers = append(o.Servers, brokerURI) - return o -} - -// SetResumeSubs will enable resuming of stored (un)subscribe messages when connecting -// but not reconnecting if CleanSession is false. Otherwise these messages are discarded. -func (o *ClientOptions) SetResumeSubs(resume bool) *ClientOptions { - o.ResumeSubs = resume - return o -} - -// SetClientID will set the client id to be used by this client when -// connecting to the MQTT broker. According to the MQTT v3.1 specification, -// a client id must be no longer than 23 characters. -func (o *ClientOptions) SetClientID(id string) *ClientOptions { - o.ClientID = id - return o -} - -// SetUsername will set the username to be used by this client when connecting -// to the MQTT broker. Note: without the use of SSL/TLS, this information will -// be sent in plaintext across the wire. -func (o *ClientOptions) SetUsername(u string) *ClientOptions { - o.Username = u - return o -} - -// SetPassword will set the password to be used by this client when connecting -// to the MQTT broker. Note: without the use of SSL/TLS, this information will -// be sent in plaintext across the wire. -func (o *ClientOptions) SetPassword(p string) *ClientOptions { - o.Password = p - return o -} - -// SetCredentialsProvider will set a method to be called by this client when -// connecting to the MQTT broker that provide the current username and password. -// Note: without the use of SSL/TLS, this information will be sent -// in plaintext across the wire. -func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOptions { - o.CredentialsProvider = p - return o -} - -// SetCleanSession will set the "clean session" flag in the connect message -// when this client connects to an MQTT broker. By setting this flag, you are -// indicating that no messages saved by the broker for this client should be -// delivered. Any messages that were going to be sent by this client before -// disconnecting previously but didn't will not be sent upon connecting to the -// broker. -func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions { - o.CleanSession = clean - return o -} - -// SetOrderMatters will set the message routing to guarantee order within -// each QoS level. By default, this value is true. If set to false (recommended), -// this flag indicates that messages can be delivered asynchronously -// from the client to the application and possibly arrive out of order. -// Specifically, the message handler is called in its own go routine. -// Note that setting this to true does not guarantee in-order delivery -// (this is subject to broker settings like "max_inflight_messages=1" in mosquitto) -// and if true then handlers must not block. -func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions { - o.Order = order - return o -} - -// SetTLSConfig will set an SSL/TLS configuration to be used when connecting -// to an MQTT broker. Please read the official Go documentation for more -// information. -func (o *ClientOptions) SetTLSConfig(t *tls.Config) *ClientOptions { - o.TLSConfig = t - return o -} - -// SetStore will set the implementation of the Store interface -// used to provide message persistence in cases where QoS levels -// QoS_ONE or QoS_TWO are used. If no store is provided, then the -// client will use MemoryStore by default. -func (o *ClientOptions) SetStore(s Store) *ClientOptions { - o.Store = s - return o -} - -// SetKeepAlive will set the amount of time (in seconds) that the client -// should wait before sending a PING request to the broker. This will -// allow the client to know that a connection has not been lost with the -// server. -func (o *ClientOptions) SetKeepAlive(k time.Duration) *ClientOptions { - o.KeepAlive = int64(k / time.Second) - return o -} - -// SetPingTimeout will set the amount of time (in seconds) that the client -// will wait after sending a PING request to the broker, before deciding -// that the connection has been lost. Default is 10 seconds. -func (o *ClientOptions) SetPingTimeout(k time.Duration) *ClientOptions { - o.PingTimeout = k - return o -} - -// SetProtocolVersion sets the MQTT version to be used to connect to the -// broker. Legitimate values are currently 3 - MQTT 3.1 or 4 - MQTT 3.1.1 -func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions { - if (pv >= 3 && pv <= 4) || (pv > 0x80) { - o.ProtocolVersion = pv - o.protocolVersionExplicit = true - } - return o -} - -// UnsetWill will cause any set will message to be disregarded. -func (o *ClientOptions) UnsetWill() *ClientOptions { - o.WillEnabled = false - return o -} - -// SetWill accepts a string will message to be set. When the client connects, -// it will give this will message to the broker, which will then publish the -// provided payload (the will) to any clients that are subscribed to the provided -// topic. -func (o *ClientOptions) SetWill(topic string, payload string, qos byte, retained bool) *ClientOptions { - o.SetBinaryWill(topic, []byte(payload), qos, retained) - return o -} - -// SetBinaryWill accepts a []byte will message to be set. When the client connects, -// it will give this will message to the broker, which will then publish the -// provided payload (the will) to any clients that are subscribed to the provided -// topic. -func (o *ClientOptions) SetBinaryWill(topic string, payload []byte, qos byte, retained bool) *ClientOptions { - o.WillEnabled = true - o.WillTopic = topic - o.WillPayload = payload - o.WillQos = qos - o.WillRetained = retained - return o -} - -// SetDefaultPublishHandler sets the MessageHandler that will be called when a message -// is received that does not match any known subscriptions. -// -// If OrderMatters is true (the defaultHandler) then callback must not block or -// call functions within this package that may block (e.g. Publish) other than in -// a new go routine. -// defaultHandler must be safe for concurrent use by multiple goroutines. -func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions { - o.DefaultPublishHandler = defaultHandler - return o -} - -// SetOnConnectHandler sets the function to be called when the client is connected. Both -// at initial connection time and upon automatic reconnect. -func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions { - o.OnConnect = onConn - return o -} - -// SetConnectionLostHandler will set the OnConnectionLost callback to be executed -// in the case where the client unexpectedly loses connection with the MQTT broker. -func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions { - o.OnConnectionLost = onLost - return o -} - -// SetReconnectingHandler sets the OnReconnecting callback to be executed prior -// to the client attempting a reconnect to the MQTT broker. -func (o *ClientOptions) SetReconnectingHandler(cb ReconnectHandler) *ClientOptions { - o.OnReconnecting = cb - return o -} - -// SetConnectionAttemptHandler sets the ConnectionAttemptHandler callback to be executed prior -// to each attempt to connect to an MQTT broker. Returns the *tls.Config that will be used when establishing -// the connection (a copy of the tls.Config from ClientOptions will be passed in along with the broker URL). -// This allows connection specific changes to be made to the *tls.Config. -func (o *ClientOptions) SetConnectionAttemptHandler(onConnectAttempt ConnectionAttemptHandler) *ClientOptions { - o.OnConnectAttempt = onConnectAttempt - return o -} - -// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a -// timeout error. A duration of 0 never times out. Default never times out -func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions { - o.WriteTimeout = t - return o -} - -// SetConnectTimeout limits how long the client will wait when trying to open a connection -// to an MQTT server before timing out. A duration of 0 never times out. -// Default 30 seconds. Currently only operational on TCP/TLS connections. -func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions { - o.ConnectTimeout = t - o.Dialer.Timeout = t - return o -} - -// SetMaxReconnectInterval sets the maximum time that will be waited between reconnection attempts -// when connection is lost -func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions { - o.MaxReconnectInterval = t - return o -} - -// SetAutoReconnect sets whether the automatic reconnection logic should be used -// when the connection is lost, even if disabled the ConnectionLostHandler is still -// called -func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions { - o.AutoReconnect = a - return o -} - -// SetConnectRetryInterval sets the time that will be waited between connection attempts -// when initially connecting if ConnectRetry is TRUE -func (o *ClientOptions) SetConnectRetryInterval(t time.Duration) *ClientOptions { - o.ConnectRetryInterval = t - return o -} - -// SetConnectRetry sets whether the connect function will automatically retry the connection -// in the event of a failure (when true the token returned by the Connect function will -// not complete until the connection is up or it is cancelled) -// If ConnectRetry is true then subscriptions should be requested in OnConnect handler -// Setting this to TRUE permits messages to be published before the connection is established -func (o *ClientOptions) SetConnectRetry(a bool) *ClientOptions { - o.ConnectRetry = a - return o -} - -// SetMessageChannelDepth DEPRECATED The value set here no longer has any effect, this function -// remains so the API is not altered. -func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions { - o.MessageChannelDepth = s - return o -} - -// SetHTTPHeaders sets the additional HTTP headers that will be sent in the WebSocket -// opening handshake. -func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions { - o.HTTPHeaders = h - return o -} - -// SetWebsocketOptions sets the additional websocket options used in a WebSocket connection -func (o *ClientOptions) SetWebsocketOptions(w *WebsocketOptions) *ClientOptions { - o.WebsocketOptions = w - return o -} - -// SetMaxResumePubInFlight sets the maximum simultaneous publish messages that will be sent while resuming. Note that -// this only applies to messages coming from the store (so additional sends may push us over the limit) -// Note that the connect token will not be flagged as complete until all messages have been sent from the -// store. If broker does not respond to messages then resume may not complete. -// This option was put in place because resuming after downtime can saturate low capacity links. -func (o *ClientOptions) SetMaxResumePubInFlight(MaxResumePubInFlight int) *ClientOptions { - o.MaxResumePubInFlight = MaxResumePubInFlight - return o -} - -// SetDialer sets the tcp dialer options used in a tcp connection -func (o *ClientOptions) SetDialer(dialer *net.Dialer) *ClientOptions { - o.Dialer = dialer - return o -} - -// SetCustomOpenConnectionFn replaces the inbuilt function that establishes a network connection with a custom function. -// The passed in function should return an open `net.Conn` or an error (see the existing openConnection function for an example) -// It enables custom networking types in addition to the defaults (tcp, tls, websockets...) -func (o *ClientOptions) SetCustomOpenConnectionFn(customOpenConnectionFn OpenConnectionFunc) *ClientOptions { - if customOpenConnectionFn != nil { - o.CustomOpenConnectionFn = customOpenConnectionFn - } - return o -} - -// SetAutoAckDisabled enables or disables the Automated Acking of Messages received by the handler. -// By default it is set to false. Setting it to true will disable the auto-ack globally. -func (o *ClientOptions) SetAutoAckDisabled(autoAckDisabled bool) *ClientOptions { - o.AutoAckDisabled = autoAckDisabled - return o -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go b/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go deleted file mode 100644 index 10a9e49a..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "crypto/tls" - "net/http" - "net/url" - "time" -) - -// ClientOptionsReader provides an interface for reading ClientOptions after the client has been initialized. -type ClientOptionsReader struct { - options *ClientOptions -} - -// Servers returns a slice of the servers defined in the clientoptions -func (r *ClientOptionsReader) Servers() []*url.URL { - s := make([]*url.URL, len(r.options.Servers)) - - for i, u := range r.options.Servers { - nu := *u - s[i] = &nu - } - - return s -} - -// ResumeSubs returns true if resuming stored (un)sub is enabled -func (r *ClientOptionsReader) ResumeSubs() bool { - s := r.options.ResumeSubs - return s -} - -// ClientID returns the set client id -func (r *ClientOptionsReader) ClientID() string { - s := r.options.ClientID - return s -} - -// Username returns the set username -func (r *ClientOptionsReader) Username() string { - s := r.options.Username - return s -} - -// Password returns the set password -func (r *ClientOptionsReader) Password() string { - s := r.options.Password - return s -} - -// CleanSession returns whether Cleansession is set -func (r *ClientOptionsReader) CleanSession() bool { - s := r.options.CleanSession - return s -} - -func (r *ClientOptionsReader) Order() bool { - s := r.options.Order - return s -} - -func (r *ClientOptionsReader) WillEnabled() bool { - s := r.options.WillEnabled - return s -} - -func (r *ClientOptionsReader) WillTopic() string { - s := r.options.WillTopic - return s -} - -func (r *ClientOptionsReader) WillPayload() []byte { - s := r.options.WillPayload - return s -} - -func (r *ClientOptionsReader) WillQos() byte { - s := r.options.WillQos - return s -} - -func (r *ClientOptionsReader) WillRetained() bool { - s := r.options.WillRetained - return s -} - -func (r *ClientOptionsReader) ProtocolVersion() uint { - s := r.options.ProtocolVersion - return s -} - -func (r *ClientOptionsReader) TLSConfig() *tls.Config { - s := r.options.TLSConfig - return s -} - -func (r *ClientOptionsReader) KeepAlive() time.Duration { - s := time.Duration(r.options.KeepAlive * int64(time.Second)) - return s -} - -func (r *ClientOptionsReader) PingTimeout() time.Duration { - s := r.options.PingTimeout - return s -} - -func (r *ClientOptionsReader) ConnectTimeout() time.Duration { - s := r.options.ConnectTimeout - return s -} - -func (r *ClientOptionsReader) MaxReconnectInterval() time.Duration { - s := r.options.MaxReconnectInterval - return s -} - -func (r *ClientOptionsReader) AutoReconnect() bool { - s := r.options.AutoReconnect - return s -} - -// ConnectRetryInterval returns the delay between retries on the initial connection (if ConnectRetry true) -func (r *ClientOptionsReader) ConnectRetryInterval() time.Duration { - s := r.options.ConnectRetryInterval - return s -} - -// ConnectRetry returns whether the initial connection request will be retried until connection established -func (r *ClientOptionsReader) ConnectRetry() bool { - s := r.options.ConnectRetry - return s -} - -func (r *ClientOptionsReader) WriteTimeout() time.Duration { - s := r.options.WriteTimeout - return s -} - -func (r *ClientOptionsReader) MessageChannelDepth() uint { - s := r.options.MessageChannelDepth - return s -} - -func (r *ClientOptionsReader) HTTPHeaders() http.Header { - h := r.options.HTTPHeaders - return h -} - -// WebsocketOptions returns the currently configured WebSocket options -func (r *ClientOptionsReader) WebsocketOptions() *WebsocketOptions { - s := r.options.WebsocketOptions - return s -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go deleted file mode 100644 index 3a7b98fc..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "bytes" - "fmt" - "io" -) - -// ConnackPacket is an internal representation of the fields of the -// Connack MQTT packet -type ConnackPacket struct { - FixedHeader - SessionPresent bool - ReturnCode byte -} - -func (ca *ConnackPacket) String() string { - return fmt.Sprintf("%s sessionpresent: %t returncode: %d", ca.FixedHeader, ca.SessionPresent, ca.ReturnCode) -} - -func (ca *ConnackPacket) Write(w io.Writer) error { - var body bytes.Buffer - var err error - - body.WriteByte(boolToByte(ca.SessionPresent)) - body.WriteByte(ca.ReturnCode) - ca.FixedHeader.RemainingLength = 2 - packet := ca.FixedHeader.pack() - packet.Write(body.Bytes()) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (ca *ConnackPacket) Unpack(b io.Reader) error { - flags, err := decodeByte(b) - if err != nil { - return err - } - ca.SessionPresent = 1&flags > 0 - ca.ReturnCode, err = decodeByte(b) - - return err -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (ca *ConnackPacket) Details() Details { - return Details{Qos: 0, MessageID: 0} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go deleted file mode 100644 index b4446a55..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "bytes" - "fmt" - "io" -) - -// ConnectPacket is an internal representation of the fields of the -// Connect MQTT packet -type ConnectPacket struct { - FixedHeader - ProtocolName string - ProtocolVersion byte - CleanSession bool - WillFlag bool - WillQos byte - WillRetain bool - UsernameFlag bool - PasswordFlag bool - ReservedBit byte - Keepalive uint16 - - ClientIdentifier string - WillTopic string - WillMessage []byte - Username string - Password []byte -} - -func (c *ConnectPacket) String() string { - var password string - if len(c.Password) > 0 { - password = "" - } - return fmt.Sprintf("%s protocolversion: %d protocolname: %s cleansession: %t willflag: %t WillQos: %d WillRetain: %t Usernameflag: %t Passwordflag: %t keepalive: %d clientId: %s willtopic: %s willmessage: %s Username: %s Password: %s", c.FixedHeader, c.ProtocolVersion, c.ProtocolName, c.CleanSession, c.WillFlag, c.WillQos, c.WillRetain, c.UsernameFlag, c.PasswordFlag, c.Keepalive, c.ClientIdentifier, c.WillTopic, c.WillMessage, c.Username, password) -} - -func (c *ConnectPacket) Write(w io.Writer) error { - var body bytes.Buffer - var err error - - body.Write(encodeString(c.ProtocolName)) - body.WriteByte(c.ProtocolVersion) - body.WriteByte(boolToByte(c.CleanSession)<<1 | boolToByte(c.WillFlag)<<2 | c.WillQos<<3 | boolToByte(c.WillRetain)<<5 | boolToByte(c.PasswordFlag)<<6 | boolToByte(c.UsernameFlag)<<7) - body.Write(encodeUint16(c.Keepalive)) - body.Write(encodeString(c.ClientIdentifier)) - if c.WillFlag { - body.Write(encodeString(c.WillTopic)) - body.Write(encodeBytes(c.WillMessage)) - } - if c.UsernameFlag { - body.Write(encodeString(c.Username)) - } - if c.PasswordFlag { - body.Write(encodeBytes(c.Password)) - } - c.FixedHeader.RemainingLength = body.Len() - packet := c.FixedHeader.pack() - packet.Write(body.Bytes()) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (c *ConnectPacket) Unpack(b io.Reader) error { - var err error - c.ProtocolName, err = decodeString(b) - if err != nil { - return err - } - c.ProtocolVersion, err = decodeByte(b) - if err != nil { - return err - } - options, err := decodeByte(b) - if err != nil { - return err - } - c.ReservedBit = 1 & options - c.CleanSession = 1&(options>>1) > 0 - c.WillFlag = 1&(options>>2) > 0 - c.WillQos = 3 & (options >> 3) - c.WillRetain = 1&(options>>5) > 0 - c.PasswordFlag = 1&(options>>6) > 0 - c.UsernameFlag = 1&(options>>7) > 0 - c.Keepalive, err = decodeUint16(b) - if err != nil { - return err - } - c.ClientIdentifier, err = decodeString(b) - if err != nil { - return err - } - if c.WillFlag { - c.WillTopic, err = decodeString(b) - if err != nil { - return err - } - c.WillMessage, err = decodeBytes(b) - if err != nil { - return err - } - } - if c.UsernameFlag { - c.Username, err = decodeString(b) - if err != nil { - return err - } - } - if c.PasswordFlag { - c.Password, err = decodeBytes(b) - if err != nil { - return err - } - } - - return nil -} - -// Validate performs validation of the fields of a Connect packet -func (c *ConnectPacket) Validate() byte { - if c.PasswordFlag && !c.UsernameFlag { - return ErrRefusedBadUsernameOrPassword - } - if c.ReservedBit != 0 { - // Bad reserved bit - return ErrProtocolViolation - } - if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) { - // Mismatched or unsupported protocol version - return ErrRefusedBadProtocolVersion - } - if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" { - // Bad protocol name - return ErrProtocolViolation - } - if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 { - // Bad size field - return ErrProtocolViolation - } - if len(c.ClientIdentifier) == 0 && !c.CleanSession { - // Bad client identifier - return ErrRefusedIDRejected - } - return Accepted -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (c *ConnectPacket) Details() Details { - return Details{Qos: 0, MessageID: 0} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go deleted file mode 100644 index cf352a37..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "io" -) - -// DisconnectPacket is an internal representation of the fields of the -// Disconnect MQTT packet -type DisconnectPacket struct { - FixedHeader -} - -func (d *DisconnectPacket) String() string { - return d.FixedHeader.String() -} - -func (d *DisconnectPacket) Write(w io.Writer) error { - packet := d.FixedHeader.pack() - _, err := packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (d *DisconnectPacket) Unpack(b io.Reader) error { - return nil -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (d *DisconnectPacket) Details() Details { - return Details{Qos: 0, MessageID: 0} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go deleted file mode 100644 index b2d7ed1b..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" -) - -// ControlPacket defines the interface for structs intended to hold -// decoded MQTT packets, either from being read or before being -// written -type ControlPacket interface { - Write(io.Writer) error - Unpack(io.Reader) error - String() string - Details() Details -} - -// PacketNames maps the constants for each of the MQTT packet types -// to a string representation of their name. -var PacketNames = map[uint8]string{ - 1: "CONNECT", - 2: "CONNACK", - 3: "PUBLISH", - 4: "PUBACK", - 5: "PUBREC", - 6: "PUBREL", - 7: "PUBCOMP", - 8: "SUBSCRIBE", - 9: "SUBACK", - 10: "UNSUBSCRIBE", - 11: "UNSUBACK", - 12: "PINGREQ", - 13: "PINGRESP", - 14: "DISCONNECT", -} - -// Below are the constants assigned to each of the MQTT packet types -const ( - Connect = 1 - Connack = 2 - Publish = 3 - Puback = 4 - Pubrec = 5 - Pubrel = 6 - Pubcomp = 7 - Subscribe = 8 - Suback = 9 - Unsubscribe = 10 - Unsuback = 11 - Pingreq = 12 - Pingresp = 13 - Disconnect = 14 -) - -// Below are the const definitions for error codes returned by -// Connect() -const ( - Accepted = 0x00 - ErrRefusedBadProtocolVersion = 0x01 - ErrRefusedIDRejected = 0x02 - ErrRefusedServerUnavailable = 0x03 - ErrRefusedBadUsernameOrPassword = 0x04 - ErrRefusedNotAuthorised = 0x05 - ErrNetworkError = 0xFE - ErrProtocolViolation = 0xFF -) - -// ConnackReturnCodes is a map of the error codes constants for Connect() -// to a string representation of the error -var ConnackReturnCodes = map[uint8]string{ - 0: "Connection Accepted", - 1: "Connection Refused: Bad Protocol Version", - 2: "Connection Refused: Client Identifier Rejected", - 3: "Connection Refused: Server Unavailable", - 4: "Connection Refused: Username or Password in unknown format", - 5: "Connection Refused: Not Authorised", - 254: "Connection Error", - 255: "Connection Refused: Protocol Violation", -} - -var ( - ErrorRefusedBadProtocolVersion = errors.New("unacceptable protocol version") - ErrorRefusedIDRejected = errors.New("identifier rejected") - ErrorRefusedServerUnavailable = errors.New("server Unavailable") - ErrorRefusedBadUsernameOrPassword = errors.New("bad user name or password") - ErrorRefusedNotAuthorised = errors.New("not Authorized") - ErrorNetworkError = errors.New("network Error") - ErrorProtocolViolation = errors.New("protocol Violation") -) - -// ConnErrors is a map of the errors codes constants for Connect() -// to a Go error -var ConnErrors = map[byte]error{ - Accepted: nil, - ErrRefusedBadProtocolVersion: ErrorRefusedBadProtocolVersion, - ErrRefusedIDRejected: ErrorRefusedIDRejected, - ErrRefusedServerUnavailable: ErrorRefusedServerUnavailable, - ErrRefusedBadUsernameOrPassword: ErrorRefusedBadUsernameOrPassword, - ErrRefusedNotAuthorised: ErrorRefusedNotAuthorised, - ErrNetworkError: ErrorNetworkError, - ErrProtocolViolation: ErrorProtocolViolation, -} - -// ReadPacket takes an instance of an io.Reader (such as net.Conn) and attempts -// to read an MQTT packet from the stream. It returns a ControlPacket -// representing the decoded MQTT packet and an error. One of these returns will -// always be nil, a nil ControlPacket indicating an error occurred. -func ReadPacket(r io.Reader) (ControlPacket, error) { - var fh FixedHeader - b := make([]byte, 1) - - _, err := io.ReadFull(r, b) - if err != nil { - return nil, err - } - - err = fh.unpack(b[0], r) - if err != nil { - return nil, err - } - - cp, err := NewControlPacketWithHeader(fh) - if err != nil { - return nil, err - } - - packetBytes := make([]byte, fh.RemainingLength) - n, err := io.ReadFull(r, packetBytes) - if err != nil { - return nil, err - } - if n != fh.RemainingLength { - return nil, errors.New("failed to read expected data") - } - - err = cp.Unpack(bytes.NewBuffer(packetBytes)) - return cp, err -} - -// NewControlPacket is used to create a new ControlPacket of the type specified -// by packetType, this is usually done by reference to the packet type constants -// defined in packets.go. The newly created ControlPacket is empty and a pointer -// is returned. -func NewControlPacket(packetType byte) ControlPacket { - switch packetType { - case Connect: - return &ConnectPacket{FixedHeader: FixedHeader{MessageType: Connect}} - case Connack: - return &ConnackPacket{FixedHeader: FixedHeader{MessageType: Connack}} - case Disconnect: - return &DisconnectPacket{FixedHeader: FixedHeader{MessageType: Disconnect}} - case Publish: - return &PublishPacket{FixedHeader: FixedHeader{MessageType: Publish}} - case Puback: - return &PubackPacket{FixedHeader: FixedHeader{MessageType: Puback}} - case Pubrec: - return &PubrecPacket{FixedHeader: FixedHeader{MessageType: Pubrec}} - case Pubrel: - return &PubrelPacket{FixedHeader: FixedHeader{MessageType: Pubrel, Qos: 1}} - case Pubcomp: - return &PubcompPacket{FixedHeader: FixedHeader{MessageType: Pubcomp}} - case Subscribe: - return &SubscribePacket{FixedHeader: FixedHeader{MessageType: Subscribe, Qos: 1}} - case Suback: - return &SubackPacket{FixedHeader: FixedHeader{MessageType: Suback}} - case Unsubscribe: - return &UnsubscribePacket{FixedHeader: FixedHeader{MessageType: Unsubscribe, Qos: 1}} - case Unsuback: - return &UnsubackPacket{FixedHeader: FixedHeader{MessageType: Unsuback}} - case Pingreq: - return &PingreqPacket{FixedHeader: FixedHeader{MessageType: Pingreq}} - case Pingresp: - return &PingrespPacket{FixedHeader: FixedHeader{MessageType: Pingresp}} - } - return nil -} - -// NewControlPacketWithHeader is used to create a new ControlPacket of the type -// specified within the FixedHeader that is passed to the function. -// The newly created ControlPacket is empty and a pointer is returned. -func NewControlPacketWithHeader(fh FixedHeader) (ControlPacket, error) { - switch fh.MessageType { - case Connect: - return &ConnectPacket{FixedHeader: fh}, nil - case Connack: - return &ConnackPacket{FixedHeader: fh}, nil - case Disconnect: - return &DisconnectPacket{FixedHeader: fh}, nil - case Publish: - return &PublishPacket{FixedHeader: fh}, nil - case Puback: - return &PubackPacket{FixedHeader: fh}, nil - case Pubrec: - return &PubrecPacket{FixedHeader: fh}, nil - case Pubrel: - return &PubrelPacket{FixedHeader: fh}, nil - case Pubcomp: - return &PubcompPacket{FixedHeader: fh}, nil - case Subscribe: - return &SubscribePacket{FixedHeader: fh}, nil - case Suback: - return &SubackPacket{FixedHeader: fh}, nil - case Unsubscribe: - return &UnsubscribePacket{FixedHeader: fh}, nil - case Unsuback: - return &UnsubackPacket{FixedHeader: fh}, nil - case Pingreq: - return &PingreqPacket{FixedHeader: fh}, nil - case Pingresp: - return &PingrespPacket{FixedHeader: fh}, nil - } - return nil, fmt.Errorf("unsupported packet type 0x%x", fh.MessageType) -} - -// Details struct returned by the Details() function called on -// ControlPackets to present details of the Qos and MessageID -// of the ControlPacket -type Details struct { - Qos byte - MessageID uint16 -} - -// FixedHeader is a struct to hold the decoded information from -// the fixed header of an MQTT ControlPacket -type FixedHeader struct { - MessageType byte - Dup bool - Qos byte - Retain bool - RemainingLength int -} - -func (fh FixedHeader) String() string { - return fmt.Sprintf("%s: dup: %t qos: %d retain: %t rLength: %d", PacketNames[fh.MessageType], fh.Dup, fh.Qos, fh.Retain, fh.RemainingLength) -} - -func boolToByte(b bool) byte { - switch b { - case true: - return 1 - default: - return 0 - } -} - -func (fh *FixedHeader) pack() bytes.Buffer { - var header bytes.Buffer - header.WriteByte(fh.MessageType<<4 | boolToByte(fh.Dup)<<3 | fh.Qos<<1 | boolToByte(fh.Retain)) - header.Write(encodeLength(fh.RemainingLength)) - return header -} - -func (fh *FixedHeader) unpack(typeAndFlags byte, r io.Reader) error { - fh.MessageType = typeAndFlags >> 4 - fh.Dup = (typeAndFlags>>3)&0x01 > 0 - fh.Qos = (typeAndFlags >> 1) & 0x03 - fh.Retain = typeAndFlags&0x01 > 0 - - var err error - fh.RemainingLength, err = decodeLength(r) - return err -} - -func decodeByte(b io.Reader) (byte, error) { - num := make([]byte, 1) - _, err := b.Read(num) - if err != nil { - return 0, err - } - - return num[0], nil -} - -func decodeUint16(b io.Reader) (uint16, error) { - num := make([]byte, 2) - _, err := b.Read(num) - if err != nil { - return 0, err - } - return binary.BigEndian.Uint16(num), nil -} - -func encodeUint16(num uint16) []byte { - bytesResult := make([]byte, 2) - binary.BigEndian.PutUint16(bytesResult, num) - return bytesResult -} - -func encodeString(field string) []byte { - return encodeBytes([]byte(field)) -} - -func decodeString(b io.Reader) (string, error) { - buf, err := decodeBytes(b) - return string(buf), err -} - -func decodeBytes(b io.Reader) ([]byte, error) { - fieldLength, err := decodeUint16(b) - if err != nil { - return nil, err - } - - field := make([]byte, fieldLength) - _, err = b.Read(field) - if err != nil { - return nil, err - } - - return field, nil -} - -func encodeBytes(field []byte) []byte { - fieldLength := make([]byte, 2) - binary.BigEndian.PutUint16(fieldLength, uint16(len(field))) - return append(fieldLength, field...) -} - -func encodeLength(length int) []byte { - var encLength []byte - for { - digit := byte(length % 128) - length /= 128 - if length > 0 { - digit |= 0x80 - } - encLength = append(encLength, digit) - if length == 0 { - break - } - } - return encLength -} - -func decodeLength(r io.Reader) (int, error) { - var rLength uint32 - var multiplier uint32 - b := make([]byte, 1) - for multiplier < 27 { // fix: Infinite '(digit & 128) == 1' will cause the dead loop - _, err := io.ReadFull(r, b) - if err != nil { - return 0, err - } - - digit := b[0] - rLength |= uint32(digit&127) << multiplier - if (digit & 128) == 0 { - break - } - multiplier += 7 - } - return int(rLength), nil -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go deleted file mode 100644 index cd52948e..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "io" -) - -// PingreqPacket is an internal representation of the fields of the -// Pingreq MQTT packet -type PingreqPacket struct { - FixedHeader -} - -func (pr *PingreqPacket) String() string { - return pr.FixedHeader.String() -} - -func (pr *PingreqPacket) Write(w io.Writer) error { - packet := pr.FixedHeader.pack() - _, err := packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (pr *PingreqPacket) Unpack(b io.Reader) error { - return nil -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (pr *PingreqPacket) Details() Details { - return Details{Qos: 0, MessageID: 0} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go deleted file mode 100644 index d7becdf2..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "io" -) - -// PingrespPacket is an internal representation of the fields of the -// Pingresp MQTT packet -type PingrespPacket struct { - FixedHeader -} - -func (pr *PingrespPacket) String() string { - return pr.FixedHeader.String() -} - -func (pr *PingrespPacket) Write(w io.Writer) error { - packet := pr.FixedHeader.pack() - _, err := packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (pr *PingrespPacket) Unpack(b io.Reader) error { - return nil -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (pr *PingrespPacket) Details() Details { - return Details{Qos: 0, MessageID: 0} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go deleted file mode 100644 index f6e727ec..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "fmt" - "io" -) - -// PubackPacket is an internal representation of the fields of the -// Puback MQTT packet -type PubackPacket struct { - FixedHeader - MessageID uint16 -} - -func (pa *PubackPacket) String() string { - return fmt.Sprintf("%s MessageID: %d", pa.FixedHeader, pa.MessageID) -} - -func (pa *PubackPacket) Write(w io.Writer) error { - var err error - pa.FixedHeader.RemainingLength = 2 - packet := pa.FixedHeader.pack() - packet.Write(encodeUint16(pa.MessageID)) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (pa *PubackPacket) Unpack(b io.Reader) error { - var err error - pa.MessageID, err = decodeUint16(b) - - return err -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (pa *PubackPacket) Details() Details { - return Details{Qos: pa.Qos, MessageID: pa.MessageID} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go deleted file mode 100644 index 84a1af5d..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "fmt" - "io" -) - -// PubcompPacket is an internal representation of the fields of the -// Pubcomp MQTT packet -type PubcompPacket struct { - FixedHeader - MessageID uint16 -} - -func (pc *PubcompPacket) String() string { - return fmt.Sprintf("%s MessageID: %d", pc.FixedHeader, pc.MessageID) -} - -func (pc *PubcompPacket) Write(w io.Writer) error { - var err error - pc.FixedHeader.RemainingLength = 2 - packet := pc.FixedHeader.pack() - packet.Write(encodeUint16(pc.MessageID)) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (pc *PubcompPacket) Unpack(b io.Reader) error { - var err error - pc.MessageID, err = decodeUint16(b) - - return err -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (pc *PubcompPacket) Details() Details { - return Details{Qos: pc.Qos, MessageID: pc.MessageID} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go deleted file mode 100644 index 9fba5df8..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "bytes" - "fmt" - "io" -) - -// PublishPacket is an internal representation of the fields of the -// Publish MQTT packet -type PublishPacket struct { - FixedHeader - TopicName string - MessageID uint16 - Payload []byte -} - -func (p *PublishPacket) String() string { - return fmt.Sprintf("%s topicName: %s MessageID: %d payload: %s", p.FixedHeader, p.TopicName, p.MessageID, string(p.Payload)) -} - -func (p *PublishPacket) Write(w io.Writer) error { - var body bytes.Buffer - var err error - - body.Write(encodeString(p.TopicName)) - if p.Qos > 0 { - body.Write(encodeUint16(p.MessageID)) - } - p.FixedHeader.RemainingLength = body.Len() + len(p.Payload) - packet := p.FixedHeader.pack() - packet.Write(body.Bytes()) - packet.Write(p.Payload) - _, err = w.Write(packet.Bytes()) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (p *PublishPacket) Unpack(b io.Reader) error { - var payloadLength = p.FixedHeader.RemainingLength - var err error - p.TopicName, err = decodeString(b) - if err != nil { - return err - } - - if p.Qos > 0 { - p.MessageID, err = decodeUint16(b) - if err != nil { - return err - } - payloadLength -= len(p.TopicName) + 4 - } else { - payloadLength -= len(p.TopicName) + 2 - } - if payloadLength < 0 { - return fmt.Errorf("error unpacking publish, payload length < 0") - } - p.Payload = make([]byte, payloadLength) - _, err = b.Read(p.Payload) - - return err -} - -// Copy creates a new PublishPacket with the same topic and payload -// but an empty fixed header, useful for when you want to deliver -// a message with different properties such as Qos but the same -// content -func (p *PublishPacket) Copy() *PublishPacket { - newP := NewControlPacket(Publish).(*PublishPacket) - newP.TopicName = p.TopicName - newP.Payload = p.Payload - - return newP -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (p *PublishPacket) Details() Details { - return Details{Qos: p.Qos, MessageID: p.MessageID} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go deleted file mode 100644 index da9ed2a4..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "fmt" - "io" -) - -// PubrecPacket is an internal representation of the fields of the -// Pubrec MQTT packet -type PubrecPacket struct { - FixedHeader - MessageID uint16 -} - -func (pr *PubrecPacket) String() string { - return fmt.Sprintf("%s MessageID: %d", pr.FixedHeader, pr.MessageID) -} - -func (pr *PubrecPacket) Write(w io.Writer) error { - var err error - pr.FixedHeader.RemainingLength = 2 - packet := pr.FixedHeader.pack() - packet.Write(encodeUint16(pr.MessageID)) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (pr *PubrecPacket) Unpack(b io.Reader) error { - var err error - pr.MessageID, err = decodeUint16(b) - - return err -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (pr *PubrecPacket) Details() Details { - return Details{Qos: pr.Qos, MessageID: pr.MessageID} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go deleted file mode 100644 index f418ff86..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "fmt" - "io" -) - -// PubrelPacket is an internal representation of the fields of the -// Pubrel MQTT packet -type PubrelPacket struct { - FixedHeader - MessageID uint16 -} - -func (pr *PubrelPacket) String() string { - return fmt.Sprintf("%s MessageID: %d", pr.FixedHeader, pr.MessageID) -} - -func (pr *PubrelPacket) Write(w io.Writer) error { - var err error - pr.FixedHeader.RemainingLength = 2 - packet := pr.FixedHeader.pack() - packet.Write(encodeUint16(pr.MessageID)) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (pr *PubrelPacket) Unpack(b io.Reader) error { - var err error - pr.MessageID, err = decodeUint16(b) - - return err -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (pr *PubrelPacket) Details() Details { - return Details{Qos: pr.Qos, MessageID: pr.MessageID} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go deleted file mode 100644 index 261cf21c..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "bytes" - "fmt" - "io" -) - -// SubackPacket is an internal representation of the fields of the -// Suback MQTT packet -type SubackPacket struct { - FixedHeader - MessageID uint16 - ReturnCodes []byte -} - -func (sa *SubackPacket) String() string { - return fmt.Sprintf("%s MessageID: %d", sa.FixedHeader, sa.MessageID) -} - -func (sa *SubackPacket) Write(w io.Writer) error { - var body bytes.Buffer - var err error - body.Write(encodeUint16(sa.MessageID)) - body.Write(sa.ReturnCodes) - sa.FixedHeader.RemainingLength = body.Len() - packet := sa.FixedHeader.pack() - packet.Write(body.Bytes()) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (sa *SubackPacket) Unpack(b io.Reader) error { - var qosBuffer bytes.Buffer - var err error - sa.MessageID, err = decodeUint16(b) - if err != nil { - return err - } - - _, err = qosBuffer.ReadFrom(b) - if err != nil { - return err - } - sa.ReturnCodes = qosBuffer.Bytes() - - return nil -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (sa *SubackPacket) Details() Details { - return Details{Qos: 0, MessageID: sa.MessageID} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go deleted file mode 100644 index 313bf5a2..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "bytes" - "fmt" - "io" -) - -// SubscribePacket is an internal representation of the fields of the -// Subscribe MQTT packet -type SubscribePacket struct { - FixedHeader - MessageID uint16 - Topics []string - Qoss []byte -} - -func (s *SubscribePacket) String() string { - return fmt.Sprintf("%s MessageID: %d topics: %s", s.FixedHeader, s.MessageID, s.Topics) -} - -func (s *SubscribePacket) Write(w io.Writer) error { - var body bytes.Buffer - var err error - - body.Write(encodeUint16(s.MessageID)) - for i, topic := range s.Topics { - body.Write(encodeString(topic)) - body.WriteByte(s.Qoss[i]) - } - s.FixedHeader.RemainingLength = body.Len() - packet := s.FixedHeader.pack() - packet.Write(body.Bytes()) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (s *SubscribePacket) Unpack(b io.Reader) error { - var err error - s.MessageID, err = decodeUint16(b) - if err != nil { - return err - } - payloadLength := s.FixedHeader.RemainingLength - 2 - for payloadLength > 0 { - topic, err := decodeString(b) - if err != nil { - return err - } - s.Topics = append(s.Topics, topic) - qos, err := decodeByte(b) - if err != nil { - return err - } - s.Qoss = append(s.Qoss, qos) - payloadLength -= 2 + len(topic) + 1 // 2 bytes of string length, plus string, plus 1 byte for Qos - } - - return nil -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (s *SubscribePacket) Details() Details { - return Details{Qos: 1, MessageID: s.MessageID} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go deleted file mode 100644 index acdd400a..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "fmt" - "io" -) - -// UnsubackPacket is an internal representation of the fields of the -// Unsuback MQTT packet -type UnsubackPacket struct { - FixedHeader - MessageID uint16 -} - -func (ua *UnsubackPacket) String() string { - return fmt.Sprintf("%s MessageID: %d", ua.FixedHeader, ua.MessageID) -} - -func (ua *UnsubackPacket) Write(w io.Writer) error { - var err error - ua.FixedHeader.RemainingLength = 2 - packet := ua.FixedHeader.pack() - packet.Write(encodeUint16(ua.MessageID)) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (ua *UnsubackPacket) Unpack(b io.Reader) error { - var err error - ua.MessageID, err = decodeUint16(b) - - return err -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (ua *UnsubackPacket) Details() Details { - return Details{Qos: 0, MessageID: ua.MessageID} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go deleted file mode 100644 index 54d06aa2..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package packets - -import ( - "bytes" - "fmt" - "io" -) - -// UnsubscribePacket is an internal representation of the fields of the -// Unsubscribe MQTT packet -type UnsubscribePacket struct { - FixedHeader - MessageID uint16 - Topics []string -} - -func (u *UnsubscribePacket) String() string { - return fmt.Sprintf("%s MessageID: %d", u.FixedHeader, u.MessageID) -} - -func (u *UnsubscribePacket) Write(w io.Writer) error { - var body bytes.Buffer - var err error - body.Write(encodeUint16(u.MessageID)) - for _, topic := range u.Topics { - body.Write(encodeString(topic)) - } - u.FixedHeader.RemainingLength = body.Len() - packet := u.FixedHeader.pack() - packet.Write(body.Bytes()) - _, err = packet.WriteTo(w) - - return err -} - -// Unpack decodes the details of a ControlPacket after the fixed -// header has been read -func (u *UnsubscribePacket) Unpack(b io.Reader) error { - var err error - u.MessageID, err = decodeUint16(b) - if err != nil { - return err - } - - for topic, err := decodeString(b); err == nil && topic != ""; topic, err = decodeString(b) { - u.Topics = append(u.Topics, topic) - } - - return err -} - -// Details returns a Details struct containing the Qos and -// MessageID of this ControlPacket -func (u *UnsubscribePacket) Details() Details { - return Details{Qos: 1, MessageID: u.MessageID} -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/ping.go b/vendor/github.com/eclipse/paho.mqtt.golang/ping.go deleted file mode 100644 index 91cd3dec..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/ping.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "errors" - "io" - "sync/atomic" - "time" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -// keepalive - Send ping when connection unused for set period -// connection passed in to avoid race condition on shutdown -func keepalive(c *client, conn io.Writer) { - defer c.workers.Done() - DEBUG.Println(PNG, "keepalive starting") - var checkInterval time.Duration - var pingSent time.Time - - if c.options.KeepAlive > 10 { - checkInterval = 5 * time.Second - } else { - checkInterval = time.Duration(c.options.KeepAlive) * time.Second / 2 - } - - intervalTicker := time.NewTicker(checkInterval) - defer intervalTicker.Stop() - - for { - select { - case <-c.stop: - DEBUG.Println(PNG, "keepalive stopped") - return - case <-intervalTicker.C: - lastSent := c.lastSent.Load().(time.Time) - lastReceived := c.lastReceived.Load().(time.Time) - - DEBUG.Println(PNG, "ping check", time.Since(lastSent).Seconds()) - if time.Since(lastSent) >= time.Duration(c.options.KeepAlive*int64(time.Second)) || time.Since(lastReceived) >= time.Duration(c.options.KeepAlive*int64(time.Second)) { - if atomic.LoadInt32(&c.pingOutstanding) == 0 { - DEBUG.Println(PNG, "keepalive sending ping") - ping := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket) - // We don't want to wait behind large messages being sent, the `Write` call - // will block until it is able to send the packet. - atomic.StoreInt32(&c.pingOutstanding, 1) - if err := ping.Write(conn); err != nil { - ERROR.Println(PNG, err) - } - c.lastSent.Store(time.Now()) - pingSent = time.Now() - } - } - if atomic.LoadInt32(&c.pingOutstanding) > 0 && time.Since(pingSent) >= c.options.PingTimeout { - CRITICAL.Println(PNG, "pingresp not received, disconnecting") - c.internalConnLost(errors.New("pingresp not received, disconnecting")) // no harm in calling this if the connection is already down (or shutdown is in progress) - return - } - } - } -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/router.go b/vendor/github.com/eclipse/paho.mqtt.golang/router.go deleted file mode 100644 index bd05a0c0..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/router.go +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "container/list" - "strings" - "sync" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -// route is a type which associates MQTT Topic strings with a -// callback to be executed upon the arrival of a message associated -// with a subscription to that topic. -type route struct { - topic string - callback MessageHandler -} - -// match takes a slice of strings which represent the route being tested having been split on '/' -// separators, and a slice of strings representing the topic string in the published message, similarly -// split. -// The function determines if the topic string matches the route according to the MQTT topic rules -// and returns a boolean of the outcome -func match(route []string, topic []string) bool { - if len(route) == 0 { - return len(topic) == 0 - } - - if len(topic) == 0 { - return route[0] == "#" - } - - if route[0] == "#" { - return true - } - - if (route[0] == "+") || (route[0] == topic[0]) { - return match(route[1:], topic[1:]) - } - return false -} - -func routeIncludesTopic(route, topic string) bool { - return match(routeSplit(route), strings.Split(topic, "/")) -} - -// removes $share and sharename when splitting the route to allow -// shared subscription routes to correctly match the topic -func routeSplit(route string) []string { - var result []string - if strings.HasPrefix(route, "$share") { - result = strings.Split(route, "/")[2:] - } else { - result = strings.Split(route, "/") - } - return result -} - -// match takes the topic string of the published message and does a basic compare to the -// string of the current Route, if they match it returns true -func (r *route) match(topic string) bool { - return r.topic == topic || routeIncludesTopic(r.topic, topic) -} - -type router struct { - sync.RWMutex - routes *list.List - defaultHandler MessageHandler - messages chan *packets.PublishPacket -} - -// newRouter returns a new instance of a Router and channel which can be used to tell the Router -// to stop -func newRouter() *router { - router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket)} - return router -} - -// addRoute takes a topic string and MessageHandler callback. It looks in the current list of -// routes to see if there is already a matching Route. If there is it replaces the current -// callback with the new one. If not it add a new entry to the list of Routes. -func (r *router) addRoute(topic string, callback MessageHandler) { - r.Lock() - defer r.Unlock() - for e := r.routes.Front(); e != nil; e = e.Next() { - if e.Value.(*route).topic == topic { - r := e.Value.(*route) - r.callback = callback - return - } - } - r.routes.PushBack(&route{topic: topic, callback: callback}) -} - -// deleteRoute takes a route string, looks for a matching Route in the list of Routes. If -// found it removes the Route from the list. -func (r *router) deleteRoute(topic string) { - r.Lock() - defer r.Unlock() - for e := r.routes.Front(); e != nil; e = e.Next() { - if e.Value.(*route).topic == topic { - r.routes.Remove(e) - return - } - } -} - -// setDefaultHandler assigns a default callback that will be called if no matching Route -// is found for an incoming Publish. -func (r *router) setDefaultHandler(handler MessageHandler) { - r.Lock() - defer r.Unlock() - r.defaultHandler = handler -} - -// matchAndDispatch takes a channel of Message pointers as input and starts a go routine that -// takes messages off the channel, matches them against the internal route list and calls the -// associated callback (or the defaultHandler, if one exists and no other route matched). If -// anything is sent down the stop channel the function will end. -func (r *router) matchAndDispatch(messages <-chan *packets.PublishPacket, order bool, client *client) <-chan *PacketAndToken { - var wg sync.WaitGroup - ackOutChan := make(chan *PacketAndToken) // Channel returned to caller; closed when messages channel closed - var ackInChan chan *PacketAndToken // ACKs generated by ackFunc get put onto this channel - - stopAckCopy := make(chan struct{}) // Closure requests stop of go routine copying ackInChan to ackOutChan - ackCopyStopped := make(chan struct{}) // Closure indicates that it is safe to close ackOutChan - goRoutinesDone := make(chan struct{}) // closed on wg.Done() - if order { - ackInChan = ackOutChan // When order = true no go routines are used so safe to use one channel and close when done - } else { - // When order = false ACK messages are sent in go routines so ackInChan cannot be closed until all goroutines done - ackInChan = make(chan *PacketAndToken) - go func() { // go routine to copy from ackInChan to ackOutChan until stopped - for { - select { - case a := <-ackInChan: - ackOutChan <- a - case <-stopAckCopy: - close(ackCopyStopped) // Signal main go routine that it is safe to close ackOutChan - for { - select { - case <-ackInChan: // drain ackInChan to ensure all goRoutines can complete cleanly (ACK dropped) - DEBUG.Println(ROU, "matchAndDispatch received acknowledgment after processing stopped (ACK dropped).") - case <-goRoutinesDone: - close(ackInChan) // Nothing further should be sent (a panic is probably better than silent failure) - DEBUG.Println(ROU, "matchAndDispatch order=false copy goroutine exiting.") - return - } - } - } - } - }() - } - - go func() { // Main go routine handling inbound messages - for message := range messages { - // DEBUG.Println(ROU, "matchAndDispatch received message") - sent := false - r.RLock() - m := messageFromPublish(message, ackFunc(ackInChan, client.persist, message)) - var handlers []MessageHandler - for e := r.routes.Front(); e != nil; e = e.Next() { - if e.Value.(*route).match(message.TopicName) { - if order { - handlers = append(handlers, e.Value.(*route).callback) - } else { - hd := e.Value.(*route).callback - wg.Add(1) - go func() { - hd(client, m) - if !client.options.AutoAckDisabled { - m.Ack() - } - wg.Done() - }() - } - sent = true - } - } - if !sent { - if r.defaultHandler != nil { - if order { - handlers = append(handlers, r.defaultHandler) - } else { - wg.Add(1) - go func() { - r.defaultHandler(client, m) - if !client.options.AutoAckDisabled { - m.Ack() - } - wg.Done() - }() - } - } else { - DEBUG.Println(ROU, "matchAndDispatch received message and no handler was available. Message will NOT be acknowledged.") - } - } - r.RUnlock() - for _, handler := range handlers { - handler(client, m) - if !client.options.AutoAckDisabled { - m.Ack() - } - } - // DEBUG.Println(ROU, "matchAndDispatch handled message") - } - if order { - close(ackOutChan) - } else { // Ensure that nothing further will be written to ackOutChan before closing it - close(stopAckCopy) - <-ackCopyStopped - close(ackOutChan) - go func() { - wg.Wait() // Note: If this remains running then the user has handlers that are not returning - close(goRoutinesDone) - }() - } - DEBUG.Println(ROU, "matchAndDispatch exiting") - }() - return ackOutChan -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/status.go b/vendor/github.com/eclipse/paho.mqtt.golang/status.go deleted file mode 100644 index d25fbf50..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/status.go +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - * Matt Brittan - */ - -package mqtt - -import ( - "errors" - "sync" -) - -// Status - Manage the connection status - -// Multiple go routines will want to access/set this. Previously status was implemented as a `uint32` and updated -// with a mixture of atomic functions and a mutex (leading to some deadlock type issues that were very hard to debug). - -// In this new implementation `connectionStatus` takes over managing the state and provides functions that allow the -// client to request a move to a particular state (it may reject these requests!). In some cases the 'state' is -// transitory, for example `connecting`, in those cases a function will be returned that allows the client to move -// to a more static state (`disconnected` or `connected`). - -// This "belts-and-braces" may be a little over the top but issues with the status have caused a number of difficult -// to trace bugs in the past and the likelihood that introducing a new system would introduce bugs seemed high! -// I have written this in a way that should make it very difficult to misuse it (but it does make things a little -// complex with functions returning functions that return functions!). - -type status uint32 - -const ( - disconnected status = iota // default (nil) status is disconnected - disconnecting // Transitioning from one of the below states back to disconnected - connecting - reconnecting - connected -) - -// String simplify output of statuses -func (s status) String() string { - switch s { - case disconnected: - return "disconnected" - case disconnecting: - return "disconnecting" - case connecting: - return "connecting" - case reconnecting: - return "reconnecting" - case connected: - return "connected" - default: - return "invalid" - } -} - -type connCompletedFn func(success bool) error -type disconnectCompletedFn func() -type connectionLostHandledFn func(bool) (connCompletedFn, error) - -/* State transitions - -static states are `disconnected` and `connected`. For all other states a process will hold a function that will move -the state to one of those. That function effectively owns the state and any other changes must not proceed until it -completes. One exception to that is that the state can always be moved to `disconnecting` which provides a signal that -transitions to `connected` will be rejected (this is required because a Disconnect can be requested while in the -Connecting state). - -# Basic Operations - -The standard workflows are: - -disconnected -> `Connecting()` -> connecting -> `connCompletedFn(true)` -> connected -connected -> `Disconnecting()` -> disconnecting -> `disconnectCompletedFn()` -> disconnected -connected -> `ConnectionLost(false)` -> disconnecting -> `connectionLostHandledFn(true/false)` -> disconnected -connected -> `ConnectionLost(true)` -> disconnecting -> `connectionLostHandledFn(true)` -> connected - -Unfortunately the above workflows are complicated by the fact that `Disconnecting()` or `ConnectionLost()` may, -potentially, be called at any time (i.e. whilst in the middle of transitioning between states). If this happens: - -* The state will be set to disconnecting (which will prevent any request to move the status to connected) -* The call to `Disconnecting()`/`ConnectionLost()` will block until the previously active call completes and then - handle the disconnection. - -Reading the tests (unit_status_test.go) might help understand these rules. -*/ - -var ( - errAbortConnection = errors.New("disconnect called whist connection attempt in progress") - errAlreadyConnectedOrReconnecting = errors.New("status is already connected or reconnecting") - errStatusMustBeDisconnected = errors.New("status can only transition to connecting from disconnected") - errAlreadyDisconnected = errors.New("status is already disconnected") - errDisconnectionRequested = errors.New("disconnection was requested whilst the action was in progress") - errDisconnectionInProgress = errors.New("disconnection already in progress") - errAlreadyHandlingConnectionLoss = errors.New("status is already Connection Lost") - errConnLossWhileDisconnecting = errors.New("connection status is disconnecting so loss of connection is expected") -) - -// connectionStatus encapsulates, and protects, the connection status. -type connectionStatus struct { - sync.RWMutex // Protects the variables below - status status - willReconnect bool // only used when status == disconnecting. Indicates that an attempt will be made to reconnect (allows us to abort that) - - // Some statuses are transitional (e.g. connecting, connectionLost, reconnecting, disconnecting), that is, whatever - // process moves us into that status will move us out of it when an action is complete. Sometimes other users - // will need to know when the action is complete (e.g. the user calls `Disconnect()` whilst the status is - // `connecting`). `actionCompleted` will be set whenever we move into one of the above statues and the channel - // returned to anything else requesting a status change. The channel will be closed when the operation is complete. - actionCompleted chan struct{} // Only valid whilst status is Connecting or Reconnecting; will be closed when connection completed (success or failure) -} - -// ConnectionStatus returns the connection status. -// WARNING: the status may change at any time so users should not assume they are the only goroutine touching this -func (c *connectionStatus) ConnectionStatus() status { - c.RLock() - defer c.RUnlock() - return c.status -} - -// ConnectionStatusRetry returns the connection status and retry flag (indicates that we expect to reconnect). -// WARNING: the status may change at any time so users should not assume they are the only goroutine touching this -func (c *connectionStatus) ConnectionStatusRetry() (status, bool) { - c.RLock() - defer c.RUnlock() - return c.status, c.willReconnect -} - -// Connecting - Changes the status to connecting if that is a permitted operation -// Will do nothing unless the current status is disconnected -// Returns a function that MUST be called when the operation is complete (pass in true if successful) -func (c *connectionStatus) Connecting() (connCompletedFn, error) { - c.Lock() - defer c.Unlock() - // Calling Connect when already connecting (or if reconnecting) may not always be considered an error - if c.status == connected || c.status == reconnecting { - return nil, errAlreadyConnectedOrReconnecting - } - if c.status != disconnected { - return nil, errStatusMustBeDisconnected - } - c.status = connecting - c.actionCompleted = make(chan struct{}) - return c.connected, nil -} - -// connected is an internal function (it is returned by functions that set the status to connecting or reconnecting, -// calling it completes the operation). `success` is used to indicate whether the operation was successfully completed. -func (c *connectionStatus) connected(success bool) error { - c.Lock() - defer func() { - close(c.actionCompleted) // Alert anything waiting on the connection process to complete - c.actionCompleted = nil // Be tidy - c.Unlock() - }() - - // Status may have moved to disconnecting in the interim (i.e. at users request) - if c.status == disconnecting { - return errAbortConnection - } - if success { - c.status = connected - } else { - c.status = disconnected - } - return nil -} - -// Disconnecting - should be called when beginning the disconnection process (cleanup etc.). -// Can be called from ANY status and the end result will always be a status of disconnected -// Note that if a connection/reconnection attempt is in progress this function will set the status to `disconnecting` -// then block until the connection process completes (or aborts). -// Returns a function that MUST be called when the operation is complete (assumed to always be successful!) -func (c *connectionStatus) Disconnecting() (disconnectCompletedFn, error) { - c.Lock() - if c.status == disconnected { - c.Unlock() - return nil, errAlreadyDisconnected // May not always be treated as an error - } - if c.status == disconnecting { // Need to wait for existing process to complete - c.willReconnect = false // Ensure that the existing disconnect process will not reconnect - disConnectDone := c.actionCompleted - c.Unlock() - <-disConnectDone // Wait for existing operation to complete - return nil, errAlreadyDisconnected // Well we are now! - } - - prevStatus := c.status - c.status = disconnecting - - // We may need to wait for connection/reconnection process to complete (they should regularly check the status) - if prevStatus == connecting || prevStatus == reconnecting { - connectDone := c.actionCompleted - c.Unlock() // Safe because the only way to leave the disconnecting status is via this function - <-connectDone - - if prevStatus == reconnecting && !c.willReconnect { - return nil, errAlreadyDisconnected // Following connectionLost process we will be disconnected - } - c.Lock() - } - c.actionCompleted = make(chan struct{}) - c.Unlock() - return c.disconnectionCompleted, nil -} - -// disconnectionCompleted is an internal function (it is returned by functions that set the status to disconnecting) -func (c *connectionStatus) disconnectionCompleted() { - c.Lock() - defer c.Unlock() - c.status = disconnected - close(c.actionCompleted) // Alert anything waiting on the connection process to complete - c.actionCompleted = nil -} - -// ConnectionLost - should be called when the connection is lost. -// This really only differs from Disconnecting in that we may transition into a reconnection (but that could be -// cancelled something else calls Disconnecting in the meantime). -// The returned function should be called when cleanup is completed. It will return a function to be called when -// reconnect completes (or nil if no reconnect requested/disconnect called in the interim). -// Note: This function may block if a connection is in progress (the move to connected will be rejected) -func (c *connectionStatus) ConnectionLost(willReconnect bool) (connectionLostHandledFn, error) { - c.Lock() - defer c.Unlock() - if c.status == disconnected { - return nil, errAlreadyDisconnected - } - if c.status == disconnecting { // its expected that connection lost will be called during the disconnection process - return nil, errDisconnectionInProgress - } - - c.willReconnect = willReconnect - prevStatus := c.status - c.status = disconnecting - - // There is a slight possibility that a connection attempt is in progress (connection up and goroutines started but - // status not yet changed). By changing the status we ensure that process will exit cleanly - if prevStatus == connecting || prevStatus == reconnecting { - connectDone := c.actionCompleted - c.Unlock() // Safe because the only way to leave the disconnecting status is via this function - <-connectDone - c.Lock() - if !willReconnect { - // In this case the connection will always be aborted so there is nothing more for us to do - return nil, errAlreadyDisconnected - } - } - c.actionCompleted = make(chan struct{}) - - return c.getConnectionLostHandler(willReconnect), nil -} - -// getConnectionLostHandler is an internal function. It returns the function to be returned by ConnectionLost -func (c *connectionStatus) getConnectionLostHandler(reconnectRequested bool) connectionLostHandledFn { - return func(proceed bool) (connCompletedFn, error) { - // Note that connCompletedFn will only be provided if both reconnectRequested and proceed are true - c.Lock() - defer c.Unlock() - - // `Disconnecting()` may have been called while the disconnection was being processed (this makes it permanent!) - if !c.willReconnect || !proceed { - c.status = disconnected - close(c.actionCompleted) // Alert anything waiting on the connection process to complete - c.actionCompleted = nil - if !reconnectRequested || !proceed { - return nil, nil - } - return nil, errDisconnectionRequested - } - - c.status = reconnecting - return c.connected, nil // Note that c.actionCompleted is still live and will be closed in connected - } -} - -// forceConnectionStatus - forces the connection status to the specified value. -// This should only be used when there is no alternative (i.e. only in tests and to recover from situations that -// are unexpected) -func (c *connectionStatus) forceConnectionStatus(s status) { - c.Lock() - defer c.Unlock() - c.status = s -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/store.go b/vendor/github.com/eclipse/paho.mqtt.golang/store.go deleted file mode 100644 index f50873cd..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/store.go +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "fmt" - "strconv" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -const ( - inboundPrefix = "i." - outboundPrefix = "o." -) - -// Store is an interface which can be used to provide implementations -// for message persistence. -// Because we may have to store distinct messages with the same -// message ID, we need a unique key for each message. This is -// possible by prepending "i." or "o." to each message id -type Store interface { - Open() - Put(key string, message packets.ControlPacket) - Get(key string) packets.ControlPacket - All() []string - Del(key string) - Close() - Reset() -} - -// A key MUST have the form "X.[messageid]" -// where X is 'i' or 'o' -func mIDFromKey(key string) uint16 { - s := key[2:] - i, err := strconv.ParseUint(s, 10, 16) - chkerr(err) - return uint16(i) -} - -// Return true if key prefix is outbound -func isKeyOutbound(key string) bool { - return key[:2] == outboundPrefix -} - -// Return true if key prefix is inbound -func isKeyInbound(key string) bool { - return key[:2] == inboundPrefix -} - -// Return a string of the form "i.[id]" -func inboundKeyFromMID(id uint16) string { - return fmt.Sprintf("%s%d", inboundPrefix, id) -} - -// Return a string of the form "o.[id]" -func outboundKeyFromMID(id uint16) string { - return fmt.Sprintf("%s%d", outboundPrefix, id) -} - -// govern which outgoing messages are persisted -func persistOutbound(s Store, m packets.ControlPacket) { - switch m.Details().Qos { - case 0: - switch m.(type) { - case *packets.PubackPacket, *packets.PubcompPacket: - // Sending puback. delete matching publish - // from ibound - s.Del(inboundKeyFromMID(m.Details().MessageID)) - } - case 1: - switch m.(type) { - case *packets.PublishPacket, *packets.PubrelPacket, *packets.SubscribePacket, *packets.UnsubscribePacket: - // Sending publish. store in obound - // until puback received - s.Put(outboundKeyFromMID(m.Details().MessageID), m) - default: - ERROR.Println(STR, "Asked to persist an invalid message type") - } - case 2: - switch m.(type) { - case *packets.PublishPacket: - // Sending publish. store in obound - // until pubrel received - s.Put(outboundKeyFromMID(m.Details().MessageID), m) - default: - ERROR.Println(STR, "Asked to persist an invalid message type") - } - } -} - -// govern which incoming messages are persisted -func persistInbound(s Store, m packets.ControlPacket) { - switch m.Details().Qos { - case 0: - switch m.(type) { - case *packets.PubackPacket, *packets.SubackPacket, *packets.UnsubackPacket, *packets.PubcompPacket: - // Received a puback. delete matching publish - // from obound - s.Del(outboundKeyFromMID(m.Details().MessageID)) - case *packets.PublishPacket, *packets.PubrecPacket, *packets.PingrespPacket, *packets.ConnackPacket: - default: - ERROR.Println(STR, "Asked to persist an invalid messages type") - } - case 1: - switch m.(type) { - case *packets.PublishPacket, *packets.PubrelPacket: - // Received a publish. store it in ibound - // until puback sent - s.Put(inboundKeyFromMID(m.Details().MessageID), m) - default: - ERROR.Println(STR, "Asked to persist an invalid messages type") - } - case 2: - switch m.(type) { - case *packets.PublishPacket: - // Received a publish. store it in ibound - // until pubrel received - s.Put(inboundKeyFromMID(m.Details().MessageID), m) - default: - ERROR.Println(STR, "Asked to persist an invalid messages type") - } - } -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/token.go b/vendor/github.com/eclipse/paho.mqtt.golang/token.go deleted file mode 100644 index 996ab5b0..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/token.go +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander - */ - -package mqtt - -import ( - "sync" - "time" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -// PacketAndToken is a struct that contains both a ControlPacket and a -// Token. This struct is passed via channels between the client interface -// code and the underlying code responsible for sending and receiving -// MQTT messages. -type PacketAndToken struct { - p packets.ControlPacket - t tokenCompletor -} - -// Token defines the interface for the tokens used to indicate when -// actions have completed. -type Token interface { - // Wait will wait indefinitely for the Token to complete, ie the Publish - // to be sent and confirmed receipt from the broker. - Wait() bool - - // WaitTimeout takes a time.Duration to wait for the flow associated with the - // Token to complete, returns true if it returned before the timeout or - // returns false if the timeout occurred. In the case of a timeout the Token - // does not have an error set in case the caller wishes to wait again. - WaitTimeout(time.Duration) bool - - // Done returns a channel that is closed when the flow associated - // with the Token completes. Clients should call Error after the - // channel is closed to check if the flow completed successfully. - // - // Done is provided for use in select statements. Simple use cases may - // use Wait or WaitTimeout. - Done() <-chan struct{} - - Error() error -} - -type TokenErrorSetter interface { - setError(error) -} - -type tokenCompletor interface { - Token - TokenErrorSetter - flowComplete() -} - -type baseToken struct { - m sync.RWMutex - complete chan struct{} - err error -} - -// Wait implements the Token Wait method. -func (b *baseToken) Wait() bool { - <-b.complete - return true -} - -// WaitTimeout implements the Token WaitTimeout method. -func (b *baseToken) WaitTimeout(d time.Duration) bool { - timer := time.NewTimer(d) - select { - case <-b.complete: - if !timer.Stop() { - <-timer.C - } - return true - case <-timer.C: - } - - return false -} - -// Done implements the Token Done method. -func (b *baseToken) Done() <-chan struct{} { - return b.complete -} - -func (b *baseToken) flowComplete() { - select { - case <-b.complete: - default: - close(b.complete) - } -} - -func (b *baseToken) Error() error { - b.m.RLock() - defer b.m.RUnlock() - return b.err -} - -func (b *baseToken) setError(e error) { - b.m.Lock() - b.err = e - b.flowComplete() - b.m.Unlock() -} - -func newToken(tType byte) tokenCompletor { - switch tType { - case packets.Connect: - return &ConnectToken{baseToken: baseToken{complete: make(chan struct{})}} - case packets.Subscribe: - return &SubscribeToken{baseToken: baseToken{complete: make(chan struct{})}, subResult: make(map[string]byte)} - case packets.Publish: - return &PublishToken{baseToken: baseToken{complete: make(chan struct{})}} - case packets.Unsubscribe: - return &UnsubscribeToken{baseToken: baseToken{complete: make(chan struct{})}} - case packets.Disconnect: - return &DisconnectToken{baseToken: baseToken{complete: make(chan struct{})}} - } - return nil -} - -// ConnectToken is an extension of Token containing the extra fields -// required to provide information about calls to Connect() -type ConnectToken struct { - baseToken - returnCode byte - sessionPresent bool -} - -// ReturnCode returns the acknowledgement code in the connack sent -// in response to a Connect() -func (c *ConnectToken) ReturnCode() byte { - c.m.RLock() - defer c.m.RUnlock() - return c.returnCode -} - -// SessionPresent returns a bool representing the value of the -// session present field in the connack sent in response to a Connect() -func (c *ConnectToken) SessionPresent() bool { - c.m.RLock() - defer c.m.RUnlock() - return c.sessionPresent -} - -// PublishToken is an extension of Token containing the extra fields -// required to provide information about calls to Publish() -type PublishToken struct { - baseToken - messageID uint16 -} - -// MessageID returns the MQTT message ID that was assigned to the -// Publish packet when it was sent to the broker -func (p *PublishToken) MessageID() uint16 { - return p.messageID -} - -// SubscribeToken is an extension of Token containing the extra fields -// required to provide information about calls to Subscribe() -type SubscribeToken struct { - baseToken - subs []string - subResult map[string]byte - messageID uint16 -} - -// Result returns a map of topics that were subscribed to along with -// the matching return code from the broker. This is either the Qos -// value of the subscription or an error code. -func (s *SubscribeToken) Result() map[string]byte { - s.m.RLock() - defer s.m.RUnlock() - return s.subResult -} - -// UnsubscribeToken is an extension of Token containing the extra fields -// required to provide information about calls to Unsubscribe() -type UnsubscribeToken struct { - baseToken - messageID uint16 -} - -// DisconnectToken is an extension of Token containing the extra fields -// required to provide information about calls to Disconnect() -type DisconnectToken struct { - baseToken -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/topic.go b/vendor/github.com/eclipse/paho.mqtt.golang/topic.go deleted file mode 100644 index 966540ae..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/topic.go +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "errors" - "strings" -) - -// ErrInvalidQos is the error returned when an packet is to be sent -// with an invalid Qos value -var ErrInvalidQos = errors.New("invalid QoS") - -// ErrInvalidTopicEmptyString is the error returned when a topic string -// is passed in that is 0 length -var ErrInvalidTopicEmptyString = errors.New("invalid Topic; empty string") - -// ErrInvalidTopicMultilevel is the error returned when a topic string -// is passed in that has the multi level wildcard in any position but -// the last -var ErrInvalidTopicMultilevel = errors.New("invalid Topic; multi-level wildcard must be last level") - -// Topic Names and Topic Filters -// The MQTT v3.1.1 spec clarifies a number of ambiguities with regard -// to the validity of Topic strings. -// - A Topic must be between 1 and 65535 bytes. -// - A Topic is case sensitive. -// - A Topic may contain whitespace. -// - A Topic containing a leading forward slash is different than a Topic without. -// - A Topic may be "/" (two levels, both empty string). -// - A Topic must be UTF-8 encoded. -// - A Topic may contain any number of levels. -// - A Topic may contain an empty level (two forward slashes in a row). -// - A TopicName may not contain a wildcard. -// - A TopicFilter may only have a # (multi-level) wildcard as the last level. -// - A TopicFilter may contain any number of + (single-level) wildcards. -// - A TopicFilter with a # will match the absence of a level -// Example: a subscription to "foo/#" will match messages published to "foo". - -func validateSubscribeMap(subs map[string]byte) ([]string, []byte, error) { - if len(subs) == 0 { - return nil, nil, errors.New("invalid subscription; subscribe map must not be empty") - } - - var topics []string - var qoss []byte - for topic, qos := range subs { - if err := validateTopicAndQos(topic, qos); err != nil { - return nil, nil, err - } - topics = append(topics, topic) - qoss = append(qoss, qos) - } - - return topics, qoss, nil -} - -func validateTopicAndQos(topic string, qos byte) error { - if len(topic) == 0 { - return ErrInvalidTopicEmptyString - } - - levels := strings.Split(topic, "/") - for i, level := range levels { - if level == "#" && i != len(levels)-1 { - return ErrInvalidTopicMultilevel - } - } - - if qos > 2 { - return ErrInvalidQos - } - return nil -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/trace.go b/vendor/github.com/eclipse/paho.mqtt.golang/trace.go deleted file mode 100644 index b07b6042..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/trace.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2021 IBM Corp and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -type ( - // Logger interface allows implementations to provide to this package any - // object that implements the methods defined in it. - Logger interface { - Println(v ...interface{}) - Printf(format string, v ...interface{}) - } - - // NOOPLogger implements the logger that does not perform any operation - // by default. This allows us to efficiently discard the unwanted messages. - NOOPLogger struct{} -) - -func (NOOPLogger) Println(v ...interface{}) {} -func (NOOPLogger) Printf(format string, v ...interface{}) {} - -// Internal levels of library output that are initialised to not print -// anything but can be overridden by programmer -var ( - ERROR Logger = NOOPLogger{} - CRITICAL Logger = NOOPLogger{} - WARN Logger = NOOPLogger{} - DEBUG Logger = NOOPLogger{} -) diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/websocket.go b/vendor/github.com/eclipse/paho.mqtt.golang/websocket.go deleted file mode 100644 index e0f2583e..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/websocket.go +++ /dev/null @@ -1,132 +0,0 @@ -/* - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v2.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * https://www.eclipse.org/legal/epl-2.0/ - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - */ - -package mqtt - -import ( - "crypto/tls" - "fmt" - "io" - "net" - "net/http" - "net/url" - "sync" - "time" - - "github.com/gorilla/websocket" -) - -// WebsocketOptions are config options for a websocket dialer -type WebsocketOptions struct { - ReadBufferSize int - WriteBufferSize int - Proxy ProxyFunction -} - -type ProxyFunction func(req *http.Request) (*url.URL, error) - -// NewWebsocket returns a new websocket and returns a net.Conn compatible interface using the gorilla/websocket package -func NewWebsocket(host string, tlsc *tls.Config, timeout time.Duration, requestHeader http.Header, options *WebsocketOptions) (net.Conn, error) { - if timeout == 0 { - timeout = 10 * time.Second - } - - if options == nil { - // Apply default options - options = &WebsocketOptions{} - } - if options.Proxy == nil { - options.Proxy = http.ProxyFromEnvironment - } - dialer := &websocket.Dialer{ - Proxy: options.Proxy, - HandshakeTimeout: timeout, - EnableCompression: false, - TLSClientConfig: tlsc, - Subprotocols: []string{"mqtt"}, - ReadBufferSize: options.ReadBufferSize, - WriteBufferSize: options.WriteBufferSize, - } - - ws, resp, err := dialer.Dial(host, requestHeader) - - if err != nil { - if resp != nil { - WARN.Println(CLI, fmt.Sprintf("Websocket handshake failure. StatusCode: %d. Body: %s", resp.StatusCode, resp.Body)) - } - return nil, err - } - - wrapper := &websocketConnector{ - Conn: ws, - } - return wrapper, err -} - -// websocketConnector is a websocket wrapper so it satisfies the net.Conn interface so it is a -// drop in replacement of the golang.org/x/net/websocket package. -// Implementation guide taken from https://github.com/gorilla/websocket/issues/282 -type websocketConnector struct { - *websocket.Conn - r io.Reader - rio sync.Mutex - wio sync.Mutex -} - -// SetDeadline sets both the read and write deadlines -func (c *websocketConnector) SetDeadline(t time.Time) error { - if err := c.SetReadDeadline(t); err != nil { - return err - } - err := c.SetWriteDeadline(t) - return err -} - -// Write writes data to the websocket -func (c *websocketConnector) Write(p []byte) (int, error) { - c.wio.Lock() - defer c.wio.Unlock() - - err := c.WriteMessage(websocket.BinaryMessage, p) - if err != nil { - return 0, err - } - return len(p), nil -} - -// Read reads the current websocket frame -func (c *websocketConnector) Read(p []byte) (int, error) { - c.rio.Lock() - defer c.rio.Unlock() - for { - if c.r == nil { - // Advance to next message. - var err error - _, c.r, err = c.NextReader() - if err != nil { - return 0, err - } - } - n, err := c.r.Read(p) - if err == io.EOF { - // At end of message. - c.r = nil - if n > 0 { - return n, nil - } - // No data read, continue to next message. - continue - } - return n, err - } -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/LICENSE b/vendor/github.com/edgexfoundry/go-mod-core-contracts/LICENSE deleted file mode 100644 index aad1af23..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2017 Dell, Inc. - - 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. \ No newline at end of file diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/constants.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/constants.go deleted file mode 100644 index fb311f66..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/constants.go +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 clients - -// Do not assume that if a constant is identified by your IDE as not being used within this module that it is not being -// used at all. Any application wishing to exchange information with the EdgeX core services will utilize this module, -// so constants located here may be used externally. -// -// Miscellaneous constants -const ( - ClientMonitorDefault = 15000 // Defaults the interval at which a given service client will refresh its endpoint from the Registry, if used - CorrelationHeader = "correlation-id" // Sets the key of the Correlation ID HTTP header -) - -// Constants related to defined routes in the service APIs -const ( - ApiVersionRoute = "/api/version" - ApiBase = "/api/v1" - ApiAddressableRoute = "/api/v1/addressable" - ApiCallbackRoute = "/api/v1/callback" - ApiCommandRoute = "/api/v1/command" - ApiConfigRoute = "/api/v1/config" - ApiDeviceRoute = "/api/v1/device" - ApiDeviceProfileRoute = "/api/v1/deviceprofile" - ApiDeviceServiceRoute = "/api/v1/deviceservice" - ApiEventRoute = "/api/v1/event" - ApiHealthRoute = "/api/v1/health" - ApiLoggingRoute = "/api/v1/logs" - ApiMetricsRoute = "/api/v1/metrics" - ApiNotificationRoute = "/api/v1/notification" - ApiNotifyRegistrationRoute = "/api/v1/notify/registrations" - ApiOperationRoute = "/api/v1/operation" - ApiPingRoute = "/api/v1/ping" - ApiProvisionWatcherRoute = "/api/v1/provisionwatcher" - ApiReadingRoute = "/api/v1/reading" - ApiRegistrationRoute = "/api/v1/registration" - ApiRegistrationByNameRoute = ApiRegistrationRoute + "/name" - ApiSubscriptionRoute = "/api/v1/subscription" - ApiTransmissionRoute = "/api/v1/transmission" - ApiValueDescriptorRoute = "/api/v1/valuedescriptor" - ApiIntervalRoute = "/api/v1/interval" - ApiIntervalActionRoute = "/api/v1/intervalaction" -) - -// Constants related to how services identify themselves in the Service Registry -const ( - ServiceKeyPrefix = "edgex-" - ConfigSeedServiceKey = "edgex-config-seed" - CoreCommandServiceKey = "edgex-core-command" - CoreDataServiceKey = "edgex-core-data" - CoreMetaDataServiceKey = "edgex-core-metadata" - SupportLoggingServiceKey = "edgex-support-logging" - SupportNotificationsServiceKey = "edgex-support-notifications" - SystemManagementAgentServiceKey = "edgex-sys-mgmt-agent" - SupportSchedulerServiceKey = "edgex-support-scheduler" - SecuritySecretStoreSetupServiceKey = "edgex-security-secretstore-setup" - SecuritySecretsSetupServiceKey = "edgex-security-secrets-setup" - SecurityProxySetupServiceKey = "edgex-security-proxy-setup" - SecurityFileTokenProviderServiceKey = "edgex-security-file-token-provider" -) - -// Constants related to the possible content types supported by the APIs -const ( - ContentType = "Content-Type" - ContentTypeCBOR = "application/cbor" - ContentTypeJSON = "application/json" - ContentTypeYAML = "application/x-yaml" - ContentTypeText = "text/plain" -) diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/context.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/context.go deleted file mode 100644 index 6f14a2f1..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/context.go +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 clients - -import ( - "context" -) - -// FromContext allows for the retrieval of the specified key's value from the supplied Context. -// If the value is not found, an empty string is returned. -func FromContext(ctx context.Context, key string) string { - hdr, ok := ctx.Value(key).(string) - if !ok { - hdr = "" - } - return hdr -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/doc.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/doc.go deleted file mode 100644 index 6547b53e..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/doc.go +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 clients provides REST-based integration with the core APIs of the EdgeX Foundry platform. - -Each individual service client can be found in its respective package within clients. View the Subdirectories section -below for more information. - -While it is certainly possible to utilize the exported functions in this package to make calls to a given service, it -is recommended (unless you really specifically know what you're doing) to use the service clients instead. The functions -here are exported primarily for the use of the service clients. - -*/ -package clients diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces/url.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces/url.go deleted file mode 100644 index 1391b7a0..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces/url.go +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright 2020 Dell Inc. - * - * 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 interfaces - -// URLClient is the interface for types that need to define some way to retrieve URLClient information about services. -// This information can be anything that must be determined at runtime, whether it is unknown or simply not yet known. -type URLClient interface { - // Prefix returns the URLClient base path (or root) of a service. - // This is the common root of all REST calls to the service, - // and is defined on a per service (rather than per endpoint) basis. - // Prefix returns the root URLClient for REST calls to the service if it was able to retrieve that URLClient; - // it returns an error otherwise. - Prefix() (string, error) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces/urlstream.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces/urlstream.go deleted file mode 100644 index f3718d32..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces/urlstream.go +++ /dev/null @@ -1,17 +0,0 @@ -/******************************************************************************* - * Copyright 2020 Dell Inc. - * - * 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 interfaces - -type URLStream string diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/request.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/request.go deleted file mode 100644 index 6db931d9..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/request.go +++ /dev/null @@ -1,353 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * Copyright 2019 Joan Duran - * - * 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 clients - -import ( - "bytes" - "context" - "encoding/json" - "github.com/google/uuid" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "path/filepath" - "strconv" - - "github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces" - "github.com/edgexfoundry/go-mod-core-contracts/clients/types" -) - -// Helper method to get the body from the response after making the request -func getBody(resp *http.Response) ([]byte, error) { - body, err := ioutil.ReadAll(resp.Body) - return body, err -} - -// Helper method to make the request and return the response -func makeRequest(req *http.Request) (*http.Response, error) { - client := &http.Client{} - resp, err := client.Do(req) - - return resp, err -} - -// GetRequest will make a GET request to the specified URL with the root URL retrieved by the URLClient prepended. -// It returns the body as a byte array if successful and an error otherwise. -func GetRequest(ctx context.Context, urlSuffix string, urlClient interfaces.URLClient) ([]byte, error) { - urlPrefix, err := urlClient.Prefix() - if err != nil { - return nil, err - } - - return GetRequestWithURL(ctx, urlPrefix+urlSuffix) -} - -// GetRequestWithURL will make a GET request to the specified URL. -// It returns the body as a byte array if successful and an error otherwise. -func GetRequestWithURL(ctx context.Context, url string) ([]byte, error) { - req, err := http.NewRequest(http.MethodGet, url, nil) - if err != nil { - return nil, err - } - - c := NewCorrelatedRequest(ctx, req) - resp, err := makeRequest(c.Request) - if err != nil { - return nil, err - } - if resp == nil { - return nil, types.ErrResponseNil{} - } - defer resp.Body.Close() - - bodyBytes, err := getBody(resp) - if err != nil { - return nil, err - } - - if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) { - return nil, types.NewErrServiceClient(resp.StatusCode, bodyBytes) - } - - return bodyBytes, nil -} - -// Helper method to make the count request -func CountRequest(ctx context.Context, urlSuffix string, urlClient interfaces.URLClient) (int, error) { - // do not get URLPrefix here since GetRequest does it - data, err := GetRequest(ctx, urlSuffix, urlClient) - if err != nil { - return 0, err - } - - count, err := strconv.Atoi(string(data)) - if err != nil { - return 0, err - } - return count, nil -} - -// Helper method to make the post JSON request and return the body -func PostJSONRequest( - ctx context.Context, - urlSuffix string, - data interface{}, - urlClient interfaces.URLClient) (string, error) { - - jsonStr, err := json.Marshal(data) - if err != nil { - return "", err - } - - ctx = context.WithValue(ctx, ContentType, ContentTypeJSON) - - // do not get URLPrefix here since PostRequest does it - return PostRequest(ctx, urlSuffix, jsonStr, urlClient) -} - -// PostJSONRequestWithURL will make a POST request to the specified URL with the object passed in -// marshaled into a JSON formatted byte array. -// It returns the body on success and an error otherwise. -func PostJSONRequestWithURL(ctx context.Context, url string, data interface{}) (string, error) { - jsonStr, err := json.Marshal(data) - if err != nil { - return "", err - } - - ctx = context.WithValue(ctx, ContentType, ContentTypeJSON) - - return PostRequestWithURL(ctx, url, jsonStr) -} - -// Helper method to make the post request and return the body -func PostRequest(ctx context.Context, urlSuffix string, data []byte, urlClient interfaces.URLClient) (string, error) { - urlPrefix, err := urlClient.Prefix() - if err != nil { - return "", err - } - - return PostRequestWithURL(ctx, urlPrefix+urlSuffix, data) -} - -// PostRequestWithURL will make a POST request to the specified URL. -// It returns the body as a byte array if successful and an error otherwise. -func PostRequestWithURL(ctx context.Context, url string, data []byte) (string, error) { - content := FromContext(ctx, ContentType) - if content == "" { - content = ContentTypeJSON - } - - req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) - if err != nil { - return "", err - } - req.Header.Set(ContentType, content) - - c := NewCorrelatedRequest(ctx, req) - resp, err := makeRequest(c.Request) - if err != nil { - return "", err - } - if resp == nil { - return "", types.ErrResponseNil{} - } - defer resp.Body.Close() - - bodyBytes, err := getBody(resp) - if err != nil { - return "", err - } - - if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) { - return "", types.NewErrServiceClient(resp.StatusCode, bodyBytes) - } - - bodyString := string(bodyBytes) - return bodyString, nil -} - -// Helper method to make a post request in order to upload a file and return the request body -func UploadFileRequest( - ctx context.Context, - urlSuffix string, - filePath string, - urlClient interfaces.URLClient) (string, error) { - - fileContents, err := ioutil.ReadFile(filePath) - if err != nil { - return "", err - } - - // Create multipart/form-data request - body := &bytes.Buffer{} - writer := multipart.NewWriter(body) - formFileWriter, err := writer.CreateFormFile("file", filepath.Base(filePath)) - if err != nil { - return "", err - } - _, err = io.Copy(formFileWriter, bytes.NewReader(fileContents)) - if err != nil { - return "", err - } - writer.Close() - - urlPrefix, err := urlClient.Prefix() - if err != nil { - return "", err - } - - req, err := http.NewRequest(http.MethodPost, urlPrefix+urlSuffix, body) - if err != nil { - return "", err - } - req.Header.Add(ContentType, writer.FormDataContentType()) - - c := NewCorrelatedRequest(ctx, req) - resp, err := makeRequest(c.Request) - if err != nil { - return "", err - } - if resp == nil { - return "", types.ErrResponseNil{} - } - defer resp.Body.Close() - - bodyBytes, err := getBody(resp) - if err != nil { - return "", err - } - - if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) { - return "", types.NewErrServiceClient(resp.StatusCode, bodyBytes) - } - - bodyString := string(bodyBytes) - return bodyString, nil -} - -// Helper method to make the update request -func UpdateRequest(ctx context.Context, urlSuffix string, data interface{}, urlClient interfaces.URLClient) error { - jsonStr, err := json.Marshal(data) - if err != nil { - return err - } - - // do not get URLPrefix here since PutRequest does it - _, err = PutRequest(ctx, urlSuffix, jsonStr, urlClient) - return err -} - -// Helper method to make the put request -func PutRequest(ctx context.Context, urlSuffix string, body []byte, urlClient interfaces.URLClient) (string, error) { - var err error - var req *http.Request - - urlPrefix, err := urlClient.Prefix() - if err != nil { - return "", err - } - if body != nil { - req, err = http.NewRequest(http.MethodPut, urlPrefix+urlSuffix, bytes.NewReader(body)) - if err != nil { - return "", err - } - - content := FromContext(ctx, ContentType) - if content == "" { - content = ContentTypeJSON - } - req.Header.Set(ContentType, content) - } else { - req, err = http.NewRequest(http.MethodPut, urlPrefix+urlSuffix, nil) - } - if err != nil { - return "", err - } - - c := NewCorrelatedRequest(ctx, req) - resp, err := makeRequest(c.Request) - if err != nil { - return "", err - } - if resp == nil { - return "", types.ErrResponseNil{} - } - defer resp.Body.Close() - - bodyBytes, err := getBody(resp) - if err != nil { - return "", err - } - - if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) { - return "", types.NewErrServiceClient(resp.StatusCode, bodyBytes) - } - - bodyString := string(bodyBytes) - return bodyString, nil -} - -// Helper method to make the delete request -func DeleteRequest(ctx context.Context, urlSuffix string, urlClient interfaces.URLClient) error { - urlPrefix, err := urlClient.Prefix() - if err != nil { - return err - } - - req, err := http.NewRequest(http.MethodDelete, urlPrefix+urlSuffix, nil) - if err != nil { - return err - } - - c := NewCorrelatedRequest(ctx, req) - resp, err := makeRequest(c.Request) - if err != nil { - return err - } - if resp == nil { - return types.ErrResponseNil{} - } - defer resp.Body.Close() - - if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) { - bodyBytes, err := getBody(resp) - if err != nil { - return err - } - - return types.NewErrServiceClient(resp.StatusCode, bodyBytes) - } - - return nil -} - -// CorrelatedRequest is a wrapper type for use in managing Correlation IDs during service to service API calls. -type CorrelatedRequest struct { - *http.Request -} - -// NewCorrelatedRequest will add the Correlation ID header to the supplied request. If no Correlation ID header is -// present in the supplied context, one will be created along with a value. -func NewCorrelatedRequest(ctx context.Context, req *http.Request) CorrelatedRequest { - c := CorrelatedRequest{Request: req} - correlation := FromContext(ctx, CorrelationHeader) - if len(correlation) == 0 { - correlation = uuid.New().String() - } - c.Header.Set(CorrelationHeader, correlation) - return c -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/types/errors.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/types/errors.go deleted file mode 100644 index e462ae61..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/clients/types/errors.go +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - -package types - -import "fmt" - -// ErrNotFound represents an error returned from a service indicating the item being asked for was not found. -type ErrNotFound struct{} - -func (e ErrNotFound) Error() string { - return "Item not found" -} - -// ErrResponseNil represents an error returned from a service indicating the response was unexpectedly empty. -type ErrResponseNil struct{} - -func (e ErrResponseNil) Error() string { - return "Response was nil" -} - -// ErrServiceClient exposes the details of a service's response in a more granular manner. This is useful when service A -// calls service B and service A needs to make a decision with regard to how it should respond to its own caller based on -// the error thrown from service B. -type ErrServiceClient struct { - StatusCode int // StatusCode contains the HTTP status code returned from the target service - bodyBytes []byte // bodyBytes contains the response from the target service - errMsg string // errMsg contains the error message to be returned. See the Error() method below. -} - -// NewErrServiceClient returns an instance of the error interface with ErrServiceClient as its implementation. -func NewErrServiceClient(statusCode int, body []byte) error { - e := ErrServiceClient{StatusCode: statusCode, bodyBytes: body} - return e -} - -// Error fulfills the error interface and returns an error message assembled from the state of ErrServiceClient. -func (e ErrServiceClient) Error() string { - return fmt.Sprintf("%d - %s", e.StatusCode, e.bodyBytes) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/action.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/action.go deleted file mode 100644 index 7d78819c..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/action.go +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" -) - -// Action describes state related to the capabilities of a device -type Action struct { - Path string `json:"path,omitempty" yaml:"path,omitempty"` // Path used by service for action on a device or sensor - Responses []Response `json:"responses,omitempty" yaml:"responses,omitempty"` // Responses from get or put requests to service - URL string `json:"url,omitempty" yaml:"url,omitempty"` // Url for requests from command service -} - -// String returns a JSON formatted string representation of the Action -func (a Action) String() string { - out, err := json.Marshal(a) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/actiontype.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/actiontype.go deleted file mode 100644 index ef19ef54..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/actiontype.go +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -// ActionType indicates the various types of actions -type ActionType string - -const ( - PROFILE ActionType = "PROFILE" - DEVICE = "DEVICE" - SERVICE = "SERVICE" - SCHEDULE = "SCHEDULE" - SCHEDULEEVENT = "SCHEDULEEVENT" - ADDRESSABLE = "ADDRESSABLE" - VALUEDESCRIPTOR = "VALUEDESCRIPTOR" - PROVISIONWATCHER = "PROVISIONWATCHER" - REPORT = "REPORT" -) diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/addressable.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/addressable.go deleted file mode 100644 index 51018b89..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/addressable.go +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "strconv" - "strings" -) - -// Addressable holds information indicating how to contact a specific endpoint -type Addressable struct { - Timestamps - Id string `json:"id,omitempty"` // ID is a unique identifier for the Addressable, such as a UUID - Name string `json:"name,omitempty"` // Name is a unique name given to the Addressable - Protocol string `json:"protocol,omitempty"` // Protocol for the address (HTTP/TCP) - HTTPMethod string `json:"method,omitempty"` // Method for connecting (i.e. POST) - Address string `json:"address,omitempty"` // Address of the addressable - Port int `json:"port,omitempty,Number"` // Port for the address - Path string `json:"path,omitempty"` // Path for callbacks - Publisher string `json:"publisher,omitempty"` // For message bus protocols - User string `json:"user,omitempty"` // User id for authentication - Password string `json:"password,omitempty"` // Password of the user for authentication for the addressable - Topic string `json:"topic,omitempty"` // Topic for message bus addressables - isValidated bool // internal member used for validation check -} - -type addressableAlias Addressable - -// MarshalJSON implements the Marshaler interface for the Addressable type -// Use custom logic to create the URL and Base URL -func (a Addressable) MarshalJSON() ([]byte, error) { - aux := struct { - addressableAlias - BaseURL string `json:"baseURL,omitempty"` - URL string `json:"url,omitempty"` - }{ - addressableAlias: addressableAlias(a), - } - - if a.Protocol != "" && a.Address != "" { - // Get the base URL - aux.BaseURL = a.GetBaseURL() - - // Get the URL - aux.URL = aux.BaseURL - if a.Publisher == "" && a.Topic != "" { - aux.URL += a.Topic + "/" - } - aux.URL += a.Path - } - - return json.Marshal(aux) -} - -// UnmarshalJSON implements the Unmarshaler interface for the Addressable type -func (a *Addressable) UnmarshalJSON(data []byte) error { - var err error - var alias addressableAlias - if err = json.Unmarshal(data, &alias); err != nil { - return err - } - - *a = Addressable(alias) - a.isValidated, err = a.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (a Addressable) Validate() (bool, error) { - if !a.isValidated { - if a.Id == "" && a.Name == "" { - return false, NewErrContractInvalid("Addressable ID and Name are both blank") - } - return true, nil - } - return a.isValidated, nil -} - -// String returns a JSON encoded string representation of the addressable. -func (a Addressable) String() string { - out, err := json.Marshal(a) - if err != nil { - return err.Error() - } - return string(out) -} - -// GetBaseURL returns a base URL consisting of protocol, host and port as a string assembled from the constituent parts of the Addressable -func (a Addressable) GetBaseURL() string { - protocol := strings.ToLower(a.Protocol) - address := a.Address - port := strconv.Itoa(a.Port) - baseUrl := protocol + "://" + address + ":" + port - return baseUrl -} - -// GetCallbackURL returns the callback url for the addressable if all relevant tokens have values. -// If any token is missing, string will be empty. Tokens include protocol, address, port and path. -func (a Addressable) GetCallbackURL() string { - url := "" - if len(a.Protocol) > 0 && len(a.Address) > 0 && a.Port > 0 && len(a.Path) > 0 { - url = a.GetBaseURL() + a.Path - } - - return url -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/adminstate.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/adminstate.go deleted file mode 100644 index 79633093..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/adminstate.go +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" - "strings" -) - -// AdminState controls the range of values which constitute valid administrative states for a device -type AdminState string - -const ( - // Locked : device is locked - // Unlocked : device is unlocked - Locked = "LOCKED" - Unlocked = "UNLOCKED" -) - -// UnmarshalJSON implements the Unmarshaler interface for the enum type -func (as *AdminState) UnmarshalJSON(data []byte) error { - // Extract the string from data. - var s string - if err := json.Unmarshal(data, &s); err != nil { - return fmt.Errorf("AdminState should be a string, got %s", data) - } - - new := AdminState(strings.ToUpper(s)) - *as = new - - return nil -} - -// Validate satisfies the Validator interface -func (as AdminState) Validate() (bool, error) { - _, found := map[string]AdminState{"LOCKED": Locked, "UNLOCKED": Unlocked}[string(as)] - if !found { - return false, NewErrContractInvalid(fmt.Sprintf("invalid AdminState %q", as)) - } - return true, nil -} - -// GetAdminState is called from within the router logic of the core services. For example, there are PUT calls -// like the one below from core-metadata which specify their update parameters in the URL -// -// d.HandleFunc("/{"+ID+"}/"+URLADMINSTATE+"/{"+ADMINSTATE+"}", restSetDeviceAdminStateById).Methods(http.MethodPut) -// -// Updates like this should be refactored to pass a body containing the new values instead of via the URL. This -// would allow us to utilize the model validation above and remove the logic from the controller. -// -// This will be removed once work on the following issue begins -- https://github.com/edgexfoundry/edgex-go/issues/1244 -func GetAdminState(as string) (AdminState, bool) { - as = strings.ToUpper(as) - retValue, err := map[string]AdminState{"LOCKED": Locked, "UNLOCKED": Unlocked}[as] - return retValue, err -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/autoevent.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/autoevent.go deleted file mode 100644 index 4de7c6a9..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/autoevent.go +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import "encoding/json" - -// AutoEvent supports auto-generated events sourced from a device service -type AutoEvent struct { - // Frequency indicates how often the specific resource needs to be polled. - // It represents as a duration string. - // The format of this field is to be an unsigned integer followed by a unit which may be "ms", "s", "m" or "h" - // representing milliseconds, seconds, minutes or hours. Eg, "100ms", "24h" - Frequency string `json:"frequency,omitempty"` - // OnChange indicates whether the device service will generate an event only, - // if the reading value is different from the previous one. - // If true, only generate events when readings change - OnChange bool `json:"onChange,omitempty"` - // Resource indicates the name of the resource in the device profile which describes the event to generate - Resource string `json:"resource,omitempty"` -} - -/* - * String function for representing an auto-generated event from a device. - */ -func (a AutoEvent) String() string { - out, err := json.Marshal(a) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/callbackalert.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/callbackalert.go deleted file mode 100644 index f1c736c9..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/callbackalert.go +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" -) - -// CallbackAlert indicates an action to take when a callback fires. -type CallbackAlert struct { - ActionType ActionType `json:"type,omitempty"` - Id string `json:"id,omitempty"` -} - -/* - * String function for representing a CallbackAlert - */ -func (ca CallbackAlert) String() string { - out, err := json.Marshal(ca) - if err != nil { - return err.Error() - } - - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/category.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/category.go deleted file mode 100644 index 8800bfa5..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/category.go +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" -) - -// NotificationsCategory controls the range of values which constitute valid categories for notifications -type NotificationsCategory string - -const ( - Security = "SECURITY" - Hwhealth = "HW_HEALTH" - Swhealth = "SW_HEALTH" -) - -// UnmarshalJSON implements the Unmarshaler interface for the type -func (as *NotificationsCategory) UnmarshalJSON(data []byte) error { - // Extract the string from data. - var s string - if err := json.Unmarshal(data, &s); err != nil { - return fmt.Errorf("NotificationsCategory should be a string, got %s", data) - } - - got, err := map[string]NotificationsCategory{"SECURITY": Security, "HW_HEALTH": Hwhealth, "SW_HEALTH": Swhealth}[s] - if !err { - return fmt.Errorf("invalid NotificationsCategory %q", s) - } - *as = got - return nil -} - -// IsNotificationsCategory allows external code to verify whether the supplied string is a valid NotificationsCategory value -func IsNotificationsCategory(as string) bool { - _, err := map[string]NotificationsCategory{"SECURITY": Security, "HW_HEALTH": Hwhealth, "SW_HEALTH": Swhealth}[as] - if !err { - return false - } - return true -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/channel.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/channel.go deleted file mode 100644 index 403387aa..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/channel.go +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" -) - -// Channel supports transmissions and notifications with fields for delivery via email or REST -type Channel struct { - Type ChannelType `json:"type,omitempty"` // Type indicates whether the channel facilitates email or REST - MailAddresses []string `json:"mailAddresses,omitempty"` // MailAddresses contains email addresses - Url string `json:"url,omitempty"` // URL contains a REST API destination -} - -func (c Channel) String() string { - out, err := json.Marshal(c) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/channel_type.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/channel_type.go deleted file mode 100644 index ddbbec0a..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/channel_type.go +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" -) - -// ChannelType controls the range of values which constitute valid delivery types for channels -type ChannelType string - -const ( - Rest = "REST" - Email = "EMAIL" -) - -// UnmarshalJSON implements the Unmarshaler interface for the type -func (as *ChannelType) UnmarshalJSON(data []byte) error { - // Extract the string from data. - var s string - if err := json.Unmarshal(data, &s); err != nil { - return fmt.Errorf("ChannelType should be a string, got %s", data) - } - - got, err := map[string]ChannelType{"REST": Rest, "EMAIL": Email}[s] - if !err { - return fmt.Errorf("invalid ChannelType %q", s) - } - *as = got - return nil -} - -func (as ChannelType) Validate() (bool, error) { - _, err := map[string]ChannelType{"REST": Rest, "EMAIL": Email}[string(as)] - if !err { - return false, NewErrContractInvalid(fmt.Sprintf("invalid Channeltype %q", as)) - } - return true, nil -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/command.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/command.go deleted file mode 100644 index be2b5d01..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/command.go +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "reflect" -) - -// Command defines a specific read/write operation targeting a device -type Command struct { - Timestamps `yaml:",inline"` - Id string `json:"id" yaml:"id,omitempty"` // Id is a unique identifier, such as a UUID - Name string `json:"name" yaml:"name,omitempty"` // Command name (unique on the profile) - Get Get `json:"get" yaml:"get,omitempty"` // Get Command - Put Put `json:"put" yaml:"put,omitempty"` // Put Command - isValidated bool // internal member used for validation check -} - -// MarshalJSON implements the Marshaler interface. Empty strings will be null. -func (c Command) MarshalJSON() ([]byte, error) { - test := struct { - Timestamps - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` // Command name (unique on the profile) - Get *Get `json:"get,omitempty"` // Get Command - Put *Put `json:"put,omitempty"` // Put Command - }{ - Timestamps: c.Timestamps, - Id: c.Id, - Name: c.Name, - Get: &c.Get, - Put: &c.Put, - } - - // Make empty structs nil pointers so they aren't marshaled - if reflect.DeepEqual(c.Get, Get{}) { - test.Get = nil - } - if reflect.DeepEqual(c.Put, Put{}) { - test.Put = nil - } - - return json.Marshal(test) -} - -// UnmarshalJSON implements the Unmarshaler interface for the Command type -func (c *Command) UnmarshalJSON(data []byte) error { - var err error - a := new(struct { - Timestamps `json:",inline"` - Id *string `json:"id"` - Name *string `json:"name"` // Command name (unique on the profile) - Get Get `json:"get"` // Get Command - Put Put `json:"put"` // Put Command - }) - - // Error with unmarshaling - if err = json.Unmarshal(data, a); err != nil { - return err - } - - // Check nil fields - if a.Id != nil { - c.Id = *a.Id - } - if a.Name != nil { - c.Name = *a.Name - } - c.Get = a.Get - c.Put = a.Put - c.Timestamps = a.Timestamps - - c.isValidated, err = c.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (c Command) Validate() (bool, error) { - if !c.isValidated { - if c.Name == "" { - return false, NewErrContractInvalid("Name cannot be blank") - } - err := validate(c) - if err != nil { - return false, err - } - return true, nil - } - return c.isValidated, nil -} - -/* - * String() function for formatting - */ -func (c Command) String() string { - out, err := json.Marshal(c) - if err != nil { - return err.Error() - } - return string(out) -} - -// AllAssociatedValueDescriptors will append all the associated value descriptors to the list -// associated by PUT command parameters and PUT/GET command return values -func (c *Command) AllAssociatedValueDescriptors(vdNames *map[string]string) { - // Check and add Get value descriptors - if &(c.Get) != nil { - c.Get.AllAssociatedValueDescriptors(vdNames) - } - - // Check and add Put value descriptors - if &(c.Put) != nil { - c.Put.AllAssociatedValueDescriptors(vdNames) - } -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/commandresponse.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/commandresponse.go deleted file mode 100644 index 02a2b4cc..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/commandresponse.go +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" - - "github.com/edgexfoundry/go-mod-core-contracts/clients" -) - -// CommandResponse identifies a specific device along with its supported commands. -type CommandResponse struct { - Id string `json:"id,omitempty"` // Id uniquely identifies the CommandResponse, UUID for example. - Name string `json:"name,omitempty"` // Unique name for identifying a device - AdminState AdminState `json:"adminState,omitempty"` // Admin state (locked/unlocked) - OperatingState OperatingState `json:"operatingState,omitempty"` // Operating state (enabled/disabled) - LastConnected int64 `json:"lastConnected,omitempty"` // Time (milliseconds) that the device last provided any feedback or responded to any request - LastReported int64 `json:"lastReported,omitempty"` // Time (milliseconds) that the device reported data to the core microservice - Labels []string `json:"labels,omitempty"` // Other labels applied to the device to help with searching - Location interface{} `json:"location,omitempty"` // Device service specific location (interface{} is an empty interface so it can be anything) - Commands []Command `json:"commands,omitempty"` // Associated Device Profile - Describes the device -} - -/* - * String function for representing a device - */ -func (d CommandResponse) String() string { - out, err := json.Marshal(d) - if err != nil { - return err.Error() - } - return string(out) -} - -/* - * CommandResponseFromDevice will create a CommandResponse struct from the supplied Device struct - */ -func CommandResponseFromDevice(d Device, commands []Command, cmdURL string) CommandResponse { - cmdResp := CommandResponse{ - Id: d.Id, - Name: d.Name, - AdminState: d.AdminState, - OperatingState: d.OperatingState, - LastConnected: d.LastConnected, - LastReported: d.LastReported, - Labels: d.Labels, - Location: d.Location, - Commands: commands, - } - - basePath := fmt.Sprintf("%s%s/%s/command/", cmdURL, clients.ApiDeviceRoute, d.Id) - // TODO: Find a way to encapsulate this within the "Action" struct if possible - for i := 0; i < len(cmdResp.Commands); i++ { - url := basePath + cmdResp.Commands[i].Id - cmdResp.Commands[i].Get.URL = url - cmdResp.Commands[i].Put.URL = url - } - - return cmdResp -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/constants.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/constants.go deleted file mode 100644 index 84c90462..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/constants.go +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -// These constants are used by the unit tests in the models. -const ( - // common - testEmptyJSON = "{}" - - // action - testCode = "200" - testDescription = "ok" - testExpectedvalue1 = "temperature" - testExpectedvalue2 = "humidity" - testActionPath = "test/path" -) diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/describedobject.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/describedobject.go deleted file mode 100644 index a04978d6..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/describedobject.go +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import "encoding/json" - -// DescribedObject is a hold-over from the Java conversion and is supposed to represent inheritance whereby a type -// with a Description property IS A DescribedObject. However since there is no inheritance in Go, this should be -// eliminated and the Description property moved to the relevant types. 4 types currently use this. -type DescribedObject struct { - Timestamps `yaml:",inline"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` // Description. Capicé? -} - -// String returns a JSON formatted string representation of this DescribedObject -func (o DescribedObject) String() string { - out, err := json.Marshal(o) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/device.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/device.go deleted file mode 100644 index acd361e6..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/device.go +++ /dev/null @@ -1,170 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "reflect" -) - -// Device represents a registered device participating within the EdgeX Foundry ecosystem -type Device struct { - DescribedObject - Id string `json:"id"` // ID uniquely identifies the device, a UUID for example - Name string `json:"name"` // Unique name for identifying a device - AdminState AdminState `json:"adminState"` // Admin state (locked/unlocked) - OperatingState OperatingState `json:"operatingState"` // Operating state (enabled/disabled) - Protocols map[string]ProtocolProperties `json:"protocols"` // A map of supported protocols for the given device - LastConnected int64 `json:"lastConnected"` // Time (milliseconds) that the device last provided any feedback or responded to any request - LastReported int64 `json:"lastReported"` // Time (milliseconds) that the device reported data to the core microservice - Labels []string `json:"labels"` // Other labels applied to the device to help with searching - Location interface{} `json:"location"` // Device service specific location (interface{} is an empty interface so it can be anything) - Service DeviceService `json:"service"` // Associated Device Service - One per device - Profile DeviceProfile `json:"profile"` // Associated Device Profile - Describes the device - AutoEvents []AutoEvent `json:"autoEvents"` // A list of auto-generated events coming from the device - isValidated bool // internal member used for validation check -} - -// ProtocolProperties contains the device connection information in key/value pair -type ProtocolProperties map[string]string - -// MarshalJSON implements the Marshaler interface in order to make empty strings null -func (d Device) MarshalJSON() ([]byte, error) { - test := struct { - DescribedObject - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - AdminState AdminState `json:"adminState,omitempty"` - OperatingState OperatingState `json:"operatingState,omitempty"` - Protocols map[string]ProtocolProperties `json:"protocols,omitempty"` - LastConnected int64 `json:"lastConnected,omitempty"` - LastReported int64 `json:"lastReported,omitempty"` - Labels []string `json:"labels,omitempty"` - Location interface{} `json:"location,omitempty"` - Service *DeviceService `json:"service,omitempty"` - Profile *DeviceProfile `json:"profile,omitempty"` - AutoEvents []AutoEvent `json:"autoEvents,omitempty"` - }{ - Id: d.Id, - Name: d.Name, - DescribedObject: d.DescribedObject, - AdminState: d.AdminState, - OperatingState: d.OperatingState, - Protocols: d.Protocols, - LastConnected: d.LastConnected, - LastReported: d.LastReported, - Labels: d.Labels, - Location: d.Location, - Service: &d.Service, - Profile: &d.Profile, - AutoEvents: d.AutoEvents, - } - - if reflect.DeepEqual(*test.Service, DeviceService{}) { - test.Service = nil - } - - if reflect.DeepEqual(*test.Profile, DeviceProfile{}) { - test.Profile = nil - } - - return json.Marshal(test) -} - -// UnmarshalJSON implements the Unmarshaler interface for the Device type -func (d *Device) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - DescribedObject `json:",inline"` - Id string `json:"id"` - Name string `json:"name"` - AdminState AdminState `json:"adminState"` - OperatingState OperatingState `json:"operatingState"` - Protocols map[string]ProtocolProperties `json:"protocols"` - LastConnected int64 `json:"lastConnected"` - LastReported int64 `json:"lastReported"` - Labels []string `json:"labels"` - Location interface{} `json:"location"` - Service DeviceService `json:"service"` - Profile DeviceProfile `json:"profile"` - AutoEvents []AutoEvent `json:"autoEvents"` - } - a := Alias{} - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - d.Id = a.Id - d.Name = a.Name - d.DescribedObject = a.DescribedObject - d.AdminState = a.AdminState - d.OperatingState = a.OperatingState - d.Protocols = a.Protocols - d.LastConnected = a.LastConnected - d.LastReported = a.LastReported - d.Labels = a.Labels - d.Location = a.Location - d.Service = a.Service - d.Profile = a.Profile - d.AutoEvents = a.AutoEvents - - d.isValidated, err = d.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (d Device) Validate() (bool, error) { - if !d.isValidated { - if d.Id == "" && d.Name == "" { - return false, NewErrContractInvalid("Device ID and Name are both blank") - } - if len(d.Protocols) == 0 { - return false, NewErrContractInvalid("no supporting protocol specified for device") - } - err := validate(d) - if err != nil { - return false, err - } - return true, nil - } - return d.isValidated, nil -} - -/* - * String function for representing a device - */ -func (d Device) String() string { - out, err := json.Marshal(d) - if err != nil { - return err.Error() - } - return string(out) -} - -// AllAssociatedValueDescriptors returns all the associated value descriptors through Put command parameters and Put/Get command return values -func (d *Device) AllAssociatedValueDescriptors(vdNames *[]string) { - // Get the value descriptors with a map (set) where the keys are the value descriptor names - vdNamesMap := map[string]string{} - for _, c := range d.Profile.CoreCommands { - c.AllAssociatedValueDescriptors(&vdNamesMap) - } - - // Add the map keys (value descriptor names) to the list - for vd := range vdNamesMap { - *vdNames = append(*vdNames, vd) - } -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceprofile.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceprofile.go deleted file mode 100644 index 8f87b07a..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceprofile.go +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" -) - -// DeviceProfile represents the attributes and operational capabilities of a device. It is a template for which -// there can be multiple matching devices within a given system. -type DeviceProfile struct { - DescribedObject `yaml:",inline"` - Id string `json:"id,omitempty" yaml:"id,omitempty"` - Name string `json:"name,omitempty" yaml:"name,omitempty"` // Non-database identifier (must be unique) - Manufacturer string `json:"manufacturer,omitempty" yaml:"manufacturer,omitempty"` // Manufacturer of the device - Model string `json:"model,omitempty" yaml:"model,omitempty"` // Model of the device - Labels []string `json:"labels,omitempty" yaml:"labels,flow,omitempty"` // Labels used to search for groups of profiles - DeviceResources []DeviceResource `json:"deviceResources,omitempty" yaml:"deviceResources,omitempty"` - DeviceCommands []ProfileResource `json:"deviceCommands,omitempty" yaml:"deviceCommands,omitempty"` - CoreCommands []Command `json:"coreCommands,omitempty" yaml:"coreCommands,omitempty"` // List of commands to Get/Put information for devices associated with this profile - isValidated bool // internal member used for validation check -} - -// UnmarshalJSON implements the Unmarshaler interface for the DeviceProfile type -func (dp *DeviceProfile) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - DescribedObject `json:",inline"` - Id *string `json:"id"` - Name *string `json:"name"` - Manufacturer *string `json:"manufacturer"` - Model *string `json:"model"` - Labels []string `json:"labels"` - DeviceResources []DeviceResource `json:"deviceResources"` - DeviceCommands []ProfileResource `json:"deviceCommands"` - CoreCommands []Command `json:"coreCommands"` - } - a := Alias{} - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Check nil fields - if a.Id != nil { - dp.Id = *a.Id - } - if a.Name != nil { - dp.Name = *a.Name - } - if a.Manufacturer != nil { - dp.Manufacturer = *a.Manufacturer - } - if a.Model != nil { - dp.Model = *a.Model - } - dp.DescribedObject = a.DescribedObject - dp.Labels = a.Labels - dp.DeviceResources = a.DeviceResources - dp.DeviceCommands = a.DeviceCommands - dp.CoreCommands = a.CoreCommands - - dp.isValidated, err = dp.Validate() - - return err - -} - -// Validate satisfies the Validator interface -func (dp DeviceProfile) Validate() (bool, error) { - if !dp.isValidated { - if dp.Id == "" && dp.Name == "" { - return false, NewErrContractInvalid("Device ID and Name are both blank") - } - // Check if there are duplicate names in the device profile command list - cmds := map[string]int{} - for _, c := range dp.CoreCommands { - if _, ok := cmds[c.Name]; !ok { - cmds[c.Name] = 1 - } else { - return false, NewErrContractInvalid("duplicate names in device profile commands") - } - } - err := validate(dp) - if err != nil { - return false, err - } - return true, nil - } - return dp.isValidated, nil -} - -/* - * To String function for DeviceProfile - */ -func (dp DeviceProfile) String() string { - out, err := json.Marshal(dp) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/devicereport.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/devicereport.go deleted file mode 100644 index 9659af65..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/devicereport.go +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" -) - -// Deprecated: DeviceReport isn't utilized and needs to be removed. -type DeviceReport struct { - Timestamps - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` // non-database identifier for a device report - must be unique - Device string `json:"device,omitempty"` // associated device name - should be a valid and unique device name - Action string `json:"action,omitempty"` // associated interval action name - should be a valid and unique interval action name - Expected []string `json:"expected,omitempty"` // array of value descriptor names describing the types of data captured in the report -} - -/* - * To String function for DeviceProfile - */ -func (dr DeviceReport) String() string { - out, err := json.Marshal(dr) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceresource.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceresource.go deleted file mode 100644 index 0f5eb9a9..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceresource.go +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "reflect" -) - -// DeviceResource represents a value on a device that can be read or written -type DeviceResource struct { - Description string `json:"description" yaml:"description,omitempty"` - Name string `json:"name" yaml:"name,omitempty"` - Tag string `json:"tag" yaml:"tag,omitempty"` - Properties ProfileProperty `json:"properties" yaml:"properties"` - Attributes map[string]string `json:"attributes" yaml:"attributes,omitempty"` -} - -// MarshalJSON implements the Marshaler interface in order to make empty strings null -func (do DeviceResource) MarshalJSON() ([]byte, error) { - test := struct { - Description string `json:"description,omitempty"` - Name string `json:"name,omitempty"` - Tag string `json:"tag,omitempty"` - Properties *ProfileProperty `json:"properties,omitempty"` - Attributes *map[string]string `json:"attributes,omitempty"` - }{ - Description: do.Description, - Name: do.Name, - Tag: do.Tag, - Properties: &do.Properties, - } - - // Empty maps are null - if len(do.Attributes) > 0 { - test.Attributes = &do.Attributes - } - if reflect.DeepEqual(do.Properties, ProfileProperty{}) { - test.Properties = nil - } - - return json.Marshal(test) -} - -/* - * To String function for DeviceResource - */ -func (do DeviceResource) String() string { - out, err := json.Marshal(do) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceservice.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceservice.go deleted file mode 100644 index 058e64a6..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/deviceservice.go +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "reflect" -) - -// DeviceService represents a service that is responsible for proxying connectivity between a set of devices and the -// EdgeX Foundry core services. -type DeviceService struct { - DescribedObject - Id string `json:"id"` - Name string `json:"name"` // time in milliseconds that the device last provided any feedback or responded to any request - LastConnected int64 `json:"lastConnected"` // time in milliseconds that the device last reported data to the core - LastReported int64 `json:"lastReported"` // operational state - either enabled or disabled - OperatingState OperatingState `json:"operatingState"` // operational state - ether enabled or disableddc - Labels []string `json:"labels"` // tags or other labels applied to the device service for search or other identification needs - Addressable Addressable `json:"addressable"` // address (MQTT topic, HTTP address, serial bus, etc.) for reaching the service - AdminState AdminState `json:"adminState"` // Device Service Admin State - isValidated bool // internal member used for validation check -} - -// MarshalJSON implements the Marshaler interface in order to make empty strings null -func (ds DeviceService) MarshalJSON() ([]byte, error) { - test := struct { - DescribedObject `json:",inline"` - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` // time in milliseconds that the device last provided any feedback or responded to any request - LastConnected int64 `json:"lastConnected,omitempty"` // time in milliseconds that the device last reported data to the core - LastReported int64 `json:"lastReported,omitempty"` // operational state - either enabled or disabled - OperatingState OperatingState `json:"operatingState,omitempty"` // operational state - ether enabled or disableddc - Labels []string `json:"labels,omitempty"` // tags or other labels applied to the device service for search or other identification needs - Addressable *Addressable `json:"addressable,omitempty"` // address (MQTT topic, HTTP address, serial bus, etc.) for reaching the service - AdminState AdminState `json:"adminState,omitempty"` // Device Service Admin State - }{ - DescribedObject: ds.DescribedObject, - Id: ds.Id, - Name: ds.Name, - LastConnected: ds.LastConnected, - LastReported: ds.LastReported, - OperatingState: ds.OperatingState, - Labels: ds.Labels, - Addressable: &ds.Addressable, - AdminState: ds.AdminState, - } - - if reflect.DeepEqual(*test.Addressable, Addressable{}) { - test.Addressable = nil - } - - return json.Marshal(test) -} - -// UnmarshalJSON implements the Unmarshaler interface for the DeviceService type -func (ds *DeviceService) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - DescribedObject `json:",inline"` - Id string `json:"id"` - Name *string `json:"name"` // time in milliseconds that the device last provided any feedback or responded to any request - LastConnected int64 `json:"lastConnected"` // time in milliseconds that the device last reported data to the core - LastReported int64 `json:"lastReported"` // operational state - either enabled or disabled - OperatingState OperatingState `json:"operatingState"` // operational state - ether enabled or disableddc - Labels []string `json:"labels"` // tags or other labels applied to the device service for search or other identification needs - Addressable Addressable `json:"addressable"` // address (MQTT topic, HTTP address, serial bus, etc.) for reaching the service - AdminState AdminState `json:"adminState"` // Device Service Admin State - } - a := Alias{} - - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Set the fields - ds.AdminState = a.AdminState - ds.DescribedObject = a.DescribedObject - ds.LastConnected = a.LastConnected - ds.LastReported = a.LastReported - ds.OperatingState = a.OperatingState - ds.Labels = a.Labels - ds.Addressable = a.Addressable - ds.Id = a.Id - - // Name can be nil - if a.Name != nil { - ds.Name = *a.Name - } - - ds.isValidated, err = ds.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (ds DeviceService) Validate() (bool, error) { - if !ds.isValidated { - if ds.Id == "" && ds.Name == "" { - return false, NewErrContractInvalid("Device Service ID and Name are both blank") - } - return true, nil - } - return ds.isValidated, nil -} - -/* - * To String function for DeviceService - */ -func (ds DeviceService) String() string { - out, err := json.Marshal(ds) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/encryptiondetails.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/encryptiondetails.go deleted file mode 100644 index 99353896..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/encryptiondetails.go +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -// Encryption types -const ( - EncNone = "NONE" - EncAes = "AES" -) - -// EncryptionDetails - Provides details for encryption -// of export data per client request -type EncryptionDetails struct { - Algo string `json:"encryptionAlgorithm,omitempty"` - Key string `json:"encryptionKey,omitempty"` - InitVector string `json:"initializingVector,omitempty"` -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/errors.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/errors.go deleted file mode 100644 index 2271af2d..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/errors.go +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -// ErrContractInvalid is a specific error type for handling model validation failures. Type checking within -// the calling application will facilitate more explicit error handling whereby it's clear that validation -// has failed as opposed to something unexpected happening. -type ErrContractInvalid struct { - errMsg string -} - -// NewErrContractInvalid returns an instance of the error interface with ErrContractInvalid as its implementation. -func NewErrContractInvalid(message string) error { - return ErrContractInvalid{errMsg: message} -} - -// Error fulfills the error interface and returns an error message assembled from the state of ErrContractInvalid. -func (e ErrContractInvalid) Error() string { - return e.errMsg -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/event.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/event.go deleted file mode 100644 index de1dd58a..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/event.go +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - - "github.com/fxamacker/cbor/v2" -) - -// Event represents a single measurable event read from a device -type Event struct { - ID string `json:"id,omitempty" codec:"id,omitempty"` // ID uniquely identifies an event, for example a UUID - Pushed int64 `json:"pushed,omitempty" codec:"pushed,omitempty"` // Pushed is a timestamp indicating when the event was exported. If unexported, the value is zero. - Device string `json:"device,omitempty" codec:"device,omitempty"` // Device identifies the source of the event, can be a device name or id. Usually the device name. - Created int64 `json:"created,omitempty" codec:"created,omitempty"` // Created is a timestamp indicating when the event was created. - Modified int64 `json:"modified,omitempty" codec:"modified,omitempty"` // Modified is a timestamp indicating when the event was last modified. - Origin int64 `json:"origin,omitempty" codec:"origin,omitempty"` // Origin is a timestamp that can communicate the time of the original reading, prior to event creation - Readings []Reading `json:"readings,omitempty" codec:"readings,omitempty"` // Readings will contain zero to many entries for the associated readings of a given event. - isValidated bool // internal member used for validation check -} - -func encodeAsCBOR(e Event) ([]byte, error) { - bytes, err := cbor.Marshal(e) - if err != nil { - return []byte{}, err - } - - return bytes, nil -} - -// UnmarshalJSON implements the Unmarshaler interface for the Event type -func (e *Event) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - ID *string `json:"id"` - Pushed int64 `json:"pushed"` - Device *string `json:"device"` - Created int64 `json:"created"` - Modified int64 `json:"modified"` - Origin int64 `json:"origin"` - Readings []Reading `json:"readings"` - } - a := Alias{} - - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Set the fields - if a.ID != nil { - e.ID = *a.ID - } - if a.Device != nil { - e.Device = *a.Device - } - e.Pushed = a.Pushed - e.Created = a.Created - e.Modified = a.Modified - e.Origin = a.Origin - e.Readings = a.Readings - - e.isValidated, err = e.Validate() - return err -} - -// Validate satisfies the Validator interface -func (e Event) Validate() (bool, error) { - if !e.isValidated { - if e.Device == "" { - return false, NewErrContractInvalid("source device for event not specified") - } - } - return true, nil -} - -// String provides a JSON representation of the Event as a string -func (e Event) String() string { - out, err := json.Marshal(e) - if err != nil { - return err.Error() - } - - return string(out) -} - -// CBOR provides a byte array CBOR-encoded representation of the Event -func (e Event) CBOR() []byte { - cbor, err := encodeAsCBOR(e) - if err != nil { - return []byte{} - } - - return cbor -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/filter.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/filter.go deleted file mode 100644 index 32e4b916..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/filter.go +++ /dev/null @@ -1,21 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -// Filter - Specifies the client filters on reading data -type Filter struct { - DeviceIDs []string `json:"deviceIdentifiers,omitempty"` - ValueDescriptorIDs []string `json:"valueDescriptorIdentifiers,omitempty"` -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/get.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/get.go deleted file mode 100644 index 51cf2aae..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/get.go +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import "encoding/json" - -type Get struct { - Action `json:",omitempty" yaml:",inline"` -} - -/* - * To String function for Get Struct - */ -func (g Get) String() string { - out, err := json.Marshal(g) - if err != nil { - return err.Error() - } - return string(out) -} - -// Append the associated value descriptors to the list -func (g *Get) AllAssociatedValueDescriptors(vdNames *map[string]string) { - for _, r := range g.Action.Responses { - for _, ev := range r.ExpectedValues { - // Only add to the map if the value is not there - if _, ok := (*vdNames)[ev]; !ok { - (*vdNames)[ev] = ev - } - } - } -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/interval.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/interval.go deleted file mode 100644 index a966b86e..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/interval.go +++ /dev/null @@ -1,168 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" - "reflect" - "regexp" - "time" -) - -const ( - frequencyPattern = `^P(\d+Y)?(\d+M)?(\d+D)?(T(\d+H)?(\d+M)?(\d+S)?)?$` - timestampLayout = "20060102T150405" -) - -// Interval a period of time -type Interval struct { - Timestamps Timestamps - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` // non-database identifier for a shcedule (*must be quitue) - Start string `json:"start,omitempty"` // Start time i ISO 8601 format YYYYMMDD'T'HHmmss - End string `json:"end,omitempty"` // Start time i ISO 8601 format YYYYMMDD'T'HHmmss - Frequency string `json:"frequency,omitempty"` // how frequently should the event occur according ISO 8601 - Cron string `json:"cron,omitempty"` // cron styled regular expression indicating how often the action under interval should occur. Use either runOnce, frequency or cron and not all. - RunOnce bool `json:"runOnce,omitempty"` // boolean indicating that this interval runs one time - at the time indicated by the start - isValidated bool // internal member used for validation check -} - -// Custom marshaling to make empty strings null -func (i Interval) MarshalJSON() ([]byte, error) { - test := struct { - Timestamps *Timestamps `json:",omitempty"` - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` // non-database identifier for a schedule (*must be quitue) - Start string `json:"start,omitempty"` // Start time i ISO 8601 format YYYYMMDD'T'HHmmss - End string `json:"end,omitempty"` // Start time i ISO 8601 format YYYYMMDD'T'HHmmss - Frequency string `json:"frequency,omitempty"` // how frequently should the event occur - Cron string `json:"cron,omitempty"` // cron styled regular expression indicating how often the action under schedule should occur. Use either runOnce, frequency or cron and not all. - RunOnce bool `json:"runOnce,omitempty"` // boolean indicating that this interval runs one time - at the time indicated by the start - }{ - Timestamps: &i.Timestamps, - ID: i.ID, - Name: i.Name, - Start: i.Start, - End: i.End, - Frequency: i.Frequency, - Cron: i.Cron, - RunOnce: i.RunOnce, - } - - if reflect.DeepEqual(i.Timestamps, Timestamps{}) { - test.Timestamps = nil - } - - return json.Marshal(test) -} - -// UnmarshalJSON implements the Unmarshaler interface for the Interval type -func (i *Interval) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - Timestamps Timestamps `json:",omitempty"` - ID *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Start *string `json:"start,omitempty"` - End *string `json:"end,omitempty"` - Frequency *string `json:"frequency,omitempty"` - Cron *string `json:"cron,omitempty"` - RunOnce bool `json:"runOnce,omitempty"` - } - a := Alias{} - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Nillable fields - if a.ID != nil { - i.ID = *a.ID - } - if a.Name != nil { - i.Name = *a.Name - } - if a.Start != nil { - i.Start = *a.Start - } - if a.End != nil { - i.End = *a.End - } - if a.Frequency != nil { - i.Frequency = *a.Frequency - } - if a.Cron != nil { - i.Cron = *a.Cron - } - i.Timestamps = a.Timestamps - i.RunOnce = a.RunOnce - - i.isValidated, err = i.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (i Interval) Validate() (bool, error) { - if !i.isValidated { - if i.ID == "" && i.Name == "" { - return false, NewErrContractInvalid("Interval ID and Name are both blank") - } - if i.Start != "" { - _, err := time.Parse(timestampLayout, i.Start) - if err != nil { - return false, NewErrContractInvalid(fmt.Sprintf("error parsing Start %v", err)) - } - } - if i.End != "" { - _, err := time.Parse(timestampLayout, i.End) - if err != nil { - return false, NewErrContractInvalid(fmt.Sprintf("error parsing End %v", err)) - } - } - if i.Frequency != "" { - /* legacy frequencyPattern */ - matched, _ := regexp.MatchString(frequencyPattern, i.Frequency) - if matched { - if i.Frequency == "P" || i.Frequency == "PT" { - matched = false - } - } - if !matched { - // parse frequency example "1h15m30s10us9ns" - _, err := time.ParseDuration(i.Frequency) - if err != nil { - return false, NewErrContractInvalid(fmt.Sprintf("invalid Interval frequency %s format", i.Frequency)) - } - } - } - err := validate(i) - if err != nil { - return false, err - } - return true, nil - } - return i.isValidated, nil -} - -// String returns a JSON encoded string representation of this Interval -func (i Interval) String() string { - out, err := json.Marshal(i) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/interval_action.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/interval_action.go deleted file mode 100644 index 7bb894cb..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/interval_action.go +++ /dev/null @@ -1,153 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "strconv" - "strings" -) - -type IntervalAction struct { - ID string `json:"id,omitempty"` - Created int64 `json:"created,omitempty"` - Modified int64 `json:"modified,omitempty"` - Origin int64 `json:"origin,omitempty"` - Name string `json:"name,omitempty"` - Interval string `json:"interval,omitempty"` - Parameters string `json:"parameters,omitempty"` - Target string `json:"target,omitempty"` - Protocol string `json:"protocol,omitempty"` - HTTPMethod string `json:"httpMethod,omitempty"` - Address string `json:"address,omitempty"` - Port int `json:"port,omitempty"` - Path string `json:"path,omitempty"` - Publisher string `json:"publisher,omitempty"` - User string `json:"user,omitempty"` - Password string `json:"password,omitempty"` - Topic string `json:"topic,omitempty"` - isValidated bool // internal member used for validation check -} - -// UnmarshalJSON implements the Unmarshaler interface for the IntervalAction type -func (ia *IntervalAction) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - ID *string `json:"id"` - Created int64 `json:"created"` - Modified int64 `json:"modified"` - Origin int64 `json:"origin"` - Name *string `json:"name"` - Interval *string `json:"interval"` - Parameters *string `json:"parameters"` - Target *string `json:"target"` - Protocol *string `json:"protocol"` - HTTPMethod *string `json:"httpMethod"` - Address *string `json:"address"` - Port int `json:"port"` - Path *string `json:"path"` - Publisher *string `json:"publisher"` - User *string `json:"user"` - Password *string `json:"password"` - Topic *string `json:"topic"` - } - a := Alias{} - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Nillable fields - if a.ID != nil { - ia.ID = *a.ID - } - if a.Name != nil { - ia.Name = *a.Name - } - if a.Interval != nil { - ia.Interval = *a.Interval - } - if a.Parameters != nil { - ia.Parameters = *a.Parameters - } - if a.Target != nil { - ia.Target = *a.Target - } - if a.Protocol != nil { - ia.Protocol = *a.Protocol - } - if a.HTTPMethod != nil { - ia.HTTPMethod = *a.HTTPMethod - } - if a.Address != nil { - ia.Address = *a.Address - } - if a.Path != nil { - ia.Path = *a.Path - } - if a.Publisher != nil { - ia.Publisher = *a.Publisher - } - if a.User != nil { - ia.User = *a.User - } - if a.Password != nil { - ia.Password = *a.Password - } - if a.Topic != nil { - ia.Topic = *a.Topic - } - ia.Created = a.Created - ia.Modified = a.Modified - ia.Origin = a.Origin - ia.Port = a.Port - - ia.isValidated, err = ia.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (ia IntervalAction) Validate() (bool, error) { - if !ia.isValidated { - if ia.ID == "" && ia.Name == "" { - return false, NewErrContractInvalid("IntervalAction ID and Name are both blank") - } - if ia.Target == "" { - return false, NewErrContractInvalid("intervalAction target is blank") - } - if ia.Interval == "" { - return false, NewErrContractInvalid("intervalAction interval is blank") - } - return true, nil - } - return ia.isValidated, nil -} - -func (ia IntervalAction) String() string { - out, err := json.Marshal(ia) - if err != nil { - return err.Error() - } - return string(out) -} - -func (ia IntervalAction) GetBaseURL() string { - protocol := strings.ToLower(ia.Protocol) - address := ia.Address - port := strconv.Itoa(ia.Port) - baseUrl := protocol + "://" + address + ":" + port - return baseUrl -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/log_entry.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/log_entry.go deleted file mode 100644 index 59382251..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/log_entry.go +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" -) - -// These constants identify the log levels in order of increasing severity. -const ( - TraceLog = "TRACE" - DebugLog = "DEBUG" - InfoLog = "INFO" - WarnLog = "WARN" - ErrorLog = "ERROR" -) - -type LogEntry struct { - Level string `bson:"logLevel,omitempty" json:"logLevel"` - Args []interface{} `bson:"args,omitempty" json:"args"` - OriginService string `bson:"originService,omitempty" json:"originService"` - Message string `bson:"message,omitempty" json:"message"` - Created int64 `bson:"created,omitempty" json:"created"` - isValidated bool // internal member used for validation check -} - -// UnmarshalJSON implements the Unmarshaler interface for the LogEntry type -func (le *LogEntry) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - Level *string `json:"logLevel,omitempty"` - Args []interface{} `json:"args,omitempty"` - OriginService *string `json:"originService,omitempty"` - Message *string `json:"message,omitempty"` - Created int64 `json:"created,omitempty"` - } - a := Alias{} - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Nillable fields - if a.Level != nil { - le.Level = *a.Level - } - if a.OriginService != nil { - le.OriginService = *a.OriginService - } - if a.Message != nil { - le.Message = *a.Message - } - le.Args = a.Args - le.Created = a.Created - - le.isValidated, err = le.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (le LogEntry) Validate() (bool, error) { - if !le.isValidated { - logLevels := []string{TraceLog, DebugLog, InfoLog, WarnLog, ErrorLog} - for _, name := range logLevels { - if name == le.Level { - return true, nil - } - } - return false, NewErrContractInvalid(fmt.Sprintf("Invalid level in LogEntry: %s", le.Level)) - } - return le.isValidated, nil -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/notifications.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/notifications.go deleted file mode 100644 index bc652577..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/notifications.go +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" - "reflect" -) - -type Notification struct { - Timestamps - ID string `json:"id,omitempty"` - Slug string `json:"slug,omitempty"` - Sender string `json:"sender,omitempty"` - Category NotificationsCategory `json:"category,omitempty"` - Severity NotificationsSeverity `json:"severity,omitempty"` - Content string `json:"content,omitempty"` - Description string `json:"description,omitempty"` - Status NotificationsStatus `json:"status,omitempty"` - Labels []string `json:"labels,omitempty"` - ContentType string `json:"contenttype,omitempty"` - isValidated bool // internal member used for validation check -} - -func (n Notification) MarshalJSON() ([]byte, error) { - test := struct { - *Timestamps `json:",omitempty"` - ID string `json:"id,omitempty"` - Slug string `json:"slug,omitempty"` - Sender string `json:"sender,omitempty"` - Category NotificationsCategory `json:"category,omitempty"` - Severity NotificationsSeverity `json:"severity,omitempty"` - Content string `json:"content,omitempty"` - Description string `json:"description,omitempty"` - Status NotificationsStatus `json:"status,omitempty"` - Labels []string `json:"labels,omitempty"` - ContentType string `json:"contenttype,omitempty"` - }{ - Timestamps: &n.Timestamps, - ID: n.ID, - Slug: n.Slug, - Sender: n.Sender, - Category: n.Category, - Severity: n.Severity, - Content: n.Content, - Description: n.Description, - Status: n.Status, - Labels: n.Labels, - ContentType: n.ContentType, - } - - if reflect.DeepEqual(n.Timestamps, Timestamps{}) { - test.Timestamps = nil - } - - return json.Marshal(test) -} - -// UnmarshalJSON implements the Unmarshaler interface for the Notification type -func (n *Notification) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - Timestamps - ID *string `json:"id"` - Slug *string `json:"slug,omitempty,omitempty"` - Sender *string `json:"sender,omitempty"` - Category NotificationsCategory `json:"category,omitempty"` - Severity NotificationsSeverity `json:"severity,omitempty"` - Content *string `json:"content,omitempty"` - Description *string `json:"description,omitempty"` - Status NotificationsStatus `json:"status,omitempty"` - Labels []string `json:"labels,omitempty"` - ContentType *string `json:"contenttype,omitempty"` - } - a := Alias{} - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Nillable fields - if a.ID != nil { - n.ID = *a.ID - } - if a.Slug != nil { - n.Slug = *a.Slug - } - if a.Sender != nil { - n.Sender = *a.Sender - } - if a.Content != nil { - n.Content = *a.Content - } - if a.Description != nil { - n.Description = *a.Description - } - if a.ContentType != nil { - n.ContentType = *a.ContentType - } - n.Timestamps = a.Timestamps - n.Category = a.Category - n.Severity = a.Severity - n.Status = a.Status - n.Labels = a.Labels - - n.isValidated, err = n.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (n Notification) Validate() (bool, error) { - if !n.isValidated { - if n.ID == "" && n.Slug == "" { - return false, NewErrContractInvalid("Notifiaction ID and Slug are both blank") - } - if n.Sender == "" { - return false, NewErrContractInvalid("Sender is empty") - } - if n.Content == "" { - return false, NewErrContractInvalid("Content is empty") - } - if n.Category == "" { - return false, NewErrContractInvalid("Category is empty") - } - if n.Severity == "" { - return false, NewErrContractInvalid("Severity is empty") - } - if n.Severity != "" && n.Severity != "CRITICAL" && n.Severity != "NORMAL" { - return false, NewErrContractInvalid("Invalid notification severity") - } - if n.Category != "" && n.Category != "SECURITY" && n.Category != "HW_HEALTH" && n.Category != "SW_HEALTH" { - return false, NewErrContractInvalid("Invalid notification severity") - } - if n.Status != "" && n.Status != "NEW" && n.Status != "PROCESSED" && n.Status != "ESCALATED" { - return false, NewErrContractInvalid("Invalid notification severity") - } - err := validate(n) - if err != nil { - return false, err - } - return true, nil - } - return n.isValidated, nil -} - -/* - * To String function for Notification Struct - */ -func (n Notification) String() string { - out, err := json.Marshal(n) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/operatingstate.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/operatingstate.go deleted file mode 100644 index 96a089a2..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/operatingstate.go +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" - "strings" -) - -// OperatingState Constant String -type OperatingState string - -/* - Enabled : ENABLED - Disabled : DISABLED -*/ -const ( - Enabled = "ENABLED" - Disabled = "DISABLED" -) - -// UnmarshalJSON : Struct into json -func (os *OperatingState) UnmarshalJSON(data []byte) error { - // Extract the string from data. - var s string - if err := json.Unmarshal(data, &s); err != nil { - return fmt.Errorf("OperatingState should be a string, got %s", data) - } - - new := OperatingState(strings.ToUpper(s)) - *os = new - - return nil -} - -// Validate satisfies the Validator interface -func (os OperatingState) Validate() (bool, error) { - _, found := map[string]OperatingState{"ENABLED": Enabled, "DISABLED": Disabled}[string(os)] - if !found { - return false, NewErrContractInvalid(fmt.Sprintf("invalid OperatingState %q", os)) - } - return true, nil -} - -// GetOperatingState is called from within the router logic of the core services. For example, there are PUT calls -// like the one below from core-metadata which specify their update parameters in the URL -// -// d.HandleFunc("/{"+ID+"}/"+OPSTATE+"/{"+OPSTATE+"}", restSetDeviceOpStateById).Methods(http.MethodPut) -// -// Updates like this should be refactored to pass a body containing the new values instead of via the URL. This -// would allow us to utilize the model validation above and remove the logic from the controller. -// -// This will be removed once work on the following issue begins -- https://github.com/edgexfoundry/edgex-go/issues/1244 -func GetOperatingState(os string) (OperatingState, bool) { - os = strings.ToUpper(os) - o, err := map[string]OperatingState{"ENABLED": Enabled, "DISABLED": Disabled}[os] - return o, err -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/profileproperty.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/profileproperty.go deleted file mode 100644 index 62b07d64..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/profileproperty.go +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "reflect" -) - -type ProfileProperty struct { - Value PropertyValue `json:"value"` - Units Units `json:"units"` -} - -// MarshalJSON implements the Marshaler interface -func (pp ProfileProperty) MarshalJSON() ([]byte, error) { - test := struct { - Value *PropertyValue `json:"value,omitempty"` - Units *Units `json:"units,omitempty"` - }{ - Value: &pp.Value, - Units: &pp.Units, - } - - if reflect.DeepEqual(pp.Value, PropertyValue{}) { - test.Value = nil - } - if reflect.DeepEqual(pp.Units, Units{}) { - test.Units = nil - } - - return json.Marshal(test) -} - -// String returns a JSON encoded string representation of this ProfileProperty -func (pp ProfileProperty) String() string { - out, err := json.Marshal(pp) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/profileresource.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/profileresource.go deleted file mode 100644 index 8db1582b..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/profileresource.go +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import "encoding/json" - -type ProfileResource struct { - Name string `json:"name,omitempty" yaml:"name,omitempty"` - Get []ResourceOperation `json:"get,omitempty" yaml:"get,omitempty"` - Set []ResourceOperation `json:"set,omitempty" yaml:"set,omitempty"` -} - -// String returns a JSON encoded string representation of the model -func (pr ProfileResource) String() string { - out, err := json.Marshal(pr) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/propertyvalue.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/propertyvalue.go deleted file mode 100644 index c811baf9..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/propertyvalue.go +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" -) - -const ( - // Base64Encoding : the float value is represented in Base64 encoding - Base64Encoding = "Base64" - // ENotation : the float value is represented in eNotation - ENotation = "eNotation" -) - -type PropertyValue struct { - Type string `json:"type,omitempty" yaml:"type,omitempty"` // ValueDescriptor Type of property after transformations - ReadWrite string `json:"readWrite,omitempty" yaml:"readWrite,omitempty"` // Read/Write Permissions set for this property - Minimum string `json:"minimum,omitempty" yaml:"minimum,omitempty"` // Minimum value that can be get/set from this property - Maximum string `json:"maximum,omitempty" yaml:"maximum,omitempty"` // Maximum value that can be get/set from this property - DefaultValue string `json:"defaultValue,omitempty" yaml:"defaultValue,omitempty"` // Default value set to this property if no argument is passed - Size string `json:"size,omitempty" yaml:"size,omitempty"` // Size of this property in its type (i.e. bytes for numeric types, characters for string types) - Mask string `json:"mask,omitempty" yaml:"mask,omitempty"` // Mask to be applied prior to get/set of property - Shift string `json:"shift,omitempty" yaml:"shift,omitempty"` // Shift to be applied after masking, prior to get/set of property - Scale string `json:"scale,omitempty" yaml:"scale,omitempty"` // Multiplicative factor to be applied after shifting, prior to get/set of property - Offset string `json:"offset,omitempty" yaml:"offset,omitempty"` // Additive factor to be applied after multiplying, prior to get/set of property - Base string `json:"base,omitempty" yaml:"base,omitempty"` // Base for property to be applied to, leave 0 for no power operation (i.e. base ^ property: 2 ^ 10) - Assertion string `json:"assertion,omitempty" yaml:"assertion,omitempty"` // Required value of the property, set for checking error state. Failing an assertion condition will mark the device with an error state - Precision string `json:"precision,omitempty" yaml:"precision,omitempty"` - FloatEncoding string `json:"floatEncoding,omitempty" yaml:"floatEncoding,omitempty"` // FloatEncoding indicates the representation of floating value of reading. It should be 'Base64' or 'eNotation' - MediaType string `json:"mediaType,omitempty" yaml:"mediaType,omitempty"` -} - -// String returns a JSON encoded string representation of the model -func (pv PropertyValue) String() string { - out, err := json.Marshal(pv) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/provisionwatcher.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/provisionwatcher.go deleted file mode 100644 index 81fa8fe2..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/provisionwatcher.go +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "reflect" -) - -type ProvisionWatcher struct { - Timestamps - Id string `json:"id"` - Name string `json:"name"` // unique name and identifier of the provision watcher - Identifiers map[string]string `json:"identifiers"` // set of key value pairs that identify property (MAC, HTTP,...) and value to watch for (00-05-1B-A1-99-99, 10.0.0.1,...) - BlockingIdentifiers map[string][]string `json:"blockingidentifiers"` // set of key-values pairs that identify devices which will not be added despite matching on Identifiers - Profile DeviceProfile `json:"profile"` // device profile that should be applied to the devices available at the identifier addresses - Service DeviceService `json:"service"` // device service that new devices will be associated to - AdminState AdminState `json:"adminState"` // administrative state for new devices - either unlocked or locked - OperatingState OperatingState `validate:"-"` // Deprecated: exists for historical compatibility and will be ignored - isValidated bool `` // internal member used for validation check -} - -// MarshalJSON returns a JSON encoded byte representation of the model -func (pw ProvisionWatcher) MarshalJSON() ([]byte, error) { - test := struct { - Timestamps - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` // unique name and identifier of the addressable - Identifiers *map[string]string `json:"identifiers,omitempty"` // set of key value pairs that identify property (MAC, HTTP,...) and value to watch for (00-05-1B-A1-99-99, 10.0.0.1,...) - BlockingIdentifiers *map[string][]string `json:"blockingidentifiers,omitempty"` // set of key-values pairs that identify devices which will not be added despite matching on Identifiers - Profile *DeviceProfile `json:"profile,omitempty"` // device profile that should be applied to the devices available at the identifier addresses - Service *DeviceService `json:"service,omitempty"` // device service that new devices will be associated to - AdminState AdminState `json:"adminState,omitempty"` // administrative state for new devices - either unlocked or locked - }{ - Timestamps: pw.Timestamps, - Id: pw.Id, - Name: pw.Name, - Identifiers: &pw.Identifiers, - BlockingIdentifiers: &pw.BlockingIdentifiers, - Profile: &pw.Profile, - Service: &pw.Service, - AdminState: pw.AdminState, - } - - // Empty maps are null - if len(pw.Identifiers) == 0 { - test.Identifiers = nil - } - if len(pw.BlockingIdentifiers) == 0 { - test.BlockingIdentifiers = nil - } - - // Empty objects are nil - if reflect.DeepEqual(pw.Profile, DeviceProfile{}) { - test.Profile = nil - } - if reflect.DeepEqual(pw.Service, DeviceService{}) { - test.Service = nil - } - - return json.Marshal(test) -} - -// UnmarshalJSON implements the Unmarshaler interface for the ProvisionWatcher type -func (pw *ProvisionWatcher) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - Timestamps `json:",inline"` - Id string `json:"id"` - Name *string `json:"name"` - Identifiers map[string]string `json:"identifiers"` - BlockingIdentifiers map[string][]string `json:"blockingidentifiers"` - Profile DeviceProfile `json:"profile"` - Service DeviceService `json:"service"` - AdminState AdminState `json:"adminState"` - } - a := Alias{} - - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Name can be nil - if a.Name != nil { - pw.Name = *a.Name - } - pw.Timestamps = a.Timestamps - pw.Id = a.Id - pw.Identifiers = a.Identifiers - pw.BlockingIdentifiers = a.BlockingIdentifiers - pw.Profile = a.Profile - pw.Service = a.Service - pw.AdminState = a.AdminState - - pw.isValidated, err = pw.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (pw ProvisionWatcher) Validate() (bool, error) { - if !pw.isValidated { - if pw.Name == "" { - return false, NewErrContractInvalid("provision watcher name is blank") - } - err := validate(pw) - if err != nil { - return false, err - } - return true, nil - } - return pw.isValidated, nil -} - -// String returns a JSON encoded string representation of the model -func (pw ProvisionWatcher) String() string { - out, err := json.Marshal(pw) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/put.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/put.go deleted file mode 100644 index 4f5ab01f..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/put.go +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import "encoding/json" - -// Put models a put command in EdgeX -type Put struct { - Action `yaml:",inline"` - ParameterNames []string `json:"parameterNames,omitempty" yaml:"parameterNames,omitempty"` -} - -// String returns a JSON encoded string representation of the model -func (p Put) String() string { - out, err := json.Marshal(p) - if err != nil { - return err.Error() - } - return string(out) -} - -// Append the associated value descriptors to the list -func (p *Put) AllAssociatedValueDescriptors(vdNames *map[string]string) { - for _, pn := range p.ParameterNames { - // Only add to the map if the value descriptor is NOT there - if _, ok := (*vdNames)[pn]; !ok { - (*vdNames)[pn] = pn - } - } -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/reading.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/reading.go deleted file mode 100644 index c3f590d4..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/reading.go +++ /dev/null @@ -1,178 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "strings" -) - -// Constants related to Reading ValueTypes -const ( - ValueTypeBool = "Bool" - ValueTypeString = "String" - ValueTypeUint8 = "Uint8" - ValueTypeUint16 = "Uint16" - ValueTypeUint32 = "Uint32" - ValueTypeUint64 = "Uint64" - ValueTypeInt8 = "Int8" - ValueTypeInt16 = "Int16" - ValueTypeInt32 = "Int32" - ValueTypeInt64 = "Int64" - ValueTypeFloat32 = "Float32" - ValueTypeFloat64 = "Float64" - ValueTypeBinary = "Binary" - ValueTypeBoolArray = "BoolArray" - ValueTypeStringArray = "StringArray" - ValueTypeUint8Array = "Uint8Array" - ValueTypeUint16Array = "Uint16Array" - ValueTypeUint32Array = "Uint32Array" - ValueTypeUint64Array = "Uint64Array" - ValueTypeInt8Array = "Int8Array" - ValueTypeInt16Array = "Int16Array" - ValueTypeInt32Array = "Int32Array" - ValueTypeInt64Array = "Int64Array" - ValueTypeFloat32Array = "Float32Array" - ValueTypeFloat64Array = "Float64Array" -) - -// Reading contains data that was gathered from a device. -// -// NOTE a Reading's BinaryValue is not to be persisted in the database. This architectural decision requires that -// serialization validation be relaxed for enforcing the presence of binary data for Binary ValueTypes. Also, that -// issuing GET operations to obtain Readings directly or indirectly via Events will result in a Reading with no -// BinaryValue for Readings with a ValueType of Binary. BinaryValue is to be present when creating or updating a Reading -// either directly, indirectly via an Event, and when the information is put on the EventBus. -type Reading struct { - Id string `json:"id,omitempty" codec:"id,omitempty"` - Pushed int64 `json:"pushed,omitempty" codec:"pushed,omitempty"` // When the data was pushed out of EdgeX (0 - not pushed yet) - Created int64 `json:"created,omitempty" codec:"created,omitempty"` // When the reading was created - Origin int64 `json:"origin,omitempty" codec:"origin,omitempty"` - Modified int64 `json:"modified,omitempty" codec:"modified,omitempty"` - Device string `json:"device,omitempty" codec:"device,omitempty"` - Name string `json:"name,omitempty" codec:"name,omitempty"` - Value string `json:"value,omitempty" codec:"value,omitempty"` // Device sensor data value - ValueType string `json:"valueType,omitempty" codec:"valueType,omitempty"` - FloatEncoding string `json:"floatEncoding,omitempty" codec:"floatEncoding,omitempty"` - // BinaryValue binary data payload. This information is not persisted in the Database and is expected to be empty - // when retrieving a Reading for the ValueType of Binary. - BinaryValue []byte `json:"binaryValue,omitempty" codec:"binaryValue,omitempty"` - MediaType string `json:"mediaType,omitempty" codec:"mediaType,omitempty"` - isValidated bool // internal member used for validation check -} - -// UnmarshalJSON implements the Unmarshaler interface for the Reading type -func (r *Reading) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - Id *string `json:"id"` - Pushed int64 `json:"pushed"` - Created int64 `json:"created"` - Origin int64 `json:"origin"` - Modified int64 `json:"modified"` - Device *string `json:"device"` - Name *string `json:"name"` - Value *string `json:"value"` - ValueType *string `json:"valueType"` - FloatEncoding *string `json:"floatEncoding"` - BinaryValue []byte `json:"binaryValue"` - MediaType *string `json:"mediaType"` - } - a := Alias{} - - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Set the fields - if a.Id != nil { - r.Id = *a.Id - } - if a.Device != nil { - r.Device = *a.Device - } - if a.Name != nil { - r.Name = *a.Name - } - if a.Value != nil { - r.Value = *a.Value - } - if a.ValueType != nil { - r.ValueType = normalizeValueTypeCase(*a.ValueType) - } - if a.FloatEncoding != nil { - r.FloatEncoding = *a.FloatEncoding - } - if a.MediaType != nil { - r.MediaType = *a.MediaType - } - r.Pushed = a.Pushed - r.Created = a.Created - r.Origin = a.Origin - r.Modified = a.Modified - r.BinaryValue = a.BinaryValue - - r.isValidated, err = r.Validate() - return err -} - -// Validate satisfies the Validator interface -func (r Reading) Validate() (bool, error) { - // Shortcut if Reading has already been validated - if r.isValidated { - return true, nil - } - - if r.Name == "" { - return false, NewErrContractInvalid("name for reading's value descriptor not specified") - } - // We do not expect the BinaryValue to always be present. This is due to an architectural decision to not persist - // Binary readings to save on memory. This means that the BinaryValue is only expected to be populated when creating - // a new reading or event. Otherwise the value will be empty as it will be coming from the database where we are - // explicitly not storing the information. - if r.ValueType != ValueTypeBinary && r.Value == "" { - return false, NewErrContractInvalid("reading has no value") - } - - // Even though we do not want to enforce the BinaryValue always being present for Readings, we still want to enforce - // the MediaType being specified when the BinaryValue is provided. This will most likely only take affect when - // creating and updating events or readings. - if len(r.BinaryValue) != 0 && len(r.MediaType) == 0 { - return false, NewErrContractInvalid("media type must be specified for binary values") - } - - if (r.ValueType == ValueTypeFloat32 || r.ValueType == ValueTypeFloat64) && len(r.FloatEncoding) == 0 { - return false, NewErrContractInvalid("float encoding must be specified for float values") - } - return true, nil -} - -// normalizeValueTypeCase normalize the reading's valueType to upper camel case -func normalizeValueTypeCase(valueType string) string { - normalized := strings.Title(strings.ToLower(valueType)) - normalized = strings.ReplaceAll(normalized, "array", "Array") - return normalized -} - -// String returns a JSON encoded string representation of the model -func (r Reading) String() string { - out, err := json.Marshal(r) - if err != nil { - return err.Error() - } - - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/resourceoperation.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/resourceoperation.go deleted file mode 100644 index f4dfcfec..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/resourceoperation.go +++ /dev/null @@ -1,151 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import "encoding/json" - -type ResourceOperation struct { - Index string `json:"index" yaml:"index,omitempty"` - Operation string `json:"operation" yaml:"operation,omitempty"` - Object string `json:"object" yaml:"object,omitempty"` // Deprecated - DeviceResource string `json:"deviceResource" yaml:"deviceResource,omitempty"` // The replacement of Object field - Parameter string `json:"parameter" yaml:"parameter,omitempty"` - Resource string `json:"resource" yaml:"resource,omitempty"` // Deprecated - DeviceCommand string `json:"deviceCommand" yaml:"deviceCommand,omitempty"` // The replacement of Resource field - Secondary []string `json:"secondary" yaml:"secondary,omitempty"` - Mappings map[string]string `json:"mappings" yaml:"mappings,omitempty"` - isValidated bool // internal member used for validation check -} - -// MarshalJSON returns a JSON encoded byte representation of the model and performs custom autofill -func (ro ResourceOperation) MarshalJSON() ([]byte, error) { - test := struct { - Index string `json:"index,omitempty"` - Operation string `json:"operation,omitempty"` - Object string `json:"object,omitempty"` - DeviceResource string `json:"deviceResource,omitempty"` - Parameter string `json:"parameter,omitempty"` - Resource string `json:"resource,omitempty"` - DeviceCommand string `json:"deviceCommand,omitempty"` - Secondary []string `json:"secondary,omitempty"` - Mappings *map[string]string `json:"mappings,omitempty"` - }{ - Index: ro.Index, - Operation: ro.Operation, - Object: ro.Object, - DeviceResource: ro.DeviceResource, - Parameter: ro.Parameter, - Resource: ro.Resource, - DeviceCommand: ro.DeviceCommand, - Secondary: ro.Secondary, - Mappings: &ro.Mappings, - } - - // Empty maps are nil - if len(ro.Mappings) == 0 { - test.Mappings = nil - } - - if ro.DeviceResource != "" { - test.Object = ro.DeviceResource - } else if ro.Object != "" { - test.Object = ro.Object - test.DeviceResource = ro.Object - } - - if ro.DeviceCommand != "" { - test.Resource = ro.DeviceCommand - } else if ro.Resource != "" { - test.DeviceCommand = ro.Resource - } - - return json.Marshal(test) -} - -// UnmarshalJSON implements the Unmarshaler interface for the ResourceOperation type -func (ro *ResourceOperation) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - Index *string `json:"index"` - Operation *string `json:"operation"` - Object *string `json:"object"` - DeviceResource *string `json:"deviceResource"` - Parameter *string `json:"parameter"` - Resource *string `json:"resource"` - DeviceCommand *string `json:"deviceCommand"` - Secondary []string `json:"secondary"` - Mappings map[string]string `json:"mappings"` - } - a := Alias{} - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Check nil fields - if a.Index != nil { - ro.Index = *a.Index - } - if a.Operation != nil { - ro.Operation = *a.Operation - } - if a.DeviceResource != nil { - ro.DeviceResource = *a.DeviceResource - ro.Object = *a.DeviceResource - } else if a.Object != nil { - ro.Object = *a.Object - ro.DeviceResource = *a.Object - } - if a.Parameter != nil { - ro.Parameter = *a.Parameter - } - if a.DeviceCommand != nil { - ro.DeviceCommand = *a.DeviceCommand - ro.Resource = *a.DeviceCommand - } else if a.Resource != nil { - ro.Resource = *a.Resource - ro.DeviceCommand = *a.Resource - } - ro.Secondary = a.Secondary - ro.Mappings = a.Mappings - - ro.isValidated, err = ro.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (ro ResourceOperation) Validate() (bool, error) { - if !ro.isValidated { - if ro.Object == "" && ro.DeviceResource == "" { - return false, NewErrContractInvalid("Object and DeviceResource are both blank") - } - err := validate(ro) - if err != nil { - return false, err - } - return true, nil - } - return ro.isValidated, nil -} - -// String returns a JSON encoded string representation of the model -func (ro ResourceOperation) String() string { - out, err := json.Marshal(ro) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/response.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/response.go deleted file mode 100644 index ed55c702..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/response.go +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "reflect" - "strings" -) - -// Response for a Get or Put request to a service -type Response struct { - Code string `json:"code,omitempty" yaml:"code,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - ExpectedValues []string `json:"expectedValues,omitempty" yaml:"expectedValues,omitempty"` -} - -// String returns a JSON encoded string representation of the model -func (r Response) String() string { - out, err := json.Marshal(r) - if err != nil { - return err.Error() - } - return string(out) -} - -func (r Response) Equals(r2 Response) bool { - if strings.Compare(r.Code, r2.Code) != 0 { - return false - } - if strings.Compare(r.Description, r2.Description) != 0 { - return false - } - if len(r.ExpectedValues) != len(r2.ExpectedValues) { - return false - } - if !reflect.DeepEqual(r.ExpectedValues, r2.ExpectedValues) { - return false - } - return true - -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/severity.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/severity.go deleted file mode 100644 index 22ba5b34..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/severity.go +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" -) - -type NotificationsSeverity string - -const ( - Critical = "CRITICAL" - Normal = "NORMAL" -) - -func (as *NotificationsSeverity) UnmarshalJSON(data []byte) error { - // Extract the string from data. - var s string - if err := json.Unmarshal(data, &s); err != nil { - return fmt.Errorf("NotificationsSeverity should be a string, got %s", data) - } - - got, err := map[string]NotificationsSeverity{"CRITICAL": Critical, "NORMAL": Normal}[s] - if !err { - return fmt.Errorf("invalid NotificationsSeverity %q", s) - } - *as = got - return nil -} - -func IsNotificationsSeverity(as string) bool { - _, err := map[string]NotificationsSeverity{"CRITICAL": Critical, "NORMAL": Normal}[as] - if !err { - return false - } - return true -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/sma_operation.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/sma_operation.go deleted file mode 100644 index 8951473a..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/sma_operation.go +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" -) - -/* - * An Operation for SMA processing. - * - * - * Operation struct - */ -type Operation struct { - Action string `bson:"action" json:"action,omitempty"` - Services []string `bson:"services,omitempty" json:"services,omitempty"` -} - -//Implements unmarshaling of JSON string to Operation type instance -func (o *Operation) UnmarshalJSON(data []byte) error { - test := struct { - Action *string `json:"action"` - Services []string `json:"services"` - }{} - - //Verify that incoming string will unmarshal successfully - if err := json.Unmarshal(data, &test); err != nil { - return err - } - - //If so, copy the fields - if test.Action != nil { - o.Action = *test.Action - } - - o.Services = []string{} - if len(test.Services) > 0 { - o.Services = test.Services - } - return nil -} - -// String returns a JSON encoded string representation of the model -func (o Operation) String() string { - out, err := json.Marshal(o) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/status.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/status.go deleted file mode 100644 index 6ac808b2..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/status.go +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" -) - -type NotificationsStatus string - -const ( - New = "NEW" - Processed = "PROCESSED" - Escalated = "ESCALATED" -) - -func (as *NotificationsStatus) UnmarshalJSON(data []byte) error { - // Extract the string from data. - var s string - if err := json.Unmarshal(data, &s); err != nil { - return fmt.Errorf("NotificationsStatus should be a string, got %s", data) - } - - got, err := map[string]NotificationsStatus{"NEW": New, "PROCESSED": Processed, "ESCALATED": Escalated}[s] - if !err { - return fmt.Errorf("invalid NotificationsStatus %q", s) - } - *as = got - return nil -} - -func IsNotificationsStatus(as string) bool { - _, err := map[string]NotificationsStatus{"NEW": New, "PROCESSED": Processed, "ESCALATED": Escalated}[as] - if !err { - return false - } - return true -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/subscription.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/subscription.go deleted file mode 100644 index 0f1e86f8..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/subscription.go +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" -) - -// Subscription represents an object for notification alerts -type Subscription struct { - Timestamps - ID string `json:"id,omitempty"` - Slug string `json:"slug,omitempty"` - Receiver string `json:"receiver,omitempty"` - Description string `json:"description,omitempty"` - SubscribedCategories []NotificationsCategory `json:"subscribedCategories,omitempty"` - SubscribedLabels []string `json:"subscribedLabels,omitempty"` - Channels []Channel `json:"channels,omitempty"` -} - -// String returns a JSON encoded string representation of the model -func (s Subscription) String() string { - out, err := json.Marshal(s) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/timestamps.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/timestamps.go deleted file mode 100644 index fb5a0ee2..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/timestamps.go +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" -) - -type Timestamps struct { - Created int64 `json:"created,omitempty" yaml:"created,omitempty"` - Modified int64 `json:"modified,omitempty" yaml:"modified,omitempty"` - Origin int64 `json:"origin,omitempty" yaml:"origin,omitempty"` -} - -// String returns a JSON encoded string representation of the model -func (ts *Timestamps) String() string { - out, err := json.Marshal(ts) - if err != nil { - return err.Error() - } - return string(out) -} - -/* - * Compare the Created of two objects to determine given is newer - */ -func (ts *Timestamps) compareTo(i Timestamps) int { - if i.Created > ts.Created { - return 1 - } - return -1 -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission.go deleted file mode 100644 index eb0851af..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission.go +++ /dev/null @@ -1,147 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" - "reflect" -) - -type Transmission struct { - Timestamps - ID string `json:"id"` - Notification Notification `json:"notification"` - Receiver string `json:"receiver,omitempty"` - Channel Channel `json:"channel,omitempty"` - Status TransmissionStatus `json:"status,omitempty"` - ResendCount int `json:"resendcount"` - Records []TransmissionRecord `json:"records,omitempty"` - isValidated bool -} - -// Marshal returns a JSON encoded byte array representation of the model -func (t Transmission) MarshalJSON() ([]byte, error) { - alias := struct { - Timestamps - ID string `json:"id,omitempty"` - Notification *Notification `json:"notification,omitempty"` - Receiver string `json:"receiver,omitempty"` - Channel *Channel `json:"channel,omitempty"` - Status TransmissionStatus `json:"status,omitempty"` - ResendCount *int `json:"resendcount,omitempty"` - Records []TransmissionRecord `json:"records,omitempty"` - }{ - Timestamps: t.Timestamps, - ID: t.ID, - Notification: &t.Notification, - Receiver: t.Receiver, - Channel: &t.Channel, - Status: t.Status, - ResendCount: &t.ResendCount, - Records: t.Records, - } - - // if we don't use omitempty, then an empty object always has a ResendCount included - // if we do use omitempty, then a ResendCount of 0 is not included in the object when it should be - if reflect.DeepEqual(t, Transmission{}) { - alias.ResendCount = nil - } - // do not marshal empty member objects - if reflect.DeepEqual(t.Notification, Notification{}) { - alias.Notification = nil - } - if reflect.DeepEqual(t.Channel, Channel{}) { - alias.Channel = nil - } - - return json.Marshal(alias) -} - -// UnmarshalJSON implements the Unmarshaler interface for the Transmission type -func (t *Transmission) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - Timestamps - ID *string `json:"id"` - Notification Notification `json:"notification,omitempty"` - Receiver *string `json:"receiver,omitempty"` - Channel Channel `json:"channel,omitempty"` - Status TransmissionStatus `json:"status,omitempty"` - ResendCount int `json:"resendcount"` - Records []TransmissionRecord `json:"records,omitempty"` - } - a := Alias{} - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - // Nillable fields - if a.ID != nil { - t.ID = *a.ID - } - if a.Receiver != nil { - t.Receiver = *a.Receiver - } - - t.Notification = a.Notification - t.Channel = a.Channel - t.Status = a.Status - t.ResendCount = a.ResendCount - t.Records = a.Records - t.Timestamps = a.Timestamps - - t.isValidated, err = t.Validate() - - return err -} - -// Validate satisfies the Validator interface -func (t Transmission) Validate() (bool, error) { - if !t.isValidated { - - if t.Notification.Slug == "" { - return false, NewErrContractInvalid("Transmission's Notification is blank") - } - if t.Receiver == "" { - return false, NewErrContractInvalid("Transmission's Receiver is blank") - } - if t.Channel.Type == "" { - return false, NewErrContractInvalid("Transmission's Channel is blank") - } - if t.Status == "" { - return false, NewErrContractInvalid("Transmission's Status is blank") - } - if t.ResendCount < 0 { - return false, NewErrContractInvalid("Transmission's ResendCount is blank") - } - - err := validate(t) - if err != nil { - return false, err - } - return true, nil - } - return t.isValidated, nil -} - -// String returns a JSON encoded string representation of the model -func (t Transmission) String() string { - out, err := json.Marshal(t) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission_record.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission_record.go deleted file mode 100644 index cdecc199..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission_record.go +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" -) - -type TransmissionRecord struct { - Status TransmissionStatus `json:"status,omitempty"` - Response string `json:"response,omitempty"` - Sent int64 `json:"sent,omitempty"` -} - -// String returns a JSON encoded string representation of the model -func (t TransmissionRecord) String() string { - out, err := json.Marshal(t) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission_status.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission_status.go deleted file mode 100644 index d4202072..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/transmission_status.go +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" - "strings" -) - -type TransmissionStatus string - -const ( - Failed = "FAILED" - Sent = "SENT" - Acknowledged = "ACKNOWLEDGED" - Trxescalated = "TRXESCALATED" -) - -/* - * Unmarshal the enum type - */ -func (as *TransmissionStatus) UnmarshalJSON(data []byte) error { - // Extract the string from data. - var s string - if err := json.Unmarshal(data, &s); err != nil { - return fmt.Errorf("TransmissionStatus should be a string, got %s", data) - } - - new := TransmissionStatus(strings.ToUpper(s)) - *as = new - return nil -} - -func (as TransmissionStatus) Validate() (bool, error) { - _, found := map[string]TransmissionStatus{"FAILED": Failed, "SENT": Sent, "ACKNOWLEDGED": Acknowledged, "TRXESCALATED": Trxescalated}[string(as)] - if !found { - return false, NewErrContractInvalid(fmt.Sprintf("invalid Transmission Status %q", as)) - } - return true, nil -} - -func IsTransmissionStatus(as string) bool { - _, err := map[string]TransmissionStatus{"FAILED": Failed, "SENT": Sent, "ACKNOWLEDGED": Acknowledged, "TRXESCALATED": Trxescalated}[as] - if !err { - return false - } - return true -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/units.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/units.go deleted file mode 100644 index fdc409fa..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/units.go +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import "encoding/json" - -type Units struct { - Type string `json:"type,omitempty" yaml:"type,omitempty"` - ReadWrite string `json:"readWrite,omitempty" yaml:"readWrite,omitempty"` - DefaultValue string `json:"defaultValue,omitempty" yaml:"defaultValue,omitempty"` -} - -// String returns a JSON encoded string representation of the model -func (u Units) String() string { - out, err := json.Marshal(u) - if err != nil { - return err.Error() - } - return string(out) -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/validator.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/validator.go deleted file mode 100644 index 74b8573d..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/validator.go +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "reflect" -) - -const ( - ValidateTag = "validate" -) - -// Validator provides an interface for struct types to implement validation of their internal state. They can also -// indicate to a caller whether their validation has already been completed. -// -// NOTE: This cannot be applied to struct types that are simply aliased to a primitive. -type Validator interface { - // Validate performs integrity checks on the internal state of the model. It returns a boolean indicating whether - // the validation passed or not, and the associated error if validation was unsuccessful. - Validate() (bool, error) -} - -func validate(t interface{}) error { - val := reflect.ValueOf(t) - typ := reflect.TypeOf(t) - fields := val.NumField() - for f := 0; f < fields; f++ { - field := val.Field(f) - typfield := typ.Field(f) - if field.Type().NumMethod() > 0 && field.CanInterface() && typfield.Tag.Get(ValidateTag) != "-" { - if v, ok := field.Interface().(Validator); ok { - cast := v.(Validator) - _, err := cast.Validate() - if err != nil { - return NewErrContractInvalid(err.Error()) - } - } - } - } - return nil -} diff --git a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/value-descriptor.go b/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/value-descriptor.go deleted file mode 100644 index 0e42854b..00000000 --- a/vendor/github.com/edgexfoundry/go-mod-core-contracts/models/value-descriptor.go +++ /dev/null @@ -1,164 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Inc. - * - * 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 models - -import ( - "encoding/json" - "fmt" - "regexp" -) - -// defaultValueDescriptorFormat defines the default formatting value used with creating a ValueDescriptor from a DeviceResource. -const defaultValueDescriptorFormat = "%s" - -/* - * Value Descriptor Struct - */ -type ValueDescriptor struct { - Id string `json:"id,omitempty"` - Created int64 `json:"created,omitempty"` - Description string `json:"description,omitempty"` - Modified int64 `json:"modified,omitempty"` - Origin int64 `json:"origin,omitempty"` - Name string `json:"name,omitempty"` - Min interface{} `json:"min,omitempty"` - Max interface{} `json:"max,omitempty"` - DefaultValue interface{} `json:"defaultValue,omitempty"` - Type string `json:"type,omitempty"` - UomLabel string `json:"uomLabel,omitempty"` - Formatting string `json:"formatting,omitempty"` - Labels []string `json:"labels,omitempty"` - MediaType string `json:"mediaType,omitempty"` - FloatEncoding string `json:"floatEncoding,omitempty"` - isValidated bool // internal member used for validation check -} - -// UnmarshalJSON implements the Unmarshaler interface for the ValueDescriptor type -func (v *ValueDescriptor) UnmarshalJSON(data []byte) error { - var err error - type Alias struct { - Id *string `json:"id"` - Created int64 `json:"created"` - Description *string `json:"description"` - Modified int64 `json:"modified"` - Origin int64 `json:"origin"` - Name *string `json:"name"` - Min *interface{} `json:"min"` - Max *interface{} `json:"max"` - DefaultValue *interface{} `json:"defaultValue"` - Type *string `json:"type"` - UomLabel *string `json:"uomLabel"` - Formatting *string `json:"formatting"` - Labels []string `json:"labels"` - MediaType *string `json:"mediaType"` - FloatEncoding *string `json:"floatEncoding"` - } - a := Alias{} - // Error with unmarshaling - if err = json.Unmarshal(data, &a); err != nil { - return err - } - - // Set the fields - if a.Id != nil { - v.Id = *a.Id - } - if a.Description != nil { - v.Description = *a.Description - } - if a.Name != nil { - v.Name = *a.Name - } - if a.Min != nil { - v.Min = *a.Min - } - if a.Max != nil { - v.Max = *a.Max - } - if a.DefaultValue != nil { - v.DefaultValue = *a.DefaultValue - } - if a.Type != nil { - v.Type = *a.Type - } - if a.UomLabel != nil { - v.UomLabel = *a.UomLabel - } - if a.Formatting != nil { - v.Formatting = *a.Formatting - } - if a.MediaType != nil { - v.MediaType = *a.MediaType - } - if a.FloatEncoding != nil { - v.FloatEncoding = *a.FloatEncoding - } - v.Created = a.Created - v.Modified = a.Modified - v.Origin = a.Origin - v.Labels = a.Labels - - v.isValidated, err = v.Validate() - return err -} - -// Validate satisfies the Validator interface -func (v ValueDescriptor) Validate() (bool, error) { - if !v.isValidated { - if v.Formatting != "" { - formatSpecifier := "%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])" - match, err := regexp.MatchString(formatSpecifier, v.Formatting) - if err != nil { - return false, NewErrContractInvalid(fmt.Sprintf("error validating format string: %s", v.Formatting)) - } - if !match { - return false, NewErrContractInvalid(fmt.Sprintf("format is not a valid printf format: %s", v.Formatting)) - } - } - if v.Name == "" { - return false, NewErrContractInvalid("name for value descriptor not specified") - } - } - return true, nil -} - -// String returns a JSON encoded string representation of the model -func (a ValueDescriptor) String() string { - out, err := json.Marshal(a) - if err != nil { - return err.Error() - } - return string(out) -} - -// From creates a ValueDescriptor based on the information provided in the DeviceResource. -func From(dr DeviceResource) ValueDescriptor { - value := dr.Properties.Value - units := dr.Properties.Units - desc := ValueDescriptor{ - Name: dr.Name, - Min: value.Minimum, - Max: value.Maximum, - Type: value.Type, - UomLabel: units.DefaultValue, - DefaultValue: value.DefaultValue, - Formatting: defaultValueDescriptorFormat, - Description: dr.Description, - FloatEncoding: value.FloatEncoding, - MediaType: value.MediaType, - } - - return desc -} diff --git a/vendor/github.com/fxamacker/cbor/v2/.gitignore b/vendor/github.com/fxamacker/cbor/v2/.gitignore deleted file mode 100644 index f1c181ec..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out diff --git a/vendor/github.com/fxamacker/cbor/v2/.golangci.yml b/vendor/github.com/fxamacker/cbor/v2/.golangci.yml deleted file mode 100644 index 4c31d564..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/.golangci.yml +++ /dev/null @@ -1,76 +0,0 @@ -# Do not delete linter settings. Linters like gocritic can be enabled on the command line. - -linters-settings: - dupl: - threshold: 100 - funlen: - lines: 100 - statements: 50 - goconst: - min-len: 2 - min-occurrences: 3 - gocritic: - enabled-tags: - - diagnostic - - experimental - - opinionated - - performance - - style - disabled-checks: - - dupImport # https://github.com/go-critic/go-critic/issues/845 - - ifElseChain - - octalLiteral - - paramTypeCombine - - whyNoLint - - wrapperFunc - gofmt: - simplify: false - goimports: - local-prefixes: github.com/fxamacker/cbor - golint: - min-confidence: 0 - govet: - check-shadowing: true - lll: - line-length: 140 - maligned: - suggest-new: true - misspell: - locale: US - -linters: - disable-all: true - enable: - - errcheck - - goconst - - gocyclo - # - gofmt # handled by safer-golangci-lint.yml - # - goimports # handled by safer-golangci-lint.yml - - gosec - - govet - - ineffassign - - misspell - # - revive # temporarily disabled to reduce noise in golangci-lint 1.52.2 - - staticcheck - - typecheck - - unconvert - - unused - -issues: - # max-issues-per-linter default is 50. Set to 0 to disable limit. - max-issues-per-linter: 0 - # max-same-issues default is 3. Set to 0 to disable limit. - max-same-issues: 0 - # Excluding configuration per-path, per-linter, per-text and per-source - exclude-rules: - - path: _test\.go - linters: - - goconst - - dupl - - gomnd - - lll - - path: doc\.go - linters: - - goimports - - gomnd - - lll diff --git a/vendor/github.com/fxamacker/cbor/v2/CODE_OF_CONDUCT.md b/vendor/github.com/fxamacker/cbor/v2/CODE_OF_CONDUCT.md deleted file mode 100644 index c794b2b0..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,133 +0,0 @@ - -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, caste, color, religion, or sexual -identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall - community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or advances of - any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, - without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders 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, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -faye.github@gmail.com. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of -actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or permanent -ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the -community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.1, available at -[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. - -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. - -For answers to common questions about this code of conduct, see the FAQ at -[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at -[https://www.contributor-covenant.org/translations][translations]. - -[homepage]: https://www.contributor-covenant.org -[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity -[FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations diff --git a/vendor/github.com/fxamacker/cbor/v2/CONTRIBUTING.md b/vendor/github.com/fxamacker/cbor/v2/CONTRIBUTING.md deleted file mode 100644 index de0965e1..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/CONTRIBUTING.md +++ /dev/null @@ -1,41 +0,0 @@ -# How to contribute - -You can contribute by using the library, opening issues, or opening pull requests. - -## Bug reports and security vulnerabilities - -Most issues are tracked publicly on [GitHub](https://github.com/fxamacker/cbor/issues). - -To report security vulnerabilities, please email faye.github@gmail.com and allow time for the problem to be resolved before disclosing it to the public. For more info, see [Security Policy](https://github.com/fxamacker/cbor#security-policy). - -Please do not send data that might contain personally identifiable information, even if you think you have permission. That type of support requires payment and a signed contract where I'm indemnified, held harmless, and defended by you for any data you send to me. - -## Pull requests - -Please [create an issue](https://github.com/fxamacker/cbor/issues/new/choose) before you begin work on a PR. The improvement may have already been considered, etc. - -Pull requests have signing requirements and must not be anonymous. Exceptions are usually made for docs and CI scripts. - -See the [Pull Request Template](https://github.com/fxamacker/cbor/blob/master/.github/pull_request_template.md) for details. - -Pull requests have a greater chance of being approved if: -- it does not reduce speed, increase memory use, reduce security, etc. for people not using the new option or feature. -- it has > 97% code coverage. - -## Describe your issue - -Clearly describe the issue: -* If it's a bug, please provide: **version of this library** and **Go** (`go version`), **unmodified error message**, and describe **how to reproduce it**. Also state **what you expected to happen** instead of the error. -* If you propose a change or addition, try to give an example how the improved code could look like or how to use it. -* If you found a compilation error, please confirm you're using a supported version of Go. If you are, then provide the output of `go version` first, followed by the complete error message. - -## Please don't - -Please don't send data containing personally identifiable information, even if you think you have permission. That type of support requires payment and a contract where I'm indemnified, held harmless, and defended for any data you send to me. - -Please don't send CBOR data larger than 1024 bytes by email. If you want to send crash-producing CBOR data > 1024 bytes by email, please get my permission before sending it to me. - -## Credits - -- This guide used nlohmann/json contribution guidelines for inspiration as suggested in issue #22. -- Special thanks to @lukseven for pointing out the contribution guidelines didn't mention signing requirements. diff --git a/vendor/github.com/fxamacker/cbor/v2/LICENSE b/vendor/github.com/fxamacker/cbor/v2/LICENSE deleted file mode 100644 index eaa85049..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019-present Faye Amacker - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/fxamacker/cbor/v2/README.md b/vendor/github.com/fxamacker/cbor/v2/README.md deleted file mode 100644 index f6409495..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/README.md +++ /dev/null @@ -1,452 +0,0 @@ -# CBOR Codec in Go - - - -[fxamacker/cbor](https://github.com/fxamacker/cbor) is a library for encoding and decoding [CBOR](https://www.rfc-editor.org/info/std94) and [CBOR Sequences](https://www.rfc-editor.org/rfc/rfc8742.html). - -CBOR is a [trusted alternative](https://www.rfc-editor.org/rfc/rfc8949.html#name-comparison-of-other-binary-) to JSON, MessagePack, Protocol Buffers, etc.  CBOR is an Internet Standard defined by [IETF STD 94 (RFC 8949)](https://www.rfc-editor.org/info/std94) and is designed to be relevant for decades. - -`fxamacker/cbor` is used in projects by Arm Ltd., Cisco, Dapper Labs, EdgeX Foundry, Fraunhofer‑AISEC, Linux Foundation, Microsoft, Mozilla, Oasis Protocol, Tailscale, Teleport, [and others](https://github.com/fxamacker/cbor#who-uses-fxamackercbor). - -See [Quick Start](#quick-start). - -## fxamacker/cbor - -[![](https://github.com/fxamacker/cbor/workflows/ci/badge.svg)](https://github.com/fxamacker/cbor/actions?query=workflow%3Aci) -[![](https://github.com/fxamacker/cbor/workflows/cover%20%E2%89%A596%25/badge.svg)](https://github.com/fxamacker/cbor/actions?query=workflow%3A%22cover+%E2%89%A596%25%22) -[![CodeQL](https://github.com/fxamacker/cbor/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/fxamacker/cbor/actions/workflows/codeql-analysis.yml) -[![](https://img.shields.io/badge/fuzzing-passing-44c010)](#fuzzing-and-code-coverage) -[![Go Report Card](https://goreportcard.com/badge/github.com/fxamacker/cbor)](https://goreportcard.com/report/github.com/fxamacker/cbor) -[![](https://img.shields.io/ossf-scorecard/github.com/fxamacker/cbor?label=openssf%20scorecard)](https://github.com/fxamacker/cbor#fuzzing-and-code-coverage) - -`fxamacker/cbor` is a CBOR codec in full conformance with [IETF STD 94 (RFC 8949)](https://www.rfc-editor.org/info/std94). It also supports CBOR Sequences ([RFC 8742](https://www.rfc-editor.org/rfc/rfc8742.html)) and Extended Diagnostic Notation ([Appendix G of RFC 8610](https://www.rfc-editor.org/rfc/rfc8610.html#appendix-G)). - -Features include full support for CBOR tags, [Core Deterministic Encoding](https://www.rfc-editor.org/rfc/rfc8949.html#name-core-deterministic-encoding), duplicate map key detection, etc. - -Struct tags (`toarray`, `keyasint`, `omitempty`) reduce encoded size of structs. - -![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.3.0/cbor_struct_tags_api.svg?sanitize=1 "CBOR API and Go Struct Tags") - -API is mostly same as `encoding/json`, plus interfaces that simplify concurrency for CBOR options. - -#### CBOR Security - -Configurable limits help defend against malicious inputs. - -Decoding 10 bytes of malicious data directly into `[]byte` is efficiently rejected. - -| Codec | Speed (ns/op) | Memory | Allocs | -| :---- | ------------: | -----: | -----: | -| fxamacker/cbor 2.5.0 | 43.95n ± 5% | 32 B/op | 2 allocs/op | -| ugorji/go 1.2.11 | 5353261.00n ± 4% | 67111321 B/op | 13 allocs/op | - -
More Details and Prior Comparions

- -Latest comparison used: -- Input: `[]byte{0x9B, 0x00, 0x00, 0x42, 0xFA, 0x42, 0xFA, 0x42, 0xFA, 0x42}` -- go1.19.10, linux/amd64, i5-13600K (disabled all e-cores, DDR4 @2933) -- go test -bench=. -benchmem -count=20 - -#### Prior comparisons - -| Codec | Speed (ns/op) | Memory | Allocs | -| :---- | ------------: | -----: | -----: | -| fxamacker/cbor 2.5.0-beta2 | 44.33 ± 2% | 32 B/op | 2 allocs/op | -| fxamacker/cbor 0.1.0 - 2.4.0 | ~44.68 ± 6% | 32 B/op | 2 allocs/op | -| ugorji/go 1.2.10 | 5524792.50 ± 3% | 67110491 B/op | 12 allocs/op | -| ugorji/go 1.1.0 - 1.2.6 | 💥 runtime: | out of memory: | cannot allocate | - -- Input: `[]byte{0x9B, 0x00, 0x00, 0x42, 0xFA, 0x42, 0xFA, 0x42, 0xFA, 0x42}` -- go1.19.6, linux/amd64, i5-13600K (DDR4) -- go test -bench=. -benchmem -count=20 - -

- -#### Design and Feature Highlights - -Design balances tradeoffs between speed, security, memory, encoded data size, usability, etc. - -
Highlights

- -__🚀  Speed__ - -Encoding and decoding is fast without using Go's `unsafe` package. Slower settings are opt-in. Default limits allow very fast and memory efficient rejection of malformed CBOR data. - -__🔒  Security__ - -Decoder has configurable limits that defend against malicious inputs. Duplicate map key detection is supported. By contrast, `encoding/gob` is [not designed to be hardened against adversarial inputs](https://pkg.go.dev/encoding/gob#hdr-Security). - -Codec passed multiple confidential security assessments in 2022. No vulnerabilities found in subset of codec in a [nonconfidential security assessment](https://github.com/veraison/go-cose/blob/v1.0.0-rc.1/reports/NCC_Microsoft-go-cose-Report_2022-05-26_v1.0.pdf) prepared by NCC Group for Microsoft Corporation. - -__🗜️  Data Size__ - -Struct tags (`toarray`, `keyasint`, `omitempty`) automatically reduce size of encoded structs. Encoding optionally shrinks float64→32→16 when values fit. - -__:jigsaw:  Usability__ - -API is mostly same as `encoding/json` plus interfaces that simplify concurrency for CBOR options. Encoding and decoding modes can be created at startup and reused by any goroutines. - -Presets include Core Deterministic Encoding, Preferred Serialization, CTAP2 Canonical CBOR, etc. - -__📆  Extensibility__ - -Features include CBOR [extension points](https://www.rfc-editor.org/rfc/rfc8949.html#section-7.1) (e.g. CBOR tags) and extensive settings. API has interfaces that allow users to create custom encoding and decoding without modifying this library. - -

- -## Quick Start - -__Install__: `go get github.com/fxamacker/cbor/v2` and `import "github.com/fxamacker/cbor/v2"`. - -### Key Points - -- Encoding and decoding modes are created from options (settings). -- Modes can be created at startup and reused. -- Modes are safe for concurrent use. - -### Default Mode - -Package level functions only use default settings. -They provide the "default mode" of encoding and decoding. - -```go -// API matches encoding/json. -b, err := cbor.Marshal(v) // encode v to []byte b -err := cbor.Unmarshal(b, &v) // decode []byte b to v -encoder := cbor.NewEncoder(w) // create encoder with io.Writer w -decoder := cbor.NewDecoder(r) // create decoder with io.Reader r -``` - -Some CBOR-based formats or protocols may require non-default settings. - -For example, WebAuthn uses "CTAP2 Canonical CBOR" settings. It is available as a preset. - -### Presets - -Presets can be used as-is or as a starting point for custom settings. - -```go -// EncOptions is a struct of encoder settings. -func CoreDetEncOptions() EncOptions // RFC 8949 Core Deterministic Encoding -func PreferredUnsortedEncOptions() EncOptions // RFC 8949 Preferred Serialization -func CanonicalEncOptions() EncOptions // RFC 7049 Canonical CBOR -func CTAP2EncOptions() EncOptions // FIDO2 CTAP2 Canonical CBOR -``` - -Presets are used to create custom modes. - -### Custom Modes - -Modes are created from settings. Once created, modes have immutable settings. - -💡 Create the mode at startup and reuse it. It is safe for concurrent use. - -```Go -// Create encoding mode. -opts := cbor.CoreDetEncOptions() // use preset options as a starting point -opts.Time = cbor.TimeUnix // change any settings if needed -em, err := opts.EncMode() // create an immutable encoding mode - -// Reuse the encoding mode. It is safe for concurrent use. - -// API matches encoding/json. -b, err := em.Marshal(v) // encode v to []byte b -encoder := em.NewEncoder(w) // create encoder with io.Writer w -err := encoder.Encode(v) // encode v to io.Writer w -``` - -Default mode and custom modes automatically apply struct tags. - -### Struct Tags - -Struct tags (`toarray`, `keyasint`, `omitempty`) reduce encoded size of structs. - -
Example using struct tags

- -![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.3.0/cbor_struct_tags_api.svg?sanitize=1 "CBOR API and Go Struct Tags") - -

- -Struct tags simplify use of CBOR-based protocols that require CBOR arrays or maps with integer keys. - -### CBOR Tags - -CBOR tags are specified in a `TagSet`. - -Custom modes can be created with a `TagSet` to handle CBOR tags. - -```go -em, err := opts.EncMode() // no CBOR tags -em, err := opts.EncModeWithTags(ts) // immutable CBOR tags -em, err := opts.EncModeWithSharedTags(ts) // mutable shared CBOR tags -``` - -`TagSet` and modes using it are safe for concurrent use. Equivalent API is available for `DecMode`. - -
Example using TagSet and TagOptions

- -```go -// Use signedCWT struct defined in "Decoding CWT" example. - -// Create TagSet (safe for concurrency). -tags := cbor.NewTagSet() -// Register tag COSE_Sign1 18 with signedCWT type. -tags.Add( - cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, - reflect.TypeOf(signedCWT{}), - 18) - -// Create DecMode with immutable tags. -dm, _ := cbor.DecOptions{}.DecModeWithTags(tags) - -// Unmarshal to signedCWT with tag support. -var v signedCWT -if err := dm.Unmarshal(data, &v); err != nil { - return err -} - -// Create EncMode with immutable tags. -em, _ := cbor.EncOptions{}.EncModeWithTags(tags) - -// Marshal signedCWT with tag number. -if data, err := cbor.Marshal(v); err != nil { - return err -} -``` - -

- -### Functions and Interfaces - -
Functions and interfaces at a glance

- -Common functions with same API as `encoding/json`: -- `Marshal`, `Unmarshal` -- `NewEncoder`, `(*Encoder).Encode` -- `NewDecoder`, `(*Decoder).Decode` - -NOTE: `Unmarshal` will return `ExtraneousDataError` if there are remaining bytes -because RFC 8949 treats CBOR data item with remaining bytes as malformed. -- 💡 Use `UnmarshalFirst` to decode first CBOR data item and return any remaining bytes. - -Other useful functions: -- `Diagnose`, `DiagnoseFirst` produce human-readable [Extended Diagnostic Notation](https://www.rfc-editor.org/rfc/rfc8610.html#appendix-G) from CBOR data. -- `UnmarshalFirst` decodes first CBOR data item and return any remaining bytes. -- `Wellformed` returns true if the the CBOR data item is well-formed. - -Interfaces identical or comparable to Go `encoding` packages include: -`Marshaler`, `Unmarshaler`, `BinaryMarshaler`, and `BinaryUnmarshaler`. - -The `RawMessage` type can be used to delay CBOR decoding or precompute CBOR encoding. - -

- -### Security Tips - -🔒 Use Go's `io.LimitReader` to limit size when decoding very large or indefinite size data. - -Default limits may need to be increased for systems handling very large data (e.g. blockchains). - -`DecOptions` can be used to modify default limits for `MaxArrayElements`, `MaxMapPairs`, and `MaxNestedLevels`. - -## Status - -v2.5.0 was released on Sunday, August 13, 2023. It is fuzz tested and production quality. - -__IMPORTANT__: Before upgrading from prior release, please read the notable changes highlighted in the release notes. - -See latest [releases](https://github.com/fxamacker/cbor/releases) and [v2.5.0 release notes](https://github.com/fxamacker/cbor/releases/tag/v2.5.0) for list of new features and improvements. - - - -## Who uses fxamacker/cbor - -`fxamacker/cbor` is used in projects by Arm Ltd., Berlin Institute of Health at Charité, Chainlink, Cisco, Confidential Computing Consortium, ConsenSys, Dapper Labs, EdgeX Foundry, F5, Fraunhofer‑AISEC, Linux Foundation, Microsoft, Mozilla, National Cybersecurity Agency of France (govt), Netherlands (govt), Oasis Protocol, Smallstep, Tailscale, Taurus SA, Teleport, TIBCO, and others. - -Although GitHub only reports around 200 repos depend on this library, that is for v1 (old version). For v2 (current version), GitHub reports [2000+ repositories](https://github.com/fxamacker/cbor/network/dependents?package_id=UGFja2FnZS0yMjcwNDY1OTQ4) depend on fxamacker/cbor. - -`fxamacker/cbor` passed multiple confidential security assessments. A [nonconfidential security assessment](https://github.com/veraison/go-cose/blob/v1.0.0-rc.1/reports/NCC_Microsoft-go-cose-Report_2022-05-26_v1.0.pdf) (prepared by NCC Group for Microsoft Corporation) includes a subset of fxamacker/cbor v2.4.0 in its scope. - -## Standards -This library is a full-featured generic CBOR [(RFC 8949)](https://tools.ietf.org/html/rfc8949) encoder and decoder. Notable CBOR features include: - -| CBOR Feature | Description | -| :--- | :--- | -| CBOR tags | API supports built-in and user-defined tags. | -| Preferred serialization | Integers encode to fewest bytes. Optional float64 → float32 → float16. | -| Map key sorting | Unsorted, length-first (Canonical CBOR), and bytewise-lexicographic (CTAP2). | -| Duplicate map keys | Always forbid for encoding and option to allow/forbid for decoding. | -| Indefinite length data | Option to allow/forbid for encoding and decoding. | -| Well-formedness | Always checked and enforced. | -| Basic validity checks | Optionally check UTF-8 validity and duplicate map keys. | -| Security considerations | Prevent integer overflow and resource exhaustion (RFC 8949 Section 10). | - -Known limitations are noted in the [Limitations section](#limitations). - -Go nil values for slices, maps, pointers, etc. are encoded as CBOR null. Empty slices, maps, etc. are encoded as empty CBOR arrays and maps. - -Decoder checks for all required well-formedness errors, including all "subkinds" of syntax errors and too little data. - -After well-formedness is verified, basic validity errors are handled as follows: - -* Invalid UTF-8 string: Decoder has option to check and return invalid UTF-8 string error. This check is enabled by default. -* Duplicate keys in a map: Decoder has options to ignore or enforce rejection of duplicate map keys. - -When decoding well-formed CBOR arrays and maps, decoder saves the first error it encounters and continues with the next item. Options to handle this differently may be added in the future. - -By default, decoder treats time values of floating-point NaN and Infinity as if they are CBOR Null or CBOR Undefined. - -__Click to expand topic:__ - -
- Duplicate Map Keys

- -This library provides options for fast detection and rejection of duplicate map keys based on applying a Go-specific data model to CBOR's extended generic data model in order to determine duplicate vs distinct map keys. Detection relies on whether the CBOR map key would be a duplicate "key" when decoded and applied to the user-provided Go map or struct. - -`DupMapKeyQuiet` turns off detection of duplicate map keys. It tries to use a "keep fastest" method by choosing either "keep first" or "keep last" depending on the Go data type. - -`DupMapKeyEnforcedAPF` enforces detection and rejection of duplidate map keys. Decoding stops immediately and returns `DupMapKeyError` when the first duplicate key is detected. The error includes the duplicate map key and the index number. - -APF suffix means "Allow Partial Fill" so the destination map or struct can contain some decoded values at the time of error. It is the caller's responsibility to respond to the `DupMapKeyError` by discarding the partially filled result if that's required by their protocol. - -

- -
- Tag Validity

- -This library checks tag validity for built-in tags (currently tag numbers 0, 1, 2, 3, and 55799): - -* Inadmissible type for tag content -* Inadmissible value for tag content - -Unknown tag data items (not tag number 0, 1, 2, 3, or 55799) are handled in two ways: - -* When decoding into an empty interface, unknown tag data item will be decoded into `cbor.Tag` data type, which contains tag number and tag content. The tag content will be decoded into the default Go data type for the CBOR data type. -* When decoding into other Go types, unknown tag data item is decoded into the specified Go type. If Go type is registered with a tag number, the tag number can optionally be verified. - -Decoder also has an option to forbid tag data items (treat any tag data item as error) which is specified by protocols such as CTAP2 Canonical CBOR. - -For more information, see [decoding options](#decoding-options-1) and [tag options](#tag-options). - -

- -## Limitations - -If any of these limitations prevent you from using this library, please open an issue along with a link to your project. - -* CBOR `Undefined` (0xf7) value decodes to Go's `nil` value. CBOR `Null` (0xf6) more closely matches Go's `nil`. -* CBOR map keys with data types not supported by Go for map keys are ignored and an error is returned after continuing to decode remaining items. -* When decoding registered CBOR tag data to interface type, decoder creates a pointer to registered Go type matching CBOR tag number. Requiring a pointer for this is a Go limitation. - -## Fuzzing and Code Coverage - -__Code coverage__ must not fall below 95% when tagging a release. Code coverage is above 96% (`go test -cover`) for fxamacker/cbor v2.5. - -__Coverage-guided fuzzing__ must pass billions of execs using before tagging a release. Fuzzing is done using nonpublic code which may eventually get merged into this project. Until then, reports like OpenSSF Scorecard can't detect fuzz tests being used by this project. - -
- -## Versions and API Changes -This project uses [Semantic Versioning](https://semver.org), so the API is always backwards compatible unless the major version number changes. - -These functions have signatures identical to encoding/json and they will likely never change even after major new releases: -`Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder`, `(*Encoder).Encode`, and `(*Decoder).Decode`. - -Exclusions from SemVer: -- Newly added API documented as "subject to change". -- Newly added API in the master branch that has never been release tagged. -- Bug fixes that change behavior (e.g. return error that was missed in prior version) if function parameters are unchanged. We try to highlight these in the release notes. - -## Code of Conduct - -This project has adopted the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md). Contact [faye.github@gmail.com](mailto:faye.github@gmail.com) with any questions or comments. - -## Contributing - -Please open an issue before beginning work on a PR. The improvement may have already been considered, etc. - -For more info, see [How to Contribute](CONTRIBUTING.md). - -## Security Policy - -Security fixes are provided for the latest released version of fxamacker/cbor. - -For the full text of the Security Policy, see [SECURITY.md](SECURITY.md). - -## Acknowledgements - -Many thanks to all the contributors on this project! - -I'm especially grateful to Bastian Müller and Dieter Shirley for suggesting and collaborating on CBOR stream mode, and much more. - -I'm very grateful to Stefan Tatschner, Yawning Angel, Jernej Kos, x448, ZenGround0, and Jakob Borg for their contributions or support in the very early days. - -This library clearly wouldn't be possible without Carsten Bormann authoring CBOR RFCs. - -Special thanks to Laurence Lundblade and Jeffrey Yasskin for their help on IETF mailing list or at [7049bis](https://github.com/cbor-wg/CBORbis). - -This library uses `x448/float16` which used to be included. Now as a standalone package, `x448/float16` is useful to other projects as well. - -## License -Copyright © 2019-2023 [Faye Amacker](https://github.com/fxamacker). - -fxamacker/cbor is licensed under the MIT License. See [LICENSE](LICENSE) for the full license text. - -
diff --git a/vendor/github.com/fxamacker/cbor/v2/SECURITY.md b/vendor/github.com/fxamacker/cbor/v2/SECURITY.md deleted file mode 100644 index 9c05146d..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/SECURITY.md +++ /dev/null @@ -1,7 +0,0 @@ -# Security Policy - -Security fixes are provided for the latest released version of fxamacker/cbor. - -If the security vulnerability is already known to the public, then you can open an issue as a bug report. - -To report security vulnerabilities not yet known to the public, please email faye.github@gmail.com and allow time for the problem to be resolved before reporting it to the public. diff --git a/vendor/github.com/fxamacker/cbor/v2/bytestring.go b/vendor/github.com/fxamacker/cbor/v2/bytestring.go deleted file mode 100644 index 26f5ef91..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/bytestring.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) Faye Amacker. All rights reserved. -// Licensed under the MIT License. See LICENSE in the project root for license information. - -package cbor - -import ( - "errors" -) - -// ByteString represents CBOR byte string (major type 2). ByteString can be used -// when using a Go []byte is not possible or convenient. For example, Go doesn't -// allow []byte as map key, so ByteString can be used to support data formats -// having CBOR map with byte string keys. ByteString can also be used to -// encode invalid UTF-8 string as CBOR byte string. -// See DecOption.MapKeyByteStringMode for more details. -type ByteString string - -// Bytes returns bytes representing ByteString. -func (bs ByteString) Bytes() []byte { - return []byte(bs) -} - -// MarshalCBOR encodes ByteString as CBOR byte string (major type 2). -func (bs ByteString) MarshalCBOR() ([]byte, error) { - e := getEncoderBuffer() - defer putEncoderBuffer(e) - - // Encode length - encodeHead(e, byte(cborTypeByteString), uint64(len(bs))) - - // Encode data - buf := make([]byte, e.Len()+len(bs)) - n := copy(buf, e.Bytes()) - copy(buf[n:], bs) - - return buf, nil -} - -// UnmarshalCBOR decodes CBOR byte string (major type 2) to ByteString. -// Decoding CBOR null and CBOR undefined sets ByteString to be empty. -func (bs *ByteString) UnmarshalCBOR(data []byte) error { - if bs == nil { - return errors.New("cbor.ByteString: UnmarshalCBOR on nil pointer") - } - - // Decoding CBOR null and CBOR undefined to ByteString resets data. - // This behavior is similar to decoding CBOR null and CBOR undefined to []byte. - if len(data) == 1 && (data[0] == 0xf6 || data[0] == 0xf7) { - *bs = "" - return nil - } - - d := decoder{data: data, dm: defaultDecMode} - - // Check if CBOR data type is byte string - if typ := d.nextCBORType(); typ != cborTypeByteString { - return &UnmarshalTypeError{CBORType: typ.String(), GoType: typeByteString.String()} - } - - *bs = ByteString(d.parseByteString()) - return nil -} diff --git a/vendor/github.com/fxamacker/cbor/v2/cache.go b/vendor/github.com/fxamacker/cbor/v2/cache.go deleted file mode 100644 index 2fdf114b..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/cache.go +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright (c) Faye Amacker. All rights reserved. -// Licensed under the MIT License. See LICENSE in the project root for license information. - -package cbor - -import ( - "bytes" - "errors" - "reflect" - "sort" - "strconv" - "strings" - "sync" -) - -type encodeFuncs struct { - ef encodeFunc - ief isEmptyFunc -} - -var ( - decodingStructTypeCache sync.Map // map[reflect.Type]*decodingStructType - encodingStructTypeCache sync.Map // map[reflect.Type]*encodingStructType - encodeFuncCache sync.Map // map[reflect.Type]encodeFuncs - typeInfoCache sync.Map // map[reflect.Type]*typeInfo -) - -type specialType int - -const ( - specialTypeNone specialType = iota - specialTypeUnmarshalerIface - specialTypeEmptyIface - specialTypeIface - specialTypeTag - specialTypeTime -) - -type typeInfo struct { - elemTypeInfo *typeInfo - keyTypeInfo *typeInfo - typ reflect.Type - kind reflect.Kind - nonPtrType reflect.Type - nonPtrKind reflect.Kind - spclType specialType -} - -func newTypeInfo(t reflect.Type) *typeInfo { - tInfo := typeInfo{typ: t, kind: t.Kind()} - - for t.Kind() == reflect.Ptr { - t = t.Elem() - } - - k := t.Kind() - - tInfo.nonPtrType = t - tInfo.nonPtrKind = k - - if k == reflect.Interface { - if t.NumMethod() == 0 { - tInfo.spclType = specialTypeEmptyIface - } else { - tInfo.spclType = specialTypeIface - } - } else if t == typeTag { - tInfo.spclType = specialTypeTag - } else if t == typeTime { - tInfo.spclType = specialTypeTime - } else if reflect.PtrTo(t).Implements(typeUnmarshaler) { - tInfo.spclType = specialTypeUnmarshalerIface - } - - switch k { - case reflect.Array, reflect.Slice: - tInfo.elemTypeInfo = getTypeInfo(t.Elem()) - case reflect.Map: - tInfo.keyTypeInfo = getTypeInfo(t.Key()) - tInfo.elemTypeInfo = getTypeInfo(t.Elem()) - } - - return &tInfo -} - -type decodingStructType struct { - fields fields - err error - toArray bool -} - -func getDecodingStructType(t reflect.Type) *decodingStructType { - if v, _ := decodingStructTypeCache.Load(t); v != nil { - return v.(*decodingStructType) - } - - flds, structOptions := getFields(t) - - toArray := hasToArrayOption(structOptions) - - var err error - for i := 0; i < len(flds); i++ { - if flds[i].keyAsInt { - nameAsInt, numErr := strconv.Atoi(flds[i].name) - if numErr != nil { - err = errors.New("cbor: failed to parse field name \"" + flds[i].name + "\" to int (" + numErr.Error() + ")") - break - } - flds[i].nameAsInt = int64(nameAsInt) - } - - flds[i].typInfo = getTypeInfo(flds[i].typ) - } - - structType := &decodingStructType{fields: flds, err: err, toArray: toArray} - decodingStructTypeCache.Store(t, structType) - return structType -} - -type encodingStructType struct { - fields fields - bytewiseFields fields - lengthFirstFields fields - omitEmptyFieldsIdx []int - err error - toArray bool - fixedLength bool // Struct type doesn't have any omitempty or anonymous fields. -} - -func (st *encodingStructType) getFields(em *encMode) fields { - if em.sort == SortNone { - return st.fields - } - if em.sort == SortLengthFirst { - return st.lengthFirstFields - } - return st.bytewiseFields -} - -type bytewiseFieldSorter struct { - fields fields -} - -func (x *bytewiseFieldSorter) Len() int { - return len(x.fields) -} - -func (x *bytewiseFieldSorter) Swap(i, j int) { - x.fields[i], x.fields[j] = x.fields[j], x.fields[i] -} - -func (x *bytewiseFieldSorter) Less(i, j int) bool { - return bytes.Compare(x.fields[i].cborName, x.fields[j].cborName) <= 0 -} - -type lengthFirstFieldSorter struct { - fields fields -} - -func (x *lengthFirstFieldSorter) Len() int { - return len(x.fields) -} - -func (x *lengthFirstFieldSorter) Swap(i, j int) { - x.fields[i], x.fields[j] = x.fields[j], x.fields[i] -} - -func (x *lengthFirstFieldSorter) Less(i, j int) bool { - if len(x.fields[i].cborName) != len(x.fields[j].cborName) { - return len(x.fields[i].cborName) < len(x.fields[j].cborName) - } - return bytes.Compare(x.fields[i].cborName, x.fields[j].cborName) <= 0 -} - -func getEncodingStructType(t reflect.Type) (*encodingStructType, error) { - if v, _ := encodingStructTypeCache.Load(t); v != nil { - structType := v.(*encodingStructType) - return structType, structType.err - } - - flds, structOptions := getFields(t) - - if hasToArrayOption(structOptions) { - return getEncodingStructToArrayType(t, flds) - } - - var err error - var hasKeyAsInt bool - var hasKeyAsStr bool - var omitEmptyIdx []int - fixedLength := true - e := getEncoderBuffer() - for i := 0; i < len(flds); i++ { - // Get field's encodeFunc - flds[i].ef, flds[i].ief = getEncodeFunc(flds[i].typ) - if flds[i].ef == nil { - err = &UnsupportedTypeError{t} - break - } - - // Encode field name - if flds[i].keyAsInt { - nameAsInt, numErr := strconv.Atoi(flds[i].name) - if numErr != nil { - err = errors.New("cbor: failed to parse field name \"" + flds[i].name + "\" to int (" + numErr.Error() + ")") - break - } - flds[i].nameAsInt = int64(nameAsInt) - if nameAsInt >= 0 { - encodeHead(e, byte(cborTypePositiveInt), uint64(nameAsInt)) - } else { - n := nameAsInt*(-1) - 1 - encodeHead(e, byte(cborTypeNegativeInt), uint64(n)) - } - flds[i].cborName = make([]byte, e.Len()) - copy(flds[i].cborName, e.Bytes()) - e.Reset() - - hasKeyAsInt = true - } else { - encodeHead(e, byte(cborTypeTextString), uint64(len(flds[i].name))) - flds[i].cborName = make([]byte, e.Len()+len(flds[i].name)) - n := copy(flds[i].cborName, e.Bytes()) - copy(flds[i].cborName[n:], flds[i].name) - e.Reset() - - hasKeyAsStr = true - } - - // Check if field is from embedded struct - if len(flds[i].idx) > 1 { - fixedLength = false - } - - // Check if field can be omitted when empty - if flds[i].omitEmpty { - fixedLength = false - omitEmptyIdx = append(omitEmptyIdx, i) - } - } - putEncoderBuffer(e) - - if err != nil { - structType := &encodingStructType{err: err} - encodingStructTypeCache.Store(t, structType) - return structType, structType.err - } - - // Sort fields by canonical order - bytewiseFields := make(fields, len(flds)) - copy(bytewiseFields, flds) - sort.Sort(&bytewiseFieldSorter{bytewiseFields}) - - lengthFirstFields := bytewiseFields - if hasKeyAsInt && hasKeyAsStr { - lengthFirstFields = make(fields, len(flds)) - copy(lengthFirstFields, flds) - sort.Sort(&lengthFirstFieldSorter{lengthFirstFields}) - } - - structType := &encodingStructType{ - fields: flds, - bytewiseFields: bytewiseFields, - lengthFirstFields: lengthFirstFields, - omitEmptyFieldsIdx: omitEmptyIdx, - fixedLength: fixedLength, - } - encodingStructTypeCache.Store(t, structType) - return structType, structType.err -} - -func getEncodingStructToArrayType(t reflect.Type, flds fields) (*encodingStructType, error) { - for i := 0; i < len(flds); i++ { - // Get field's encodeFunc - flds[i].ef, flds[i].ief = getEncodeFunc(flds[i].typ) - if flds[i].ef == nil { - structType := &encodingStructType{err: &UnsupportedTypeError{t}} - encodingStructTypeCache.Store(t, structType) - return structType, structType.err - } - } - - structType := &encodingStructType{ - fields: flds, - toArray: true, - fixedLength: true, - } - encodingStructTypeCache.Store(t, structType) - return structType, structType.err -} - -func getEncodeFunc(t reflect.Type) (encodeFunc, isEmptyFunc) { - if v, _ := encodeFuncCache.Load(t); v != nil { - fs := v.(encodeFuncs) - return fs.ef, fs.ief - } - ef, ief := getEncodeFuncInternal(t) - encodeFuncCache.Store(t, encodeFuncs{ef, ief}) - return ef, ief -} - -func getTypeInfo(t reflect.Type) *typeInfo { - if v, _ := typeInfoCache.Load(t); v != nil { - return v.(*typeInfo) - } - tInfo := newTypeInfo(t) - typeInfoCache.Store(t, tInfo) - return tInfo -} - -func hasToArrayOption(tag string) bool { - s := ",toarray" - idx := strings.Index(tag, s) - return idx >= 0 && (len(tag) == idx+len(s) || tag[idx+len(s)] == ',') -} diff --git a/vendor/github.com/fxamacker/cbor/v2/decode.go b/vendor/github.com/fxamacker/cbor/v2/decode.go deleted file mode 100644 index c0ee14ab..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/decode.go +++ /dev/null @@ -1,2171 +0,0 @@ -// Copyright (c) Faye Amacker. All rights reserved. -// Licensed under the MIT License. See LICENSE in the project root for license information. - -package cbor - -import ( - "encoding" - "encoding/binary" - "errors" - "fmt" - "io" - "math" - "math/big" - "reflect" - "strconv" - "strings" - "time" - "unicode/utf8" - - "github.com/x448/float16" -) - -// Unmarshal parses the CBOR-encoded data into the value pointed to by v -// using default decoding options. If v is nil, not a pointer, or -// a nil pointer, Unmarshal returns an error. -// -// To unmarshal CBOR into a value implementing the Unmarshaler interface, -// Unmarshal calls that value's UnmarshalCBOR method with a valid -// CBOR value. -// -// To unmarshal CBOR byte string into a value implementing the -// encoding.BinaryUnmarshaler interface, Unmarshal calls that value's -// UnmarshalBinary method with decoded CBOR byte string. -// -// To unmarshal CBOR into a pointer, Unmarshal sets the pointer to nil -// if CBOR data is null (0xf6) or undefined (0xf7). Otherwise, Unmarshal -// unmarshals CBOR into the value pointed to by the pointer. If the -// pointer is nil, Unmarshal creates a new value for it to point to. -// -// To unmarshal CBOR into an empty interface value, Unmarshal uses the -// following rules: -// -// CBOR booleans decode to bool. -// CBOR positive integers decode to uint64. -// CBOR negative integers decode to int64 (big.Int if value overflows). -// CBOR floating points decode to float64. -// CBOR byte strings decode to []byte. -// CBOR text strings decode to string. -// CBOR arrays decode to []interface{}. -// CBOR maps decode to map[interface{}]interface{}. -// CBOR null and undefined values decode to nil. -// CBOR times (tag 0 and 1) decode to time.Time. -// CBOR bignums (tag 2 and 3) decode to big.Int. -// -// To unmarshal a CBOR array into a slice, Unmarshal allocates a new slice -// if the CBOR array is empty or slice capacity is less than CBOR array length. -// Otherwise Unmarshal overwrites existing elements, and sets slice length -// to CBOR array length. -// -// To unmarshal a CBOR array into a Go array, Unmarshal decodes CBOR array -// elements into Go array elements. If the Go array is smaller than the -// CBOR array, the extra CBOR array elements are discarded. If the CBOR -// array is smaller than the Go array, the extra Go array elements are -// set to zero values. -// -// To unmarshal a CBOR array into a struct, struct must have a special field "_" -// with struct tag `cbor:",toarray"`. Go array elements are decoded into struct -// fields. Any "omitempty" struct field tag option is ignored in this case. -// -// To unmarshal a CBOR map into a map, Unmarshal allocates a new map only if the -// map is nil. Otherwise Unmarshal reuses the existing map and keeps existing -// entries. Unmarshal stores key-value pairs from the CBOR map into Go map. -// See DecOptions.DupMapKey to enable duplicate map key detection. -// -// To unmarshal a CBOR map into a struct, Unmarshal matches CBOR map keys to the -// keys in the following priority: -// -// 1. "cbor" key in struct field tag, -// 2. "json" key in struct field tag, -// 3. struct field name. -// -// Unmarshal tries an exact match for field name, then a case-insensitive match. -// Map key-value pairs without corresponding struct fields are ignored. See -// DecOptions.ExtraReturnErrors to return error at unknown field. -// -// To unmarshal a CBOR text string into a time.Time value, Unmarshal parses text -// string formatted in RFC3339. To unmarshal a CBOR integer/float into a -// time.Time value, Unmarshal creates an unix time with integer/float as seconds -// and fractional seconds since January 1, 1970 UTC. -// -// To unmarshal CBOR null (0xf6) and undefined (0xf7) values into a -// slice/map/pointer, Unmarshal sets Go value to nil. Because null is often -// used to mean "not present", unmarshalling CBOR null and undefined value -// into any other Go type has no effect and returns no error. -// -// Unmarshal supports CBOR tag 55799 (self-describe CBOR), tag 0 and 1 (time), -// and tag 2 and 3 (bignum). -// -// Unmarshal returns ExtraneousDataError error (without decoding into v) -// if there are any remaining bytes following the first valid CBOR data item. -// See UnmarshalFirst, if you want to unmarshal only the first -// CBOR data item without ExtraneousDataError caused by remaining bytes. -func Unmarshal(data []byte, v interface{}) error { - return defaultDecMode.Unmarshal(data, v) -} - -// UnmarshalFirst parses the first CBOR data item into the value pointed to by v -// using default decoding options. Any remaining bytes are returned in rest. -// -// If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error. -// -// See the documentation for Unmarshal for details. -func UnmarshalFirst(data []byte, v interface{}) (rest []byte, err error) { - return defaultDecMode.UnmarshalFirst(data, v) -} - -// Valid checks whether data is a well-formed encoded CBOR data item and -// that it complies with default restrictions such as MaxNestedLevels, -// MaxArrayElements, MaxMapPairs, etc. -// -// If there are any remaining bytes after the CBOR data item, -// an ExtraneousDataError is returned. -// -// WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity) -// and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed". -// -// Deprecated: Valid is kept for compatibility and should not be used. -// Use Wellformed instead because it has a more appropriate name. -func Valid(data []byte) error { - return defaultDecMode.Valid(data) -} - -// Wellformed checks whether data is a well-formed encoded CBOR data item and -// that it complies with default restrictions such as MaxNestedLevels, -// MaxArrayElements, MaxMapPairs, etc. -// -// If there are any remaining bytes after the CBOR data item, -// an ExtraneousDataError is returned. -func Wellformed(data []byte) error { - return defaultDecMode.Wellformed(data) -} - -// Unmarshaler is the interface implemented by types that wish to unmarshal -// CBOR data themselves. The input is a valid CBOR value. UnmarshalCBOR -// must copy the CBOR data if it needs to use it after returning. -type Unmarshaler interface { - UnmarshalCBOR([]byte) error -} - -// InvalidUnmarshalError describes an invalid argument passed to Unmarshal. -type InvalidUnmarshalError struct { - s string -} - -func (e *InvalidUnmarshalError) Error() string { - return e.s -} - -// UnmarshalTypeError describes a CBOR value that can't be decoded to a Go type. -type UnmarshalTypeError struct { - CBORType string // type of CBOR value - GoType string // type of Go value it could not be decoded into - StructFieldName string // name of the struct field holding the Go value (optional) - errorMsg string // additional error message (optional) -} - -func (e *UnmarshalTypeError) Error() string { - var s string - if e.StructFieldName != "" { - s = "cbor: cannot unmarshal " + e.CBORType + " into Go struct field " + e.StructFieldName + " of type " + e.GoType - } else { - s = "cbor: cannot unmarshal " + e.CBORType + " into Go value of type " + e.GoType - } - if e.errorMsg != "" { - s += " (" + e.errorMsg + ")" - } - return s -} - -// InvalidMapKeyTypeError describes invalid Go map key type when decoding CBOR map. -// For example, Go doesn't allow slice as map key. -type InvalidMapKeyTypeError struct { - GoType string -} - -func (e *InvalidMapKeyTypeError) Error() string { - return "cbor: invalid map key type: " + e.GoType -} - -// DupMapKeyError describes detected duplicate map key in CBOR map. -type DupMapKeyError struct { - Key interface{} - Index int -} - -func (e *DupMapKeyError) Error() string { - return fmt.Sprintf("cbor: found duplicate map key \"%v\" at map element index %d", e.Key, e.Index) -} - -// UnknownFieldError describes detected unknown field in CBOR map when decoding to Go struct. -type UnknownFieldError struct { - Index int -} - -func (e *UnknownFieldError) Error() string { - return fmt.Sprintf("cbor: found unknown field at map element index %d", e.Index) -} - -// DupMapKeyMode specifies how to enforce duplicate map key. -type DupMapKeyMode int - -const ( - // DupMapKeyQuiet doesn't enforce duplicate map key. Decoder quietly (no error) - // uses faster of "keep first" or "keep last" depending on Go data type and other factors. - DupMapKeyQuiet DupMapKeyMode = iota - - // DupMapKeyEnforcedAPF enforces detection and rejection of duplicate map keys. - // APF means "Allow Partial Fill" and the destination map or struct can be partially filled. - // If a duplicate map key is detected, DupMapKeyError is returned without further decoding - // of the map. It's the caller's responsibility to respond to DupMapKeyError by - // discarding the partially filled result if their protocol requires it. - // WARNING: using DupMapKeyEnforcedAPF will decrease performance and increase memory use. - DupMapKeyEnforcedAPF - - maxDupMapKeyMode -) - -func (dmkm DupMapKeyMode) valid() bool { - return dmkm < maxDupMapKeyMode -} - -// IndefLengthMode specifies whether to allow indefinite length items. -type IndefLengthMode int - -const ( - // IndefLengthAllowed allows indefinite length items. - IndefLengthAllowed IndefLengthMode = iota - - // IndefLengthForbidden disallows indefinite length items. - IndefLengthForbidden - - maxIndefLengthMode -) - -func (m IndefLengthMode) valid() bool { - return m < maxIndefLengthMode -} - -// TagsMode specifies whether to allow CBOR tags. -type TagsMode int - -const ( - // TagsAllowed allows CBOR tags. - TagsAllowed TagsMode = iota - - // TagsForbidden disallows CBOR tags. - TagsForbidden - - maxTagsMode -) - -func (tm TagsMode) valid() bool { - return tm < maxTagsMode -} - -// IntDecMode specifies which Go int type (int64 or uint64) should -// be used when decoding CBOR int (major type 0 and 1) to Go interface{}. -type IntDecMode int - -const ( - // IntDecConvertNone affects how CBOR int (major type 0 and 1) decodes to Go interface{}. - // It makes CBOR positive int (major type 0) decode to uint64 value, and - // CBOR negative int (major type 1) decode to int64 value. - IntDecConvertNone IntDecMode = iota - - // IntDecConvertSigned affects how CBOR int (major type 0 and 1) decodes to Go interface{}. - // It makes CBOR positive/negative int (major type 0 and 1) decode to int64 value. - // If value overflows int64, UnmarshalTypeError is returned. - IntDecConvertSigned - - maxIntDec -) - -func (idm IntDecMode) valid() bool { - return idm < maxIntDec -} - -// MapKeyByteStringMode specifies how to decode CBOR byte string (major type 2) -// as Go map key when decoding CBOR map key into an empty Go interface value. -// Specifically, this option applies when decoding CBOR map into -// - Go empty interface, or -// - Go map with empty interface as key type. -// The CBOR map key types handled by this option are -// - byte string -// - tagged byte string -// - nested tagged byte string -type MapKeyByteStringMode int - -const ( - // MapKeyByteStringAllowed allows CBOR byte string to be decoded as Go map key. - // Since Go doesn't allow []byte as map key, CBOR byte string is decoded to - // ByteString which has underlying string type. - // This is the default setting. - MapKeyByteStringAllowed MapKeyByteStringMode = iota - - // MapKeyByteStringForbidden forbids CBOR byte string being decoded as Go map key. - // Attempting to decode CBOR byte string as map key into empty interface value - // returns a decoding error. - MapKeyByteStringForbidden - - maxMapKeyByteStringMode -) - -func (mkbsm MapKeyByteStringMode) valid() bool { - return mkbsm < maxMapKeyByteStringMode -} - -// ExtraDecErrorCond specifies extra conditions that should be treated as errors. -type ExtraDecErrorCond uint - -// ExtraDecErrorNone indicates no extra error condition. -const ExtraDecErrorNone ExtraDecErrorCond = 0 - -const ( - // ExtraDecErrorUnknownField indicates error condition when destination - // Go struct doesn't have a field matching a CBOR map key. - ExtraDecErrorUnknownField ExtraDecErrorCond = 1 << iota - - maxExtraDecError -) - -func (ec ExtraDecErrorCond) valid() bool { - return ec < maxExtraDecError -} - -// UTF8Mode option specifies if decoder should -// decode CBOR Text containing invalid UTF-8 string. -type UTF8Mode int - -const ( - // UTF8RejectInvalid rejects CBOR Text containing - // invalid UTF-8 string. - UTF8RejectInvalid UTF8Mode = iota - - // UTF8DecodeInvalid allows decoding CBOR Text containing - // invalid UTF-8 string. - UTF8DecodeInvalid - - maxUTF8Mode -) - -func (um UTF8Mode) valid() bool { - return um < maxUTF8Mode -} - -// DecOptions specifies decoding options. -type DecOptions struct { - // DupMapKey specifies whether to enforce duplicate map key. - DupMapKey DupMapKeyMode - - // TimeTag specifies whether to check validity of time.Time (e.g. valid tag number and tag content type). - // For now, valid tag number means 0 or 1 as specified in RFC 7049 if the Go type is time.Time. - TimeTag DecTagMode - - // MaxNestedLevels specifies the max nested levels allowed for any combination of CBOR array, maps, and tags. - // Default is 32 levels and it can be set to [4, 65535]. Note that higher maximum levels of nesting can - // require larger amounts of stack to deserialize. Don't increase this higher than you require. - MaxNestedLevels int - - // MaxArrayElements specifies the max number of elements for CBOR arrays. - // Default is 128*1024=131072 and it can be set to [16, 2147483647] - MaxArrayElements int - - // MaxMapPairs specifies the max number of key-value pairs for CBOR maps. - // Default is 128*1024=131072 and it can be set to [16, 2147483647] - MaxMapPairs int - - // IndefLength specifies whether to allow indefinite length CBOR items. - IndefLength IndefLengthMode - - // TagsMd specifies whether to allow CBOR tags (major type 6). - TagsMd TagsMode - - // IntDec specifies which Go integer type (int64 or uint64) to use - // when decoding CBOR int (major type 0 and 1) to Go interface{}. - IntDec IntDecMode - - // MapKeyByteString specifies how to decode CBOR byte string as map key - // when decoding CBOR map with byte string key into an empty interface value. - // By default, an error is returned when attempting to decode CBOR byte string - // as map key because Go doesn't allow []byte as map key. - MapKeyByteString MapKeyByteStringMode - - // ExtraReturnErrors specifies extra conditions that should be treated as errors. - ExtraReturnErrors ExtraDecErrorCond - - // DefaultMapType specifies Go map type to create and decode to - // when unmarshalling CBOR into an empty interface value. - // By default, unmarshal uses map[interface{}]interface{}. - DefaultMapType reflect.Type - - // UTF8 specifies if decoder should decode CBOR Text containing invalid UTF-8. - // By default, unmarshal rejects CBOR text containing invalid UTF-8. - UTF8 UTF8Mode -} - -// DecMode returns DecMode with immutable options and no tags (safe for concurrency). -func (opts DecOptions) DecMode() (DecMode, error) { - return opts.decMode() -} - -// DecModeWithTags returns DecMode with options and tags that are both immutable (safe for concurrency). -func (opts DecOptions) DecModeWithTags(tags TagSet) (DecMode, error) { - if opts.TagsMd == TagsForbidden { - return nil, errors.New("cbor: cannot create DecMode with TagSet when TagsMd is TagsForbidden") - } - if tags == nil { - return nil, errors.New("cbor: cannot create DecMode with nil value as TagSet") - } - - dm, err := opts.decMode() - if err != nil { - return nil, err - } - - // Copy tags - ts := tagSet(make(map[reflect.Type]*tagItem)) - syncTags := tags.(*syncTagSet) - syncTags.RLock() - for contentType, tag := range syncTags.t { - if tag.opts.DecTag != DecTagIgnored { - ts[contentType] = tag - } - } - syncTags.RUnlock() - - if len(ts) > 0 { - dm.tags = ts - } - - return dm, nil -} - -// DecModeWithSharedTags returns DecMode with immutable options and mutable shared tags (safe for concurrency). -func (opts DecOptions) DecModeWithSharedTags(tags TagSet) (DecMode, error) { - if opts.TagsMd == TagsForbidden { - return nil, errors.New("cbor: cannot create DecMode with TagSet when TagsMd is TagsForbidden") - } - if tags == nil { - return nil, errors.New("cbor: cannot create DecMode with nil value as TagSet") - } - dm, err := opts.decMode() - if err != nil { - return nil, err - } - dm.tags = tags - return dm, nil -} - -const ( - defaultMaxArrayElements = 131072 - minMaxArrayElements = 16 - maxMaxArrayElements = 2147483647 - - defaultMaxMapPairs = 131072 - minMaxMapPairs = 16 - maxMaxMapPairs = 2147483647 -) - -func (opts DecOptions) decMode() (*decMode, error) { - if !opts.DupMapKey.valid() { - return nil, errors.New("cbor: invalid DupMapKey " + strconv.Itoa(int(opts.DupMapKey))) - } - if !opts.TimeTag.valid() { - return nil, errors.New("cbor: invalid TimeTag " + strconv.Itoa(int(opts.TimeTag))) - } - if !opts.IndefLength.valid() { - return nil, errors.New("cbor: invalid IndefLength " + strconv.Itoa(int(opts.IndefLength))) - } - if !opts.TagsMd.valid() { - return nil, errors.New("cbor: invalid TagsMd " + strconv.Itoa(int(opts.TagsMd))) - } - if !opts.IntDec.valid() { - return nil, errors.New("cbor: invalid IntDec " + strconv.Itoa(int(opts.IntDec))) - } - if !opts.MapKeyByteString.valid() { - return nil, errors.New("cbor: invalid MapKeyByteString " + strconv.Itoa(int(opts.MapKeyByteString))) - } - if opts.MaxNestedLevels == 0 { - opts.MaxNestedLevels = 32 - } else if opts.MaxNestedLevels < 4 || opts.MaxNestedLevels > 65535 { - return nil, errors.New("cbor: invalid MaxNestedLevels " + strconv.Itoa(opts.MaxNestedLevels) + " (range is [4, 65535])") - } - if opts.MaxArrayElements == 0 { - opts.MaxArrayElements = defaultMaxArrayElements - } else if opts.MaxArrayElements < minMaxArrayElements || opts.MaxArrayElements > maxMaxArrayElements { - return nil, errors.New("cbor: invalid MaxArrayElements " + strconv.Itoa(opts.MaxArrayElements) + " (range is [" + strconv.Itoa(minMaxArrayElements) + ", " + strconv.Itoa(maxMaxArrayElements) + "])") - } - if opts.MaxMapPairs == 0 { - opts.MaxMapPairs = defaultMaxMapPairs - } else if opts.MaxMapPairs < minMaxMapPairs || opts.MaxMapPairs > maxMaxMapPairs { - return nil, errors.New("cbor: invalid MaxMapPairs " + strconv.Itoa(opts.MaxMapPairs) + " (range is [" + strconv.Itoa(minMaxMapPairs) + ", " + strconv.Itoa(maxMaxMapPairs) + "])") - } - if !opts.ExtraReturnErrors.valid() { - return nil, errors.New("cbor: invalid ExtraReturnErrors " + strconv.Itoa(int(opts.ExtraReturnErrors))) - } - if opts.DefaultMapType != nil && opts.DefaultMapType.Kind() != reflect.Map { - return nil, fmt.Errorf("cbor: invalid DefaultMapType %s", opts.DefaultMapType) - } - if !opts.UTF8.valid() { - return nil, errors.New("cbor: invalid UTF8 " + strconv.Itoa(int(opts.UTF8))) - } - dm := decMode{ - dupMapKey: opts.DupMapKey, - timeTag: opts.TimeTag, - maxNestedLevels: opts.MaxNestedLevels, - maxArrayElements: opts.MaxArrayElements, - maxMapPairs: opts.MaxMapPairs, - indefLength: opts.IndefLength, - tagsMd: opts.TagsMd, - intDec: opts.IntDec, - mapKeyByteString: opts.MapKeyByteString, - extraReturnErrors: opts.ExtraReturnErrors, - defaultMapType: opts.DefaultMapType, - utf8: opts.UTF8, - } - return &dm, nil -} - -// DecMode is the main interface for CBOR decoding. -type DecMode interface { - // Unmarshal parses the CBOR-encoded data into the value pointed to by v - // using the decoding mode. If v is nil, not a pointer, or a nil pointer, - // Unmarshal returns an error. - // - // See the documentation for Unmarshal for details. - Unmarshal(data []byte, v interface{}) error - - // UnmarshalFirst parses the first CBOR data item into the value pointed to by v - // using the decoding mode. Any remaining bytes are returned in rest. - // - // If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error. - // - // See the documentation for Unmarshal for details. - UnmarshalFirst(data []byte, v interface{}) (rest []byte, err error) - - // Valid checks whether data is a well-formed encoded CBOR data item and - // that it complies with configurable restrictions such as MaxNestedLevels, - // MaxArrayElements, MaxMapPairs, etc. - // - // If there are any remaining bytes after the CBOR data item, - // an ExtraneousDataError is returned. - // - // WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity) - // and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed". - // - // Deprecated: Valid is kept for compatibility and should not be used. - // Use Wellformed instead because it has a more appropriate name. - Valid(data []byte) error - - // Wellformed checks whether data is a well-formed encoded CBOR data item and - // that it complies with configurable restrictions such as MaxNestedLevels, - // MaxArrayElements, MaxMapPairs, etc. - // - // If there are any remaining bytes after the CBOR data item, - // an ExtraneousDataError is returned. - Wellformed(data []byte) error - - // NewDecoder returns a new decoder that reads from r using dm DecMode. - NewDecoder(r io.Reader) *Decoder - - // DecOptions returns user specified options used to create this DecMode. - DecOptions() DecOptions -} - -type decMode struct { - tags tagProvider - dupMapKey DupMapKeyMode - timeTag DecTagMode - maxNestedLevels int - maxArrayElements int - maxMapPairs int - indefLength IndefLengthMode - tagsMd TagsMode - intDec IntDecMode - mapKeyByteString MapKeyByteStringMode - extraReturnErrors ExtraDecErrorCond - defaultMapType reflect.Type - utf8 UTF8Mode -} - -var defaultDecMode, _ = DecOptions{}.decMode() - -// DecOptions returns user specified options used to create this DecMode. -func (dm *decMode) DecOptions() DecOptions { - return DecOptions{ - DupMapKey: dm.dupMapKey, - TimeTag: dm.timeTag, - MaxNestedLevels: dm.maxNestedLevels, - MaxArrayElements: dm.maxArrayElements, - MaxMapPairs: dm.maxMapPairs, - IndefLength: dm.indefLength, - TagsMd: dm.tagsMd, - IntDec: dm.intDec, - MapKeyByteString: dm.mapKeyByteString, - ExtraReturnErrors: dm.extraReturnErrors, - UTF8: dm.utf8, - } -} - -// Unmarshal parses the CBOR-encoded data into the value pointed to by v -// using dm decoding mode. If v is nil, not a pointer, or a nil pointer, -// Unmarshal returns an error. -// -// See the documentation for Unmarshal for details. -func (dm *decMode) Unmarshal(data []byte, v interface{}) error { - d := decoder{data: data, dm: dm} - - // Check well-formedness. - off := d.off // Save offset before data validation - err := d.wellformed(false) // don't allow any extra data after valid data item. - d.off = off // Restore offset - if err != nil { - return err - } - - return d.value(v) -} - -// UnmarshalFirst parses the first CBOR data item into the value pointed to by v -// using dm decoding mode. Any remaining bytes are returned in rest. -// -// If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error. -// -// See the documentation for Unmarshal for details. -func (dm *decMode) UnmarshalFirst(data []byte, v interface{}) (rest []byte, err error) { - d := decoder{data: data, dm: dm} - - // check well-formedness. - off := d.off // Save offset before data validation - err = d.wellformed(true) // allow extra data after well-formed data item - d.off = off // Restore offset - - // If it is well-formed, parse the value. This is structured like this to allow - // better test coverage - if err == nil { - err = d.value(v) - } - - // If either wellformed or value returned an error, do not return rest bytes - if err != nil { - return nil, err - } - - // Return the rest of the data slice (which might be len 0) - return d.data[d.off:], nil -} - -// Valid checks whether data is a well-formed encoded CBOR data item and -// that it complies with configurable restrictions such as MaxNestedLevels, -// MaxArrayElements, MaxMapPairs, etc. -// -// If there are any remaining bytes after the CBOR data item, -// an ExtraneousDataError is returned. -// -// WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity) -// and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed". -// -// Deprecated: Valid is kept for compatibility and should not be used. -// Use Wellformed instead because it has a more appropriate name. -func (dm *decMode) Valid(data []byte) error { - return dm.Wellformed(data) -} - -// Wellformed checks whether data is a well-formed encoded CBOR data item and -// that it complies with configurable restrictions such as MaxNestedLevels, -// MaxArrayElements, MaxMapPairs, etc. -// -// If there are any remaining bytes after the CBOR data item, -// an ExtraneousDataError is returned. -func (dm *decMode) Wellformed(data []byte) error { - d := decoder{data: data, dm: dm} - return d.wellformed(false) -} - -// NewDecoder returns a new decoder that reads from r using dm DecMode. -func (dm *decMode) NewDecoder(r io.Reader) *Decoder { - return &Decoder{r: r, d: decoder{dm: dm}} -} - -type decoder struct { - data []byte - off int // next read offset in data - dm *decMode -} - -// value decodes CBOR data item into the value pointed to by v. -// If CBOR data item fails to be decoded into v, -// error is returned and offset is moved to the next CBOR data item. -// Precondition: d.data contains at least one well-formed CBOR data item. -func (d *decoder) value(v interface{}) error { - // v can't be nil, non-pointer, or nil pointer value. - if v == nil { - return &InvalidUnmarshalError{"cbor: Unmarshal(nil)"} - } - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr { - return &InvalidUnmarshalError{"cbor: Unmarshal(non-pointer " + rv.Type().String() + ")"} - } else if rv.IsNil() { - return &InvalidUnmarshalError{"cbor: Unmarshal(nil " + rv.Type().String() + ")"} - } - rv = rv.Elem() - return d.parseToValue(rv, getTypeInfo(rv.Type())) -} - -type cborType uint8 - -const ( - cborTypePositiveInt cborType = 0x00 - cborTypeNegativeInt cborType = 0x20 - cborTypeByteString cborType = 0x40 - cborTypeTextString cborType = 0x60 - cborTypeArray cborType = 0x80 - cborTypeMap cborType = 0xa0 - cborTypeTag cborType = 0xc0 - cborTypePrimitives cborType = 0xe0 -) - -func (t cborType) String() string { - switch t { - case cborTypePositiveInt: - return "positive integer" - case cborTypeNegativeInt: - return "negative integer" - case cborTypeByteString: - return "byte string" - case cborTypeTextString: - return "UTF-8 text string" - case cborTypeArray: - return "array" - case cborTypeMap: - return "map" - case cborTypeTag: - return "tag" - case cborTypePrimitives: - return "primitives" - default: - return "Invalid type " + strconv.Itoa(int(t)) - } -} - -const ( - selfDescribedCBORTagNum = 55799 -) - -// parseToValue decodes CBOR data to value. It assumes data is well-formed, -// and does not perform bounds checking. -func (d *decoder) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo - - if tInfo.spclType == specialTypeIface { - if !v.IsNil() { - // Use value type - v = v.Elem() - tInfo = getTypeInfo(v.Type()) - } else { - // Create and use registered type if CBOR data is registered tag - if d.dm.tags != nil && d.nextCBORType() == cborTypeTag { - - off := d.off - var tagNums []uint64 - for d.nextCBORType() == cborTypeTag { - _, _, tagNum := d.getHead() - tagNums = append(tagNums, tagNum) - } - d.off = off - - registeredType := d.dm.tags.getTypeFromTagNum(tagNums) - if registeredType != nil { - if registeredType.Implements(tInfo.nonPtrType) || - reflect.PtrTo(registeredType).Implements(tInfo.nonPtrType) { - v.Set(reflect.New(registeredType)) - v = v.Elem() - tInfo = getTypeInfo(registeredType) - } - } - } - } - } - - // Create new value for the pointer v to point to if CBOR value is not nil/undefined. - if !d.nextCBORNil() { - for v.Kind() == reflect.Ptr { - if v.IsNil() { - if !v.CanSet() { - d.skip() - return errors.New("cbor: cannot set new value for " + v.Type().String()) - } - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - } - - // Strip self-described CBOR tag number. - for d.nextCBORType() == cborTypeTag { - off := d.off - _, _, tagNum := d.getHead() - if tagNum != selfDescribedCBORTagNum { - d.off = off - break - } - } - - // Check validity of supported built-in tags. - if d.nextCBORType() == cborTypeTag { - off := d.off - _, _, tagNum := d.getHead() - if err := validBuiltinTag(tagNum, d.data[d.off]); err != nil { - d.skip() - return err - } - d.off = off - } - - if tInfo.spclType != specialTypeNone { - switch tInfo.spclType { - case specialTypeEmptyIface: - iv, err := d.parse(false) // Skipped self-described CBOR tag number already. - if iv != nil { - v.Set(reflect.ValueOf(iv)) - } - return err - case specialTypeTag: - return d.parseToTag(v) - case specialTypeTime: - if d.nextCBORNil() { - // Decoding CBOR null and undefined to time.Time is no-op. - d.skip() - return nil - } - tm, err := d.parseToTime() - if err != nil { - return err - } - v.Set(reflect.ValueOf(tm)) - return nil - case specialTypeUnmarshalerIface: - return d.parseToUnmarshaler(v) - } - } - - // Check registered tag number - if tagItem := d.getRegisteredTagItem(tInfo.nonPtrType); tagItem != nil { - t := d.nextCBORType() - if t != cborTypeTag { - if tagItem.opts.DecTag == DecTagRequired { - d.skip() // Required tag number is absent, skip entire tag - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: tInfo.typ.String(), - errorMsg: "expect CBOR tag value"} - } - } else if err := d.validRegisteredTagNums(tagItem); err != nil { - d.skip() // Skip tag content - return err - } - } - - t := d.nextCBORType() - - switch t { - case cborTypePositiveInt: - _, _, val := d.getHead() - return fillPositiveInt(t, val, v) - case cborTypeNegativeInt: - _, _, val := d.getHead() - if val > math.MaxInt64 { - // CBOR negative integer overflows int64, use big.Int to store value. - bi := new(big.Int) - bi.SetUint64(val) - bi.Add(bi, big.NewInt(1)) - bi.Neg(bi) - - if tInfo.nonPtrType == typeBigInt { - v.Set(reflect.ValueOf(*bi)) - return nil - } - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: tInfo.nonPtrType.String(), - errorMsg: bi.String() + " overflows Go's int64", - } - } - nValue := int64(-1) ^ int64(val) - return fillNegativeInt(t, nValue, v) - case cborTypeByteString: - b := d.parseByteString() - return fillByteString(t, b, v) - case cborTypeTextString: - b, err := d.parseTextString() - if err != nil { - return err - } - return fillTextString(t, b, v) - case cborTypePrimitives: - _, ai, val := d.getHead() - switch ai { - case 25: - f := float64(float16.Frombits(uint16(val)).Float32()) - return fillFloat(t, f, v) - case 26: - f := float64(math.Float32frombits(uint32(val))) - return fillFloat(t, f, v) - case 27: - f := math.Float64frombits(val) - return fillFloat(t, f, v) - default: // ai <= 24 - // Decode simple values (including false, true, null, and undefined) - if tInfo.nonPtrType == typeSimpleValue { - v.SetUint(val) - return nil - } - switch ai { - case 20, 21: - return fillBool(t, ai == 21, v) - case 22, 23: - return fillNil(t, v) - default: - return fillPositiveInt(t, val, v) - } - } - - case cborTypeTag: - _, _, tagNum := d.getHead() - switch tagNum { - case 2: - // Bignum (tag 2) can be decoded to uint, int, float, slice, array, or big.Int. - b := d.parseByteString() - bi := new(big.Int).SetBytes(b) - - if tInfo.nonPtrType == typeBigInt { - v.Set(reflect.ValueOf(*bi)) - return nil - } - if tInfo.nonPtrKind == reflect.Slice || tInfo.nonPtrKind == reflect.Array { - return fillByteString(t, b, v) - } - if bi.IsUint64() { - return fillPositiveInt(t, bi.Uint64(), v) - } - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: tInfo.nonPtrType.String(), - errorMsg: bi.String() + " overflows " + v.Type().String(), - } - case 3: - // Bignum (tag 3) can be decoded to int, float, slice, array, or big.Int. - b := d.parseByteString() - bi := new(big.Int).SetBytes(b) - bi.Add(bi, big.NewInt(1)) - bi.Neg(bi) - - if tInfo.nonPtrType == typeBigInt { - v.Set(reflect.ValueOf(*bi)) - return nil - } - if tInfo.nonPtrKind == reflect.Slice || tInfo.nonPtrKind == reflect.Array { - return fillByteString(t, b, v) - } - if bi.IsInt64() { - return fillNegativeInt(t, bi.Int64(), v) - } - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: tInfo.nonPtrType.String(), - errorMsg: bi.String() + " overflows " + v.Type().String(), - } - } - return d.parseToValue(v, tInfo) - case cborTypeArray: - if tInfo.nonPtrKind == reflect.Slice { - return d.parseArrayToSlice(v, tInfo) - } else if tInfo.nonPtrKind == reflect.Array { - return d.parseArrayToArray(v, tInfo) - } else if tInfo.nonPtrKind == reflect.Struct { - return d.parseArrayToStruct(v, tInfo) - } - d.skip() - return &UnmarshalTypeError{CBORType: t.String(), GoType: tInfo.nonPtrType.String()} - case cborTypeMap: - if tInfo.nonPtrKind == reflect.Struct { - return d.parseMapToStruct(v, tInfo) - } else if tInfo.nonPtrKind == reflect.Map { - return d.parseMapToMap(v, tInfo) - } - d.skip() - return &UnmarshalTypeError{CBORType: t.String(), GoType: tInfo.nonPtrType.String()} - } - return nil -} - -func (d *decoder) parseToTag(v reflect.Value) error { - if d.nextCBORNil() { - // Decoding CBOR null and undefined to cbor.Tag is no-op. - d.skip() - return nil - } - - t := d.nextCBORType() - if t != cborTypeTag { - d.skip() - return &UnmarshalTypeError{CBORType: t.String(), GoType: typeTag.String()} - } - - // Unmarshal tag number - _, _, num := d.getHead() - - // Unmarshal tag content - content, err := d.parse(false) - if err != nil { - return err - } - - v.Set(reflect.ValueOf(Tag{num, content})) - return nil -} - -func (d *decoder) parseToTime() (tm time.Time, err error) { - t := d.nextCBORType() - - // Verify that tag number or absence of tag number is acceptable to specified timeTag. - if t == cborTypeTag { - if d.dm.timeTag == DecTagIgnored { - // Skip tag number - for t == cborTypeTag { - d.getHead() - t = d.nextCBORType() - } - } else { - // Read tag number - _, _, tagNum := d.getHead() - if tagNum != 0 && tagNum != 1 { - d.skip() - err = errors.New("cbor: wrong tag number for time.Time, got " + strconv.Itoa(int(tagNum)) + ", expect 0 or 1") - return - } - } - } else { - if d.dm.timeTag == DecTagRequired { - d.skip() - err = &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String(), errorMsg: "expect CBOR tag value"} - return - } - } - - var content interface{} - content, err = d.parse(false) - if err != nil { - return - } - - switch c := content.(type) { - case nil: - return - case uint64: - return time.Unix(int64(c), 0), nil - case int64: - return time.Unix(c, 0), nil - case float64: - if math.IsNaN(c) || math.IsInf(c, 0) { - return - } - f1, f2 := math.Modf(c) - return time.Unix(int64(f1), int64(f2*1e9)), nil - case string: - tm, err = time.Parse(time.RFC3339, c) - if err != nil { - tm = time.Time{} - err = errors.New("cbor: cannot set " + c + " for time.Time: " + err.Error()) - return - } - return - default: - err = &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String()} - return - } -} - -// parseToUnmarshaler parses CBOR data to value implementing Unmarshaler interface. -// It assumes data is well-formed, and does not perform bounds checking. -func (d *decoder) parseToUnmarshaler(v reflect.Value) error { - if d.nextCBORNil() && v.Kind() == reflect.Ptr && v.IsNil() { - d.skip() - return nil - } - - if v.Kind() != reflect.Ptr && v.CanAddr() { - v = v.Addr() - } - if u, ok := v.Interface().(Unmarshaler); ok { - start := d.off - d.skip() - return u.UnmarshalCBOR(d.data[start:d.off]) - } - d.skip() - return errors.New("cbor: failed to assert " + v.Type().String() + " as cbor.Unmarshaler") -} - -// parse parses CBOR data and returns value in default Go type. -// It assumes data is well-formed, and does not perform bounds checking. -func (d *decoder) parse(skipSelfDescribedTag bool) (interface{}, error) { //nolint:gocyclo - // Strip self-described CBOR tag number. - if skipSelfDescribedTag { - for d.nextCBORType() == cborTypeTag { - off := d.off - _, _, tagNum := d.getHead() - if tagNum != selfDescribedCBORTagNum { - d.off = off - break - } - } - } - - // Check validity of supported built-in tags. - if d.nextCBORType() == cborTypeTag { - off := d.off - _, _, tagNum := d.getHead() - if err := validBuiltinTag(tagNum, d.data[d.off]); err != nil { - d.skip() - return nil, err - } - d.off = off - } - - t := d.nextCBORType() - switch t { - case cborTypePositiveInt: - _, _, val := d.getHead() - if d.dm.intDec == IntDecConvertNone { - return val, nil - } - if val > math.MaxInt64 { - return nil, &UnmarshalTypeError{ - CBORType: t.String(), - GoType: reflect.TypeOf(int64(0)).String(), - errorMsg: strconv.FormatUint(val, 10) + " overflows Go's int64", - } - } - return int64(val), nil - case cborTypeNegativeInt: - _, _, val := d.getHead() - if val > math.MaxInt64 { - // CBOR negative integer value overflows Go int64, use big.Int instead. - bi := new(big.Int).SetUint64(val) - bi.Add(bi, big.NewInt(1)) - bi.Neg(bi) - return *bi, nil - } - nValue := int64(-1) ^ int64(val) - return nValue, nil - case cborTypeByteString: - return d.parseByteString(), nil - case cborTypeTextString: - b, err := d.parseTextString() - if err != nil { - return nil, err - } - return string(b), nil - case cborTypeTag: - tagOff := d.off - _, _, tagNum := d.getHead() - contentOff := d.off - - switch tagNum { - case 0, 1: - d.off = tagOff - return d.parseToTime() - case 2: - b := d.parseByteString() - bi := new(big.Int).SetBytes(b) - return *bi, nil - case 3: - b := d.parseByteString() - bi := new(big.Int).SetBytes(b) - bi.Add(bi, big.NewInt(1)) - bi.Neg(bi) - return *bi, nil - } - - if d.dm.tags != nil { - // Parse to specified type if tag number is registered. - tagNums := []uint64{tagNum} - for d.nextCBORType() == cborTypeTag { - _, _, num := d.getHead() - tagNums = append(tagNums, num) - } - registeredType := d.dm.tags.getTypeFromTagNum(tagNums) - if registeredType != nil { - d.off = tagOff - rv := reflect.New(registeredType) - if err := d.parseToValue(rv.Elem(), getTypeInfo(registeredType)); err != nil { - return nil, err - } - return rv.Elem().Interface(), nil - } - } - - // Parse tag content - d.off = contentOff - content, err := d.parse(false) - if err != nil { - return nil, err - } - return Tag{tagNum, content}, nil - case cborTypePrimitives: - _, ai, val := d.getHead() - if ai < 20 || ai == 24 { - return SimpleValue(val), nil - } - switch ai { - case 20, 21: - return (ai == 21), nil - case 22, 23: - return nil, nil - case 25: - f := float64(float16.Frombits(uint16(val)).Float32()) - return f, nil - case 26: - f := float64(math.Float32frombits(uint32(val))) - return f, nil - case 27: - f := math.Float64frombits(val) - return f, nil - } - case cborTypeArray: - return d.parseArray() - case cborTypeMap: - if d.dm.defaultMapType != nil { - m := reflect.New(d.dm.defaultMapType) - err := d.parseToValue(m, getTypeInfo(m.Elem().Type())) - if err != nil { - return nil, err - } - return m.Elem().Interface(), nil - } - return d.parseMap() - } - return nil, nil -} - -// parseByteString parses CBOR encoded byte string. It returns a byte slice -// pointing to a copy of parsed data. -func (d *decoder) parseByteString() []byte { - _, ai, val := d.getHead() - if ai != 31 { - b := make([]byte, int(val)) - copy(b, d.data[d.off:d.off+int(val)]) - d.off += int(val) - return b - } - // Process indefinite length string chunks. - b := []byte{} - for !d.foundBreak() { - _, _, val = d.getHead() - b = append(b, d.data[d.off:d.off+int(val)]...) - d.off += int(val) - } - return b -} - -// parseTextString parses CBOR encoded text string. It returns a byte slice -// to prevent creating an extra copy of string. Caller should wrap returned -// byte slice as string when needed. -func (d *decoder) parseTextString() ([]byte, error) { - _, ai, val := d.getHead() - if ai != 31 { - b := d.data[d.off : d.off+int(val)] - d.off += int(val) - if d.dm.utf8 == UTF8RejectInvalid && !utf8.Valid(b) { - return nil, &SemanticError{"cbor: invalid UTF-8 string"} - } - return b, nil - } - // Process indefinite length string chunks. - b := []byte{} - for !d.foundBreak() { - _, _, val = d.getHead() - x := d.data[d.off : d.off+int(val)] - d.off += int(val) - if d.dm.utf8 == UTF8RejectInvalid && !utf8.Valid(x) { - for !d.foundBreak() { - d.skip() // Skip remaining chunk on error - } - return nil, &SemanticError{"cbor: invalid UTF-8 string"} - } - b = append(b, x...) - } - return b, nil -} - -func (d *decoder) parseArray() ([]interface{}, error) { - _, ai, val := d.getHead() - hasSize := (ai != 31) - count := int(val) - if !hasSize { - count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance - } - v := make([]interface{}, count) - var e interface{} - var err, lastErr error - for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { - if e, lastErr = d.parse(true); lastErr != nil { - if err == nil { - err = lastErr - } - continue - } - v[i] = e - } - return v, err -} - -func (d *decoder) parseArrayToSlice(v reflect.Value, tInfo *typeInfo) error { - _, ai, val := d.getHead() - hasSize := (ai != 31) - count := int(val) - if !hasSize { - count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance - } - if v.IsNil() || v.Cap() < count || count == 0 { - v.Set(reflect.MakeSlice(tInfo.nonPtrType, count, count)) - } - v.SetLen(count) - var err error - for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { - if lastErr := d.parseToValue(v.Index(i), tInfo.elemTypeInfo); lastErr != nil { - if err == nil { - err = lastErr - } - } - } - return err -} - -func (d *decoder) parseArrayToArray(v reflect.Value, tInfo *typeInfo) error { - _, ai, val := d.getHead() - hasSize := (ai != 31) - count := int(val) - gi := 0 - vLen := v.Len() - var err error - for ci := 0; (hasSize && ci < count) || (!hasSize && !d.foundBreak()); ci++ { - if gi < vLen { - // Read CBOR array element and set array element - if lastErr := d.parseToValue(v.Index(gi), tInfo.elemTypeInfo); lastErr != nil { - if err == nil { - err = lastErr - } - } - gi++ - } else { - d.skip() // Skip remaining CBOR array element - } - } - // Set remaining Go array elements to zero values. - if gi < vLen { - zeroV := reflect.Zero(tInfo.elemTypeInfo.typ) - for ; gi < vLen; gi++ { - v.Index(gi).Set(zeroV) - } - } - return err -} - -func (d *decoder) parseMap() (interface{}, error) { - _, ai, val := d.getHead() - hasSize := (ai != 31) - count := int(val) - m := make(map[interface{}]interface{}) - var k, e interface{} - var err, lastErr error - keyCount := 0 - for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { - // Parse CBOR map key. - if k, lastErr = d.parse(true); lastErr != nil { - if err == nil { - err = lastErr - } - d.skip() - continue - } - - // Detect if CBOR map key can be used as Go map key. - rv := reflect.ValueOf(k) - if !isHashableValue(rv) { - var converted bool - if d.dm.mapKeyByteString == MapKeyByteStringAllowed { - k, converted = convertByteSliceToByteString(k) - } - if !converted { - if err == nil { - err = &InvalidMapKeyTypeError{rv.Type().String()} - } - d.skip() - continue - } - } - - // Parse CBOR map value. - if e, lastErr = d.parse(true); lastErr != nil { - if err == nil { - err = lastErr - } - continue - } - - // Add key-value pair to Go map. - m[k] = e - - // Detect duplicate map key. - if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - newKeyCount := len(m) - if newKeyCount == keyCount { - m[k] = nil - err = &DupMapKeyError{k, i} - i++ - // skip the rest of the map - for ; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { - d.skip() // Skip map key - d.skip() // Skip map value - } - return m, err - } - keyCount = newKeyCount - } - } - return m, err -} - -func (d *decoder) parseMapToMap(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo - _, ai, val := d.getHead() - hasSize := (ai != 31) - count := int(val) - if v.IsNil() { - mapsize := count - if !hasSize { - mapsize = 0 - } - v.Set(reflect.MakeMapWithSize(tInfo.nonPtrType, mapsize)) - } - keyType, eleType := tInfo.keyTypeInfo.typ, tInfo.elemTypeInfo.typ - reuseKey, reuseEle := isImmutableKind(tInfo.keyTypeInfo.kind), isImmutableKind(tInfo.elemTypeInfo.kind) - var keyValue, eleValue, zeroKeyValue, zeroEleValue reflect.Value - keyIsInterfaceType := keyType == typeIntf // If key type is interface{}, need to check if key value is hashable. - var err, lastErr error - keyCount := v.Len() - var existingKeys map[interface{}]bool // Store existing map keys, used for detecting duplicate map key. - if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - existingKeys = make(map[interface{}]bool, keyCount) - if keyCount > 0 { - vKeys := v.MapKeys() - for i := 0; i < len(vKeys); i++ { - existingKeys[vKeys[i].Interface()] = true - } - } - } - for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { - // Parse CBOR map key. - if !keyValue.IsValid() { - keyValue = reflect.New(keyType).Elem() - } else if !reuseKey { - if !zeroKeyValue.IsValid() { - zeroKeyValue = reflect.Zero(keyType) - } - keyValue.Set(zeroKeyValue) - } - if lastErr = d.parseToValue(keyValue, tInfo.keyTypeInfo); lastErr != nil { - if err == nil { - err = lastErr - } - d.skip() - continue - } - - // Detect if CBOR map key can be used as Go map key. - if keyIsInterfaceType && keyValue.Elem().IsValid() { - if !isHashableValue(keyValue.Elem()) { - var converted bool - if d.dm.mapKeyByteString == MapKeyByteStringAllowed { - var k interface{} - k, converted = convertByteSliceToByteString(keyValue.Elem().Interface()) - if converted { - keyValue.Set(reflect.ValueOf(k)) - } - } - if !converted { - if err == nil { - err = &InvalidMapKeyTypeError{keyValue.Elem().Type().String()} - } - d.skip() - continue - } - } - } - - // Parse CBOR map value. - if !eleValue.IsValid() { - eleValue = reflect.New(eleType).Elem() - } else if !reuseEle { - if !zeroEleValue.IsValid() { - zeroEleValue = reflect.Zero(eleType) - } - eleValue.Set(zeroEleValue) - } - if lastErr := d.parseToValue(eleValue, tInfo.elemTypeInfo); lastErr != nil { - if err == nil { - err = lastErr - } - continue - } - - // Add key-value pair to Go map. - v.SetMapIndex(keyValue, eleValue) - - // Detect duplicate map key. - if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - newKeyCount := v.Len() - if newKeyCount == keyCount { - kvi := keyValue.Interface() - if !existingKeys[kvi] { - v.SetMapIndex(keyValue, reflect.New(eleType).Elem()) - err = &DupMapKeyError{kvi, i} - i++ - // skip the rest of the map - for ; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { - d.skip() // skip map key - d.skip() // skip map value - } - return err - } - delete(existingKeys, kvi) - } - keyCount = newKeyCount - } - } - return err -} - -func (d *decoder) parseArrayToStruct(v reflect.Value, tInfo *typeInfo) error { - structType := getDecodingStructType(tInfo.nonPtrType) - if structType.err != nil { - return structType.err - } - - if !structType.toArray { - t := d.nextCBORType() - d.skip() - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: tInfo.nonPtrType.String(), - errorMsg: "cannot decode CBOR array to struct without toarray option", - } - } - - start := d.off - t, ai, val := d.getHead() - hasSize := (ai != 31) - count := int(val) - if !hasSize { - count = d.numOfItemsUntilBreak() // peek ahead to get array size - } - if count != len(structType.fields) { - d.off = start - d.skip() - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: tInfo.typ.String(), - errorMsg: "cannot decode CBOR array to struct with different number of elements", - } - } - var err, lastErr error - for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { - f := structType.fields[i] - - // Get field value by index - var fv reflect.Value - if len(f.idx) == 1 { - fv = v.Field(f.idx[0]) - } else { - fv, lastErr = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) { - // Return a new value for embedded field null pointer to point to, or return error. - if !v.CanSet() { - return reflect.Value{}, errors.New("cbor: cannot set embedded pointer to unexported struct: " + v.Type().String()) - } - v.Set(reflect.New(v.Type().Elem())) - return v, nil - }) - if lastErr != nil && err == nil { - err = lastErr - } - if !fv.IsValid() { - d.skip() - continue - } - } - - if lastErr = d.parseToValue(fv, f.typInfo); lastErr != nil { - if err == nil { - if typeError, ok := lastErr.(*UnmarshalTypeError); ok { - typeError.StructFieldName = tInfo.typ.String() + "." + f.name - err = typeError - } else { - err = lastErr - } - } - } - } - return err -} - -// parseMapToStruct needs to be fast so gocyclo can be ignored for now. -func (d *decoder) parseMapToStruct(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo - structType := getDecodingStructType(tInfo.nonPtrType) - if structType.err != nil { - return structType.err - } - - if structType.toArray { - t := d.nextCBORType() - d.skip() - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: tInfo.nonPtrType.String(), - errorMsg: "cannot decode CBOR map to struct with toarray option", - } - } - - var err, lastErr error - - // Get CBOR map size - _, ai, val := d.getHead() - hasSize := (ai != 31) - count := int(val) - - // Keeps track of matched struct fields - foundFldIdx := make([]bool, len(structType.fields)) - - // Keeps track of CBOR map keys to detect duplicate map key - keyCount := 0 - var mapKeys map[interface{}]struct{} - if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - mapKeys = make(map[interface{}]struct{}, len(structType.fields)) - } - - errOnUnknownField := (d.dm.extraReturnErrors & ExtraDecErrorUnknownField) > 0 - - for j := 0; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { - var f *field - var k interface{} // Used by duplicate map key detection - - t := d.nextCBORType() - if t == cborTypeTextString { - var keyBytes []byte - keyBytes, lastErr = d.parseTextString() - if lastErr != nil { - if err == nil { - err = lastErr - } - d.skip() // skip value - continue - } - - keyLen := len(keyBytes) - // Find field with exact match - for i := 0; i < len(structType.fields); i++ { - fld := structType.fields[i] - if !foundFldIdx[i] && len(fld.name) == keyLen && fld.name == string(keyBytes) { - f = fld - foundFldIdx[i] = true - break - } - } - // Find field with case-insensitive match - if f == nil { - keyString := string(keyBytes) - for i := 0; i < len(structType.fields); i++ { - fld := structType.fields[i] - if !foundFldIdx[i] && len(fld.name) == keyLen && strings.EqualFold(fld.name, keyString) { - f = fld - foundFldIdx[i] = true - break - } - } - } - - if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - k = string(keyBytes) - } - } else if t <= cborTypeNegativeInt { // uint/int - var nameAsInt int64 - - if t == cborTypePositiveInt { - _, _, val := d.getHead() - nameAsInt = int64(val) - } else { - _, _, val := d.getHead() - if val > math.MaxInt64 { - if err == nil { - err = &UnmarshalTypeError{ - CBORType: t.String(), - GoType: reflect.TypeOf(int64(0)).String(), - errorMsg: "-1-" + strconv.FormatUint(val, 10) + " overflows Go's int64", - } - } - d.skip() // skip value - continue - } - nameAsInt = int64(-1) ^ int64(val) - } - - // Find field - for i := 0; i < len(structType.fields); i++ { - fld := structType.fields[i] - if !foundFldIdx[i] && fld.keyAsInt && fld.nameAsInt == nameAsInt { - f = fld - foundFldIdx[i] = true - break - } - } - - if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - k = nameAsInt - } - } else { - if err == nil { - err = &UnmarshalTypeError{ - CBORType: t.String(), - GoType: reflect.TypeOf("").String(), - errorMsg: "map key is of type " + t.String() + " and cannot be used to match struct field name", - } - } - if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - // parse key - k, lastErr = d.parse(true) - if lastErr != nil { - d.skip() // skip value - continue - } - // Detect if CBOR map key can be used as Go map key. - if !isHashableValue(reflect.ValueOf(k)) { - d.skip() // skip value - continue - } - } else { - d.skip() // skip key - } - } - - if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - mapKeys[k] = struct{}{} - newKeyCount := len(mapKeys) - if newKeyCount == keyCount { - err = &DupMapKeyError{k, j} - d.skip() // skip value - j++ - // skip the rest of the map - for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { - d.skip() - d.skip() - } - return err - } - keyCount = newKeyCount - } - - if f == nil { - if errOnUnknownField { - err = &UnknownFieldError{j} - d.skip() // Skip value - j++ - // skip the rest of the map - for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { - d.skip() - d.skip() - } - return err - } - d.skip() // Skip value - continue - } - - // Get field value by index - var fv reflect.Value - if len(f.idx) == 1 { - fv = v.Field(f.idx[0]) - } else { - fv, lastErr = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) { - // Return a new value for embedded field null pointer to point to, or return error. - if !v.CanSet() { - return reflect.Value{}, errors.New("cbor: cannot set embedded pointer to unexported struct: " + v.Type().String()) - } - v.Set(reflect.New(v.Type().Elem())) - return v, nil - }) - if lastErr != nil && err == nil { - err = lastErr - } - if !fv.IsValid() { - d.skip() - continue - } - } - - if lastErr = d.parseToValue(fv, f.typInfo); lastErr != nil { - if err == nil { - if typeError, ok := lastErr.(*UnmarshalTypeError); ok { - typeError.StructFieldName = tInfo.nonPtrType.String() + "." + f.name - err = typeError - } else { - err = lastErr - } - } - } - } - return err -} - -// validRegisteredTagNums verifies that tag numbers match registered tag numbers of type t. -// validRegisteredTagNums assumes next CBOR data type is tag. It scans all tag numbers, and stops at tag content. -func (d *decoder) validRegisteredTagNums(registeredTag *tagItem) error { - // Scan until next cbor data is tag content. - tagNums := make([]uint64, 0, 1) - for d.nextCBORType() == cborTypeTag { - _, _, val := d.getHead() - tagNums = append(tagNums, val) - } - - if !registeredTag.equalTagNum(tagNums) { - return &WrongTagError{registeredTag.contentType, registeredTag.num, tagNums} - } - return nil -} - -func (d *decoder) getRegisteredTagItem(vt reflect.Type) *tagItem { - if d.dm.tags != nil { - return d.dm.tags.getTagItemFromType(vt) - } - return nil -} - -// skip moves data offset to the next item. skip assumes data is well-formed, -// and does not perform bounds checking. -func (d *decoder) skip() { - t, ai, val := d.getHead() - - if ai == 31 { - switch t { - case cborTypeByteString, cborTypeTextString, cborTypeArray, cborTypeMap: - for { - if d.data[d.off] == 0xff { - d.off++ - return - } - d.skip() - } - } - } - - switch t { - case cborTypeByteString, cborTypeTextString: - d.off += int(val) - case cborTypeArray: - for i := 0; i < int(val); i++ { - d.skip() - } - case cborTypeMap: - for i := 0; i < int(val)*2; i++ { - d.skip() - } - case cborTypeTag: - d.skip() - } -} - -// getHead assumes data is well-formed, and does not perform bounds checking. -func (d *decoder) getHead() (t cborType, ai byte, val uint64) { - t = cborType(d.data[d.off] & 0xe0) - ai = d.data[d.off] & 0x1f - val = uint64(ai) - d.off++ - - if ai < 24 { - return - } - if ai == 24 { - val = uint64(d.data[d.off]) - d.off++ - return - } - if ai == 25 { - val = uint64(binary.BigEndian.Uint16(d.data[d.off : d.off+2])) - d.off += 2 - return - } - if ai == 26 { - val = uint64(binary.BigEndian.Uint32(d.data[d.off : d.off+4])) - d.off += 4 - return - } - if ai == 27 { - val = binary.BigEndian.Uint64(d.data[d.off : d.off+8]) - d.off += 8 - return - } - return -} - -func (d *decoder) numOfItemsUntilBreak() int { - savedOff := d.off - i := 0 - for !d.foundBreak() { - d.skip() - i++ - } - d.off = savedOff - return i -} - -// foundBreak assumes data is well-formed, and does not perform bounds checking. -func (d *decoder) foundBreak() bool { - if d.data[d.off] == 0xff { - d.off++ - return true - } - return false -} - -func (d *decoder) reset(data []byte) { - d.data = data - d.off = 0 -} - -func (d *decoder) nextCBORType() cborType { - return cborType(d.data[d.off] & 0xe0) -} - -func (d *decoder) nextCBORNil() bool { - return d.data[d.off] == 0xf6 || d.data[d.off] == 0xf7 -} - -var ( - typeIntf = reflect.TypeOf([]interface{}(nil)).Elem() - typeTime = reflect.TypeOf(time.Time{}) - typeBigInt = reflect.TypeOf(big.Int{}) - typeUnmarshaler = reflect.TypeOf((*Unmarshaler)(nil)).Elem() - typeBinaryUnmarshaler = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem() -) - -func fillNil(t cborType, v reflect.Value) error { - switch v.Kind() { - case reflect.Slice, reflect.Map, reflect.Interface, reflect.Ptr: - v.Set(reflect.Zero(v.Type())) - return nil - } - return nil -} - -func fillPositiveInt(t cborType, val uint64, v reflect.Value) error { - switch v.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if val > math.MaxInt64 { - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: v.Type().String(), - errorMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String(), - } - } - if v.OverflowInt(int64(val)) { - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: v.Type().String(), - errorMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String(), - } - } - v.SetInt(int64(val)) - return nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - if v.OverflowUint(val) { - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: v.Type().String(), - errorMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String(), - } - } - v.SetUint(val) - return nil - case reflect.Float32, reflect.Float64: - f := float64(val) - v.SetFloat(f) - return nil - } - if v.Type() == typeBigInt { - i := new(big.Int).SetUint64(val) - v.Set(reflect.ValueOf(*i)) - return nil - } - return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()} -} - -func fillNegativeInt(t cborType, val int64, v reflect.Value) error { - switch v.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if v.OverflowInt(val) { - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: v.Type().String(), - errorMsg: strconv.FormatInt(val, 10) + " overflows " + v.Type().String(), - } - } - v.SetInt(val) - return nil - case reflect.Float32, reflect.Float64: - f := float64(val) - v.SetFloat(f) - return nil - } - if v.Type() == typeBigInt { - i := new(big.Int).SetInt64(val) - v.Set(reflect.ValueOf(*i)) - return nil - } - return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()} -} - -func fillBool(t cborType, val bool, v reflect.Value) error { - if v.Kind() == reflect.Bool { - v.SetBool(val) - return nil - } - return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()} -} - -func fillFloat(t cborType, val float64, v reflect.Value) error { - switch v.Kind() { - case reflect.Float32, reflect.Float64: - if v.OverflowFloat(val) { - return &UnmarshalTypeError{ - CBORType: t.String(), - GoType: v.Type().String(), - errorMsg: strconv.FormatFloat(val, 'E', -1, 64) + " overflows " + v.Type().String(), - } - } - v.SetFloat(val) - return nil - } - return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()} -} - -func fillByteString(t cborType, val []byte, v reflect.Value) error { - if reflect.PtrTo(v.Type()).Implements(typeBinaryUnmarshaler) { - if v.CanAddr() { - v = v.Addr() - if u, ok := v.Interface().(encoding.BinaryUnmarshaler); ok { - return u.UnmarshalBinary(val) - } - } - return errors.New("cbor: cannot set new value for " + v.Type().String()) - } - if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 { - v.SetBytes(val) - return nil - } - if v.Kind() == reflect.Array && v.Type().Elem().Kind() == reflect.Uint8 { - vLen := v.Len() - i := 0 - for ; i < vLen && i < len(val); i++ { - v.Index(i).SetUint(uint64(val[i])) - } - // Set remaining Go array elements to zero values. - if i < vLen { - zeroV := reflect.Zero(reflect.TypeOf(byte(0))) - for ; i < vLen; i++ { - v.Index(i).Set(zeroV) - } - } - return nil - } - return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()} -} - -func fillTextString(t cborType, val []byte, v reflect.Value) error { - if v.Kind() == reflect.String { - v.SetString(string(val)) - return nil - } - return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()} -} - -func isImmutableKind(k reflect.Kind) bool { - switch k { - case reflect.Bool, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float32, reflect.Float64, - reflect.String: - return true - default: - return false - } -} - -func isHashableValue(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Slice, reflect.Map, reflect.Func: - return false - case reflect.Struct: - switch rv.Type() { - case typeTag: - tag := rv.Interface().(Tag) - return isHashableValue(reflect.ValueOf(tag.Content)) - case typeBigInt: - return false - } - } - return true -} - -// convertByteSliceToByteString converts []byte to ByteString if -// - v is []byte type, or -// - v is Tag type and tag content type is []byte -// This function also handles nested tags. -// CBOR data is already verified to be well-formed before this function is used, -// so the recursion won't exceed max nested levels. -func convertByteSliceToByteString(v interface{}) (interface{}, bool) { - switch v := v.(type) { - case []byte: - return ByteString(v), true - case Tag: - content, converted := convertByteSliceToByteString(v.Content) - if converted { - return Tag{Number: v.Number, Content: content}, true - } - } - return v, false -} - -// validBuiltinTag checks that supported built-in tag numbers are followed by expected content types. -func validBuiltinTag(tagNum uint64, contentHead byte) error { - t := cborType(contentHead & 0xe0) - switch tagNum { - case 0: - // Tag content (date/time text string in RFC 3339 format) must be string type. - if t != cborTypeTextString { - return errors.New("cbor: tag number 0 must be followed by text string, got " + t.String()) - } - return nil - case 1: - // Tag content (epoch date/time) must be uint, int, or float type. - if t != cborTypePositiveInt && t != cborTypeNegativeInt && (contentHead < 0xf9 || contentHead > 0xfb) { - return errors.New("cbor: tag number 1 must be followed by integer or floating-point number, got " + t.String()) - } - return nil - case 2, 3: - // Tag content (bignum) must be byte type. - if t != cborTypeByteString { - return errors.New("cbor: tag number 2 or 3 must be followed by byte string, got " + t.String()) - } - return nil - } - return nil -} diff --git a/vendor/github.com/fxamacker/cbor/v2/diagnose.go b/vendor/github.com/fxamacker/cbor/v2/diagnose.go deleted file mode 100644 index dcb03002..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/diagnose.go +++ /dev/null @@ -1,741 +0,0 @@ -// Copyright (c) Faye Amacker. All rights reserved. -// Licensed under the MIT License. See LICENSE in the project root for license information. - -package cbor - -import ( - "bytes" - "encoding/base32" - "encoding/base64" - "encoding/hex" - "errors" - "io" - "math" - "math/big" - "strconv" - "unicode/utf16" - "unicode/utf8" - - "github.com/x448/float16" -) - -// DiagMode is the main interface for CBOR diagnostic notation. -type DiagMode interface { - // Diagnose returns extended diagnostic notation (EDN) of CBOR data items using this DiagMode. - Diagnose([]byte) (string, error) - - // DiagnoseFirst returns extended diagnostic notation (EDN) of the first CBOR data item using the DiagMode. Any remaining bytes are returned in rest. - DiagnoseFirst([]byte) (string, []byte, error) - - // DiagOptions returns user specified options used to create this DiagMode. - DiagOptions() DiagOptions -} - -// ByteStringEncoding specifies the base encoding that byte strings are notated. -type ByteStringEncoding uint8 - -const ( - // ByteStringBase16Encoding encodes byte strings in base16, without padding. - ByteStringBase16Encoding ByteStringEncoding = iota - - // ByteStringBase32Encoding encodes byte strings in base32, without padding. - ByteStringBase32Encoding - - // ByteStringBase32HexEncoding encodes byte strings in base32hex, without padding. - ByteStringBase32HexEncoding - - // ByteStringBase64Encoding encodes byte strings in base64url, without padding. - ByteStringBase64Encoding - - maxByteStringEncoding -) - -func (bse ByteStringEncoding) valid() error { - if bse >= maxByteStringEncoding { - return errors.New("cbor: invalid ByteStringEncoding " + strconv.Itoa(int(bse))) - } - return nil -} - -// DiagOptions specifies Diag options. -type DiagOptions struct { - // ByteStringEncoding specifies the base encoding that byte strings are notated. - // Default is ByteStringBase16Encoding. - ByteStringEncoding ByteStringEncoding - - // ByteStringHexWhitespace specifies notating with whitespace in byte string - // when ByteStringEncoding is ByteStringBase16Encoding. - ByteStringHexWhitespace bool - - // ByteStringText specifies notating with text in byte string - // if it is a valid UTF-8 text. - ByteStringText bool - - // ByteStringEmbeddedCBOR specifies notating embedded CBOR in byte string - // if it is a valid CBOR bytes. - ByteStringEmbeddedCBOR bool - - // CBORSequence specifies notating CBOR sequences. - // otherwise, it returns an error if there are more bytes after the first CBOR. - CBORSequence bool - - // FloatPrecisionIndicator specifies appending a suffix to indicate float precision. - // Refer to https://www.rfc-editor.org/rfc/rfc8949.html#name-encoding-indicators. - FloatPrecisionIndicator bool - - // MaxNestedLevels specifies the max nested levels allowed for any combination of CBOR array, maps, and tags. - // Default is 32 levels and it can be set to [4, 65535]. Note that higher maximum levels of nesting can - // require larger amounts of stack to deserialize. Don't increase this higher than you require. - MaxNestedLevels int - - // MaxArrayElements specifies the max number of elements for CBOR arrays. - // Default is 128*1024=131072 and it can be set to [16, 2147483647] - MaxArrayElements int - - // MaxMapPairs specifies the max number of key-value pairs for CBOR maps. - // Default is 128*1024=131072 and it can be set to [16, 2147483647] - MaxMapPairs int -} - -// DiagMode returns a DiagMode with immutable options. -func (opts DiagOptions) DiagMode() (DiagMode, error) { - return opts.diagMode() -} - -func (opts DiagOptions) diagMode() (*diagMode, error) { - if err := opts.ByteStringEncoding.valid(); err != nil { - return nil, err - } - - decMode, err := DecOptions{ - MaxNestedLevels: opts.MaxNestedLevels, - MaxArrayElements: opts.MaxArrayElements, - MaxMapPairs: opts.MaxMapPairs, - }.decMode() - if err != nil { - return nil, err - } - - return &diagMode{ - byteStringEncoding: opts.ByteStringEncoding, - byteStringHexWhitespace: opts.ByteStringHexWhitespace, - byteStringText: opts.ByteStringText, - byteStringEmbeddedCBOR: opts.ByteStringEmbeddedCBOR, - cborSequence: opts.CBORSequence, - floatPrecisionIndicator: opts.FloatPrecisionIndicator, - decMode: decMode, - }, nil -} - -type diagMode struct { - byteStringEncoding ByteStringEncoding - byteStringHexWhitespace bool - byteStringText bool - byteStringEmbeddedCBOR bool - cborSequence bool - floatPrecisionIndicator bool - decMode *decMode -} - -// DiagOptions returns user specified options used to create this DiagMode. -func (dm *diagMode) DiagOptions() DiagOptions { - return DiagOptions{ - ByteStringEncoding: dm.byteStringEncoding, - ByteStringHexWhitespace: dm.byteStringHexWhitespace, - ByteStringText: dm.byteStringText, - ByteStringEmbeddedCBOR: dm.byteStringEmbeddedCBOR, - CBORSequence: dm.cborSequence, - FloatPrecisionIndicator: dm.floatPrecisionIndicator, - MaxNestedLevels: dm.decMode.maxNestedLevels, - MaxArrayElements: dm.decMode.maxArrayElements, - MaxMapPairs: dm.decMode.maxMapPairs, - } -} - -// Diagnose returns extended diagnostic notation (EDN) of CBOR data items using the DiagMode. -func (dm *diagMode) Diagnose(data []byte) (string, error) { - return newDiagnose(data, dm.decMode, dm).diag(dm.cborSequence) -} - -// DiagnoseFirst returns extended diagnostic notation (EDN) of the first CBOR data item using the DiagMode. Any remaining bytes are returned in rest. -func (dm *diagMode) DiagnoseFirst(data []byte) (string, []byte, error) { - return newDiagnose(data, dm.decMode, dm).diagFirst() -} - -var defaultDiagMode, _ = DiagOptions{}.diagMode() - -// Diagnose returns extended diagnostic notation (EDN) of CBOR data items -// using the default diagnostic mode. -// -// Refer to https://www.rfc-editor.org/rfc/rfc8949.html#name-diagnostic-notation. -func Diagnose(data []byte) (string, error) { - return defaultDiagMode.Diagnose(data) -} - -// Diagnose returns extended diagnostic notation (EDN) of the first CBOR data item using the DiagMode. Any remaining bytes are returned in rest. -func DiagnoseFirst(data []byte) (string, []byte, error) { - return defaultDiagMode.DiagnoseFirst(data) -} - -type diagnose struct { - dm *diagMode - d *decoder - w *bytes.Buffer -} - -func newDiagnose(data []byte, decm *decMode, diagm *diagMode) *diagnose { - return &diagnose{ - dm: diagm, - d: &decoder{data: data, dm: decm}, - w: &bytes.Buffer{}, - } -} - -func (di *diagnose) diag(cborSequence bool) (string, error) { - // CBOR Sequence - firstItem := true - for { - switch err := di.wellformed(cborSequence); err { - case nil: - if !firstItem { - if err = di.writeString(", "); err != nil { - return di.w.String(), err - } - } - firstItem = false - if err = di.item(); err != nil { - return di.w.String(), err - } - - case io.EOF: - if firstItem { - return di.w.String(), err - } - return di.w.String(), nil - - default: - return di.w.String(), err - } - } -} - -func (di *diagnose) diagFirst() (string, []byte, error) { - err := di.wellformed(true) - if err == nil { - err = di.item() - } - - if err == nil { - // Return EDN and the rest of the data slice (which might be len 0) - return di.w.String(), di.d.data[di.d.off:], nil - } - - return di.w.String(), nil, err -} - -func (di *diagnose) wellformed(allowExtraData bool) error { - off := di.d.off - err := di.d.wellformed(allowExtraData) - di.d.off = off - return err -} - -func (di *diagnose) item() error { //nolint:gocyclo - initialByte := di.d.data[di.d.off] - switch initialByte { - case 0x5f, 0x7f: // indefinite-length byte/text string - di.d.off++ - if di.d.data[di.d.off] == 0xff { - di.d.off++ - switch initialByte { - case 0x5f: - // indefinite-length bytes with no chunks. - return di.writeString(`''_`) - case 0x7f: - // indefinite-length text with no chunks. - return di.writeString(`""_`) - } - } - - if err := di.writeString("(_ "); err != nil { - return err - } - - i := 0 - for !di.d.foundBreak() { - if i > 0 { - if err := di.writeString(", "); err != nil { - return err - } - } - - i++ - // wellformedIndefiniteString() already checked that the next item is a byte/text string. - if err := di.item(); err != nil { - return err - } - } - - return di.writeByte(')') - - case 0x9f: // indefinite-length array - di.d.off++ - if err := di.writeString("[_ "); err != nil { - return err - } - - i := 0 - for !di.d.foundBreak() { - if i > 0 { - if err := di.writeString(", "); err != nil { - return err - } - } - - i++ - if err := di.item(); err != nil { - return err - } - } - - return di.writeByte(']') - - case 0xbf: // indefinite-length map - di.d.off++ - if err := di.writeString("{_ "); err != nil { - return err - } - - i := 0 - for !di.d.foundBreak() { - if i > 0 { - if err := di.writeString(", "); err != nil { - return err - } - } - - i++ - // key - if err := di.item(); err != nil { - return err - } - - if err := di.writeString(": "); err != nil { - return err - } - - // value - if err := di.item(); err != nil { - return err - } - } - - return di.writeByte('}') - } - - t := di.d.nextCBORType() - switch t { - case cborTypePositiveInt: - _, _, val := di.d.getHead() - return di.writeString(strconv.FormatUint(val, 10)) - - case cborTypeNegativeInt: - _, _, val := di.d.getHead() - if val > math.MaxInt64 { - // CBOR negative integer overflows int64, use big.Int to store value. - bi := new(big.Int) - bi.SetUint64(val) - bi.Add(bi, big.NewInt(1)) - bi.Neg(bi) - return di.writeString(bi.String()) - } - - nValue := int64(-1) ^ int64(val) - return di.writeString(strconv.FormatInt(nValue, 10)) - - case cborTypeByteString: - b := di.d.parseByteString() - return di.encodeByteString(b) - - case cborTypeTextString: - b, err := di.d.parseTextString() - if err != nil { - return err - } - return di.encodeTextString(string(b), '"') - - case cborTypeArray: - _, _, val := di.d.getHead() - count := int(val) - if err := di.writeByte('['); err != nil { - return err - } - - for i := 0; i < count; i++ { - if i > 0 { - if err := di.writeString(", "); err != nil { - return err - } - } - if err := di.item(); err != nil { - return err - } - } - return di.writeByte(']') - - case cborTypeMap: - _, _, val := di.d.getHead() - count := int(val) - if err := di.writeByte('{'); err != nil { - return err - } - - for i := 0; i < count; i++ { - if i > 0 { - if err := di.writeString(", "); err != nil { - return err - } - } - // key - if err := di.item(); err != nil { - return err - } - if err := di.writeString(": "); err != nil { - return err - } - // value - if err := di.item(); err != nil { - return err - } - } - return di.writeByte('}') - - case cborTypeTag: - _, _, tagNum := di.d.getHead() - switch tagNum { - case 2: - if nt := di.d.nextCBORType(); nt != cborTypeByteString { - return errors.New("cbor: tag number 2 must be followed by byte string, got " + nt.String()) - } - - b := di.d.parseByteString() - bi := new(big.Int).SetBytes(b) - return di.writeString(bi.String()) - - case 3: - if nt := di.d.nextCBORType(); nt != cborTypeByteString { - return errors.New("cbor: tag number 3 must be followed by byte string, got " + nt.String()) - } - - b := di.d.parseByteString() - bi := new(big.Int).SetBytes(b) - bi.Add(bi, big.NewInt(1)) - bi.Neg(bi) - return di.writeString(bi.String()) - - default: - if err := di.writeString(strconv.FormatUint(tagNum, 10)); err != nil { - return err - } - if err := di.writeByte('('); err != nil { - return err - } - if err := di.item(); err != nil { - return err - } - return di.writeByte(')') - } - - case cborTypePrimitives: - _, ai, val := di.d.getHead() - switch ai { - case 20: - return di.writeString("false") - - case 21: - return di.writeString("true") - - case 22: - return di.writeString("null") - - case 23: - return di.writeString("undefined") - - case 25, 26, 27: - return di.encodeFloat(ai, val) - - default: - if err := di.writeString("simple("); err != nil { - return err - } - if err := di.writeString(strconv.FormatUint(val, 10)); err != nil { - return err - } - return di.writeByte(')') - } - } - - return nil -} - -func (di *diagnose) writeByte(val byte) error { - return di.w.WriteByte(val) -} - -func (di *diagnose) writeString(val string) error { - _, err := di.w.WriteString(val) - return err -} - -// writeU16 format a rune as "\uxxxx" -func (di *diagnose) writeU16(val rune) error { - if err := di.writeString("\\u"); err != nil { - return err - } - b := make([]byte, 2) - b[0] = byte(val >> 8) - b[1] = byte(val) - return di.writeString(hex.EncodeToString(b)) -} - -var rawBase32Encoding = base32.StdEncoding.WithPadding(base32.NoPadding) -var rawBase32HexEncoding = base32.HexEncoding.WithPadding(base32.NoPadding) - -func (di *diagnose) encodeByteString(val []byte) error { - if len(val) > 0 { - if di.dm.byteStringText && utf8.Valid(val) { - return di.encodeTextString(string(val), '\'') - } - - if di.dm.byteStringEmbeddedCBOR { - di2 := newDiagnose(val, di.dm.decMode, di.dm) - // should always notating embedded CBOR sequence. - if str, err := di2.diag(true); err == nil { - if err := di.writeString("<<"); err != nil { - return err - } - if err := di.writeString(str); err != nil { - return err - } - return di.writeString(">>") - } - } - } - - switch di.dm.byteStringEncoding { - case ByteStringBase16Encoding: - if err := di.writeString("h'"); err != nil { - return err - } - - encoder := hex.NewEncoder(di.w) - if di.dm.byteStringHexWhitespace { - for i, b := range val { - if i > 0 { - if err := di.writeByte(' '); err != nil { - return err - } - } - if _, err := encoder.Write([]byte{b}); err != nil { - return err - } - } - } else { - if _, err := encoder.Write(val); err != nil { - return err - } - } - return di.writeByte('\'') - - case ByteStringBase32Encoding: - if err := di.writeString("b32'"); err != nil { - return err - } - encoder := base32.NewEncoder(rawBase32Encoding, di.w) - if _, err := encoder.Write(val); err != nil { - return err - } - encoder.Close() - return di.writeByte('\'') - - case ByteStringBase32HexEncoding: - if err := di.writeString("h32'"); err != nil { - return err - } - encoder := base32.NewEncoder(rawBase32HexEncoding, di.w) - if _, err := encoder.Write(val); err != nil { - return err - } - encoder.Close() - return di.writeByte('\'') - - case ByteStringBase64Encoding: - if err := di.writeString("b64'"); err != nil { - return err - } - encoder := base64.NewEncoder(base64.RawURLEncoding, di.w) - if _, err := encoder.Write(val); err != nil { - return err - } - encoder.Close() - return di.writeByte('\'') - - default: - return di.dm.byteStringEncoding.valid() - } -} - -var utf16SurrSelf = rune(0x10000) - -// quote should be either `'` or `"` -func (di *diagnose) encodeTextString(val string, quote byte) error { - if err := di.writeByte(quote); err != nil { - return err - } - - for i := 0; i < len(val); { - if b := val[i]; b < utf8.RuneSelf { - switch { - case b == '\t', b == '\n', b == '\r', b == '\\', b == quote: - if err := di.writeByte('\\'); err != nil { - return err - } - - switch b { - case '\t': - b = 't' - case '\n': - b = 'n' - case '\r': - b = 'r' - } - if err := di.writeByte(b); err != nil { - return err - } - - case b >= ' ' && b <= '~': - if err := di.writeByte(b); err != nil { - return err - } - - default: - if err := di.writeU16(rune(b)); err != nil { - return err - } - } - - i++ - continue - } - - c, size := utf8.DecodeRuneInString(val[i:]) - switch { - case c == utf8.RuneError: - // if err := di.writeU16(rune(val[i])); err != nil { - // return err - // } - return &SemanticError{"cbor: invalid UTF-8 string"} - - case c < utf16SurrSelf: - if err := di.writeU16(c); err != nil { - return err - } - - default: - c1, c2 := utf16.EncodeRune(c) - if err := di.writeU16(c1); err != nil { - return err - } - if err := di.writeU16(c2); err != nil { - return err - } - } - - i += size - } - - return di.writeByte(quote) -} - -func (di *diagnose) encodeFloat(ai byte, val uint64) error { - f64 := float64(0) - switch ai { - case 25: - f16 := float16.Frombits(uint16(val)) - switch { - case f16.IsNaN(): - return di.writeString("NaN") - case f16.IsInf(1): - return di.writeString("Infinity") - case f16.IsInf(-1): - return di.writeString("-Infinity") - default: - f64 = float64(f16.Float32()) - } - - case 26: - f32 := math.Float32frombits(uint32(val)) - switch { - case f32 != f32: - return di.writeString("NaN") - case f32 > math.MaxFloat32: - return di.writeString("Infinity") - case f32 < -math.MaxFloat32: - return di.writeString("-Infinity") - default: - f64 = float64(f32) - } - - case 27: - f64 = math.Float64frombits(val) - switch { - case f64 != f64: - return di.writeString("NaN") - case f64 > math.MaxFloat64: - return di.writeString("Infinity") - case f64 < -math.MaxFloat64: - return di.writeString("-Infinity") - } - } - // Use ES6 number to string conversion which should match most JSON generators. - // Inspired by https://github.com/golang/go/blob/4df10fba1687a6d4f51d7238a403f8f2298f6a16/src/encoding/json/encode.go#L585 - b := make([]byte, 0, 32) - if abs := math.Abs(f64); abs != 0 && (abs < 1e-6 || abs >= 1e21) { - b = strconv.AppendFloat(b, f64, 'e', -1, 64) - // clean up e-09 to e-9 - n := len(b) - if n >= 4 && string(b[n-4:n-1]) == "e-0" { - b = append(b[:n-2], b[n-1]) - } - } else { - b = strconv.AppendFloat(b, f64, 'f', -1, 64) - } - - // add decimal point and trailing zero if needed - if bytes.IndexByte(b, '.') < 0 { - if i := bytes.IndexByte(b, 'e'); i < 0 { - b = append(b, '.', '0') - } else { - b = append(b[:i+2], b[i:]...) - b[i] = '.' - b[i+1] = '0' - } - } - - if err := di.writeString(string(b)); err != nil { - return err - } - - if di.dm.floatPrecisionIndicator { - switch ai { - case 25: - return di.writeString("_1") - case 26: - return di.writeString("_2") - case 27: - return di.writeString("_3") - } - } - - return nil -} diff --git a/vendor/github.com/fxamacker/cbor/v2/doc.go b/vendor/github.com/fxamacker/cbor/v2/doc.go deleted file mode 100644 index b7e377f3..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/doc.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Faye Amacker. All rights reserved. -// Licensed under the MIT License. See LICENSE in the project root for license information. - -/* -Package cbor is a modern CBOR codec (RFC 8949 & RFC 7049) with CBOR tags, -Go struct tags (toarray/keyasint/omitempty), Core Deterministic Encoding, -CTAP2, Canonical CBOR, float64->32->16, and duplicate map key detection. - -Encoding options allow "preferred serialization" by encoding integers and floats -to their smallest forms (e.g. float16) when values fit. - -Struct tags like "keyasint", "toarray" and "omitempty" make CBOR data smaller -and easier to use with structs. - -For example, "toarray" tag makes struct fields encode to CBOR array elements. And -"keyasint" makes a field encode to an element of CBOR map with specified int key. - -Latest docs can be viewed at https://github.com/fxamacker/cbor#cbor-library-in-go - -Basics - -The Quick Start guide is at https://github.com/fxamacker/cbor#quick-start - -Function signatures identical to encoding/json include: - - Marshal, Unmarshal, NewEncoder, NewDecoder, (*Encoder).Encode, (*Decoder).Decode. - -Standard interfaces include: - - BinaryMarshaler, BinaryUnmarshaler, Marshaler, and Unmarshaler. - -Custom encoding and decoding is possible by implementing standard interfaces for -user-defined Go types. - -Codec functions are available at package-level (using defaults options) or by -creating modes from options at runtime. - -"Mode" in this API means definite way of encoding (EncMode) or decoding (DecMode). - -EncMode and DecMode interfaces are created from EncOptions or DecOptions structs. - - em, err := cbor.EncOptions{...}.EncMode() - em, err := cbor.CanonicalEncOptions().EncMode() - em, err := cbor.CTAP2EncOptions().EncMode() - -Modes use immutable options to avoid side-effects and simplify concurrency. Behavior of -modes won't accidentally change at runtime after they're created. - -Modes are intended to be reused and are safe for concurrent use. - -EncMode and DecMode Interfaces - - // EncMode interface uses immutable options and is safe for concurrent use. - type EncMode interface { - Marshal(v interface{}) ([]byte, error) - NewEncoder(w io.Writer) *Encoder - EncOptions() EncOptions // returns copy of options - } - - // DecMode interface uses immutable options and is safe for concurrent use. - type DecMode interface { - Unmarshal(data []byte, v interface{}) error - NewDecoder(r io.Reader) *Decoder - DecOptions() DecOptions // returns copy of options - } - -Using Default Encoding Mode - - b, err := cbor.Marshal(v) - - encoder := cbor.NewEncoder(w) - err = encoder.Encode(v) - -Using Default Decoding Mode - - err := cbor.Unmarshal(b, &v) - - decoder := cbor.NewDecoder(r) - err = decoder.Decode(&v) - -Creating and Using Encoding Modes - - // Create EncOptions using either struct literal or a function. - opts := cbor.CanonicalEncOptions() - - // If needed, modify encoding options - opts.Time = cbor.TimeUnix - - // Create reusable EncMode interface with immutable options, safe for concurrent use. - em, err := opts.EncMode() - - // Use EncMode like encoding/json, with same function signatures. - b, err := em.Marshal(v) - // or - encoder := em.NewEncoder(w) - err := encoder.Encode(v) - - // NOTE: Both em.Marshal(v) and encoder.Encode(v) use encoding options - // specified during creation of em (encoding mode). - -CBOR Options - -Predefined Encoding Options: https://github.com/fxamacker/cbor#predefined-encoding-options - -Encoding Options: https://github.com/fxamacker/cbor#encoding-options - -Decoding Options: https://github.com/fxamacker/cbor#decoding-options - -Struct Tags - -Struct tags like `cbor:"name,omitempty"` and `json:"name,omitempty"` work as expected. -If both struct tags are specified then `cbor` is used. - -Struct tags like "keyasint", "toarray", and "omitempty" make it easy to use -very compact formats like COSE and CWT (CBOR Web Tokens) with structs. - -For example, "toarray" makes struct fields encode to array elements. And "keyasint" -makes struct fields encode to elements of CBOR map with int keys. - -https://raw.githubusercontent.com/fxamacker/images/master/cbor/v2.0.0/cbor_easy_api.png - -Struct tags are listed at https://github.com/fxamacker/cbor#struct-tags-1 - -Tests and Fuzzing - -Over 375 tests are included in this package. Cover-guided fuzzing is handled by -fxamacker/cbor-fuzz. -*/ -package cbor diff --git a/vendor/github.com/fxamacker/cbor/v2/encode.go b/vendor/github.com/fxamacker/cbor/v2/encode.go deleted file mode 100644 index 10255a60..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/encode.go +++ /dev/null @@ -1,1521 +0,0 @@ -// Copyright (c) Faye Amacker. All rights reserved. -// Licensed under the MIT License. See LICENSE in the project root for license information. - -package cbor - -import ( - "bytes" - "encoding" - "encoding/binary" - "errors" - "io" - "math" - "math/big" - "reflect" - "sort" - "strconv" - "sync" - "time" - - "github.com/x448/float16" -) - -// Marshal returns the CBOR encoding of v using default encoding options. -// See EncOptions for encoding options. -// -// Marshal uses the following encoding rules: -// -// If value implements the Marshaler interface, Marshal calls its -// MarshalCBOR method. -// -// If value implements encoding.BinaryMarshaler, Marhsal calls its -// MarshalBinary method and encode it as CBOR byte string. -// -// Boolean values encode as CBOR booleans (type 7). -// -// Positive integer values encode as CBOR positive integers (type 0). -// -// Negative integer values encode as CBOR negative integers (type 1). -// -// Floating point values encode as CBOR floating points (type 7). -// -// String values encode as CBOR text strings (type 3). -// -// []byte values encode as CBOR byte strings (type 2). -// -// Array and slice values encode as CBOR arrays (type 4). -// -// Map values encode as CBOR maps (type 5). -// -// Struct values encode as CBOR maps (type 5). Each exported struct field -// becomes a pair with field name encoded as CBOR text string (type 3) and -// field value encoded based on its type. See struct tag option "keyasint" -// to encode field name as CBOR integer (type 0 and 1). Also see struct -// tag option "toarray" for special field "_" to encode struct values as -// CBOR array (type 4). -// -// Marshal supports format string stored under the "cbor" key in the struct -// field's tag. CBOR format string can specify the name of the field, -// "omitempty" and "keyasint" options, and special case "-" for field omission. -// If "cbor" key is absent, Marshal uses "json" key. -// -// Struct field name is treated as integer if it has "keyasint" option in -// its format string. The format string must specify an integer as its -// field name. -// -// Special struct field "_" is used to specify struct level options, such as -// "toarray". "toarray" option enables Go struct to be encoded as CBOR array. -// "omitempty" is disabled by "toarray" to ensure that the same number -// of elements are encoded every time. -// -// Anonymous struct fields are marshaled as if their exported fields -// were fields in the outer struct. Marshal follows the same struct fields -// visibility rules used by JSON encoding package. -// -// time.Time values encode as text strings specified in RFC3339 or numerical -// representation of seconds since January 1, 1970 UTC depending on -// EncOptions.Time setting. Also See EncOptions.TimeTag to encode -// time.Time as CBOR tag with tag number 0 or 1. -// -// big.Int values encode as CBOR integers (type 0 and 1) if values fit. -// Otherwise, big.Int values encode as CBOR bignums (tag 2 and 3). See -// EncOptions.BigIntConvert to always encode big.Int values as CBOR -// bignums. -// -// Pointer values encode as the value pointed to. -// -// Interface values encode as the value stored in the interface. -// -// Nil slice/map/pointer/interface values encode as CBOR nulls (type 7). -// -// Values of other types cannot be encoded in CBOR. Attempting -// to encode such a value causes Marshal to return an UnsupportedTypeError. -func Marshal(v interface{}) ([]byte, error) { - return defaultEncMode.Marshal(v) -} - -// Marshaler is the interface implemented by types that can marshal themselves -// into valid CBOR. -type Marshaler interface { - MarshalCBOR() ([]byte, error) -} - -// UnsupportedTypeError is returned by Marshal when attempting to encode value -// of an unsupported type. -type UnsupportedTypeError struct { - Type reflect.Type -} - -func (e *UnsupportedTypeError) Error() string { - return "cbor: unsupported type: " + e.Type.String() -} - -// SortMode identifies supported sorting order. -type SortMode int - -const ( - // SortNone means no sorting. - SortNone SortMode = 0 - - // SortLengthFirst causes map keys or struct fields to be sorted such that: - // - If two keys have different lengths, the shorter one sorts earlier; - // - If two keys have the same length, the one with the lower value in - // (byte-wise) lexical order sorts earlier. - // It is used in "Canonical CBOR" encoding in RFC 7049 3.9. - SortLengthFirst SortMode = 1 - - // SortBytewiseLexical causes map keys or struct fields to be sorted in the - // bytewise lexicographic order of their deterministic CBOR encodings. - // It is used in "CTAP2 Canonical CBOR" and "Core Deterministic Encoding" - // in RFC 7049bis. - SortBytewiseLexical SortMode = 2 - - // SortCanonical is used in "Canonical CBOR" encoding in RFC 7049 3.9. - SortCanonical SortMode = SortLengthFirst - - // SortCTAP2 is used in "CTAP2 Canonical CBOR". - SortCTAP2 SortMode = SortBytewiseLexical - - // SortCoreDeterministic is used in "Core Deterministic Encoding" in RFC 7049bis. - SortCoreDeterministic SortMode = SortBytewiseLexical - - maxSortMode SortMode = 3 -) - -func (sm SortMode) valid() bool { - return sm < maxSortMode -} - -// ShortestFloatMode specifies which floating-point format should -// be used as the shortest possible format for CBOR encoding. -// It is not used for encoding Infinity and NaN values. -type ShortestFloatMode int - -const ( - // ShortestFloatNone makes float values encode without any conversion. - // This is the default for ShortestFloatMode in v1. - // E.g. a float32 in Go will encode to CBOR float32. And - // a float64 in Go will encode to CBOR float64. - ShortestFloatNone ShortestFloatMode = iota - - // ShortestFloat16 specifies float16 as the shortest form that preserves value. - // E.g. if float64 can convert to float32 while preserving value, then - // encoding will also try to convert float32 to float16. So a float64 might - // encode as CBOR float64, float32 or float16 depending on the value. - ShortestFloat16 - - maxShortestFloat -) - -func (sfm ShortestFloatMode) valid() bool { - return sfm < maxShortestFloat -} - -// NaNConvertMode specifies how to encode NaN and overrides ShortestFloatMode. -// ShortestFloatMode is not used for encoding Infinity and NaN values. -type NaNConvertMode int - -const ( - // NaNConvert7e00 always encodes NaN to 0xf97e00 (CBOR float16 = 0x7e00). - NaNConvert7e00 NaNConvertMode = iota - - // NaNConvertNone never modifies or converts NaN to other representations - // (float64 NaN stays float64, etc. even if it can use float16 without losing - // any bits). - NaNConvertNone - - // NaNConvertPreserveSignal converts NaN to the smallest form that preserves - // value (quiet bit + payload) as described in RFC 7049bis Draft 12. - NaNConvertPreserveSignal - - // NaNConvertQuiet always forces quiet bit = 1 and shortest form that preserves - // NaN payload. - NaNConvertQuiet - - maxNaNConvert -) - -func (ncm NaNConvertMode) valid() bool { - return ncm < maxNaNConvert -} - -// InfConvertMode specifies how to encode Infinity and overrides ShortestFloatMode. -// ShortestFloatMode is not used for encoding Infinity and NaN values. -type InfConvertMode int - -const ( - // InfConvertFloat16 always converts Inf to lossless IEEE binary16 (float16). - InfConvertFloat16 InfConvertMode = iota - - // InfConvertNone never converts (used by CTAP2 Canonical CBOR). - InfConvertNone - - maxInfConvert -) - -func (icm InfConvertMode) valid() bool { - return icm < maxInfConvert -} - -// TimeMode specifies how to encode time.Time values. -type TimeMode int - -const ( - // TimeUnix causes time.Time to be encoded as epoch time in integer with second precision. - TimeUnix TimeMode = iota - - // TimeUnixMicro causes time.Time to be encoded as epoch time in float-point rounded to microsecond precision. - TimeUnixMicro - - // TimeUnixDynamic causes time.Time to be encoded as integer if time.Time doesn't have fractional seconds, - // otherwise float-point rounded to microsecond precision. - TimeUnixDynamic - - // TimeRFC3339 causes time.Time to be encoded as RFC3339 formatted string with second precision. - TimeRFC3339 - - // TimeRFC3339Nano causes time.Time to be encoded as RFC3339 formatted string with nanosecond precision. - TimeRFC3339Nano - - maxTimeMode -) - -func (tm TimeMode) valid() bool { - return tm < maxTimeMode -} - -// BigIntConvertMode specifies how to encode big.Int values. -type BigIntConvertMode int - -const ( - // BigIntConvertShortest makes big.Int encode to CBOR integer if value fits. - // E.g. if big.Int value can be converted to CBOR integer while preserving - // value, encoder will encode it to CBOR integer (major type 0 or 1). - BigIntConvertShortest BigIntConvertMode = iota - - // BigIntConvertNone makes big.Int encode to CBOR bignum (tag 2 or 3) without - // converting it to another CBOR type. - BigIntConvertNone - - maxBigIntConvert -) - -func (bim BigIntConvertMode) valid() bool { - return bim < maxBigIntConvert -} - -// NilContainersMode specifies how to encode nil slices and maps. -type NilContainersMode int - -const ( - // NilContainerAsNull encodes nil slices and maps as CBOR null. - // This is the default. - NilContainerAsNull NilContainersMode = iota - - // NilContainerAsEmpty encodes nil slices and maps as - // empty container (CBOR bytestring, array, or map). - NilContainerAsEmpty - - maxNilContainersMode -) - -func (m NilContainersMode) valid() bool { - return m < maxNilContainersMode -} - -// EncOptions specifies encoding options. -type EncOptions struct { - // Sort specifies sorting order. - Sort SortMode - - // ShortestFloat specifies the shortest floating-point encoding that preserves - // the value being encoded. - ShortestFloat ShortestFloatMode - - // NaNConvert specifies how to encode NaN and it overrides ShortestFloatMode. - NaNConvert NaNConvertMode - - // InfConvert specifies how to encode Inf and it overrides ShortestFloatMode. - InfConvert InfConvertMode - - // BigIntConvert specifies how to encode big.Int values. - BigIntConvert BigIntConvertMode - - // Time specifies how to encode time.Time. - Time TimeMode - - // TimeTag allows time.Time to be encoded with a tag number. - // RFC3339 format gets tag number 0, and numeric epoch time tag number 1. - TimeTag EncTagMode - - // IndefLength specifies whether to allow indefinite length CBOR items. - IndefLength IndefLengthMode - - // NilContainers specifies how to encode nil slices and maps. - NilContainers NilContainersMode - - // TagsMd specifies whether to allow CBOR tags (major type 6). - TagsMd TagsMode -} - -// CanonicalEncOptions returns EncOptions for "Canonical CBOR" encoding, -// defined in RFC 7049 Section 3.9 with the following rules: -// -// 1. "Integers must be as small as possible." -// 2. "The expression of lengths in major types 2 through 5 must be as short as possible." -// 3. The keys in every map must be sorted in length-first sorting order. -// See SortLengthFirst for details. -// 4. "Indefinite-length items must be made into definite-length items." -// 5. "If a protocol allows for IEEE floats, then additional canonicalization rules might -// need to be added. One example rule might be to have all floats start as a 64-bit -// float, then do a test conversion to a 32-bit float; if the result is the same numeric -// value, use the shorter value and repeat the process with a test conversion to a -// 16-bit float. (This rule selects 16-bit float for positive and negative Infinity -// as well.) Also, there are many representations for NaN. If NaN is an allowed value, -// it must always be represented as 0xf97e00." -// -func CanonicalEncOptions() EncOptions { - return EncOptions{ - Sort: SortCanonical, - ShortestFloat: ShortestFloat16, - NaNConvert: NaNConvert7e00, - InfConvert: InfConvertFloat16, - IndefLength: IndefLengthForbidden, - } -} - -// CTAP2EncOptions returns EncOptions for "CTAP2 Canonical CBOR" encoding, -// defined in CTAP specification, with the following rules: -// -// 1. "Integers must be encoded as small as possible." -// 2. "The representations of any floating-point values are not changed." -// 3. "The expression of lengths in major types 2 through 5 must be as short as possible." -// 4. "Indefinite-length items must be made into definite-length items."" -// 5. The keys in every map must be sorted in bytewise lexicographic order. -// See SortBytewiseLexical for details. -// 6. "Tags as defined in Section 2.4 in [RFC7049] MUST NOT be present." -// -func CTAP2EncOptions() EncOptions { - return EncOptions{ - Sort: SortCTAP2, - ShortestFloat: ShortestFloatNone, - NaNConvert: NaNConvertNone, - InfConvert: InfConvertNone, - IndefLength: IndefLengthForbidden, - TagsMd: TagsForbidden, - } -} - -// CoreDetEncOptions returns EncOptions for "Core Deterministic" encoding, -// defined in RFC 7049bis with the following rules: -// -// 1. "Preferred serialization MUST be used. In particular, this means that arguments -// (see Section 3) for integers, lengths in major types 2 through 5, and tags MUST -// be as short as possible" -// "Floating point values also MUST use the shortest form that preserves the value" -// 2. "Indefinite-length items MUST NOT appear." -// 3. "The keys in every map MUST be sorted in the bytewise lexicographic order of -// their deterministic encodings." -// -func CoreDetEncOptions() EncOptions { - return EncOptions{ - Sort: SortCoreDeterministic, - ShortestFloat: ShortestFloat16, - NaNConvert: NaNConvert7e00, - InfConvert: InfConvertFloat16, - IndefLength: IndefLengthForbidden, - } -} - -// PreferredUnsortedEncOptions returns EncOptions for "Preferred Serialization" encoding, -// defined in RFC 7049bis with the following rules: -// -// 1. "The preferred serialization always uses the shortest form of representing the argument -// (Section 3);" -// 2. "it also uses the shortest floating-point encoding that preserves the value being -// encoded (see Section 5.5)." -// "The preferred encoding for a floating-point value is the shortest floating-point encoding -// that preserves its value, e.g., 0xf94580 for the number 5.5, and 0xfa45ad9c00 for the -// number 5555.5, unless the CBOR-based protocol specifically excludes the use of the shorter -// floating-point encodings. For NaN values, a shorter encoding is preferred if zero-padding -// the shorter significand towards the right reconstitutes the original NaN value (for many -// applications, the single NaN encoding 0xf97e00 will suffice)." -// 3. "Definite length encoding is preferred whenever the length is known at the time the -// serialization of the item starts." -// -func PreferredUnsortedEncOptions() EncOptions { - return EncOptions{ - Sort: SortNone, - ShortestFloat: ShortestFloat16, - NaNConvert: NaNConvert7e00, - InfConvert: InfConvertFloat16, - } -} - -// EncMode returns EncMode with immutable options and no tags (safe for concurrency). -func (opts EncOptions) EncMode() (EncMode, error) { - return opts.encMode() -} - -// EncModeWithTags returns EncMode with options and tags that are both immutable (safe for concurrency). -func (opts EncOptions) EncModeWithTags(tags TagSet) (EncMode, error) { - if opts.TagsMd == TagsForbidden { - return nil, errors.New("cbor: cannot create EncMode with TagSet when TagsMd is TagsForbidden") - } - if tags == nil { - return nil, errors.New("cbor: cannot create EncMode with nil value as TagSet") - } - em, err := opts.encMode() - if err != nil { - return nil, err - } - // Copy tags - ts := tagSet(make(map[reflect.Type]*tagItem)) - syncTags := tags.(*syncTagSet) - syncTags.RLock() - for contentType, tag := range syncTags.t { - if tag.opts.EncTag != EncTagNone { - ts[contentType] = tag - } - } - syncTags.RUnlock() - if len(ts) > 0 { - em.tags = ts - } - return em, nil -} - -// EncModeWithSharedTags returns EncMode with immutable options and mutable shared tags (safe for concurrency). -func (opts EncOptions) EncModeWithSharedTags(tags TagSet) (EncMode, error) { - if opts.TagsMd == TagsForbidden { - return nil, errors.New("cbor: cannot create EncMode with TagSet when TagsMd is TagsForbidden") - } - if tags == nil { - return nil, errors.New("cbor: cannot create EncMode with nil value as TagSet") - } - em, err := opts.encMode() - if err != nil { - return nil, err - } - em.tags = tags - return em, nil -} - -func (opts EncOptions) encMode() (*encMode, error) { - if !opts.Sort.valid() { - return nil, errors.New("cbor: invalid SortMode " + strconv.Itoa(int(opts.Sort))) - } - if !opts.ShortestFloat.valid() { - return nil, errors.New("cbor: invalid ShortestFloatMode " + strconv.Itoa(int(opts.ShortestFloat))) - } - if !opts.NaNConvert.valid() { - return nil, errors.New("cbor: invalid NaNConvertMode " + strconv.Itoa(int(opts.NaNConvert))) - } - if !opts.InfConvert.valid() { - return nil, errors.New("cbor: invalid InfConvertMode " + strconv.Itoa(int(opts.InfConvert))) - } - if !opts.BigIntConvert.valid() { - return nil, errors.New("cbor: invalid BigIntConvertMode " + strconv.Itoa(int(opts.BigIntConvert))) - } - if !opts.Time.valid() { - return nil, errors.New("cbor: invalid TimeMode " + strconv.Itoa(int(opts.Time))) - } - if !opts.TimeTag.valid() { - return nil, errors.New("cbor: invalid TimeTag " + strconv.Itoa(int(opts.TimeTag))) - } - if !opts.IndefLength.valid() { - return nil, errors.New("cbor: invalid IndefLength " + strconv.Itoa(int(opts.IndefLength))) - } - if !opts.NilContainers.valid() { - return nil, errors.New("cbor: invalid NilContainers " + strconv.Itoa(int(opts.NilContainers))) - } - if !opts.TagsMd.valid() { - return nil, errors.New("cbor: invalid TagsMd " + strconv.Itoa(int(opts.TagsMd))) - } - if opts.TagsMd == TagsForbidden && opts.TimeTag == EncTagRequired { - return nil, errors.New("cbor: cannot set TagsMd to TagsForbidden when TimeTag is EncTagRequired") - } - em := encMode{ - sort: opts.Sort, - shortestFloat: opts.ShortestFloat, - nanConvert: opts.NaNConvert, - infConvert: opts.InfConvert, - bigIntConvert: opts.BigIntConvert, - time: opts.Time, - timeTag: opts.TimeTag, - indefLength: opts.IndefLength, - nilContainers: opts.NilContainers, - tagsMd: opts.TagsMd, - } - return &em, nil -} - -// EncMode is the main interface for CBOR encoding. -type EncMode interface { - Marshal(v interface{}) ([]byte, error) - NewEncoder(w io.Writer) *Encoder - EncOptions() EncOptions -} - -type encMode struct { - tags tagProvider - sort SortMode - shortestFloat ShortestFloatMode - nanConvert NaNConvertMode - infConvert InfConvertMode - bigIntConvert BigIntConvertMode - time TimeMode - timeTag EncTagMode - indefLength IndefLengthMode - nilContainers NilContainersMode - tagsMd TagsMode -} - -var defaultEncMode = &encMode{} - -// EncOptions returns user specified options used to create this EncMode. -func (em *encMode) EncOptions() EncOptions { - return EncOptions{ - Sort: em.sort, - ShortestFloat: em.shortestFloat, - NaNConvert: em.nanConvert, - InfConvert: em.infConvert, - BigIntConvert: em.bigIntConvert, - Time: em.time, - TimeTag: em.timeTag, - IndefLength: em.indefLength, - TagsMd: em.tagsMd, - } -} - -func (em *encMode) encTagBytes(t reflect.Type) []byte { - if em.tags != nil { - if tagItem := em.tags.getTagItemFromType(t); tagItem != nil { - return tagItem.cborTagNum - } - } - return nil -} - -// Marshal returns the CBOR encoding of v using em encoding mode. -// -// See the documentation for Marshal for details. -func (em *encMode) Marshal(v interface{}) ([]byte, error) { - e := getEncoderBuffer() - - if err := encode(e, em, reflect.ValueOf(v)); err != nil { - putEncoderBuffer(e) - return nil, err - } - - buf := make([]byte, e.Len()) - copy(buf, e.Bytes()) - - putEncoderBuffer(e) - return buf, nil -} - -// NewEncoder returns a new encoder that writes to w using em EncMode. -func (em *encMode) NewEncoder(w io.Writer) *Encoder { - return &Encoder{w: w, em: em} -} - -type encoderBuffer struct { - bytes.Buffer - scratch [16]byte -} - -// encoderBufferPool caches unused encoderBuffer objects for later reuse. -var encoderBufferPool = sync.Pool{ - New: func() interface{} { - e := new(encoderBuffer) - e.Grow(32) // TODO: make this configurable - return e - }, -} - -func getEncoderBuffer() *encoderBuffer { - return encoderBufferPool.Get().(*encoderBuffer) -} - -func putEncoderBuffer(e *encoderBuffer) { - e.Reset() - encoderBufferPool.Put(e) -} - -type encodeFunc func(e *encoderBuffer, em *encMode, v reflect.Value) error -type isEmptyFunc func(v reflect.Value) (empty bool, err error) - -var ( - cborFalse = []byte{0xf4} - cborTrue = []byte{0xf5} - cborNil = []byte{0xf6} - cborNaN = []byte{0xf9, 0x7e, 0x00} - cborPositiveInfinity = []byte{0xf9, 0x7c, 0x00} - cborNegativeInfinity = []byte{0xf9, 0xfc, 0x00} -) - -func encode(e *encoderBuffer, em *encMode, v reflect.Value) error { - if !v.IsValid() { - // v is zero value - e.Write(cborNil) - return nil - } - vt := v.Type() - f, _ := getEncodeFunc(vt) - if f == nil { - return &UnsupportedTypeError{vt} - } - - return f(e, em, v) -} - -func encodeBool(e *encoderBuffer, em *encMode, v reflect.Value) error { - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - b := cborFalse - if v.Bool() { - b = cborTrue - } - e.Write(b) - return nil -} - -func encodeInt(e *encoderBuffer, em *encMode, v reflect.Value) error { - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - i := v.Int() - if i >= 0 { - encodeHead(e, byte(cborTypePositiveInt), uint64(i)) - return nil - } - i = i*(-1) - 1 - encodeHead(e, byte(cborTypeNegativeInt), uint64(i)) - return nil -} - -func encodeUint(e *encoderBuffer, em *encMode, v reflect.Value) error { - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - encodeHead(e, byte(cborTypePositiveInt), v.Uint()) - return nil -} - -func encodeFloat(e *encoderBuffer, em *encMode, v reflect.Value) error { - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - f64 := v.Float() - if math.IsNaN(f64) { - return encodeNaN(e, em, v) - } - if math.IsInf(f64, 0) { - return encodeInf(e, em, v) - } - fopt := em.shortestFloat - if v.Kind() == reflect.Float64 && (fopt == ShortestFloatNone || cannotFitFloat32(f64)) { - // Encode float64 - // Don't use encodeFloat64() because it cannot be inlined. - e.scratch[0] = byte(cborTypePrimitives) | byte(27) - binary.BigEndian.PutUint64(e.scratch[1:], math.Float64bits(f64)) - e.Write(e.scratch[:9]) - return nil - } - - f32 := float32(f64) - if fopt == ShortestFloat16 { - var f16 float16.Float16 - p := float16.PrecisionFromfloat32(f32) - if p == float16.PrecisionExact { - // Roundtrip float32->float16->float32 test isn't needed. - f16 = float16.Fromfloat32(f32) - } else if p == float16.PrecisionUnknown { - // Try roundtrip float32->float16->float32 to determine if float32 can fit into float16. - f16 = float16.Fromfloat32(f32) - if f16.Float32() == f32 { - p = float16.PrecisionExact - } - } - if p == float16.PrecisionExact { - // Encode float16 - // Don't use encodeFloat16() because it cannot be inlined. - e.scratch[0] = byte(cborTypePrimitives) | byte(25) - binary.BigEndian.PutUint16(e.scratch[1:], uint16(f16)) - e.Write(e.scratch[:3]) - return nil - } - } - - // Encode float32 - // Don't use encodeFloat32() because it cannot be inlined. - e.scratch[0] = byte(cborTypePrimitives) | byte(26) - binary.BigEndian.PutUint32(e.scratch[1:], math.Float32bits(f32)) - e.Write(e.scratch[:5]) - return nil -} - -func encodeInf(e *encoderBuffer, em *encMode, v reflect.Value) error { - f64 := v.Float() - if em.infConvert == InfConvertFloat16 { - if f64 > 0 { - e.Write(cborPositiveInfinity) - } else { - e.Write(cborNegativeInfinity) - } - return nil - } - if v.Kind() == reflect.Float64 { - return encodeFloat64(e, f64) - } - return encodeFloat32(e, float32(f64)) -} - -func encodeNaN(e *encoderBuffer, em *encMode, v reflect.Value) error { - switch em.nanConvert { - case NaNConvert7e00: - e.Write(cborNaN) - return nil - - case NaNConvertNone: - if v.Kind() == reflect.Float64 { - return encodeFloat64(e, v.Float()) - } - f32 := float32NaNFromReflectValue(v) - return encodeFloat32(e, f32) - - default: // NaNConvertPreserveSignal, NaNConvertQuiet - if v.Kind() == reflect.Float64 { - f64 := v.Float() - f64bits := math.Float64bits(f64) - if em.nanConvert == NaNConvertQuiet && f64bits&(1<<51) == 0 { - f64bits |= 1 << 51 // Set quiet bit = 1 - f64 = math.Float64frombits(f64bits) - } - // The lower 29 bits are dropped when converting from float64 to float32. - if f64bits&0x1fffffff != 0 { - // Encode NaN as float64 because dropped coef bits from float64 to float32 are not all 0s. - return encodeFloat64(e, f64) - } - // Create float32 from float64 manually because float32(f64) always turns on NaN's quiet bits. - sign := uint32(f64bits>>32) & (1 << 31) - exp := uint32(0x7f800000) - coef := uint32((f64bits & 0xfffffffffffff) >> 29) - f32bits := sign | exp | coef - f32 := math.Float32frombits(f32bits) - // The lower 13 bits are dropped when converting from float32 to float16. - if f32bits&0x1fff != 0 { - // Encode NaN as float32 because dropped coef bits from float32 to float16 are not all 0s. - return encodeFloat32(e, f32) - } - // Encode NaN as float16 - f16, _ := float16.FromNaN32ps(f32) // Ignore err because it only returns error when f32 is not a NaN. - return encodeFloat16(e, f16) - } - - f32 := float32NaNFromReflectValue(v) - f32bits := math.Float32bits(f32) - if em.nanConvert == NaNConvertQuiet && f32bits&(1<<22) == 0 { - f32bits |= 1 << 22 // Set quiet bit = 1 - f32 = math.Float32frombits(f32bits) - } - // The lower 13 bits are dropped coef bits when converting from float32 to float16. - if f32bits&0x1fff != 0 { - // Encode NaN as float32 because dropped coef bits from float32 to float16 are not all 0s. - return encodeFloat32(e, f32) - } - f16, _ := float16.FromNaN32ps(f32) // Ignore err because it only returns error when f32 is not a NaN. - return encodeFloat16(e, f16) - } -} - -func encodeFloat16(e *encoderBuffer, f16 float16.Float16) error { - e.scratch[0] = byte(cborTypePrimitives) | byte(25) - binary.BigEndian.PutUint16(e.scratch[1:], uint16(f16)) - e.Write(e.scratch[:3]) - return nil -} - -func encodeFloat32(e *encoderBuffer, f32 float32) error { - e.scratch[0] = byte(cborTypePrimitives) | byte(26) - binary.BigEndian.PutUint32(e.scratch[1:], math.Float32bits(f32)) - e.Write(e.scratch[:5]) - return nil -} - -func encodeFloat64(e *encoderBuffer, f64 float64) error { - e.scratch[0] = byte(cborTypePrimitives) | byte(27) - binary.BigEndian.PutUint64(e.scratch[1:], math.Float64bits(f64)) - e.Write(e.scratch[:9]) - return nil -} - -func encodeByteString(e *encoderBuffer, em *encMode, v reflect.Value) error { - vk := v.Kind() - if vk == reflect.Slice && v.IsNil() && em.nilContainers == NilContainerAsNull { - e.Write(cborNil) - return nil - } - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - slen := v.Len() - if slen == 0 { - return e.WriteByte(byte(cborTypeByteString)) - } - encodeHead(e, byte(cborTypeByteString), uint64(slen)) - if vk == reflect.Array { - for i := 0; i < slen; i++ { - e.WriteByte(byte(v.Index(i).Uint())) - } - return nil - } - e.Write(v.Bytes()) - return nil -} - -func encodeString(e *encoderBuffer, em *encMode, v reflect.Value) error { - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - s := v.String() - encodeHead(e, byte(cborTypeTextString), uint64(len(s))) - e.WriteString(s) - return nil -} - -type arrayEncodeFunc struct { - f encodeFunc -} - -func (ae arrayEncodeFunc) encode(e *encoderBuffer, em *encMode, v reflect.Value) error { - if v.Kind() == reflect.Slice && v.IsNil() && em.nilContainers == NilContainerAsNull { - e.Write(cborNil) - return nil - } - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - alen := v.Len() - if alen == 0 { - return e.WriteByte(byte(cborTypeArray)) - } - encodeHead(e, byte(cborTypeArray), uint64(alen)) - for i := 0; i < alen; i++ { - if err := ae.f(e, em, v.Index(i)); err != nil { - return err - } - } - return nil -} - -type mapEncodeFunc struct { - kf, ef encodeFunc -} - -func (me mapEncodeFunc) encode(e *encoderBuffer, em *encMode, v reflect.Value) error { - if v.IsNil() && em.nilContainers == NilContainerAsNull { - e.Write(cborNil) - return nil - } - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - mlen := v.Len() - if mlen == 0 { - return e.WriteByte(byte(cborTypeMap)) - } - if em.sort != SortNone { - return me.encodeCanonical(e, em, v) - } - encodeHead(e, byte(cborTypeMap), uint64(mlen)) - iter := v.MapRange() - for iter.Next() { - if err := me.kf(e, em, iter.Key()); err != nil { - return err - } - if err := me.ef(e, em, iter.Value()); err != nil { - return err - } - } - return nil -} - -type keyValue struct { - keyCBORData, keyValueCBORData []byte - keyLen, keyValueLen int -} - -type bytewiseKeyValueSorter struct { - kvs []keyValue -} - -func (x *bytewiseKeyValueSorter) Len() int { - return len(x.kvs) -} - -func (x *bytewiseKeyValueSorter) Swap(i, j int) { - x.kvs[i], x.kvs[j] = x.kvs[j], x.kvs[i] -} - -func (x *bytewiseKeyValueSorter) Less(i, j int) bool { - return bytes.Compare(x.kvs[i].keyCBORData, x.kvs[j].keyCBORData) <= 0 -} - -type lengthFirstKeyValueSorter struct { - kvs []keyValue -} - -func (x *lengthFirstKeyValueSorter) Len() int { - return len(x.kvs) -} - -func (x *lengthFirstKeyValueSorter) Swap(i, j int) { - x.kvs[i], x.kvs[j] = x.kvs[j], x.kvs[i] -} - -func (x *lengthFirstKeyValueSorter) Less(i, j int) bool { - if len(x.kvs[i].keyCBORData) != len(x.kvs[j].keyCBORData) { - return len(x.kvs[i].keyCBORData) < len(x.kvs[j].keyCBORData) - } - return bytes.Compare(x.kvs[i].keyCBORData, x.kvs[j].keyCBORData) <= 0 -} - -var keyValuePool = sync.Pool{} - -func getKeyValues(length int) *[]keyValue { - v := keyValuePool.Get() - if v == nil { - y := make([]keyValue, length) - return &y - } - x := v.(*[]keyValue) - if cap(*x) >= length { - *x = (*x)[:length] - return x - } - // []keyValue from the pool does not have enough capacity. - // Return it back to the pool and create a new one. - keyValuePool.Put(x) - y := make([]keyValue, length) - return &y -} - -func putKeyValues(x *[]keyValue) { - *x = (*x)[:0] - keyValuePool.Put(x) -} - -func (me mapEncodeFunc) encodeCanonical(e *encoderBuffer, em *encMode, v reflect.Value) error { - kve := getEncoderBuffer() // accumulated cbor encoded key-values - kvsp := getKeyValues(v.Len()) // for sorting keys - kvs := *kvsp - iter := v.MapRange() - for i := 0; iter.Next(); i++ { - off := kve.Len() - if err := me.kf(kve, em, iter.Key()); err != nil { - putEncoderBuffer(kve) - putKeyValues(kvsp) - return err - } - n1 := kve.Len() - off - if err := me.ef(kve, em, iter.Value()); err != nil { - putEncoderBuffer(kve) - putKeyValues(kvsp) - return err - } - n2 := kve.Len() - off - // Save key and keyvalue length to create slice later. - kvs[i] = keyValue{keyLen: n1, keyValueLen: n2} - } - - b := kve.Bytes() - for i, off := 0, 0; i < len(kvs); i++ { - kvs[i].keyCBORData = b[off : off+kvs[i].keyLen] - kvs[i].keyValueCBORData = b[off : off+kvs[i].keyValueLen] - off += kvs[i].keyValueLen - } - - if em.sort == SortBytewiseLexical { - sort.Sort(&bytewiseKeyValueSorter{kvs}) - } else { - sort.Sort(&lengthFirstKeyValueSorter{kvs}) - } - - encodeHead(e, byte(cborTypeMap), uint64(len(kvs))) - for i := 0; i < len(kvs); i++ { - e.Write(kvs[i].keyValueCBORData) - } - - putEncoderBuffer(kve) - putKeyValues(kvsp) - return nil -} - -func encodeStructToArray(e *encoderBuffer, em *encMode, v reflect.Value) (err error) { - structType, err := getEncodingStructType(v.Type()) - if err != nil { - return err - } - - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - - flds := structType.fields - - encodeHead(e, byte(cborTypeArray), uint64(len(flds))) - for i := 0; i < len(flds); i++ { - f := flds[i] - - var fv reflect.Value - if len(f.idx) == 1 { - fv = v.Field(f.idx[0]) - } else { - // Get embedded field value. No error is expected. - fv, _ = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) { - // Write CBOR nil for null pointer to embedded struct - e.Write(cborNil) - return reflect.Value{}, nil - }) - if !fv.IsValid() { - continue - } - } - - if err := f.ef(e, em, fv); err != nil { - return err - } - } - return nil -} - -func encodeFixedLengthStruct(e *encoderBuffer, em *encMode, v reflect.Value, flds fields) error { - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - - encodeHead(e, byte(cborTypeMap), uint64(len(flds))) - - for i := 0; i < len(flds); i++ { - f := flds[i] - e.Write(f.cborName) - - fv := v.Field(f.idx[0]) - if err := f.ef(e, em, fv); err != nil { - return err - } - } - - return nil -} - -func encodeStruct(e *encoderBuffer, em *encMode, v reflect.Value) (err error) { - structType, err := getEncodingStructType(v.Type()) - if err != nil { - return err - } - - flds := structType.getFields(em) - - if structType.fixedLength { - return encodeFixedLengthStruct(e, em, v, flds) - } - - kve := getEncoderBuffer() // encode key-value pairs based on struct field tag options - kvcount := 0 - for i := 0; i < len(flds); i++ { - f := flds[i] - - var fv reflect.Value - if len(f.idx) == 1 { - fv = v.Field(f.idx[0]) - } else { - // Get embedded field value. No error is expected. - fv, _ = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) { - // Skip null pointer to embedded struct - return reflect.Value{}, nil - }) - if !fv.IsValid() { - continue - } - } - - if f.omitEmpty { - empty, err := f.ief(fv) - if err != nil { - putEncoderBuffer(kve) - return err - } - if empty { - continue - } - } - - kve.Write(f.cborName) - - if err := f.ef(kve, em, fv); err != nil { - putEncoderBuffer(kve) - return err - } - kvcount++ - } - - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - - encodeHead(e, byte(cborTypeMap), uint64(kvcount)) - e.Write(kve.Bytes()) - - putEncoderBuffer(kve) - return nil -} - -func encodeIntf(e *encoderBuffer, em *encMode, v reflect.Value) error { - if v.IsNil() { - e.Write(cborNil) - return nil - } - return encode(e, em, v.Elem()) -} - -func encodeTime(e *encoderBuffer, em *encMode, v reflect.Value) error { - t := v.Interface().(time.Time) - if t.IsZero() { - e.Write(cborNil) // Even if tag is required, encode as CBOR null. - return nil - } - if em.timeTag == EncTagRequired { - tagNumber := 1 - if em.time == TimeRFC3339 || em.time == TimeRFC3339Nano { - tagNumber = 0 - } - encodeHead(e, byte(cborTypeTag), uint64(tagNumber)) - } - switch em.time { - case TimeUnix: - secs := t.Unix() - return encodeInt(e, em, reflect.ValueOf(secs)) - case TimeUnixMicro: - t = t.UTC().Round(time.Microsecond) - f := float64(t.UnixNano()) / 1e9 - return encodeFloat(e, em, reflect.ValueOf(f)) - case TimeUnixDynamic: - t = t.UTC().Round(time.Microsecond) - secs, nsecs := t.Unix(), uint64(t.Nanosecond()) - if nsecs == 0 { - return encodeInt(e, em, reflect.ValueOf(secs)) - } - f := float64(secs) + float64(nsecs)/1e9 - return encodeFloat(e, em, reflect.ValueOf(f)) - case TimeRFC3339: - s := t.Format(time.RFC3339) - return encodeString(e, em, reflect.ValueOf(s)) - default: // TimeRFC3339Nano - s := t.Format(time.RFC3339Nano) - return encodeString(e, em, reflect.ValueOf(s)) - } -} - -func encodeBigInt(e *encoderBuffer, em *encMode, v reflect.Value) error { - vbi := v.Interface().(big.Int) - sign := vbi.Sign() - bi := new(big.Int).SetBytes(vbi.Bytes()) // bi is absolute value of v - if sign < 0 { - // For negative number, convert to CBOR encoded number (-v-1). - bi.Sub(bi, big.NewInt(1)) - } - - if em.bigIntConvert == BigIntConvertShortest { - if bi.IsUint64() { - if sign >= 0 { - // Encode as CBOR pos int (major type 0) - encodeHead(e, byte(cborTypePositiveInt), bi.Uint64()) - return nil - } - // Encode as CBOR neg int (major type 1) - encodeHead(e, byte(cborTypeNegativeInt), bi.Uint64()) - return nil - } - } - - tagNum := 2 - if sign < 0 { - tagNum = 3 - } - // Write tag number - encodeHead(e, byte(cborTypeTag), uint64(tagNum)) - // Write bignum byte string - b := bi.Bytes() - encodeHead(e, byte(cborTypeByteString), uint64(len(b))) - e.Write(b) - return nil -} - -func encodeBinaryMarshalerType(e *encoderBuffer, em *encMode, v reflect.Value) error { - vt := v.Type() - m, ok := v.Interface().(encoding.BinaryMarshaler) - if !ok { - pv := reflect.New(vt) - pv.Elem().Set(v) - m = pv.Interface().(encoding.BinaryMarshaler) - } - data, err := m.MarshalBinary() - if err != nil { - return err - } - if b := em.encTagBytes(vt); b != nil { - e.Write(b) - } - encodeHead(e, byte(cborTypeByteString), uint64(len(data))) - e.Write(data) - return nil -} - -func encodeMarshalerType(e *encoderBuffer, em *encMode, v reflect.Value) error { - if em.tagsMd == TagsForbidden && v.Type() == typeRawTag { - return errors.New("cbor: cannot encode cbor.RawTag when TagsMd is TagsForbidden") - } - m, ok := v.Interface().(Marshaler) - if !ok { - pv := reflect.New(v.Type()) - pv.Elem().Set(v) - m = pv.Interface().(Marshaler) - } - data, err := m.MarshalCBOR() - if err != nil { - return err - } - e.Write(data) - return nil -} - -func encodeTag(e *encoderBuffer, em *encMode, v reflect.Value) error { - if em.tagsMd == TagsForbidden { - return errors.New("cbor: cannot encode cbor.Tag when TagsMd is TagsForbidden") - } - - t := v.Interface().(Tag) - - if t.Number == 0 && t.Content == nil { - // Marshal uninitialized cbor.Tag - e.Write(cborNil) - return nil - } - - // Marshal tag number - encodeHead(e, byte(cborTypeTag), t.Number) - - // Marshal tag content - if err := encode(e, em, reflect.ValueOf(t.Content)); err != nil { - return err - } - - return nil -} - -func encodeSimpleValue(e *encoderBuffer, em *encMode, v reflect.Value) error { - if b := em.encTagBytes(v.Type()); b != nil { - e.Write(b) - } - encodeHead(e, byte(cborTypePrimitives), v.Uint()) - return nil -} - -func encodeHead(e *encoderBuffer, t byte, n uint64) { - if n <= 23 { - e.WriteByte(t | byte(n)) - return - } - if n <= math.MaxUint8 { - e.scratch[0] = t | byte(24) - e.scratch[1] = byte(n) - e.Write(e.scratch[:2]) - return - } - if n <= math.MaxUint16 { - e.scratch[0] = t | byte(25) - binary.BigEndian.PutUint16(e.scratch[1:], uint16(n)) - e.Write(e.scratch[:3]) - return - } - if n <= math.MaxUint32 { - e.scratch[0] = t | byte(26) - binary.BigEndian.PutUint32(e.scratch[1:], uint32(n)) - e.Write(e.scratch[:5]) - return - } - e.scratch[0] = t | byte(27) - binary.BigEndian.PutUint64(e.scratch[1:], n) - e.Write(e.scratch[:9]) -} - -var ( - typeMarshaler = reflect.TypeOf((*Marshaler)(nil)).Elem() - typeBinaryMarshaler = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem() - typeRawMessage = reflect.TypeOf(RawMessage(nil)) - typeByteString = reflect.TypeOf(ByteString("")) -) - -func getEncodeFuncInternal(t reflect.Type) (encodeFunc, isEmptyFunc) { - k := t.Kind() - if k == reflect.Ptr { - return getEncodeIndirectValueFunc(t), isEmptyPtr - } - switch t { - case typeSimpleValue: - return encodeSimpleValue, isEmptyUint - case typeTag: - return encodeTag, alwaysNotEmpty - case typeTime: - return encodeTime, alwaysNotEmpty - case typeBigInt: - return encodeBigInt, alwaysNotEmpty - case typeRawMessage: - return encodeMarshalerType, isEmptySlice - case typeByteString: - return encodeMarshalerType, isEmptyString - } - if reflect.PtrTo(t).Implements(typeMarshaler) { - return encodeMarshalerType, alwaysNotEmpty - } - if reflect.PtrTo(t).Implements(typeBinaryMarshaler) { - return encodeBinaryMarshalerType, isEmptyBinaryMarshaler - } - switch k { - case reflect.Bool: - return encodeBool, isEmptyBool - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return encodeInt, isEmptyInt - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return encodeUint, isEmptyUint - case reflect.Float32, reflect.Float64: - return encodeFloat, isEmptyFloat - case reflect.String: - return encodeString, isEmptyString - case reflect.Slice, reflect.Array: - if t.Elem().Kind() == reflect.Uint8 { - return encodeByteString, isEmptySlice - } - f, _ := getEncodeFunc(t.Elem()) - if f == nil { - return nil, nil - } - return arrayEncodeFunc{f: f}.encode, isEmptySlice - case reflect.Map: - kf, _ := getEncodeFunc(t.Key()) - ef, _ := getEncodeFunc(t.Elem()) - if kf == nil || ef == nil { - return nil, nil - } - return mapEncodeFunc{kf: kf, ef: ef}.encode, isEmptyMap - case reflect.Struct: - // Get struct's special field "_" tag options - if f, ok := t.FieldByName("_"); ok { - tag := f.Tag.Get("cbor") - if tag != "-" { - if hasToArrayOption(tag) { - return encodeStructToArray, isEmptyStruct - } - } - } - return encodeStruct, isEmptyStruct - case reflect.Interface: - return encodeIntf, isEmptyIntf - } - return nil, nil -} - -func getEncodeIndirectValueFunc(t reflect.Type) encodeFunc { - for t.Kind() == reflect.Ptr { - t = t.Elem() - } - f, _ := getEncodeFunc(t) - if f == nil { - return nil - } - return func(e *encoderBuffer, em *encMode, v reflect.Value) error { - for v.Kind() == reflect.Ptr && !v.IsNil() { - v = v.Elem() - } - if v.Kind() == reflect.Ptr && v.IsNil() { - e.Write(cborNil) - return nil - } - return f(e, em, v) - } -} - -func alwaysNotEmpty(v reflect.Value) (empty bool, err error) { - return false, nil -} - -func isEmptyBool(v reflect.Value) (bool, error) { - return !v.Bool(), nil -} - -func isEmptyInt(v reflect.Value) (bool, error) { - return v.Int() == 0, nil -} - -func isEmptyUint(v reflect.Value) (bool, error) { - return v.Uint() == 0, nil -} - -func isEmptyFloat(v reflect.Value) (bool, error) { - return v.Float() == 0.0, nil -} - -func isEmptyString(v reflect.Value) (bool, error) { - return v.Len() == 0, nil -} - -func isEmptySlice(v reflect.Value) (bool, error) { - return v.Len() == 0, nil -} - -func isEmptyMap(v reflect.Value) (bool, error) { - return v.Len() == 0, nil -} - -func isEmptyPtr(v reflect.Value) (bool, error) { - return v.IsNil(), nil -} - -func isEmptyIntf(v reflect.Value) (bool, error) { - return v.IsNil(), nil -} - -func isEmptyStruct(v reflect.Value) (bool, error) { - structType, err := getEncodingStructType(v.Type()) - if err != nil { - return false, err - } - - if structType.toArray { - return len(structType.fields) == 0, nil - } - - if len(structType.fields) > len(structType.omitEmptyFieldsIdx) { - return false, nil - } - - for _, i := range structType.omitEmptyFieldsIdx { - f := structType.fields[i] - - // Get field value - var fv reflect.Value - if len(f.idx) == 1 { - fv = v.Field(f.idx[0]) - } else { - // Get embedded field value. No error is expected. - fv, _ = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) { - // Skip null pointer to embedded struct - return reflect.Value{}, nil - }) - if !fv.IsValid() { - continue - } - } - - empty, err := f.ief(fv) - if err != nil { - return false, err - } - if !empty { - return false, nil - } - } - return true, nil -} - -func isEmptyBinaryMarshaler(v reflect.Value) (bool, error) { - m, ok := v.Interface().(encoding.BinaryMarshaler) - if !ok { - pv := reflect.New(v.Type()) - pv.Elem().Set(v) - m = pv.Interface().(encoding.BinaryMarshaler) - } - data, err := m.MarshalBinary() - if err != nil { - return false, err - } - return len(data) == 0, nil -} - -func cannotFitFloat32(f64 float64) bool { - f32 := float32(f64) - return float64(f32) != f64 -} - -// float32NaNFromReflectValue extracts float32 NaN from reflect.Value while preserving NaN's quiet bit. -func float32NaNFromReflectValue(v reflect.Value) float32 { - // Keith Randall's workaround for issue https://github.com/golang/go/issues/36400 - p := reflect.New(v.Type()) - p.Elem().Set(v) - f32 := p.Convert(reflect.TypeOf((*float32)(nil))).Elem().Interface().(float32) - return f32 -} diff --git a/vendor/github.com/fxamacker/cbor/v2/simplevalue.go b/vendor/github.com/fxamacker/cbor/v2/simplevalue.go deleted file mode 100644 index ec77a946..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/simplevalue.go +++ /dev/null @@ -1,17 +0,0 @@ -package cbor - -import "reflect" - -// SimpleValue represents CBOR simple value. -// CBOR simple value is: -// * an extension point like CBOR tag. -// * a subset of CBOR major type 7 that isn't floating-point. -// * "identified by a number between 0 and 255, but distinct from that number itself". -// For example, "a simple value 2 is not equivalent to an integer 2" as a CBOR map key. -// CBOR simple values identified by 20..23 are: "false", "true" , "null", and "undefined". -// Other CBOR simple values are currently unassigned/reserved by IANA. -type SimpleValue uint8 - -var ( - typeSimpleValue = reflect.TypeOf(SimpleValue(0)) -) diff --git a/vendor/github.com/fxamacker/cbor/v2/stream.go b/vendor/github.com/fxamacker/cbor/v2/stream.go deleted file mode 100644 index 02fea43c..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/stream.go +++ /dev/null @@ -1,277 +0,0 @@ -// Copyright (c) Faye Amacker. All rights reserved. -// Licensed under the MIT License. See LICENSE in the project root for license information. - -package cbor - -import ( - "bytes" - "errors" - "io" - "reflect" -) - -// Decoder reads and decodes CBOR values from io.Reader. -type Decoder struct { - r io.Reader - d decoder - buf []byte - off int // next read offset in buf - bytesRead int -} - -// NewDecoder returns a new decoder that reads and decodes from r using -// the default decoding options. -func NewDecoder(r io.Reader) *Decoder { - return defaultDecMode.NewDecoder(r) -} - -// Decode reads CBOR value and decodes it into the value pointed to by v. -func (dec *Decoder) Decode(v interface{}) error { - _, err := dec.readNext() - if err != nil { - // Return validation error or read error. - return err - } - - dec.d.reset(dec.buf[dec.off:]) - err = dec.d.value(v) - - // Increment dec.off even if decoding err is not nil because - // dec.d.off points to the next CBOR data item if current - // CBOR data item is valid but failed to be decoded into v. - // This allows next CBOR data item to be decoded in next - // call to this function. - dec.off += dec.d.off - dec.bytesRead += dec.d.off - - return err -} - -// Skip skips to the next CBOR data item (if there is any), -// otherwise it returns error such as io.EOF, io.UnexpectedEOF, etc. -func (dec *Decoder) Skip() error { - n, err := dec.readNext() - if err != nil { - // Return validation error or read error. - return err - } - - dec.off += n - dec.bytesRead += n - return nil -} - -// NumBytesRead returns the number of bytes read. -func (dec *Decoder) NumBytesRead() int { - return dec.bytesRead -} - -// Buffered returns a reader for data remaining in Decoder's buffer. -// Returned reader is valid until the next call to Decode or Skip. -func (dec *Decoder) Buffered() io.Reader { - return bytes.NewReader(dec.buf[dec.off:]) -} - -// readNext() reads next CBOR data item from Reader to buffer. -// It returns the size of next CBOR data item. -// It also returns validation error or read error if any. -func (dec *Decoder) readNext() (int, error) { - var readErr error - var validErr error - - for { - // Process any unread data in dec.buf. - if dec.off < len(dec.buf) { - dec.d.reset(dec.buf[dec.off:]) - off := dec.off // Save offset before data validation - validErr = dec.d.wellformed(true) - dec.off = off // Restore offset - - if validErr == nil { - return dec.d.off, nil - } - - if validErr != io.ErrUnexpectedEOF { - return 0, validErr - } - - // Process last read error on io.ErrUnexpectedEOF. - if readErr != nil { - if readErr == io.EOF { - // current CBOR data item is incomplete. - return 0, io.ErrUnexpectedEOF - } - return 0, readErr - } - } - - // More data is needed and there was no read error. - var n int - for n == 0 { - n, readErr = dec.read() - if n == 0 && readErr != nil { - // No more data can be read and read error is encountered. - // At this point, validErr is either nil or io.ErrUnexpectedEOF. - if readErr == io.EOF { - if validErr == io.ErrUnexpectedEOF { - // current CBOR data item is incomplete. - return 0, io.ErrUnexpectedEOF - } - } - return 0, readErr - } - } - - // At this point, dec.buf contains new data from last read (n > 0). - } -} - -// read() reads data from Reader to buffer. -// It returns number of bytes read and any read error encountered. -// Postconditions: -// - dec.buf contains previously unread data and new data. -// - dec.off is 0. -func (dec *Decoder) read() (int, error) { - // Grow buf if needed. - const minRead = 512 - if cap(dec.buf)-len(dec.buf)+dec.off < minRead { - oldUnreadBuf := dec.buf[dec.off:] - dec.buf = make([]byte, len(dec.buf)-dec.off, 2*cap(dec.buf)+minRead) - dec.overwriteBuf(oldUnreadBuf) - } - - // Copy unread data over read data and reset off to 0. - if dec.off > 0 { - dec.overwriteBuf(dec.buf[dec.off:]) - } - - // Read from reader and reslice buf. - n, err := dec.r.Read(dec.buf[len(dec.buf):cap(dec.buf)]) - dec.buf = dec.buf[0 : len(dec.buf)+n] - return n, err -} - -func (dec *Decoder) overwriteBuf(newBuf []byte) { - n := copy(dec.buf, newBuf) - dec.buf = dec.buf[:n] - dec.off = 0 -} - -// Encoder writes CBOR values to io.Writer. -type Encoder struct { - w io.Writer - em *encMode - indefTypes []cborType -} - -// NewEncoder returns a new encoder that writes to w using the default encoding options. -func NewEncoder(w io.Writer) *Encoder { - return defaultEncMode.NewEncoder(w) -} - -// Encode writes the CBOR encoding of v. -func (enc *Encoder) Encode(v interface{}) error { - if len(enc.indefTypes) > 0 && v != nil { - indefType := enc.indefTypes[len(enc.indefTypes)-1] - if indefType == cborTypeTextString { - k := reflect.TypeOf(v).Kind() - if k != reflect.String { - return errors.New("cbor: cannot encode item type " + k.String() + " for indefinite-length text string") - } - } else if indefType == cborTypeByteString { - t := reflect.TypeOf(v) - k := t.Kind() - if (k != reflect.Array && k != reflect.Slice) || t.Elem().Kind() != reflect.Uint8 { - return errors.New("cbor: cannot encode item type " + k.String() + " for indefinite-length byte string") - } - } - } - - buf := getEncoderBuffer() - - err := encode(buf, enc.em, reflect.ValueOf(v)) - if err == nil { - _, err = enc.w.Write(buf.Bytes()) - } - - putEncoderBuffer(buf) - return err -} - -// StartIndefiniteByteString starts byte string encoding of indefinite length. -// Subsequent calls of (*Encoder).Encode() encodes definite length byte strings -// ("chunks") as one contiguous string until EndIndefinite is called. -func (enc *Encoder) StartIndefiniteByteString() error { - return enc.startIndefinite(cborTypeByteString) -} - -// StartIndefiniteTextString starts text string encoding of indefinite length. -// Subsequent calls of (*Encoder).Encode() encodes definite length text strings -// ("chunks") as one contiguous string until EndIndefinite is called. -func (enc *Encoder) StartIndefiniteTextString() error { - return enc.startIndefinite(cborTypeTextString) -} - -// StartIndefiniteArray starts array encoding of indefinite length. -// Subsequent calls of (*Encoder).Encode() encodes elements of the array -// until EndIndefinite is called. -func (enc *Encoder) StartIndefiniteArray() error { - return enc.startIndefinite(cborTypeArray) -} - -// StartIndefiniteMap starts array encoding of indefinite length. -// Subsequent calls of (*Encoder).Encode() encodes elements of the map -// until EndIndefinite is called. -func (enc *Encoder) StartIndefiniteMap() error { - return enc.startIndefinite(cborTypeMap) -} - -// EndIndefinite closes last opened indefinite length value. -func (enc *Encoder) EndIndefinite() error { - if len(enc.indefTypes) == 0 { - return errors.New("cbor: cannot encode \"break\" code outside indefinite length values") - } - _, err := enc.w.Write([]byte{0xff}) - if err == nil { - enc.indefTypes = enc.indefTypes[:len(enc.indefTypes)-1] - } - return err -} - -var cborIndefHeader = map[cborType][]byte{ - cborTypeByteString: {0x5f}, - cborTypeTextString: {0x7f}, - cborTypeArray: {0x9f}, - cborTypeMap: {0xbf}, -} - -func (enc *Encoder) startIndefinite(typ cborType) error { - if enc.em.indefLength == IndefLengthForbidden { - return &IndefiniteLengthError{typ} - } - _, err := enc.w.Write(cborIndefHeader[typ]) - if err == nil { - enc.indefTypes = append(enc.indefTypes, typ) - } - return err -} - -// RawMessage is a raw encoded CBOR value. -type RawMessage []byte - -// MarshalCBOR returns m or CBOR nil if m is nil. -func (m RawMessage) MarshalCBOR() ([]byte, error) { - if len(m) == 0 { - return cborNil, nil - } - return m, nil -} - -// UnmarshalCBOR creates a copy of data and saves to *m. -func (m *RawMessage) UnmarshalCBOR(data []byte) error { - if m == nil { - return errors.New("cbor.RawMessage: UnmarshalCBOR on nil pointer") - } - *m = append((*m)[0:0], data...) - return nil -} diff --git a/vendor/github.com/fxamacker/cbor/v2/structfields.go b/vendor/github.com/fxamacker/cbor/v2/structfields.go deleted file mode 100644 index 7c5974f3..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/structfields.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright (c) Faye Amacker. All rights reserved. -// Licensed under the MIT License. See LICENSE in the project root for license information. - -package cbor - -import ( - "reflect" - "sort" - "strings" -) - -type field struct { - name string - nameAsInt int64 // used to decoder to match field name with CBOR int - cborName []byte - idx []int - typ reflect.Type - ef encodeFunc - ief isEmptyFunc - typInfo *typeInfo // used to decoder to reuse type info - tagged bool // used to choose dominant field (at the same level tagged fields dominate untagged fields) - omitEmpty bool // used to skip empty field - keyAsInt bool // used to encode/decode field name as int -} - -type fields []*field - -// indexFieldSorter sorts fields by field idx at each level, breaking ties with idx depth. -type indexFieldSorter struct { - fields fields -} - -func (x *indexFieldSorter) Len() int { - return len(x.fields) -} - -func (x *indexFieldSorter) Swap(i, j int) { - x.fields[i], x.fields[j] = x.fields[j], x.fields[i] -} - -func (x *indexFieldSorter) Less(i, j int) bool { - iIdx, jIdx := x.fields[i].idx, x.fields[j].idx - for k := 0; k < len(iIdx) && k < len(jIdx); k++ { - if iIdx[k] != jIdx[k] { - return iIdx[k] < jIdx[k] - } - } - return len(iIdx) <= len(jIdx) -} - -// nameLevelAndTagFieldSorter sorts fields by field name, idx depth, and presence of tag. -type nameLevelAndTagFieldSorter struct { - fields fields -} - -func (x *nameLevelAndTagFieldSorter) Len() int { - return len(x.fields) -} - -func (x *nameLevelAndTagFieldSorter) Swap(i, j int) { - x.fields[i], x.fields[j] = x.fields[j], x.fields[i] -} - -func (x *nameLevelAndTagFieldSorter) Less(i, j int) bool { - fi, fj := x.fields[i], x.fields[j] - if fi.name != fj.name { - return fi.name < fj.name - } - if len(fi.idx) != len(fj.idx) { - return len(fi.idx) < len(fj.idx) - } - if fi.tagged != fj.tagged { - return fi.tagged - } - return i < j // Field i and j have the same name, depth, and tagged status. Nothing else matters. -} - -// getFields returns visible fields of struct type t following visibility rules for JSON encoding. -func getFields(t reflect.Type) (flds fields, structOptions string) { - // Get special field "_" tag options - if f, ok := t.FieldByName("_"); ok { - tag := f.Tag.Get("cbor") - if tag != "-" { - structOptions = tag - } - } - - // nTypes contains next level anonymous fields' types and indexes - // (there can be multiple fields of the same type at the same level) - flds, nTypes := appendFields(t, nil, nil, nil) - - if len(nTypes) > 0 { - - var cTypes map[reflect.Type][][]int // current level anonymous fields' types and indexes - vTypes := map[reflect.Type]bool{t: true} // visited field types at less nested levels - - for len(nTypes) > 0 { - cTypes, nTypes = nTypes, nil - - for t, idx := range cTypes { - // If there are multiple anonymous fields of the same struct type at the same level, all are ignored. - if len(idx) > 1 { - continue - } - - // Anonymous field of the same type at deeper nested level is ignored. - if vTypes[t] { - continue - } - vTypes[t] = true - - flds, nTypes = appendFields(t, idx[0], flds, nTypes) - } - } - } - - sort.Sort(&nameLevelAndTagFieldSorter{flds}) - - // Keep visible fields. - j := 0 // index of next unique field - for i := 0; i < len(flds); { - name := flds[i].name - if i == len(flds)-1 || // last field - name != flds[i+1].name || // field i has unique field name - len(flds[i].idx) < len(flds[i+1].idx) || // field i is at a less nested level than field i+1 - (flds[i].tagged && !flds[i+1].tagged) { // field i is tagged while field i+1 is not - flds[j] = flds[i] - j++ - } - - // Skip fields with the same field name. - for i++; i < len(flds) && name == flds[i].name; i++ { - } - } - if j != len(flds) { - flds = flds[:j] - } - - // Sort fields by field index - sort.Sort(&indexFieldSorter{flds}) - - return flds, structOptions -} - -// appendFields appends type t's exportable fields to flds and anonymous struct fields to nTypes . -func appendFields(t reflect.Type, idx []int, flds fields, nTypes map[reflect.Type][][]int) (fields, map[reflect.Type][][]int) { - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - - ft := f.Type - for ft.Kind() == reflect.Ptr { - ft = ft.Elem() - } - - if !isFieldExportable(f, ft.Kind()) { - continue - } - - tag := f.Tag.Get("cbor") - if tag == "" { - tag = f.Tag.Get("json") - } - if tag == "-" { - continue - } - - tagged := len(tag) > 0 - - // Parse field tag options - var tagFieldName string - var omitempty, keyasint bool - for j := 0; len(tag) > 0; j++ { - var token string - idx := strings.IndexByte(tag, ',') - if idx == -1 { - token, tag = tag, "" - } else { - token, tag = tag[:idx], tag[idx+1:] - } - if j == 0 { - tagFieldName = token - } else { - switch token { - case "omitempty": - omitempty = true - case "keyasint": - keyasint = true - } - } - } - - fieldName := tagFieldName - if tagFieldName == "" { - fieldName = f.Name - } - - fIdx := make([]int, len(idx)+1) - copy(fIdx, idx) - fIdx[len(fIdx)-1] = i - - if !f.Anonymous || ft.Kind() != reflect.Struct || len(tagFieldName) > 0 { - flds = append(flds, &field{ - name: fieldName, - idx: fIdx, - typ: f.Type, - omitEmpty: omitempty, - keyAsInt: keyasint, - tagged: tagged}) - } else { - if nTypes == nil { - nTypes = make(map[reflect.Type][][]int) - } - nTypes[ft] = append(nTypes[ft], fIdx) - } - } - - return flds, nTypes -} - -// isFieldExportable returns true if f is an exportable (regular or anonymous) field or -// a nonexportable anonymous field of struct type. -// Nonexportable anonymous field of struct type can contain exportable fields. -func isFieldExportable(f reflect.StructField, fk reflect.Kind) bool { - exportable := f.PkgPath == "" - return exportable || (f.Anonymous && fk == reflect.Struct) -} - -type embeddedFieldNullPtrFunc func(reflect.Value) (reflect.Value, error) - -// getFieldValue returns field value of struct v by index. When encountering null pointer -// to anonymous (embedded) struct field, f is called with the last traversed field value. -func getFieldValue(v reflect.Value, idx []int, f embeddedFieldNullPtrFunc) (fv reflect.Value, err error) { - fv = v - for i, n := range idx { - fv = fv.Field(n) - - if i < len(idx)-1 { - if fv.Kind() == reflect.Ptr && fv.Type().Elem().Kind() == reflect.Struct { - if fv.IsNil() { - // Null pointer to embedded struct field - fv, err = f(fv) - if err != nil || !fv.IsValid() { - return fv, err - } - } - fv = fv.Elem() - } - } - } - return fv, nil -} diff --git a/vendor/github.com/fxamacker/cbor/v2/tag.go b/vendor/github.com/fxamacker/cbor/v2/tag.go deleted file mode 100644 index 5205aa66..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/tag.go +++ /dev/null @@ -1,297 +0,0 @@ -package cbor - -import ( - "errors" - "fmt" - "reflect" - "sync" -) - -// Tag represents CBOR tag data, including tag number and unmarshaled tag content. -type Tag struct { - Number uint64 - Content interface{} -} - -// RawTag represents CBOR tag data, including tag number and raw tag content. -// RawTag implements Unmarshaler and Marshaler interfaces. -type RawTag struct { - Number uint64 - Content RawMessage -} - -// UnmarshalCBOR sets *t with tag number and raw tag content copied from data. -func (t *RawTag) UnmarshalCBOR(data []byte) error { - if t == nil { - return errors.New("cbor.RawTag: UnmarshalCBOR on nil pointer") - } - - // Decoding CBOR null and undefined to cbor.RawTag is no-op. - if len(data) == 1 && (data[0] == 0xf6 || data[0] == 0xf7) { - return nil - } - - d := decoder{data: data, dm: defaultDecMode} - - // Unmarshal tag number. - typ, _, num := d.getHead() - if typ != cborTypeTag { - return &UnmarshalTypeError{CBORType: typ.String(), GoType: typeRawTag.String()} - } - t.Number = num - - // Unmarshal tag content. - c := d.data[d.off:] - t.Content = make([]byte, len(c)) - copy(t.Content, c) - return nil -} - -// MarshalCBOR returns CBOR encoding of t. -func (t RawTag) MarshalCBOR() ([]byte, error) { - if t.Number == 0 && len(t.Content) == 0 { - // Marshal uninitialized cbor.RawTag - b := make([]byte, len(cborNil)) - copy(b, cborNil) - return b, nil - } - - e := getEncoderBuffer() - - encodeHead(e, byte(cborTypeTag), t.Number) - - content := t.Content - if len(content) == 0 { - content = cborNil - } - - buf := make([]byte, len(e.Bytes())+len(content)) - n := copy(buf, e.Bytes()) - copy(buf[n:], content) - - putEncoderBuffer(e) - return buf, nil -} - -// DecTagMode specifies how decoder handles tag number. -type DecTagMode int - -const ( - // DecTagIgnored makes decoder ignore tag number (skips if present). - DecTagIgnored DecTagMode = iota - - // DecTagOptional makes decoder verify tag number if it's present. - DecTagOptional - - // DecTagRequired makes decoder verify tag number and tag number must be present. - DecTagRequired - - maxDecTagMode -) - -func (dtm DecTagMode) valid() bool { - return dtm < maxDecTagMode -} - -// EncTagMode specifies how encoder handles tag number. -type EncTagMode int - -const ( - // EncTagNone makes encoder not encode tag number. - EncTagNone EncTagMode = iota - - // EncTagRequired makes encoder encode tag number. - EncTagRequired - - maxEncTagMode -) - -func (etm EncTagMode) valid() bool { - return etm < maxEncTagMode -} - -// TagOptions specifies how encoder and decoder handle tag number. -type TagOptions struct { - DecTag DecTagMode - EncTag EncTagMode -} - -// TagSet is an interface to add and remove tag info. It is used by EncMode and DecMode -// to provide CBOR tag support. -type TagSet interface { - // Add adds given tag number(s), content type, and tag options to TagSet. - Add(opts TagOptions, contentType reflect.Type, num uint64, nestedNum ...uint64) error - - // Remove removes given tag content type from TagSet. - Remove(contentType reflect.Type) - - tagProvider -} - -type tagProvider interface { - getTagItemFromType(t reflect.Type) *tagItem - getTypeFromTagNum(num []uint64) reflect.Type -} - -type tagItem struct { - num []uint64 - cborTagNum []byte - contentType reflect.Type - opts TagOptions -} - -func (t *tagItem) equalTagNum(num []uint64) bool { - // Fast path to compare 1 tag number - if len(t.num) == 1 && len(num) == 1 && t.num[0] == num[0] { - return true - } - - if len(t.num) != len(num) { - return false - } - - for i := 0; i < len(t.num); i++ { - if t.num[i] != num[i] { - return false - } - } - - return true -} - -type ( - tagSet map[reflect.Type]*tagItem - - syncTagSet struct { - sync.RWMutex - t tagSet - } -) - -func (t tagSet) getTagItemFromType(typ reflect.Type) *tagItem { - return t[typ] -} - -func (t tagSet) getTypeFromTagNum(num []uint64) reflect.Type { - for typ, tag := range t { - if tag.equalTagNum(num) { - return typ - } - } - return nil -} - -// NewTagSet returns TagSet (safe for concurrency). -func NewTagSet() TagSet { - return &syncTagSet{t: make(map[reflect.Type]*tagItem)} -} - -// Add adds given tag number(s), content type, and tag options to TagSet. -func (t *syncTagSet) Add(opts TagOptions, contentType reflect.Type, num uint64, nestedNum ...uint64) error { - if contentType == nil { - return errors.New("cbor: cannot add nil content type to TagSet") - } - for contentType.Kind() == reflect.Ptr { - contentType = contentType.Elem() - } - tag, err := newTagItem(opts, contentType, num, nestedNum...) - if err != nil { - return err - } - t.Lock() - defer t.Unlock() - for typ, ti := range t.t { - if typ == contentType { - return errors.New("cbor: content type " + contentType.String() + " already exists in TagSet") - } - if ti.equalTagNum(tag.num) { - return fmt.Errorf("cbor: tag number %v already exists in TagSet", tag.num) - } - } - t.t[contentType] = tag - return nil -} - -// Remove removes given tag content type from TagSet. -func (t *syncTagSet) Remove(contentType reflect.Type) { - for contentType.Kind() == reflect.Ptr { - contentType = contentType.Elem() - } - t.Lock() - delete(t.t, contentType) - t.Unlock() -} - -func (t *syncTagSet) getTagItemFromType(typ reflect.Type) *tagItem { - t.RLock() - ti := t.t[typ] - t.RUnlock() - return ti -} - -func (t *syncTagSet) getTypeFromTagNum(num []uint64) reflect.Type { - t.RLock() - rt := t.t.getTypeFromTagNum(num) - t.RUnlock() - return rt -} - -func newTagItem(opts TagOptions, contentType reflect.Type, num uint64, nestedNum ...uint64) (*tagItem, error) { - if opts.DecTag == DecTagIgnored && opts.EncTag == EncTagNone { - return nil, errors.New("cbor: cannot add tag with DecTagIgnored and EncTagNone options to TagSet") - } - if contentType.PkgPath() == "" || contentType.Kind() == reflect.Interface { - return nil, errors.New("cbor: can only add named types to TagSet, got " + contentType.String()) - } - if contentType == typeTime { - return nil, errors.New("cbor: cannot add time.Time to TagSet, use EncOptions.TimeTag and DecOptions.TimeTag instead") - } - if contentType == typeBigInt { - return nil, errors.New("cbor: cannot add big.Int to TagSet, it's built-in and supported automatically") - } - if contentType == typeTag { - return nil, errors.New("cbor: cannot add cbor.Tag to TagSet") - } - if contentType == typeRawTag { - return nil, errors.New("cbor: cannot add cbor.RawTag to TagSet") - } - if num == 0 || num == 1 { - return nil, errors.New("cbor: cannot add tag number 0 or 1 to TagSet, use EncOptions.TimeTag and DecOptions.TimeTag instead") - } - if num == 2 || num == 3 { - return nil, errors.New("cbor: cannot add tag number 2 or 3 to TagSet, it's built-in and supported automatically") - } - if num == selfDescribedCBORTagNum { - return nil, errors.New("cbor: cannot add tag number 55799 to TagSet, it's built-in and ignored automatically") - } - - te := tagItem{num: []uint64{num}, opts: opts, contentType: contentType} - te.num = append(te.num, nestedNum...) - - // Cache encoded tag numbers - e := getEncoderBuffer() - for _, n := range te.num { - encodeHead(e, byte(cborTypeTag), n) - } - te.cborTagNum = make([]byte, e.Len()) - copy(te.cborTagNum, e.Bytes()) - putEncoderBuffer(e) - - return &te, nil -} - -var ( - typeTag = reflect.TypeOf(Tag{}) - typeRawTag = reflect.TypeOf(RawTag{}) -) - -// WrongTagError describes mismatch between CBOR tag and registered tag. -type WrongTagError struct { - RegisteredType reflect.Type - RegisteredTagNum []uint64 - TagNum []uint64 -} - -func (e *WrongTagError) Error() string { - return fmt.Sprintf("cbor: wrong tag number for %s, got %v, expected %v", e.RegisteredType.String(), e.TagNum, e.RegisteredTagNum) -} diff --git a/vendor/github.com/fxamacker/cbor/v2/valid.go b/vendor/github.com/fxamacker/cbor/v2/valid.go deleted file mode 100644 index a5213d06..00000000 --- a/vendor/github.com/fxamacker/cbor/v2/valid.go +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright (c) Faye Amacker. All rights reserved. -// Licensed under the MIT License. See LICENSE in the project root for license information. - -package cbor - -import ( - "encoding/binary" - "errors" - "io" - "strconv" -) - -// SyntaxError is a description of a CBOR syntax error. -type SyntaxError struct { - msg string -} - -func (e *SyntaxError) Error() string { return e.msg } - -// SemanticError is a description of a CBOR semantic error. -type SemanticError struct { - msg string -} - -func (e *SemanticError) Error() string { return e.msg } - -// MaxNestedLevelError indicates exceeded max nested level of any combination of CBOR arrays/maps/tags. -type MaxNestedLevelError struct { - maxNestedLevels int -} - -func (e *MaxNestedLevelError) Error() string { - return "cbor: exceeded max nested level " + strconv.Itoa(e.maxNestedLevels) -} - -// MaxArrayElementsError indicates exceeded max number of elements for CBOR arrays. -type MaxArrayElementsError struct { - maxArrayElements int -} - -func (e *MaxArrayElementsError) Error() string { - return "cbor: exceeded max number of elements " + strconv.Itoa(e.maxArrayElements) + " for CBOR array" -} - -// MaxMapPairsError indicates exceeded max number of key-value pairs for CBOR maps. -type MaxMapPairsError struct { - maxMapPairs int -} - -func (e *MaxMapPairsError) Error() string { - return "cbor: exceeded max number of key-value pairs " + strconv.Itoa(e.maxMapPairs) + " for CBOR map" -} - -// IndefiniteLengthError indicates found disallowed indefinite length items. -type IndefiniteLengthError struct { - t cborType -} - -func (e *IndefiniteLengthError) Error() string { - return "cbor: indefinite-length " + e.t.String() + " isn't allowed" -} - -// TagsMdError indicates found disallowed CBOR tags. -type TagsMdError struct { -} - -func (e *TagsMdError) Error() string { - return "cbor: CBOR tag isn't allowed" -} - -// ExtraneousDataError indicates found extraneous data following well-formed CBOR data item. -type ExtraneousDataError struct { - numOfBytes int // number of bytes of extraneous data - index int // location of extraneous data -} - -func (e *ExtraneousDataError) Error() string { - return "cbor: " + strconv.Itoa(e.numOfBytes) + " bytes of extraneous data starting at index " + strconv.Itoa(e.index) -} - -// wellformed checks whether the CBOR data item is well-formed. -// allowExtraData indicates if extraneous data is allowed after the CBOR data item. -// - use allowExtraData = true when using Decoder.Decode() -// - use allowExtraData = false when using Unmarshal() -func (d *decoder) wellformed(allowExtraData bool) error { - if len(d.data) == d.off { - return io.EOF - } - _, err := d.wellformedInternal(0) - if err == nil { - if !allowExtraData && d.off != len(d.data) { - err = &ExtraneousDataError{len(d.data) - d.off, d.off} - } - } - return err -} - -// wellformedInternal checks data's well-formedness and returns max depth and error. -func (d *decoder) wellformedInternal(depth int) (int, error) { - t, ai, val, err := d.wellformedHead() - if err != nil { - return 0, err - } - - switch t { - case cborTypeByteString, cborTypeTextString: - if ai == 31 { - if d.dm.indefLength == IndefLengthForbidden { - return 0, &IndefiniteLengthError{t} - } - return d.wellformedIndefiniteString(t, depth) - } - valInt := int(val) - if valInt < 0 { - // Detect integer overflow - return 0, errors.New("cbor: " + t.String() + " length " + strconv.FormatUint(val, 10) + " is too large, causing integer overflow") - } - if len(d.data)-d.off < valInt { // valInt+off may overflow integer - return 0, io.ErrUnexpectedEOF - } - d.off += valInt - case cborTypeArray, cborTypeMap: - depth++ - if depth > d.dm.maxNestedLevels { - return 0, &MaxNestedLevelError{d.dm.maxNestedLevels} - } - - if ai == 31 { - if d.dm.indefLength == IndefLengthForbidden { - return 0, &IndefiniteLengthError{t} - } - return d.wellformedIndefiniteArrayOrMap(t, depth) - } - - valInt := int(val) - if valInt < 0 { - // Detect integer overflow - return 0, errors.New("cbor: " + t.String() + " length " + strconv.FormatUint(val, 10) + " is too large, it would cause integer overflow") - } - - if t == cborTypeArray { - if valInt > d.dm.maxArrayElements { - return 0, &MaxArrayElementsError{d.dm.maxArrayElements} - } - } else { - if valInt > d.dm.maxMapPairs { - return 0, &MaxMapPairsError{d.dm.maxMapPairs} - } - } - - count := 1 - if t == cborTypeMap { - count = 2 - } - maxDepth := depth - for j := 0; j < count; j++ { - for i := 0; i < valInt; i++ { - var dpt int - if dpt, err = d.wellformedInternal(depth); err != nil { - return 0, err - } - if dpt > maxDepth { - maxDepth = dpt // Save max depth - } - } - } - depth = maxDepth - case cborTypeTag: - if d.dm.tagsMd == TagsForbidden { - return 0, &TagsMdError{} - } - - // Scan nested tag numbers to avoid recursion. - for { - if len(d.data) == d.off { // Tag number must be followed by tag content. - return 0, io.ErrUnexpectedEOF - } - if cborType(d.data[d.off]&0xe0) != cborTypeTag { - break - } - if _, _, _, err = d.wellformedHead(); err != nil { - return 0, err - } - depth++ - if depth > d.dm.maxNestedLevels { - return 0, &MaxNestedLevelError{d.dm.maxNestedLevels} - } - } - // Check tag content. - return d.wellformedInternal(depth) - } - return depth, nil -} - -// wellformedIndefiniteString checks indefinite length byte/text string's well-formedness and returns max depth and error. -func (d *decoder) wellformedIndefiniteString(t cborType, depth int) (int, error) { - var err error - for { - if len(d.data) == d.off { - return 0, io.ErrUnexpectedEOF - } - if d.data[d.off] == 0xff { - d.off++ - break - } - // Peek ahead to get next type and indefinite length status. - nt := cborType(d.data[d.off] & 0xe0) - if t != nt { - return 0, &SyntaxError{"cbor: wrong element type " + nt.String() + " for indefinite-length " + t.String()} - } - if (d.data[d.off] & 0x1f) == 31 { - return 0, &SyntaxError{"cbor: indefinite-length " + t.String() + " chunk is not definite-length"} - } - if depth, err = d.wellformedInternal(depth); err != nil { - return 0, err - } - } - return depth, nil -} - -// wellformedIndefiniteArrayOrMap checks indefinite length array/map's well-formedness and returns max depth and error. -func (d *decoder) wellformedIndefiniteArrayOrMap(t cborType, depth int) (int, error) { - var err error - maxDepth := depth - i := 0 - for { - if len(d.data) == d.off { - return 0, io.ErrUnexpectedEOF - } - if d.data[d.off] == 0xff { - d.off++ - break - } - var dpt int - if dpt, err = d.wellformedInternal(depth); err != nil { - return 0, err - } - if dpt > maxDepth { - maxDepth = dpt - } - i++ - if t == cborTypeArray { - if i > d.dm.maxArrayElements { - return 0, &MaxArrayElementsError{d.dm.maxArrayElements} - } - } else { - if i%2 == 0 && i/2 > d.dm.maxMapPairs { - return 0, &MaxMapPairsError{d.dm.maxMapPairs} - } - } - } - if t == cborTypeMap && i%2 == 1 { - return 0, &SyntaxError{"cbor: unexpected \"break\" code"} - } - return maxDepth, nil -} - -func (d *decoder) wellformedHead() (t cborType, ai byte, val uint64, err error) { - dataLen := len(d.data) - d.off - if dataLen == 0 { - return 0, 0, 0, io.ErrUnexpectedEOF - } - - t = cborType(d.data[d.off] & 0xe0) - ai = d.data[d.off] & 0x1f - val = uint64(ai) - d.off++ - - if ai < 24 { - return t, ai, val, nil - } - if ai == 24 { - if dataLen < 2 { - return 0, 0, 0, io.ErrUnexpectedEOF - } - val = uint64(d.data[d.off]) - d.off++ - if t == cborTypePrimitives && val < 32 { - return 0, 0, 0, &SyntaxError{"cbor: invalid simple value " + strconv.Itoa(int(val)) + " for type " + t.String()} - } - return t, ai, val, nil - } - if ai == 25 { - if dataLen < 3 { - return 0, 0, 0, io.ErrUnexpectedEOF - } - val = uint64(binary.BigEndian.Uint16(d.data[d.off : d.off+2])) - d.off += 2 - return t, ai, val, nil - } - if ai == 26 { - if dataLen < 5 { - return 0, 0, 0, io.ErrUnexpectedEOF - } - val = uint64(binary.BigEndian.Uint32(d.data[d.off : d.off+4])) - d.off += 4 - return t, ai, val, nil - } - if ai == 27 { - if dataLen < 9 { - return 0, 0, 0, io.ErrUnexpectedEOF - } - val = binary.BigEndian.Uint64(d.data[d.off : d.off+8]) - d.off += 8 - return t, ai, val, nil - } - if ai == 31 { - switch t { - case cborTypePositiveInt, cborTypeNegativeInt, cborTypeTag: - return 0, 0, 0, &SyntaxError{"cbor: invalid additional information " + strconv.Itoa(int(ai)) + " for type " + t.String()} - case cborTypePrimitives: // 0xff (break code) should not be outside wellformedIndefinite(). - return 0, 0, 0, &SyntaxError{"cbor: unexpected \"break\" code"} - } - return t, ai, val, nil - } - // ai == 28, 29, 30 - return 0, 0, 0, &SyntaxError{"cbor: invalid additional information " + strconv.Itoa(int(ai)) + " for type " + t.String()} -} diff --git a/vendor/github.com/go-chi/chi/v5/.gitignore b/vendor/github.com/go-chi/chi/v5/.gitignore deleted file mode 100644 index ba22c99a..00000000 --- a/vendor/github.com/go-chi/chi/v5/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.idea -*.sw? -.vscode diff --git a/vendor/github.com/go-chi/chi/v5/CHANGELOG.md b/vendor/github.com/go-chi/chi/v5/CHANGELOG.md deleted file mode 100644 index f6eb7e6e..00000000 --- a/vendor/github.com/go-chi/chi/v5/CHANGELOG.md +++ /dev/null @@ -1,331 +0,0 @@ -# Changelog - -## v5.0.10 (2023-07-13) - -- Fixed small edge case in tests of v5.0.9 for older Go versions -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.8...v5.0.10 - - -## v5.0.9 (2023-07-13) - -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.8...v5.0.9 - - -## v5.0.8 (2022-12-07) - -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.7...v5.0.8 - - -## v5.0.7 (2021-11-18) - -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.6...v5.0.7 - - -## v5.0.6 (2021-11-15) - -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.5...v5.0.6 - - -## v5.0.5 (2021-10-27) - -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.4...v5.0.5 - - -## v5.0.4 (2021-08-29) - -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.3...v5.0.4 - - -## v5.0.3 (2021-04-29) - -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.2...v5.0.3 - - -## v5.0.2 (2021-03-25) - -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.1...v5.0.2 - - -## v5.0.1 (2021-03-10) - -- Small improvements -- History of changes: see https://github.com/go-chi/chi/compare/v5.0.0...v5.0.1 - - -## v5.0.0 (2021-02-27) - -- chi v5, `github.com/go-chi/chi/v5` introduces the adoption of Go's SIV to adhere to the current state-of-the-tools in Go. -- chi v1.5.x did not work out as planned, as the Go tooling is too powerful and chi's adoption is too wide. - The most responsible thing to do for everyone's benefit is to just release v5 with SIV, so I present to you all, - chi v5 at `github.com/go-chi/chi/v5`. I hope someday the developer experience and ergonomics I've been seeking - will still come to fruition in some form, see https://github.com/golang/go/issues/44550 -- History of changes: see https://github.com/go-chi/chi/compare/v1.5.4...v5.0.0 - - -## v1.5.4 (2021-02-27) - -- Undo prior retraction in v1.5.3 as we prepare for v5.0.0 release -- History of changes: see https://github.com/go-chi/chi/compare/v1.5.3...v1.5.4 - - -## v1.5.3 (2021-02-21) - -- Update go.mod to go 1.16 with new retract directive marking all versions without prior go.mod support -- History of changes: see https://github.com/go-chi/chi/compare/v1.5.2...v1.5.3 - - -## v1.5.2 (2021-02-10) - -- Reverting allocation optimization as a precaution as go test -race fails. -- Minor improvements, see history below -- History of changes: see https://github.com/go-chi/chi/compare/v1.5.1...v1.5.2 - - -## v1.5.1 (2020-12-06) - -- Performance improvement: removing 1 allocation by foregoing context.WithValue, thank you @bouk for - your contribution (https://github.com/go-chi/chi/pull/555). Note: new benchmarks posted in README. -- `middleware.CleanPath`: new middleware that clean's request path of double slashes -- deprecate & remove `chi.ServerBaseContext` in favour of stdlib `http.Server#BaseContext` -- plus other tiny improvements, see full commit history below -- History of changes: see https://github.com/go-chi/chi/compare/v4.1.2...v1.5.1 - - -## v1.5.0 (2020-11-12) - now with go.mod support - -`chi` dates back to 2016 with it's original implementation as one of the first routers to adopt the newly introduced -context.Context api to the stdlib -- set out to design a router that is faster, more modular and simpler than anything -else out there -- while not introducing any custom handler types or dependencies. Today, `chi` still has zero dependencies, -and in many ways is future proofed from changes, given it's minimal nature. Between versions, chi's iterations have been very -incremental, with the architecture and api being the same today as it was originally designed in 2016. For this reason it -makes chi a pretty easy project to maintain, as well thanks to the many amazing community contributions over the years -to who all help make chi better (total of 86 contributors to date -- thanks all!). - -Chi has been a labour of love, art and engineering, with the goals to offer beautiful ergonomics, flexibility, performance -and simplicity when building HTTP services with Go. I've strived to keep the router very minimal in surface area / code size, -and always improving the code wherever possible -- and as of today the `chi` package is just 1082 lines of code (not counting -middlewares, which are all optional). As well, I don't have the exact metrics, but from my analysis and email exchanges from -companies and developers, chi is used by thousands of projects around the world -- thank you all as there is no better form of -joy for me than to have art I had started be helpful and enjoyed by others. And of course I use chi in all of my own projects too :) - -For me, the aesthetics of chi's code and usage are very important. With the introduction of Go's module support -(which I'm a big fan of), chi's past versioning scheme choice to v2, v3 and v4 would mean I'd require the import path -of "github.com/go-chi/chi/v4", leading to the lengthy discussion at https://github.com/go-chi/chi/issues/462. -Haha, to some, you may be scratching your head why I've spent > 1 year stalling to adopt "/vXX" convention in the import -path -- which isn't horrible in general -- but for chi, I'm unable to accept it as I strive for perfection in it's API design, -aesthetics and simplicity. It just doesn't feel good to me given chi's simple nature -- I do not foresee a "v5" or "v6", -and upgrading between versions in the future will also be just incremental. - -I do understand versioning is a part of the API design as well, which is why the solution for a while has been to "do nothing", -as Go supports both old and new import paths with/out go.mod. However, now that Go module support has had time to iron out kinks and -is adopted everywhere, it's time for chi to get with the times. Luckily, I've discovered a path forward that will make me happy, -while also not breaking anyone's app who adopted a prior versioning from tags in v2/v3/v4. I've made an experimental release of -v1.5.0 with go.mod silently, and tested it with new and old projects, to ensure the developer experience is preserved, and it's -largely unnoticed. Fortunately, Go's toolchain will check the tags of a repo and consider the "latest" tag the one with go.mod. -However, you can still request a specific older tag such as v4.1.2, and everything will "just work". But new users can just -`go get github.com/go-chi/chi` or `go get github.com/go-chi/chi@latest` and they will get the latest version which contains -go.mod support, which is v1.5.0+. `chi` will not change very much over the years, just like it hasn't changed much from 4 years ago. -Therefore, we will stay on v1.x from here on, starting from v1.5.0. Any breaking changes will bump a "minor" release and -backwards-compatible improvements/fixes will bump a "tiny" release. - -For existing projects who want to upgrade to the latest go.mod version, run: `go get -u github.com/go-chi/chi@v1.5.0`, -which will get you on the go.mod version line (as Go's mod cache may still remember v4.x). Brand new systems can run -`go get -u github.com/go-chi/chi` or `go get -u github.com/go-chi/chi@latest` to install chi, which will install v1.5.0+ -built with go.mod support. - -My apologies to the developers who will disagree with the decisions above, but, hope you'll try it and see it's a very -minor request which is backwards compatible and won't break your existing installations. - -Cheers all, happy coding! - - ---- - - -## v4.1.2 (2020-06-02) - -- fix that handles MethodNotAllowed with path variables, thank you @caseyhadden for your contribution -- fix to replace nested wildcards correctly in RoutePattern, thank you @@unmultimedio for your contribution -- History of changes: see https://github.com/go-chi/chi/compare/v4.1.1...v4.1.2 - - -## v4.1.1 (2020-04-16) - -- fix for issue https://github.com/go-chi/chi/issues/411 which allows for overlapping regexp - route to the correct handler through a recursive tree search, thanks to @Jahaja for the PR/fix! -- new middleware.RouteHeaders as a simple router for request headers with wildcard support -- History of changes: see https://github.com/go-chi/chi/compare/v4.1.0...v4.1.1 - - -## v4.1.0 (2020-04-1) - -- middleware.LogEntry: Write method on interface now passes the response header - and an extra interface type useful for custom logger implementations. -- middleware.WrapResponseWriter: minor fix -- middleware.Recoverer: a bit prettier -- History of changes: see https://github.com/go-chi/chi/compare/v4.0.4...v4.1.0 - -## v4.0.4 (2020-03-24) - -- middleware.Recoverer: new pretty stack trace printing (https://github.com/go-chi/chi/pull/496) -- a few minor improvements and fixes -- History of changes: see https://github.com/go-chi/chi/compare/v4.0.3...v4.0.4 - - -## v4.0.3 (2020-01-09) - -- core: fix regexp routing to include default value when param is not matched -- middleware: rewrite of middleware.Compress -- middleware: suppress http.ErrAbortHandler in middleware.Recoverer -- History of changes: see https://github.com/go-chi/chi/compare/v4.0.2...v4.0.3 - - -## v4.0.2 (2019-02-26) - -- Minor fixes -- History of changes: see https://github.com/go-chi/chi/compare/v4.0.1...v4.0.2 - - -## v4.0.1 (2019-01-21) - -- Fixes issue with compress middleware: #382 #385 -- History of changes: see https://github.com/go-chi/chi/compare/v4.0.0...v4.0.1 - - -## v4.0.0 (2019-01-10) - -- chi v4 requires Go 1.10.3+ (or Go 1.9.7+) - we have deprecated support for Go 1.7 and 1.8 -- router: respond with 404 on router with no routes (#362) -- router: additional check to ensure wildcard is at the end of a url pattern (#333) -- middleware: deprecate use of http.CloseNotifier (#347) -- middleware: fix RedirectSlashes to include query params on redirect (#334) -- History of changes: see https://github.com/go-chi/chi/compare/v3.3.4...v4.0.0 - - -## v3.3.4 (2019-01-07) - -- Minor middleware improvements. No changes to core library/router. Moving v3 into its -- own branch as a version of chi for Go 1.7, 1.8, 1.9, 1.10, 1.11 -- History of changes: see https://github.com/go-chi/chi/compare/v3.3.3...v3.3.4 - - -## v3.3.3 (2018-08-27) - -- Minor release -- See https://github.com/go-chi/chi/compare/v3.3.2...v3.3.3 - - -## v3.3.2 (2017-12-22) - -- Support to route trailing slashes on mounted sub-routers (#281) -- middleware: new `ContentCharset` to check matching charsets. Thank you - @csucu for your community contribution! - - -## v3.3.1 (2017-11-20) - -- middleware: new `AllowContentType` handler for explicit whitelist of accepted request Content-Types -- middleware: new `SetHeader` handler for short-hand middleware to set a response header key/value -- Minor bug fixes - - -## v3.3.0 (2017-10-10) - -- New chi.RegisterMethod(method) to add support for custom HTTP methods, see _examples/custom-method for usage -- Deprecated LINK and UNLINK methods from the default list, please use `chi.RegisterMethod("LINK")` and `chi.RegisterMethod("UNLINK")` in an `init()` function - - -## v3.2.1 (2017-08-31) - -- Add new `Match(rctx *Context, method, path string) bool` method to `Routes` interface - and `Mux`. Match searches the mux's routing tree for a handler that matches the method/path -- Add new `RouteMethod` to `*Context` -- Add new `Routes` pointer to `*Context` -- Add new `middleware.GetHead` to route missing HEAD requests to GET handler -- Updated benchmarks (see README) - - -## v3.1.5 (2017-08-02) - -- Setup golint and go vet for the project -- As per golint, we've redefined `func ServerBaseContext(h http.Handler, baseCtx context.Context) http.Handler` - to `func ServerBaseContext(baseCtx context.Context, h http.Handler) http.Handler` - - -## v3.1.0 (2017-07-10) - -- Fix a few minor issues after v3 release -- Move `docgen` sub-pkg to https://github.com/go-chi/docgen -- Move `render` sub-pkg to https://github.com/go-chi/render -- Add new `URLFormat` handler to chi/middleware sub-pkg to make working with url mime - suffixes easier, ie. parsing `/articles/1.json` and `/articles/1.xml`. See comments in - https://github.com/go-chi/chi/blob/master/middleware/url_format.go for example usage. - - -## v3.0.0 (2017-06-21) - -- Major update to chi library with many exciting updates, but also some *breaking changes* -- URL parameter syntax changed from `/:id` to `/{id}` for even more flexible routing, such as - `/articles/{month}-{day}-{year}-{slug}`, `/articles/{id}`, and `/articles/{id}.{ext}` on the - same router -- Support for regexp for routing patterns, in the form of `/{paramKey:regExp}` for example: - `r.Get("/articles/{name:[a-z]+}", h)` and `chi.URLParam(r, "name")` -- Add `Method` and `MethodFunc` to `chi.Router` to allow routing definitions such as - `r.Method("GET", "/", h)` which provides a cleaner interface for custom handlers like - in `_examples/custom-handler` -- Deprecating `mux#FileServer` helper function. Instead, we encourage users to create their - own using file handler with the stdlib, see `_examples/fileserver` for an example -- Add support for LINK/UNLINK http methods via `r.Method()` and `r.MethodFunc()` -- Moved the chi project to its own organization, to allow chi-related community packages to - be easily discovered and supported, at: https://github.com/go-chi -- *NOTE:* please update your import paths to `"github.com/go-chi/chi"` -- *NOTE:* chi v2 is still available at https://github.com/go-chi/chi/tree/v2 - - -## v2.1.0 (2017-03-30) - -- Minor improvements and update to the chi core library -- Introduced a brand new `chi/render` sub-package to complete the story of building - APIs to offer a pattern for managing well-defined request / response payloads. Please - check out the updated `_examples/rest` example for how it works. -- Added `MethodNotAllowed(h http.HandlerFunc)` to chi.Router interface - - -## v2.0.0 (2017-01-06) - -- After many months of v2 being in an RC state with many companies and users running it in - production, the inclusion of some improvements to the middlewares, we are very pleased to - announce v2.0.0 of chi. - - -## v2.0.0-rc1 (2016-07-26) - -- Huge update! chi v2 is a large refactor targeting Go 1.7+. As of Go 1.7, the popular - community `"net/context"` package has been included in the standard library as `"context"` and - utilized by `"net/http"` and `http.Request` to managing deadlines, cancelation signals and other - request-scoped values. We're very excited about the new context addition and are proud to - introduce chi v2, a minimal and powerful routing package for building large HTTP services, - with zero external dependencies. Chi focuses on idiomatic design and encourages the use of - stdlib HTTP handlers and middlwares. -- chi v2 deprecates its `chi.Handler` interface and requires `http.Handler` or `http.HandlerFunc` -- chi v2 stores URL routing parameters and patterns in the standard request context: `r.Context()` -- chi v2 lower-level routing context is accessible by `chi.RouteContext(r.Context()) *chi.Context`, - which provides direct access to URL routing parameters, the routing path and the matching - routing patterns. -- Users upgrading from chi v1 to v2, need to: - 1. Update the old chi.Handler signature, `func(ctx context.Context, w http.ResponseWriter, r *http.Request)` to - the standard http.Handler: `func(w http.ResponseWriter, r *http.Request)` - 2. Use `chi.URLParam(r *http.Request, paramKey string) string` - or `URLParamFromCtx(ctx context.Context, paramKey string) string` to access a url parameter value - - -## v1.0.0 (2016-07-01) - -- Released chi v1 stable https://github.com/go-chi/chi/tree/v1.0.0 for Go 1.6 and older. - - -## v0.9.0 (2016-03-31) - -- Reuse context objects via sync.Pool for zero-allocation routing [#33](https://github.com/go-chi/chi/pull/33) -- BREAKING NOTE: due to subtle API changes, previously `chi.URLParams(ctx)["id"]` used to access url parameters - has changed to: `chi.URLParam(ctx, "id")` diff --git a/vendor/github.com/go-chi/chi/v5/CONTRIBUTING.md b/vendor/github.com/go-chi/chi/v5/CONTRIBUTING.md deleted file mode 100644 index c0ac2dfe..00000000 --- a/vendor/github.com/go-chi/chi/v5/CONTRIBUTING.md +++ /dev/null @@ -1,31 +0,0 @@ -# Contributing - -## Prerequisites - -1. [Install Go][go-install]. -2. Download the sources and switch the working directory: - - ```bash - go get -u -d github.com/go-chi/chi - cd $GOPATH/src/github.com/go-chi/chi - ``` - -## Submitting a Pull Request - -A typical workflow is: - -1. [Fork the repository.][fork] [This tip maybe also helpful.][go-fork-tip] -2. [Create a topic branch.][branch] -3. Add tests for your change. -4. Run `go test`. If your tests pass, return to the step 3. -5. Implement the change and ensure the steps from the previous step pass. -6. Run `goimports -w .`, to ensure the new code conforms to Go formatting guideline. -7. [Add, commit and push your changes.][git-help] -8. [Submit a pull request.][pull-req] - -[go-install]: https://golang.org/doc/install -[go-fork-tip]: http://blog.campoy.cat/2014/03/github-and-go-forking-pull-requests-and.html -[fork]: https://help.github.com/articles/fork-a-repo -[branch]: http://learn.github.com/p/branching.html -[git-help]: https://guides.github.com -[pull-req]: https://help.github.com/articles/using-pull-requests diff --git a/vendor/github.com/go-chi/chi/v5/LICENSE b/vendor/github.com/go-chi/chi/v5/LICENSE deleted file mode 100644 index d99f02ff..00000000 --- a/vendor/github.com/go-chi/chi/v5/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2015-present Peter Kieltyka (https://github.com/pkieltyka), Google Inc. - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/go-chi/chi/v5/Makefile b/vendor/github.com/go-chi/chi/v5/Makefile deleted file mode 100644 index e0f18c7d..00000000 --- a/vendor/github.com/go-chi/chi/v5/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -.PHONY: all -all: - @echo "**********************************************************" - @echo "** chi build tool **" - @echo "**********************************************************" - - -.PHONY: test -test: - go clean -testcache && $(MAKE) test-router && $(MAKE) test-middleware - -.PHONY: test-router -test-router: - go test -race -v . - -.PHONY: test-middleware -test-middleware: - go test -race -v ./middleware - -.PHONY: docs -docs: - npx docsify-cli serve ./docs diff --git a/vendor/github.com/go-chi/chi/v5/README.md b/vendor/github.com/go-chi/chi/v5/README.md deleted file mode 100644 index 718e373f..00000000 --- a/vendor/github.com/go-chi/chi/v5/README.md +++ /dev/null @@ -1,500 +0,0 @@ -# chi - - -[![GoDoc Widget]][GoDoc] - -`chi` is a lightweight, idiomatic and composable router for building Go HTTP services. It's -especially good at helping you write large REST API services that are kept maintainable as your -project grows and changes. `chi` is built on the new `context` package introduced in Go 1.7 to -handle signaling, cancelation and request-scoped values across a handler chain. - -The focus of the project has been to seek out an elegant and comfortable design for writing -REST API servers, written during the development of the Pressly API service that powers our -public API service, which in turn powers all of our client-side applications. - -The key considerations of chi's design are: project structure, maintainability, standard http -handlers (stdlib-only), developer productivity, and deconstructing a large system into many small -parts. The core router `github.com/go-chi/chi` is quite small (less than 1000 LOC), but we've also -included some useful/optional subpackages: [middleware](/middleware), [render](https://github.com/go-chi/render) -and [docgen](https://github.com/go-chi/docgen). We hope you enjoy it too! - -## Install - -`go get -u github.com/go-chi/chi/v5` - - -## Features - -* **Lightweight** - cloc'd in ~1000 LOC for the chi router -* **Fast** - yes, see [benchmarks](#benchmarks) -* **100% compatible with net/http** - use any http or middleware pkg in the ecosystem that is also compatible with `net/http` -* **Designed for modular/composable APIs** - middlewares, inline middlewares, route groups and sub-router mounting -* **Context control** - built on new `context` package, providing value chaining, cancellations and timeouts -* **Robust** - in production at Pressly, Cloudflare, Heroku, 99Designs, and many others (see [discussion](https://github.com/go-chi/chi/issues/91)) -* **Doc generation** - `docgen` auto-generates routing documentation from your source to JSON or Markdown -* **Go.mod support** - as of v5, go.mod support (see [CHANGELOG](https://github.com/go-chi/chi/blob/master/CHANGELOG.md)) -* **No external dependencies** - plain ol' Go stdlib + net/http - - -## Examples - -See [_examples/](https://github.com/go-chi/chi/blob/master/_examples/) for a variety of examples. - - -**As easy as:** - -```go -package main - -import ( - "net/http" - - "github.com/go-chi/chi/v5" - "github.com/go-chi/chi/v5/middleware" -) - -func main() { - r := chi.NewRouter() - r.Use(middleware.Logger) - r.Get("/", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("welcome")) - }) - http.ListenAndServe(":3000", r) -} -``` - -**REST Preview:** - -Here is a little preview of how routing looks like with chi. Also take a look at the generated routing docs -in JSON ([routes.json](https://github.com/go-chi/chi/blob/master/_examples/rest/routes.json)) and in -Markdown ([routes.md](https://github.com/go-chi/chi/blob/master/_examples/rest/routes.md)). - -I highly recommend reading the source of the [examples](https://github.com/go-chi/chi/blob/master/_examples/) listed -above, they will show you all the features of chi and serve as a good form of documentation. - -```go -import ( - //... - "context" - "github.com/go-chi/chi/v5" - "github.com/go-chi/chi/v5/middleware" -) - -func main() { - r := chi.NewRouter() - - // A good base middleware stack - r.Use(middleware.RequestID) - r.Use(middleware.RealIP) - r.Use(middleware.Logger) - r.Use(middleware.Recoverer) - - // Set a timeout value on the request context (ctx), that will signal - // through ctx.Done() that the request has timed out and further - // processing should be stopped. - r.Use(middleware.Timeout(60 * time.Second)) - - r.Get("/", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("hi")) - }) - - // RESTy routes for "articles" resource - r.Route("/articles", func(r chi.Router) { - r.With(paginate).Get("/", listArticles) // GET /articles - r.With(paginate).Get("/{month}-{day}-{year}", listArticlesByDate) // GET /articles/01-16-2017 - - r.Post("/", createArticle) // POST /articles - r.Get("/search", searchArticles) // GET /articles/search - - // Regexp url parameters: - r.Get("/{articleSlug:[a-z-]+}", getArticleBySlug) // GET /articles/home-is-toronto - - // Subrouters: - r.Route("/{articleID}", func(r chi.Router) { - r.Use(ArticleCtx) - r.Get("/", getArticle) // GET /articles/123 - r.Put("/", updateArticle) // PUT /articles/123 - r.Delete("/", deleteArticle) // DELETE /articles/123 - }) - }) - - // Mount the admin sub-router - r.Mount("/admin", adminRouter()) - - http.ListenAndServe(":3333", r) -} - -func ArticleCtx(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - articleID := chi.URLParam(r, "articleID") - article, err := dbGetArticle(articleID) - if err != nil { - http.Error(w, http.StatusText(404), 404) - return - } - ctx := context.WithValue(r.Context(), "article", article) - next.ServeHTTP(w, r.WithContext(ctx)) - }) -} - -func getArticle(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - article, ok := ctx.Value("article").(*Article) - if !ok { - http.Error(w, http.StatusText(422), 422) - return - } - w.Write([]byte(fmt.Sprintf("title:%s", article.Title))) -} - -// A completely separate router for administrator routes -func adminRouter() http.Handler { - r := chi.NewRouter() - r.Use(AdminOnly) - r.Get("/", adminIndex) - r.Get("/accounts", adminListAccounts) - return r -} - -func AdminOnly(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - perm, ok := ctx.Value("acl.permission").(YourPermissionType) - if !ok || !perm.IsAdmin() { - http.Error(w, http.StatusText(403), 403) - return - } - next.ServeHTTP(w, r) - }) -} -``` - - -## Router interface - -chi's router is based on a kind of [Patricia Radix trie](https://en.wikipedia.org/wiki/Radix_tree). -The router is fully compatible with `net/http`. - -Built on top of the tree is the `Router` interface: - -```go -// Router consisting of the core routing methods used by chi's Mux, -// using only the standard net/http. -type Router interface { - http.Handler - Routes - - // Use appends one or more middlewares onto the Router stack. - Use(middlewares ...func(http.Handler) http.Handler) - - // With adds inline middlewares for an endpoint handler. - With(middlewares ...func(http.Handler) http.Handler) Router - - // Group adds a new inline-Router along the current routing - // path, with a fresh middleware stack for the inline-Router. - Group(fn func(r Router)) Router - - // Route mounts a sub-Router along a `pattern`` string. - Route(pattern string, fn func(r Router)) Router - - // Mount attaches another http.Handler along ./pattern/* - Mount(pattern string, h http.Handler) - - // Handle and HandleFunc adds routes for `pattern` that matches - // all HTTP methods. - Handle(pattern string, h http.Handler) - HandleFunc(pattern string, h http.HandlerFunc) - - // Method and MethodFunc adds routes for `pattern` that matches - // the `method` HTTP method. - Method(method, pattern string, h http.Handler) - MethodFunc(method, pattern string, h http.HandlerFunc) - - // HTTP-method routing along `pattern` - Connect(pattern string, h http.HandlerFunc) - Delete(pattern string, h http.HandlerFunc) - Get(pattern string, h http.HandlerFunc) - Head(pattern string, h http.HandlerFunc) - Options(pattern string, h http.HandlerFunc) - Patch(pattern string, h http.HandlerFunc) - Post(pattern string, h http.HandlerFunc) - Put(pattern string, h http.HandlerFunc) - Trace(pattern string, h http.HandlerFunc) - - // NotFound defines a handler to respond whenever a route could - // not be found. - NotFound(h http.HandlerFunc) - - // MethodNotAllowed defines a handler to respond whenever a method is - // not allowed. - MethodNotAllowed(h http.HandlerFunc) -} - -// Routes interface adds two methods for router traversal, which is also -// used by the github.com/go-chi/docgen package to generate documentation for Routers. -type Routes interface { - // Routes returns the routing tree in an easily traversable structure. - Routes() []Route - - // Middlewares returns the list of middlewares in use by the router. - Middlewares() Middlewares - - // Match searches the routing tree for a handler that matches - // the method/path - similar to routing a http request, but without - // executing the handler thereafter. - Match(rctx *Context, method, path string) bool -} -``` - -Each routing method accepts a URL `pattern` and chain of `handlers`. The URL pattern -supports named params (ie. `/users/{userID}`) and wildcards (ie. `/admin/*`). URL parameters -can be fetched at runtime by calling `chi.URLParam(r, "userID")` for named parameters -and `chi.URLParam(r, "*")` for a wildcard parameter. - - -### Middleware handlers - -chi's middlewares are just stdlib net/http middleware handlers. There is nothing special -about them, which means the router and all the tooling is designed to be compatible and -friendly with any middleware in the community. This offers much better extensibility and reuse -of packages and is at the heart of chi's purpose. - -Here is an example of a standard net/http middleware where we assign a context key `"user"` -the value of `"123"`. This middleware sets a hypothetical user identifier on the request -context and calls the next handler in the chain. - -```go -// HTTP middleware setting a value on the request context -func MyMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // create new context from `r` request context, and assign key `"user"` - // to value of `"123"` - ctx := context.WithValue(r.Context(), "user", "123") - - // call the next handler in the chain, passing the response writer and - // the updated request object with the new context value. - // - // note: context.Context values are nested, so any previously set - // values will be accessible as well, and the new `"user"` key - // will be accessible from this point forward. - next.ServeHTTP(w, r.WithContext(ctx)) - }) -} -``` - - -### Request handlers - -chi uses standard net/http request handlers. This little snippet is an example of a http.Handler -func that reads a user identifier from the request context - hypothetically, identifying -the user sending an authenticated request, validated+set by a previous middleware handler. - -```go -// HTTP handler accessing data from the request context. -func MyRequestHandler(w http.ResponseWriter, r *http.Request) { - // here we read from the request context and fetch out `"user"` key set in - // the MyMiddleware example above. - user := r.Context().Value("user").(string) - - // respond to the client - w.Write([]byte(fmt.Sprintf("hi %s", user))) -} -``` - - -### URL parameters - -chi's router parses and stores URL parameters right onto the request context. Here is -an example of how to access URL params in your net/http handlers. And of course, middlewares -are able to access the same information. - -```go -// HTTP handler accessing the url routing parameters. -func MyRequestHandler(w http.ResponseWriter, r *http.Request) { - // fetch the url parameter `"userID"` from the request of a matching - // routing pattern. An example routing pattern could be: /users/{userID} - userID := chi.URLParam(r, "userID") - - // fetch `"key"` from the request context - ctx := r.Context() - key := ctx.Value("key").(string) - - // respond to the client - w.Write([]byte(fmt.Sprintf("hi %v, %v", userID, key))) -} -``` - - -## Middlewares - -chi comes equipped with an optional `middleware` package, providing a suite of standard -`net/http` middlewares. Please note, any middleware in the ecosystem that is also compatible -with `net/http` can be used with chi's mux. - -### Core middlewares - ----------------------------------------------------------------------------------------------------- -| chi/middleware Handler | description | -| :--------------------- | :---------------------------------------------------------------------- | -| [AllowContentEncoding] | Enforces a whitelist of request Content-Encoding headers | -| [AllowContentType] | Explicit whitelist of accepted request Content-Types | -| [BasicAuth] | Basic HTTP authentication | -| [Compress] | Gzip compression for clients that accept compressed responses | -| [ContentCharset] | Ensure charset for Content-Type request headers | -| [CleanPath] | Clean double slashes from request path | -| [GetHead] | Automatically route undefined HEAD requests to GET handlers | -| [Heartbeat] | Monitoring endpoint to check the servers pulse | -| [Logger] | Logs the start and end of each request with the elapsed processing time | -| [NoCache] | Sets response headers to prevent clients from caching | -| [Profiler] | Easily attach net/http/pprof to your routers | -| [RealIP] | Sets a http.Request's RemoteAddr to either X-Real-IP or X-Forwarded-For | -| [Recoverer] | Gracefully absorb panics and prints the stack trace | -| [RequestID] | Injects a request ID into the context of each request | -| [RedirectSlashes] | Redirect slashes on routing paths | -| [RouteHeaders] | Route handling for request headers | -| [SetHeader] | Short-hand middleware to set a response header key/value | -| [StripSlashes] | Strip slashes on routing paths | -| [Throttle] | Puts a ceiling on the number of concurrent requests | -| [Timeout] | Signals to the request context when the timeout deadline is reached | -| [URLFormat] | Parse extension from url and put it on request context | -| [WithValue] | Short-hand middleware to set a key/value on the request context | ----------------------------------------------------------------------------------------------------- - -[AllowContentEncoding]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentEncoding -[AllowContentType]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentType -[BasicAuth]: https://pkg.go.dev/github.com/go-chi/chi/middleware#BasicAuth -[Compress]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compress -[ContentCharset]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ContentCharset -[CleanPath]: https://pkg.go.dev/github.com/go-chi/chi/middleware#CleanPath -[GetHead]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetHead -[GetReqID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetReqID -[Heartbeat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Heartbeat -[Logger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Logger -[NoCache]: https://pkg.go.dev/github.com/go-chi/chi/middleware#NoCache -[Profiler]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Profiler -[RealIP]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RealIP -[Recoverer]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Recoverer -[RedirectSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RedirectSlashes -[RequestLogger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestLogger -[RequestID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestID -[RouteHeaders]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RouteHeaders -[SetHeader]: https://pkg.go.dev/github.com/go-chi/chi/middleware#SetHeader -[StripSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#StripSlashes -[Throttle]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Throttle -[ThrottleBacklog]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleBacklog -[ThrottleWithOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleWithOpts -[Timeout]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Timeout -[URLFormat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#URLFormat -[WithLogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithLogEntry -[WithValue]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithValue -[Compressor]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compressor -[DefaultLogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#DefaultLogFormatter -[EncoderFunc]: https://pkg.go.dev/github.com/go-chi/chi/middleware#EncoderFunc -[HeaderRoute]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRoute -[HeaderRouter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRouter -[LogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogEntry -[LogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogFormatter -[LoggerInterface]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LoggerInterface -[ThrottleOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleOpts -[WrapResponseWriter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WrapResponseWriter - -### Extra middlewares & packages - -Please see https://github.com/go-chi for additional packages. - --------------------------------------------------------------------------------------------------------------------- -| package | description | -|:---------------------------------------------------|:------------------------------------------------------------- -| [cors](https://github.com/go-chi/cors) | Cross-origin resource sharing (CORS) | -| [docgen](https://github.com/go-chi/docgen) | Print chi.Router routes at runtime | -| [jwtauth](https://github.com/go-chi/jwtauth) | JWT authentication | -| [hostrouter](https://github.com/go-chi/hostrouter) | Domain/host based request routing | -| [httplog](https://github.com/go-chi/httplog) | Small but powerful structured HTTP request logging | -| [httprate](https://github.com/go-chi/httprate) | HTTP request rate limiter | -| [httptracer](https://github.com/go-chi/httptracer) | HTTP request performance tracing library | -| [httpvcr](https://github.com/go-chi/httpvcr) | Write deterministic tests for external sources | -| [stampede](https://github.com/go-chi/stampede) | HTTP request coalescer | --------------------------------------------------------------------------------------------------------------------- - - -## context? - -`context` is a tiny pkg that provides simple interface to signal context across call stacks -and goroutines. It was originally written by [Sameer Ajmani](https://github.com/Sajmani) -and is available in stdlib since go1.7. - -Learn more at https://blog.golang.org/context - -and.. -* Docs: https://golang.org/pkg/context -* Source: https://github.com/golang/go/tree/master/src/context - - -## Benchmarks - -The benchmark suite: https://github.com/pkieltyka/go-http-routing-benchmark - -Results as of Nov 29, 2020 with Go 1.15.5 on Linux AMD 3950x - -```shell -BenchmarkChi_Param 3075895 384 ns/op 400 B/op 2 allocs/op -BenchmarkChi_Param5 2116603 566 ns/op 400 B/op 2 allocs/op -BenchmarkChi_Param20 964117 1227 ns/op 400 B/op 2 allocs/op -BenchmarkChi_ParamWrite 2863413 420 ns/op 400 B/op 2 allocs/op -BenchmarkChi_GithubStatic 3045488 395 ns/op 400 B/op 2 allocs/op -BenchmarkChi_GithubParam 2204115 540 ns/op 400 B/op 2 allocs/op -BenchmarkChi_GithubAll 10000 113811 ns/op 81203 B/op 406 allocs/op -BenchmarkChi_GPlusStatic 3337485 359 ns/op 400 B/op 2 allocs/op -BenchmarkChi_GPlusParam 2825853 423 ns/op 400 B/op 2 allocs/op -BenchmarkChi_GPlus2Params 2471697 483 ns/op 400 B/op 2 allocs/op -BenchmarkChi_GPlusAll 194220 5950 ns/op 5200 B/op 26 allocs/op -BenchmarkChi_ParseStatic 3365324 356 ns/op 400 B/op 2 allocs/op -BenchmarkChi_ParseParam 2976614 404 ns/op 400 B/op 2 allocs/op -BenchmarkChi_Parse2Params 2638084 439 ns/op 400 B/op 2 allocs/op -BenchmarkChi_ParseAll 109567 11295 ns/op 10400 B/op 52 allocs/op -BenchmarkChi_StaticAll 16846 71308 ns/op 62802 B/op 314 allocs/op -``` - -Comparison with other routers: https://gist.github.com/pkieltyka/123032f12052520aaccab752bd3e78cc - -NOTE: the allocs in the benchmark above are from the calls to http.Request's -`WithContext(context.Context)` method that clones the http.Request, sets the `Context()` -on the duplicated (alloc'd) request and returns it the new request object. This is just -how setting context on a request in Go works. - - -## Credits - -* Carl Jackson for https://github.com/zenazn/goji - * Parts of chi's thinking comes from goji, and chi's middleware package - sources from goji. -* Armon Dadgar for https://github.com/armon/go-radix -* Contributions: [@VojtechVitek](https://github.com/VojtechVitek) - -We'll be more than happy to see [your contributions](./CONTRIBUTING.md)! - - -## Beyond REST - -chi is just a http router that lets you decompose request handling into many smaller layers. -Many companies use chi to write REST services for their public APIs. But, REST is just a convention -for managing state via HTTP, and there's a lot of other pieces required to write a complete client-server -system or network of microservices. - -Looking beyond REST, I also recommend some newer works in the field: -* [webrpc](https://github.com/webrpc/webrpc) - Web-focused RPC client+server framework with code-gen -* [gRPC](https://github.com/grpc/grpc-go) - Google's RPC framework via protobufs -* [graphql](https://github.com/99designs/gqlgen) - Declarative query language -* [NATS](https://nats.io) - lightweight pub-sub - - -## License - -Copyright (c) 2015-present [Peter Kieltyka](https://github.com/pkieltyka) - -Licensed under [MIT License](./LICENSE) - -[GoDoc]: https://pkg.go.dev/github.com/go-chi/chi?tab=versions -[GoDoc Widget]: https://godoc.org/github.com/go-chi/chi?status.svg -[Travis]: https://travis-ci.org/go-chi/chi -[Travis Widget]: https://travis-ci.org/go-chi/chi.svg?branch=master diff --git a/vendor/github.com/go-chi/chi/v5/chain.go b/vendor/github.com/go-chi/chi/v5/chain.go deleted file mode 100644 index a2278414..00000000 --- a/vendor/github.com/go-chi/chi/v5/chain.go +++ /dev/null @@ -1,49 +0,0 @@ -package chi - -import "net/http" - -// Chain returns a Middlewares type from a slice of middleware handlers. -func Chain(middlewares ...func(http.Handler) http.Handler) Middlewares { - return Middlewares(middlewares) -} - -// Handler builds and returns a http.Handler from the chain of middlewares, -// with `h http.Handler` as the final handler. -func (mws Middlewares) Handler(h http.Handler) http.Handler { - return &ChainHandler{h, chain(mws, h), mws} -} - -// HandlerFunc builds and returns a http.Handler from the chain of middlewares, -// with `h http.Handler` as the final handler. -func (mws Middlewares) HandlerFunc(h http.HandlerFunc) http.Handler { - return &ChainHandler{h, chain(mws, h), mws} -} - -// ChainHandler is a http.Handler with support for handler composition and -// execution. -type ChainHandler struct { - Endpoint http.Handler - chain http.Handler - Middlewares Middlewares -} - -func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - c.chain.ServeHTTP(w, r) -} - -// chain builds a http.Handler composed of an inline middleware stack and endpoint -// handler in the order they are passed. -func chain(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler { - // Return ahead of time if there aren't any middlewares for the chain - if len(middlewares) == 0 { - return endpoint - } - - // Wrap the end handler with the middleware chain - h := middlewares[len(middlewares)-1](endpoint) - for i := len(middlewares) - 2; i >= 0; i-- { - h = middlewares[i](h) - } - - return h -} diff --git a/vendor/github.com/go-chi/chi/v5/chi.go b/vendor/github.com/go-chi/chi/v5/chi.go deleted file mode 100644 index a1691bbe..00000000 --- a/vendor/github.com/go-chi/chi/v5/chi.go +++ /dev/null @@ -1,134 +0,0 @@ -// Package chi is a small, idiomatic and composable router for building HTTP services. -// -// chi requires Go 1.14 or newer. -// -// Example: -// -// package main -// -// import ( -// "net/http" -// -// "github.com/go-chi/chi/v5" -// "github.com/go-chi/chi/v5/middleware" -// ) -// -// func main() { -// r := chi.NewRouter() -// r.Use(middleware.Logger) -// r.Use(middleware.Recoverer) -// -// r.Get("/", func(w http.ResponseWriter, r *http.Request) { -// w.Write([]byte("root.")) -// }) -// -// http.ListenAndServe(":3333", r) -// } -// -// See github.com/go-chi/chi/_examples/ for more in-depth examples. -// -// URL patterns allow for easy matching of path components in HTTP -// requests. The matching components can then be accessed using -// chi.URLParam(). All patterns must begin with a slash. -// -// A simple named placeholder {name} matches any sequence of characters -// up to the next / or the end of the URL. Trailing slashes on paths must -// be handled explicitly. -// -// A placeholder with a name followed by a colon allows a regular -// expression match, for example {number:\\d+}. The regular expression -// syntax is Go's normal regexp RE2 syntax, except that regular expressions -// including { or } are not supported, and / will never be -// matched. An anonymous regexp pattern is allowed, using an empty string -// before the colon in the placeholder, such as {:\\d+} -// -// The special placeholder of asterisk matches the rest of the requested -// URL. Any trailing characters in the pattern are ignored. This is the only -// placeholder which will match / characters. -// -// Examples: -// -// "/user/{name}" matches "/user/jsmith" but not "/user/jsmith/info" or "/user/jsmith/" -// "/user/{name}/info" matches "/user/jsmith/info" -// "/page/*" matches "/page/intro/latest" -// "/page/{other}/index" also matches "/page/intro/latest" -// "/date/{yyyy:\\d\\d\\d\\d}/{mm:\\d\\d}/{dd:\\d\\d}" matches "/date/2017/04/01" -package chi - -import "net/http" - -// NewRouter returns a new Mux object that implements the Router interface. -func NewRouter() *Mux { - return NewMux() -} - -// Router consisting of the core routing methods used by chi's Mux, -// using only the standard net/http. -type Router interface { - http.Handler - Routes - - // Use appends one or more middlewares onto the Router stack. - Use(middlewares ...func(http.Handler) http.Handler) - - // With adds inline middlewares for an endpoint handler. - With(middlewares ...func(http.Handler) http.Handler) Router - - // Group adds a new inline-Router along the current routing - // path, with a fresh middleware stack for the inline-Router. - Group(fn func(r Router)) Router - - // Route mounts a sub-Router along a `pattern`` string. - Route(pattern string, fn func(r Router)) Router - - // Mount attaches another http.Handler along ./pattern/* - Mount(pattern string, h http.Handler) - - // Handle and HandleFunc adds routes for `pattern` that matches - // all HTTP methods. - Handle(pattern string, h http.Handler) - HandleFunc(pattern string, h http.HandlerFunc) - - // Method and MethodFunc adds routes for `pattern` that matches - // the `method` HTTP method. - Method(method, pattern string, h http.Handler) - MethodFunc(method, pattern string, h http.HandlerFunc) - - // HTTP-method routing along `pattern` - Connect(pattern string, h http.HandlerFunc) - Delete(pattern string, h http.HandlerFunc) - Get(pattern string, h http.HandlerFunc) - Head(pattern string, h http.HandlerFunc) - Options(pattern string, h http.HandlerFunc) - Patch(pattern string, h http.HandlerFunc) - Post(pattern string, h http.HandlerFunc) - Put(pattern string, h http.HandlerFunc) - Trace(pattern string, h http.HandlerFunc) - - // NotFound defines a handler to respond whenever a route could - // not be found. - NotFound(h http.HandlerFunc) - - // MethodNotAllowed defines a handler to respond whenever a method is - // not allowed. - MethodNotAllowed(h http.HandlerFunc) -} - -// Routes interface adds two methods for router traversal, which is also -// used by the `docgen` subpackage to generation documentation for Routers. -type Routes interface { - // Routes returns the routing tree in an easily traversable structure. - Routes() []Route - - // Middlewares returns the list of middlewares in use by the router. - Middlewares() Middlewares - - // Match searches the routing tree for a handler that matches - // the method/path - similar to routing a http request, but without - // executing the handler thereafter. - Match(rctx *Context, method, path string) bool -} - -// Middlewares type is a slice of standard middleware handlers with methods -// to compose middleware chains and http.Handler's. -type Middlewares []func(http.Handler) http.Handler diff --git a/vendor/github.com/go-chi/chi/v5/context.go b/vendor/github.com/go-chi/chi/v5/context.go deleted file mode 100644 index 88f8e221..00000000 --- a/vendor/github.com/go-chi/chi/v5/context.go +++ /dev/null @@ -1,160 +0,0 @@ -package chi - -import ( - "context" - "net/http" - "strings" -) - -// URLParam returns the url parameter from a http.Request object. -func URLParam(r *http.Request, key string) string { - if rctx := RouteContext(r.Context()); rctx != nil { - return rctx.URLParam(key) - } - return "" -} - -// URLParamFromCtx returns the url parameter from a http.Request Context. -func URLParamFromCtx(ctx context.Context, key string) string { - if rctx := RouteContext(ctx); rctx != nil { - return rctx.URLParam(key) - } - return "" -} - -// RouteContext returns chi's routing Context object from a -// http.Request Context. -func RouteContext(ctx context.Context) *Context { - val, _ := ctx.Value(RouteCtxKey).(*Context) - return val -} - -// NewRouteContext returns a new routing Context object. -func NewRouteContext() *Context { - return &Context{} -} - -var ( - // RouteCtxKey is the context.Context key to store the request context. - RouteCtxKey = &contextKey{"RouteContext"} -) - -// Context is the default routing context set on the root node of a -// request context to track route patterns, URL parameters and -// an optional routing path. -type Context struct { - Routes Routes - - // parentCtx is the parent of this one, for using Context as a - // context.Context directly. This is an optimization that saves - // 1 allocation. - parentCtx context.Context - - // Routing path/method override used during the route search. - // See Mux#routeHTTP method. - RoutePath string - RouteMethod string - - // URLParams are the stack of routeParams captured during the - // routing lifecycle across a stack of sub-routers. - URLParams RouteParams - - // Route parameters matched for the current sub-router. It is - // intentionally unexported so it cant be tampered. - routeParams RouteParams - - // The endpoint routing pattern that matched the request URI path - // or `RoutePath` of the current sub-router. This value will update - // during the lifecycle of a request passing through a stack of - // sub-routers. - routePattern string - - // Routing pattern stack throughout the lifecycle of the request, - // across all connected routers. It is a record of all matching - // patterns across a stack of sub-routers. - RoutePatterns []string - - // methodNotAllowed hint - methodNotAllowed bool - methodsAllowed []methodTyp // allowed methods in case of a 405 -} - -// Reset a routing context to its initial state. -func (x *Context) Reset() { - x.Routes = nil - x.RoutePath = "" - x.RouteMethod = "" - x.RoutePatterns = x.RoutePatterns[:0] - x.URLParams.Keys = x.URLParams.Keys[:0] - x.URLParams.Values = x.URLParams.Values[:0] - - x.routePattern = "" - x.routeParams.Keys = x.routeParams.Keys[:0] - x.routeParams.Values = x.routeParams.Values[:0] - x.methodNotAllowed = false - x.parentCtx = nil -} - -// URLParam returns the corresponding URL parameter value from the request -// routing context. -func (x *Context) URLParam(key string) string { - for k := len(x.URLParams.Keys) - 1; k >= 0; k-- { - if x.URLParams.Keys[k] == key { - return x.URLParams.Values[k] - } - } - return "" -} - -// RoutePattern builds the routing pattern string for the particular -// request, at the particular point during routing. This means, the value -// will change throughout the execution of a request in a router. That is -// why its advised to only use this value after calling the next handler. -// -// For example, -// -// func Instrument(next http.Handler) http.Handler { -// return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { -// next.ServeHTTP(w, r) -// routePattern := chi.RouteContext(r.Context()).RoutePattern() -// measure(w, r, routePattern) -// }) -// } -func (x *Context) RoutePattern() string { - routePattern := strings.Join(x.RoutePatterns, "") - routePattern = replaceWildcards(routePattern) - routePattern = strings.TrimSuffix(routePattern, "//") - routePattern = strings.TrimSuffix(routePattern, "/") - return routePattern -} - -// replaceWildcards takes a route pattern and recursively replaces all -// occurrences of "/*/" to "/". -func replaceWildcards(p string) string { - if strings.Contains(p, "/*/") { - return replaceWildcards(strings.Replace(p, "/*/", "/", -1)) - } - return p -} - -// RouteParams is a structure to track URL routing parameters efficiently. -type RouteParams struct { - Keys, Values []string -} - -// Add will append a URL parameter to the end of the route param -func (s *RouteParams) Add(key, value string) { - s.Keys = append(s.Keys, key) - s.Values = append(s.Values, value) -} - -// contextKey is a value for use with context.WithValue. It's used as -// a pointer so it fits in an interface{} without allocation. This technique -// for defining context keys was copied from Go 1.7's new use of context in net/http. -type contextKey struct { - name string -} - -func (k *contextKey) String() string { - return "chi context value " + k.name -} diff --git a/vendor/github.com/go-chi/chi/v5/mux.go b/vendor/github.com/go-chi/chi/v5/mux.go deleted file mode 100644 index 977aa52d..00000000 --- a/vendor/github.com/go-chi/chi/v5/mux.go +++ /dev/null @@ -1,493 +0,0 @@ -package chi - -import ( - "context" - "fmt" - "net/http" - "strings" - "sync" -) - -var _ Router = &Mux{} - -// Mux is a simple HTTP route multiplexer that parses a request path, -// records any URL params, and executes an end handler. It implements -// the http.Handler interface and is friendly with the standard library. -// -// Mux is designed to be fast, minimal and offer a powerful API for building -// modular and composable HTTP services with a large set of handlers. It's -// particularly useful for writing large REST API services that break a handler -// into many smaller parts composed of middlewares and end handlers. -type Mux struct { - // The computed mux handler made of the chained middleware stack and - // the tree router - handler http.Handler - - // The radix trie router - tree *node - - // Custom method not allowed handler - methodNotAllowedHandler http.HandlerFunc - - // A reference to the parent mux used by subrouters when mounting - // to a parent mux - parent *Mux - - // Routing context pool - pool *sync.Pool - - // Custom route not found handler - notFoundHandler http.HandlerFunc - - // The middleware stack - middlewares []func(http.Handler) http.Handler - - // Controls the behaviour of middleware chain generation when a mux - // is registered as an inline group inside another mux. - inline bool -} - -// NewMux returns a newly initialized Mux object that implements the Router -// interface. -func NewMux() *Mux { - mux := &Mux{tree: &node{}, pool: &sync.Pool{}} - mux.pool.New = func() interface{} { - return NewRouteContext() - } - return mux -} - -// ServeHTTP is the single method of the http.Handler interface that makes -// Mux interoperable with the standard library. It uses a sync.Pool to get and -// reuse routing contexts for each request. -func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Ensure the mux has some routes defined on the mux - if mx.handler == nil { - mx.NotFoundHandler().ServeHTTP(w, r) - return - } - - // Check if a routing context already exists from a parent router. - rctx, _ := r.Context().Value(RouteCtxKey).(*Context) - if rctx != nil { - mx.handler.ServeHTTP(w, r) - return - } - - // Fetch a RouteContext object from the sync pool, and call the computed - // mx.handler that is comprised of mx.middlewares + mx.routeHTTP. - // Once the request is finished, reset the routing context and put it back - // into the pool for reuse from another request. - rctx = mx.pool.Get().(*Context) - rctx.Reset() - rctx.Routes = mx - rctx.parentCtx = r.Context() - - // NOTE: r.WithContext() causes 2 allocations and context.WithValue() causes 1 allocation - r = r.WithContext(context.WithValue(r.Context(), RouteCtxKey, rctx)) - - // Serve the request and once its done, put the request context back in the sync pool - mx.handler.ServeHTTP(w, r) - mx.pool.Put(rctx) -} - -// Use appends a middleware handler to the Mux middleware stack. -// -// The middleware stack for any Mux will execute before searching for a matching -// route to a specific handler, which provides opportunity to respond early, -// change the course of the request execution, or set request-scoped values for -// the next http.Handler. -func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler) { - if mx.handler != nil { - panic("chi: all middlewares must be defined before routes on a mux") - } - mx.middlewares = append(mx.middlewares, middlewares...) -} - -// Handle adds the route `pattern` that matches any http method to -// execute the `handler` http.Handler. -func (mx *Mux) Handle(pattern string, handler http.Handler) { - mx.handle(mALL, pattern, handler) -} - -// HandleFunc adds the route `pattern` that matches any http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) HandleFunc(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mALL, pattern, handlerFn) -} - -// Method adds the route `pattern` that matches `method` http method to -// execute the `handler` http.Handler. -func (mx *Mux) Method(method, pattern string, handler http.Handler) { - m, ok := methodMap[strings.ToUpper(method)] - if !ok { - panic(fmt.Sprintf("chi: '%s' http method is not supported.", method)) - } - mx.handle(m, pattern, handler) -} - -// MethodFunc adds the route `pattern` that matches `method` http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) MethodFunc(method, pattern string, handlerFn http.HandlerFunc) { - mx.Method(method, pattern, handlerFn) -} - -// Connect adds the route `pattern` that matches a CONNECT http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) Connect(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mCONNECT, pattern, handlerFn) -} - -// Delete adds the route `pattern` that matches a DELETE http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) Delete(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mDELETE, pattern, handlerFn) -} - -// Get adds the route `pattern` that matches a GET http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) Get(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mGET, pattern, handlerFn) -} - -// Head adds the route `pattern` that matches a HEAD http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) Head(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mHEAD, pattern, handlerFn) -} - -// Options adds the route `pattern` that matches an OPTIONS http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) Options(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mOPTIONS, pattern, handlerFn) -} - -// Patch adds the route `pattern` that matches a PATCH http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) Patch(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mPATCH, pattern, handlerFn) -} - -// Post adds the route `pattern` that matches a POST http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) Post(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mPOST, pattern, handlerFn) -} - -// Put adds the route `pattern` that matches a PUT http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) Put(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mPUT, pattern, handlerFn) -} - -// Trace adds the route `pattern` that matches a TRACE http method to -// execute the `handlerFn` http.HandlerFunc. -func (mx *Mux) Trace(pattern string, handlerFn http.HandlerFunc) { - mx.handle(mTRACE, pattern, handlerFn) -} - -// NotFound sets a custom http.HandlerFunc for routing paths that could -// not be found. The default 404 handler is `http.NotFound`. -func (mx *Mux) NotFound(handlerFn http.HandlerFunc) { - // Build NotFound handler chain - m := mx - hFn := handlerFn - if mx.inline && mx.parent != nil { - m = mx.parent - hFn = Chain(mx.middlewares...).HandlerFunc(hFn).ServeHTTP - } - - // Update the notFoundHandler from this point forward - m.notFoundHandler = hFn - m.updateSubRoutes(func(subMux *Mux) { - if subMux.notFoundHandler == nil { - subMux.NotFound(hFn) - } - }) -} - -// MethodNotAllowed sets a custom http.HandlerFunc for routing paths where the -// method is unresolved. The default handler returns a 405 with an empty body. -func (mx *Mux) MethodNotAllowed(handlerFn http.HandlerFunc) { - // Build MethodNotAllowed handler chain - m := mx - hFn := handlerFn - if mx.inline && mx.parent != nil { - m = mx.parent - hFn = Chain(mx.middlewares...).HandlerFunc(hFn).ServeHTTP - } - - // Update the methodNotAllowedHandler from this point forward - m.methodNotAllowedHandler = hFn - m.updateSubRoutes(func(subMux *Mux) { - if subMux.methodNotAllowedHandler == nil { - subMux.MethodNotAllowed(hFn) - } - }) -} - -// With adds inline middlewares for an endpoint handler. -func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router { - // Similarly as in handle(), we must build the mux handler once additional - // middleware registration isn't allowed for this stack, like now. - if !mx.inline && mx.handler == nil { - mx.updateRouteHandler() - } - - // Copy middlewares from parent inline muxs - var mws Middlewares - if mx.inline { - mws = make(Middlewares, len(mx.middlewares)) - copy(mws, mx.middlewares) - } - mws = append(mws, middlewares...) - - im := &Mux{ - pool: mx.pool, inline: true, parent: mx, tree: mx.tree, middlewares: mws, - notFoundHandler: mx.notFoundHandler, methodNotAllowedHandler: mx.methodNotAllowedHandler, - } - - return im -} - -// Group creates a new inline-Mux with a fresh middleware stack. It's useful -// for a group of handlers along the same routing path that use an additional -// set of middlewares. See _examples/. -func (mx *Mux) Group(fn func(r Router)) Router { - im := mx.With().(*Mux) - if fn != nil { - fn(im) - } - return im -} - -// Route creates a new Mux with a fresh middleware stack and mounts it -// along the `pattern` as a subrouter. Effectively, this is a short-hand -// call to Mount. See _examples/. -func (mx *Mux) Route(pattern string, fn func(r Router)) Router { - if fn == nil { - panic(fmt.Sprintf("chi: attempting to Route() a nil subrouter on '%s'", pattern)) - } - subRouter := NewRouter() - fn(subRouter) - mx.Mount(pattern, subRouter) - return subRouter -} - -// Mount attaches another http.Handler or chi Router as a subrouter along a routing -// path. It's very useful to split up a large API as many independent routers and -// compose them as a single service using Mount. See _examples/. -// -// Note that Mount() simply sets a wildcard along the `pattern` that will continue -// routing at the `handler`, which in most cases is another chi.Router. As a result, -// if you define two Mount() routes on the exact same pattern the mount will panic. -func (mx *Mux) Mount(pattern string, handler http.Handler) { - if handler == nil { - panic(fmt.Sprintf("chi: attempting to Mount() a nil handler on '%s'", pattern)) - } - - // Provide runtime safety for ensuring a pattern isn't mounted on an existing - // routing pattern. - if mx.tree.findPattern(pattern+"*") || mx.tree.findPattern(pattern+"/*") { - panic(fmt.Sprintf("chi: attempting to Mount() a handler on an existing path, '%s'", pattern)) - } - - // Assign sub-Router's with the parent not found & method not allowed handler if not specified. - subr, ok := handler.(*Mux) - if ok && subr.notFoundHandler == nil && mx.notFoundHandler != nil { - subr.NotFound(mx.notFoundHandler) - } - if ok && subr.methodNotAllowedHandler == nil && mx.methodNotAllowedHandler != nil { - subr.MethodNotAllowed(mx.methodNotAllowedHandler) - } - - mountHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - rctx := RouteContext(r.Context()) - - // shift the url path past the previous subrouter - rctx.RoutePath = mx.nextRoutePath(rctx) - - // reset the wildcard URLParam which connects the subrouter - n := len(rctx.URLParams.Keys) - 1 - if n >= 0 && rctx.URLParams.Keys[n] == "*" && len(rctx.URLParams.Values) > n { - rctx.URLParams.Values[n] = "" - } - - handler.ServeHTTP(w, r) - }) - - if pattern == "" || pattern[len(pattern)-1] != '/' { - mx.handle(mALL|mSTUB, pattern, mountHandler) - mx.handle(mALL|mSTUB, pattern+"/", mountHandler) - pattern += "/" - } - - method := mALL - subroutes, _ := handler.(Routes) - if subroutes != nil { - method |= mSTUB - } - n := mx.handle(method, pattern+"*", mountHandler) - - if subroutes != nil { - n.subroutes = subroutes - } -} - -// Routes returns a slice of routing information from the tree, -// useful for traversing available routes of a router. -func (mx *Mux) Routes() []Route { - return mx.tree.routes() -} - -// Middlewares returns a slice of middleware handler functions. -func (mx *Mux) Middlewares() Middlewares { - return mx.middlewares -} - -// Match searches the routing tree for a handler that matches the method/path. -// It's similar to routing a http request, but without executing the handler -// thereafter. -// -// Note: the *Context state is updated during execution, so manage -// the state carefully or make a NewRouteContext(). -func (mx *Mux) Match(rctx *Context, method, path string) bool { - m, ok := methodMap[method] - if !ok { - return false - } - - node, _, h := mx.tree.FindRoute(rctx, m, path) - - if node != nil && node.subroutes != nil { - rctx.RoutePath = mx.nextRoutePath(rctx) - return node.subroutes.Match(rctx, method, rctx.RoutePath) - } - - return h != nil -} - -// NotFoundHandler returns the default Mux 404 responder whenever a route -// cannot be found. -func (mx *Mux) NotFoundHandler() http.HandlerFunc { - if mx.notFoundHandler != nil { - return mx.notFoundHandler - } - return http.NotFound -} - -// MethodNotAllowedHandler returns the default Mux 405 responder whenever -// a method cannot be resolved for a route. -func (mx *Mux) MethodNotAllowedHandler(methodsAllowed ...methodTyp) http.HandlerFunc { - if mx.methodNotAllowedHandler != nil { - return mx.methodNotAllowedHandler - } - return methodNotAllowedHandler(methodsAllowed...) -} - -// handle registers a http.Handler in the routing tree for a particular http method -// and routing pattern. -func (mx *Mux) handle(method methodTyp, pattern string, handler http.Handler) *node { - if len(pattern) == 0 || pattern[0] != '/' { - panic(fmt.Sprintf("chi: routing pattern must begin with '/' in '%s'", pattern)) - } - - // Build the computed routing handler for this routing pattern. - if !mx.inline && mx.handler == nil { - mx.updateRouteHandler() - } - - // Build endpoint handler with inline middlewares for the route - var h http.Handler - if mx.inline { - mx.handler = http.HandlerFunc(mx.routeHTTP) - h = Chain(mx.middlewares...).Handler(handler) - } else { - h = handler - } - - // Add the endpoint to the tree and return the node - return mx.tree.InsertRoute(method, pattern, h) -} - -// routeHTTP routes a http.Request through the Mux routing tree to serve -// the matching handler for a particular http method. -func (mx *Mux) routeHTTP(w http.ResponseWriter, r *http.Request) { - // Grab the route context object - rctx := r.Context().Value(RouteCtxKey).(*Context) - - // The request routing path - routePath := rctx.RoutePath - if routePath == "" { - if r.URL.RawPath != "" { - routePath = r.URL.RawPath - } else { - routePath = r.URL.Path - } - if routePath == "" { - routePath = "/" - } - } - - // Check if method is supported by chi - if rctx.RouteMethod == "" { - rctx.RouteMethod = r.Method - } - method, ok := methodMap[rctx.RouteMethod] - if !ok { - mx.MethodNotAllowedHandler().ServeHTTP(w, r) - return - } - - // Find the route - if _, _, h := mx.tree.FindRoute(rctx, method, routePath); h != nil { - h.ServeHTTP(w, r) - return - } - if rctx.methodNotAllowed { - mx.MethodNotAllowedHandler(rctx.methodsAllowed...).ServeHTTP(w, r) - } else { - mx.NotFoundHandler().ServeHTTP(w, r) - } -} - -func (mx *Mux) nextRoutePath(rctx *Context) string { - routePath := "/" - nx := len(rctx.routeParams.Keys) - 1 // index of last param in list - if nx >= 0 && rctx.routeParams.Keys[nx] == "*" && len(rctx.routeParams.Values) > nx { - routePath = "/" + rctx.routeParams.Values[nx] - } - return routePath -} - -// Recursively update data on child routers. -func (mx *Mux) updateSubRoutes(fn func(subMux *Mux)) { - for _, r := range mx.tree.routes() { - subMux, ok := r.SubRoutes.(*Mux) - if !ok { - continue - } - fn(subMux) - } -} - -// updateRouteHandler builds the single mux handler that is a chain of the middleware -// stack, as defined by calls to Use(), and the tree router (Mux) itself. After this -// point, no other middlewares can be registered on this Mux's stack. But you can still -// compose additional middlewares via Group()'s or using a chained middleware handler. -func (mx *Mux) updateRouteHandler() { - mx.handler = chain(mx.middlewares, http.HandlerFunc(mx.routeHTTP)) -} - -// methodNotAllowedHandler is a helper function to respond with a 405, -// method not allowed. It sets the Allow header with the list of allowed -// methods for the route. -func methodNotAllowedHandler(methodsAllowed ...methodTyp) func(w http.ResponseWriter, r *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { - for _, m := range methodsAllowed { - w.Header().Add("Allow", reverseMethodMap[m]) - } - w.WriteHeader(405) - w.Write(nil) - } -} diff --git a/vendor/github.com/go-chi/chi/v5/tree.go b/vendor/github.com/go-chi/chi/v5/tree.go deleted file mode 100644 index c7d3bc57..00000000 --- a/vendor/github.com/go-chi/chi/v5/tree.go +++ /dev/null @@ -1,892 +0,0 @@ -package chi - -// Radix tree implementation below is a based on the original work by -// Armon Dadgar in https://github.com/armon/go-radix/blob/master/radix.go -// (MIT licensed). It's been heavily modified for use as a HTTP routing tree. - -import ( - "fmt" - "net/http" - "regexp" - "sort" - "strconv" - "strings" -) - -type methodTyp uint - -const ( - mSTUB methodTyp = 1 << iota - mCONNECT - mDELETE - mGET - mHEAD - mOPTIONS - mPATCH - mPOST - mPUT - mTRACE -) - -var mALL = mCONNECT | mDELETE | mGET | mHEAD | - mOPTIONS | mPATCH | mPOST | mPUT | mTRACE - -var methodMap = map[string]methodTyp{ - http.MethodConnect: mCONNECT, - http.MethodDelete: mDELETE, - http.MethodGet: mGET, - http.MethodHead: mHEAD, - http.MethodOptions: mOPTIONS, - http.MethodPatch: mPATCH, - http.MethodPost: mPOST, - http.MethodPut: mPUT, - http.MethodTrace: mTRACE, -} - -var reverseMethodMap = map[methodTyp]string{ - mCONNECT: http.MethodConnect, - mDELETE: http.MethodDelete, - mGET: http.MethodGet, - mHEAD: http.MethodHead, - mOPTIONS: http.MethodOptions, - mPATCH: http.MethodPatch, - mPOST: http.MethodPost, - mPUT: http.MethodPut, - mTRACE: http.MethodTrace, -} - -// RegisterMethod adds support for custom HTTP method handlers, available -// via Router#Method and Router#MethodFunc -func RegisterMethod(method string) { - if method == "" { - return - } - method = strings.ToUpper(method) - if _, ok := methodMap[method]; ok { - return - } - n := len(methodMap) - if n > strconv.IntSize-2 { - panic(fmt.Sprintf("chi: max number of methods reached (%d)", strconv.IntSize)) - } - mt := methodTyp(2 << n) - methodMap[method] = mt - mALL |= mt -} - -type nodeTyp uint8 - -const ( - ntStatic nodeTyp = iota // /home - ntRegexp // /{id:[0-9]+} - ntParam // /{user} - ntCatchAll // /api/v1/* -) - -type node struct { - // subroutes on the leaf node - subroutes Routes - - // regexp matcher for regexp nodes - rex *regexp.Regexp - - // HTTP handler endpoints on the leaf node - endpoints endpoints - - // prefix is the common prefix we ignore - prefix string - - // child nodes should be stored in-order for iteration, - // in groups of the node type. - children [ntCatchAll + 1]nodes - - // first byte of the child prefix - tail byte - - // node type: static, regexp, param, catchAll - typ nodeTyp - - // first byte of the prefix - label byte -} - -// endpoints is a mapping of http method constants to handlers -// for a given route. -type endpoints map[methodTyp]*endpoint - -type endpoint struct { - // endpoint handler - handler http.Handler - - // pattern is the routing pattern for handler nodes - pattern string - - // parameter keys recorded on handler nodes - paramKeys []string -} - -func (s endpoints) Value(method methodTyp) *endpoint { - mh, ok := s[method] - if !ok { - mh = &endpoint{} - s[method] = mh - } - return mh -} - -func (n *node) InsertRoute(method methodTyp, pattern string, handler http.Handler) *node { - var parent *node - search := pattern - - for { - // Handle key exhaustion - if len(search) == 0 { - // Insert or update the node's leaf handler - n.setEndpoint(method, handler, pattern) - return n - } - - // We're going to be searching for a wild node next, - // in this case, we need to get the tail - var label = search[0] - var segTail byte - var segEndIdx int - var segTyp nodeTyp - var segRexpat string - if label == '{' || label == '*' { - segTyp, _, segRexpat, segTail, _, segEndIdx = patNextSegment(search) - } - - var prefix string - if segTyp == ntRegexp { - prefix = segRexpat - } - - // Look for the edge to attach to - parent = n - n = n.getEdge(segTyp, label, segTail, prefix) - - // No edge, create one - if n == nil { - child := &node{label: label, tail: segTail, prefix: search} - hn := parent.addChild(child, search) - hn.setEndpoint(method, handler, pattern) - - return hn - } - - // Found an edge to match the pattern - - if n.typ > ntStatic { - // We found a param node, trim the param from the search path and continue. - // This param/wild pattern segment would already be on the tree from a previous - // call to addChild when creating a new node. - search = search[segEndIdx:] - continue - } - - // Static nodes fall below here. - // Determine longest prefix of the search key on match. - commonPrefix := longestPrefix(search, n.prefix) - if commonPrefix == len(n.prefix) { - // the common prefix is as long as the current node's prefix we're attempting to insert. - // keep the search going. - search = search[commonPrefix:] - continue - } - - // Split the node - child := &node{ - typ: ntStatic, - prefix: search[:commonPrefix], - } - parent.replaceChild(search[0], segTail, child) - - // Restore the existing node - n.label = n.prefix[commonPrefix] - n.prefix = n.prefix[commonPrefix:] - child.addChild(n, n.prefix) - - // If the new key is a subset, set the method/handler on this node and finish. - search = search[commonPrefix:] - if len(search) == 0 { - child.setEndpoint(method, handler, pattern) - return child - } - - // Create a new edge for the node - subchild := &node{ - typ: ntStatic, - label: search[0], - prefix: search, - } - hn := child.addChild(subchild, search) - hn.setEndpoint(method, handler, pattern) - return hn - } -} - -// addChild appends the new `child` node to the tree using the `pattern` as the trie key. -// For a URL router like chi's, we split the static, param, regexp and wildcard segments -// into different nodes. In addition, addChild will recursively call itself until every -// pattern segment is added to the url pattern tree as individual nodes, depending on type. -func (n *node) addChild(child *node, prefix string) *node { - search := prefix - - // handler leaf node added to the tree is the child. - // this may be overridden later down the flow - hn := child - - // Parse next segment - segTyp, _, segRexpat, segTail, segStartIdx, segEndIdx := patNextSegment(search) - - // Add child depending on next up segment - switch segTyp { - - case ntStatic: - // Search prefix is all static (that is, has no params in path) - // noop - - default: - // Search prefix contains a param, regexp or wildcard - - if segTyp == ntRegexp { - rex, err := regexp.Compile(segRexpat) - if err != nil { - panic(fmt.Sprintf("chi: invalid regexp pattern '%s' in route param", segRexpat)) - } - child.prefix = segRexpat - child.rex = rex - } - - if segStartIdx == 0 { - // Route starts with a param - child.typ = segTyp - - if segTyp == ntCatchAll { - segStartIdx = -1 - } else { - segStartIdx = segEndIdx - } - if segStartIdx < 0 { - segStartIdx = len(search) - } - child.tail = segTail // for params, we set the tail - - if segStartIdx != len(search) { - // add static edge for the remaining part, split the end. - // its not possible to have adjacent param nodes, so its certainly - // going to be a static node next. - - search = search[segStartIdx:] // advance search position - - nn := &node{ - typ: ntStatic, - label: search[0], - prefix: search, - } - hn = child.addChild(nn, search) - } - - } else if segStartIdx > 0 { - // Route has some param - - // starts with a static segment - child.typ = ntStatic - child.prefix = search[:segStartIdx] - child.rex = nil - - // add the param edge node - search = search[segStartIdx:] - - nn := &node{ - typ: segTyp, - label: search[0], - tail: segTail, - } - hn = child.addChild(nn, search) - - } - } - - n.children[child.typ] = append(n.children[child.typ], child) - n.children[child.typ].Sort() - return hn -} - -func (n *node) replaceChild(label, tail byte, child *node) { - for i := 0; i < len(n.children[child.typ]); i++ { - if n.children[child.typ][i].label == label && n.children[child.typ][i].tail == tail { - n.children[child.typ][i] = child - n.children[child.typ][i].label = label - n.children[child.typ][i].tail = tail - return - } - } - panic("chi: replacing missing child") -} - -func (n *node) getEdge(ntyp nodeTyp, label, tail byte, prefix string) *node { - nds := n.children[ntyp] - for i := 0; i < len(nds); i++ { - if nds[i].label == label && nds[i].tail == tail { - if ntyp == ntRegexp && nds[i].prefix != prefix { - continue - } - return nds[i] - } - } - return nil -} - -func (n *node) setEndpoint(method methodTyp, handler http.Handler, pattern string) { - // Set the handler for the method type on the node - if n.endpoints == nil { - n.endpoints = make(endpoints) - } - - paramKeys := patParamKeys(pattern) - - if method&mSTUB == mSTUB { - n.endpoints.Value(mSTUB).handler = handler - } - if method&mALL == mALL { - h := n.endpoints.Value(mALL) - h.handler = handler - h.pattern = pattern - h.paramKeys = paramKeys - for _, m := range methodMap { - h := n.endpoints.Value(m) - h.handler = handler - h.pattern = pattern - h.paramKeys = paramKeys - } - } else { - h := n.endpoints.Value(method) - h.handler = handler - h.pattern = pattern - h.paramKeys = paramKeys - } -} - -func (n *node) FindRoute(rctx *Context, method methodTyp, path string) (*node, endpoints, http.Handler) { - // Reset the context routing pattern and params - rctx.routePattern = "" - rctx.routeParams.Keys = rctx.routeParams.Keys[:0] - rctx.routeParams.Values = rctx.routeParams.Values[:0] - - // Find the routing handlers for the path - rn := n.findRoute(rctx, method, path) - if rn == nil { - return nil, nil, nil - } - - // Record the routing params in the request lifecycle - rctx.URLParams.Keys = append(rctx.URLParams.Keys, rctx.routeParams.Keys...) - rctx.URLParams.Values = append(rctx.URLParams.Values, rctx.routeParams.Values...) - - // Record the routing pattern in the request lifecycle - if rn.endpoints[method].pattern != "" { - rctx.routePattern = rn.endpoints[method].pattern - rctx.RoutePatterns = append(rctx.RoutePatterns, rctx.routePattern) - } - - return rn, rn.endpoints, rn.endpoints[method].handler -} - -// Recursive edge traversal by checking all nodeTyp groups along the way. -// It's like searching through a multi-dimensional radix trie. -func (n *node) findRoute(rctx *Context, method methodTyp, path string) *node { - nn := n - search := path - - for t, nds := range nn.children { - ntyp := nodeTyp(t) - if len(nds) == 0 { - continue - } - - var xn *node - xsearch := search - - var label byte - if search != "" { - label = search[0] - } - - switch ntyp { - case ntStatic: - xn = nds.findEdge(label) - if xn == nil || !strings.HasPrefix(xsearch, xn.prefix) { - continue - } - xsearch = xsearch[len(xn.prefix):] - - case ntParam, ntRegexp: - // short-circuit and return no matching route for empty param values - if xsearch == "" { - continue - } - - // serially loop through each node grouped by the tail delimiter - for idx := 0; idx < len(nds); idx++ { - xn = nds[idx] - - // label for param nodes is the delimiter byte - p := strings.IndexByte(xsearch, xn.tail) - - if p < 0 { - if xn.tail == '/' { - p = len(xsearch) - } else { - continue - } - } else if ntyp == ntRegexp && p == 0 { - continue - } - - if ntyp == ntRegexp && xn.rex != nil { - if !xn.rex.MatchString(xsearch[:p]) { - continue - } - } else if strings.IndexByte(xsearch[:p], '/') != -1 { - // avoid a match across path segments - continue - } - - prevlen := len(rctx.routeParams.Values) - rctx.routeParams.Values = append(rctx.routeParams.Values, xsearch[:p]) - xsearch = xsearch[p:] - - if len(xsearch) == 0 { - if xn.isLeaf() { - h := xn.endpoints[method] - if h != nil && h.handler != nil { - rctx.routeParams.Keys = append(rctx.routeParams.Keys, h.paramKeys...) - return xn - } - - for endpoints := range xn.endpoints { - if endpoints == mALL || endpoints == mSTUB { - continue - } - rctx.methodsAllowed = append(rctx.methodsAllowed, endpoints) - } - - // flag that the routing context found a route, but not a corresponding - // supported method - rctx.methodNotAllowed = true - } - } - - // recursively find the next node on this branch - fin := xn.findRoute(rctx, method, xsearch) - if fin != nil { - return fin - } - - // not found on this branch, reset vars - rctx.routeParams.Values = rctx.routeParams.Values[:prevlen] - xsearch = search - } - - rctx.routeParams.Values = append(rctx.routeParams.Values, "") - - default: - // catch-all nodes - rctx.routeParams.Values = append(rctx.routeParams.Values, search) - xn = nds[0] - xsearch = "" - } - - if xn == nil { - continue - } - - // did we find it yet? - if len(xsearch) == 0 { - if xn.isLeaf() { - h := xn.endpoints[method] - if h != nil && h.handler != nil { - rctx.routeParams.Keys = append(rctx.routeParams.Keys, h.paramKeys...) - return xn - } - - for endpoints := range xn.endpoints { - if endpoints == mALL || endpoints == mSTUB { - continue - } - rctx.methodsAllowed = append(rctx.methodsAllowed, endpoints) - } - - // flag that the routing context found a route, but not a corresponding - // supported method - rctx.methodNotAllowed = true - } - } - - // recursively find the next node.. - fin := xn.findRoute(rctx, method, xsearch) - if fin != nil { - return fin - } - - // Did not find final handler, let's remove the param here if it was set - if xn.typ > ntStatic { - if len(rctx.routeParams.Values) > 0 { - rctx.routeParams.Values = rctx.routeParams.Values[:len(rctx.routeParams.Values)-1] - } - } - - } - - return nil -} - -func (n *node) findEdge(ntyp nodeTyp, label byte) *node { - nds := n.children[ntyp] - num := len(nds) - idx := 0 - - switch ntyp { - case ntStatic, ntParam, ntRegexp: - i, j := 0, num-1 - for i <= j { - idx = i + (j-i)/2 - if label > nds[idx].label { - i = idx + 1 - } else if label < nds[idx].label { - j = idx - 1 - } else { - i = num // breaks cond - } - } - if nds[idx].label != label { - return nil - } - return nds[idx] - - default: // catch all - return nds[idx] - } -} - -func (n *node) isLeaf() bool { - return n.endpoints != nil -} - -func (n *node) findPattern(pattern string) bool { - nn := n - for _, nds := range nn.children { - if len(nds) == 0 { - continue - } - - n = nn.findEdge(nds[0].typ, pattern[0]) - if n == nil { - continue - } - - var idx int - var xpattern string - - switch n.typ { - case ntStatic: - idx = longestPrefix(pattern, n.prefix) - if idx < len(n.prefix) { - continue - } - - case ntParam, ntRegexp: - idx = strings.IndexByte(pattern, '}') + 1 - - case ntCatchAll: - idx = longestPrefix(pattern, "*") - - default: - panic("chi: unknown node type") - } - - xpattern = pattern[idx:] - if len(xpattern) == 0 { - return true - } - - return n.findPattern(xpattern) - } - return false -} - -func (n *node) routes() []Route { - rts := []Route{} - - n.walk(func(eps endpoints, subroutes Routes) bool { - if eps[mSTUB] != nil && eps[mSTUB].handler != nil && subroutes == nil { - return false - } - - // Group methodHandlers by unique patterns - pats := make(map[string]endpoints) - - for mt, h := range eps { - if h.pattern == "" { - continue - } - p, ok := pats[h.pattern] - if !ok { - p = endpoints{} - pats[h.pattern] = p - } - p[mt] = h - } - - for p, mh := range pats { - hs := make(map[string]http.Handler) - if mh[mALL] != nil && mh[mALL].handler != nil { - hs["*"] = mh[mALL].handler - } - - for mt, h := range mh { - if h.handler == nil { - continue - } - m := methodTypString(mt) - if m == "" { - continue - } - hs[m] = h.handler - } - - rt := Route{subroutes, hs, p} - rts = append(rts, rt) - } - - return false - }) - - return rts -} - -func (n *node) walk(fn func(eps endpoints, subroutes Routes) bool) bool { - // Visit the leaf values if any - if (n.endpoints != nil || n.subroutes != nil) && fn(n.endpoints, n.subroutes) { - return true - } - - // Recurse on the children - for _, ns := range n.children { - for _, cn := range ns { - if cn.walk(fn) { - return true - } - } - } - return false -} - -// patNextSegment returns the next segment details from a pattern: -// node type, param key, regexp string, param tail byte, param starting index, param ending index -func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) { - ps := strings.Index(pattern, "{") - ws := strings.Index(pattern, "*") - - if ps < 0 && ws < 0 { - return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing - } - - // Sanity check - if ps >= 0 && ws >= 0 && ws < ps { - panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'") - } - - var tail byte = '/' // Default endpoint tail to / byte - - if ps >= 0 { - // Param/Regexp pattern is next - nt := ntParam - - // Read to closing } taking into account opens and closes in curl count (cc) - cc := 0 - pe := ps - for i, c := range pattern[ps:] { - if c == '{' { - cc++ - } else if c == '}' { - cc-- - if cc == 0 { - pe = ps + i - break - } - } - } - if pe == ps { - panic("chi: route param closing delimiter '}' is missing") - } - - key := pattern[ps+1 : pe] - pe++ // set end to next position - - if pe < len(pattern) { - tail = pattern[pe] - } - - var rexpat string - if idx := strings.Index(key, ":"); idx >= 0 { - nt = ntRegexp - rexpat = key[idx+1:] - key = key[:idx] - } - - if len(rexpat) > 0 { - if rexpat[0] != '^' { - rexpat = "^" + rexpat - } - if rexpat[len(rexpat)-1] != '$' { - rexpat += "$" - } - } - - return nt, key, rexpat, tail, ps, pe - } - - // Wildcard pattern as finale - if ws < len(pattern)-1 { - panic("chi: wildcard '*' must be the last value in a route. trim trailing text or use a '{param}' instead") - } - return ntCatchAll, "*", "", 0, ws, len(pattern) -} - -func patParamKeys(pattern string) []string { - pat := pattern - paramKeys := []string{} - for { - ptyp, paramKey, _, _, _, e := patNextSegment(pat) - if ptyp == ntStatic { - return paramKeys - } - for i := 0; i < len(paramKeys); i++ { - if paramKeys[i] == paramKey { - panic(fmt.Sprintf("chi: routing pattern '%s' contains duplicate param key, '%s'", pattern, paramKey)) - } - } - paramKeys = append(paramKeys, paramKey) - pat = pat[e:] - } -} - -// longestPrefix finds the length of the shared prefix -// of two strings -func longestPrefix(k1, k2 string) int { - max := len(k1) - if l := len(k2); l < max { - max = l - } - var i int - for i = 0; i < max; i++ { - if k1[i] != k2[i] { - break - } - } - return i -} - -func methodTypString(method methodTyp) string { - for s, t := range methodMap { - if method == t { - return s - } - } - return "" -} - -type nodes []*node - -// Sort the list of nodes by label -func (ns nodes) Sort() { sort.Sort(ns); ns.tailSort() } -func (ns nodes) Len() int { return len(ns) } -func (ns nodes) Swap(i, j int) { ns[i], ns[j] = ns[j], ns[i] } -func (ns nodes) Less(i, j int) bool { return ns[i].label < ns[j].label } - -// tailSort pushes nodes with '/' as the tail to the end of the list for param nodes. -// The list order determines the traversal order. -func (ns nodes) tailSort() { - for i := len(ns) - 1; i >= 0; i-- { - if ns[i].typ > ntStatic && ns[i].tail == '/' { - ns.Swap(i, len(ns)-1) - return - } - } -} - -func (ns nodes) findEdge(label byte) *node { - num := len(ns) - idx := 0 - i, j := 0, num-1 - for i <= j { - idx = i + (j-i)/2 - if label > ns[idx].label { - i = idx + 1 - } else if label < ns[idx].label { - j = idx - 1 - } else { - i = num // breaks cond - } - } - if ns[idx].label != label { - return nil - } - return ns[idx] -} - -// Route describes the details of a routing handler. -// Handlers map key is an HTTP method -type Route struct { - SubRoutes Routes - Handlers map[string]http.Handler - Pattern string -} - -// WalkFunc is the type of the function called for each method and route visited by Walk. -type WalkFunc func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error - -// Walk walks any router tree that implements Routes interface. -func Walk(r Routes, walkFn WalkFunc) error { - return walk(r, walkFn, "") -} - -func walk(r Routes, walkFn WalkFunc, parentRoute string, parentMw ...func(http.Handler) http.Handler) error { - for _, route := range r.Routes() { - mws := make([]func(http.Handler) http.Handler, len(parentMw)) - copy(mws, parentMw) - mws = append(mws, r.Middlewares()...) - - if route.SubRoutes != nil { - if err := walk(route.SubRoutes, walkFn, parentRoute+route.Pattern, mws...); err != nil { - return err - } - continue - } - - for method, handler := range route.Handlers { - if method == "*" { - // Ignore a "catchAll" method, since we pass down all the specific methods for each route. - continue - } - - fullRoute := parentRoute + route.Pattern - fullRoute = strings.Replace(fullRoute, "/*/", "/", -1) - - if chain, ok := handler.(*ChainHandler); ok { - if err := walkFn(method, fullRoute, chain.Endpoint, append(mws, chain.Middlewares...)...); err != nil { - return err - } - } else { - if err := walkFn(method, fullRoute, handler, mws...); err != nil { - return err - } - } - } - } - - return nil -} diff --git a/vendor/github.com/go-kit/kit/LICENSE b/vendor/github.com/go-kit/kit/LICENSE deleted file mode 100644 index 9d83342a..00000000 --- a/vendor/github.com/go-kit/kit/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Peter Bourgon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/github.com/go-kit/kit/endpoint/doc.go b/vendor/github.com/go-kit/kit/endpoint/doc.go deleted file mode 100644 index 84e27b95..00000000 --- a/vendor/github.com/go-kit/kit/endpoint/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package endpoint defines an abstraction for RPCs. -// -// Endpoints are a fundamental building block for many Go kit components. -// Endpoints are implemented by servers, and called by clients. -package endpoint diff --git a/vendor/github.com/go-kit/kit/endpoint/endpoint.go b/vendor/github.com/go-kit/kit/endpoint/endpoint.go deleted file mode 100644 index 6e9da367..00000000 --- a/vendor/github.com/go-kit/kit/endpoint/endpoint.go +++ /dev/null @@ -1,40 +0,0 @@ -package endpoint - -import ( - "context" -) - -// Endpoint is the fundamental building block of servers and clients. -// It represents a single RPC method. -type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error) - -// Nop is an endpoint that does nothing and returns a nil error. -// Useful for tests. -func Nop(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil } - -// Middleware is a chainable behavior modifier for endpoints. -type Middleware func(Endpoint) Endpoint - -// Chain is a helper function for composing middlewares. Requests will -// traverse them in the order they're declared. That is, the first middleware -// is treated as the outermost middleware. -func Chain(outer Middleware, others ...Middleware) Middleware { - return func(next Endpoint) Endpoint { - for i := len(others) - 1; i >= 0; i-- { // reverse - next = others[i](next) - } - return outer(next) - } -} - -// Failer may be implemented by Go kit response types that contain business -// logic error details. If Failed returns a non-nil error, the Go kit transport -// layer may interpret this as a business logic error, and may encode it -// differently than a regular, successful response. -// -// It's not necessary for your response types to implement Failer, but it may -// help for more sophisticated use cases. The addsvc example shows how Failer -// should be used by a complete application. -type Failer interface { - Failed() error -} diff --git a/vendor/github.com/go-kit/kit/metrics/README.md b/vendor/github.com/go-kit/kit/metrics/README.md deleted file mode 100644 index 5aa791a7..00000000 --- a/vendor/github.com/go-kit/kit/metrics/README.md +++ /dev/null @@ -1,98 +0,0 @@ -# package metrics - -`package metrics` provides a set of uniform interfaces for service instrumentation. -It has - [counters](http://prometheus.io/docs/concepts/metric_types/#counter), - [gauges](http://prometheus.io/docs/concepts/metric_types/#gauge), and - [histograms](http://prometheus.io/docs/concepts/metric_types/#histogram), -and provides adapters to popular metrics packages, like - [expvar](https://golang.org/pkg/expvar), - [StatsD](https://github.com/etsy/statsd), and - [Prometheus](https://prometheus.io). - -## Rationale - -Code instrumentation is absolutely essential to achieve - [observability](https://speakerdeck.com/mattheath/observability-in-micro-service-architectures) - into a distributed system. -Metrics and instrumentation tools have coalesced around a few well-defined idioms. -`package metrics` provides a common, minimal interface those idioms for service authors. - -## Usage - -A simple counter, exported via expvar. - -```go -import ( - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/expvar" -) - -func main() { - var myCount metrics.Counter - myCount = expvar.NewCounter("my_count") - myCount.Add(1) -} -``` - -A histogram for request duration, - exported via a Prometheus summary with dynamically-computed quantiles. - -```go -import ( - "time" - - stdprometheus "github.com/prometheus/client_golang/prometheus" - - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/prometheus" -) - -func main() { - var dur metrics.Histogram = prometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ - Namespace: "myservice", - Subsystem: "api", - Name: "request_duration_seconds", - Help: "Total time spent serving requests.", - }, []string{}) - // ... -} - -func handleRequest(dur metrics.Histogram) { - defer func(begin time.Time) { dur.Observe(time.Since(begin).Seconds()) }(time.Now()) - // handle request -} -``` - -A gauge for the number of goroutines currently running, exported via StatsD. - -```go -import ( - "context" - "net" - "os" - "runtime" - "time" - - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/statsd" -) - -func main() { - statsd := statsd.New("foo_svc.", log.NewNopLogger()) - report := time.NewTicker(5 * time.Second) - defer report.Stop() - go statsd.SendLoop(context.Background(), report.C, "tcp", "statsd.internal:8125") - goroutines := statsd.NewGauge("goroutine_count") - go exportGoroutines(goroutines) - // ... -} - -func exportGoroutines(g metrics.Gauge) { - for range time.Tick(time.Second) { - g.Set(float64(runtime.NumGoroutine())) - } -} -``` - -For more information, see [the package documentation](https://godoc.org/github.com/go-kit/kit/metrics). diff --git a/vendor/github.com/go-kit/kit/metrics/doc.go b/vendor/github.com/go-kit/kit/metrics/doc.go deleted file mode 100644 index 25cda4f7..00000000 --- a/vendor/github.com/go-kit/kit/metrics/doc.go +++ /dev/null @@ -1,97 +0,0 @@ -// Package metrics provides a framework for application instrumentation. It's -// primarily designed to help you get started with good and robust -// instrumentation, and to help you migrate from a less-capable system like -// Graphite to a more-capable system like Prometheus. If your organization has -// already standardized on an instrumentation system like Prometheus, and has no -// plans to change, it may make sense to use that system's instrumentation -// library directly. -// -// This package provides three core metric abstractions (Counter, Gauge, and -// Histogram) and implementations for almost all common instrumentation -// backends. Each metric has an observation method (Add, Set, or Observe, -// respectively) used to record values, and a With method to "scope" the -// observation by various parameters. For example, you might have a Histogram to -// record request durations, parameterized by the method that's being called. -// -// var requestDuration metrics.Histogram -// // ... -// requestDuration.With("method", "MyMethod").Observe(time.Since(begin)) -// -// This allows a single high-level metrics object (requestDuration) to work with -// many code paths somewhat dynamically. The concept of With is fully supported -// in some backends like Prometheus, and not supported in other backends like -// Graphite. So, With may be a no-op, depending on the concrete implementation -// you choose. Please check the implementation to know for sure. For -// implementations that don't provide With, it's necessary to fully parameterize -// each metric in the metric name, e.g. -// -// // Statsd -// c := statsd.NewCounter("request_duration_MyMethod_200") -// c.Add(1) -// -// // Prometheus -// c := prometheus.NewCounter(stdprometheus.CounterOpts{ -// Name: "request_duration", -// ... -// }, []string{"method", "status_code"}) -// c.With("method", "MyMethod", "status_code", strconv.Itoa(code)).Add(1) -// -// Usage -// -// Metrics are dependencies, and should be passed to the components that need -// them in the same way you'd construct and pass a database handle, or reference -// to another component. Metrics should *not* be created in the global scope. -// Instead, instantiate metrics in your func main, using whichever concrete -// implementation is appropriate for your organization. -// -// latency := prometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ -// Namespace: "myteam", -// Subsystem: "foosvc", -// Name: "request_latency_seconds", -// Help: "Incoming request latency in seconds.", -// }, []string{"method", "status_code"}) -// -// Write your components to take the metrics they will use as parameters to -// their constructors. Use the interface types, not the concrete types. That is, -// -// // NewAPI takes metrics.Histogram, not *prometheus.Summary -// func NewAPI(s Store, logger log.Logger, latency metrics.Histogram) *API { -// // ... -// } -// -// func (a *API) ServeFoo(w http.ResponseWriter, r *http.Request) { -// begin := time.Now() -// // ... -// a.latency.Observe(time.Since(begin).Seconds()) -// } -// -// Finally, pass the metrics as dependencies when building your object graph. -// This should happen in func main, not in the global scope. -// -// api := NewAPI(store, logger, latency) -// http.ListenAndServe("/", api) -// -// Note that metrics are "write-only" interfaces. -// -// Implementation details -// -// All metrics are safe for concurrent use. Considerable design influence has -// been taken from https://github.com/codahale/metrics and -// https://prometheus.io. -// -// Each telemetry system has different semantics for label values, push vs. -// pull, support for histograms, etc. These properties influence the design of -// their respective packages. This table attempts to summarize the key points of -// distinction. -// -// SYSTEM DIM COUNTERS GAUGES HISTOGRAMS -// dogstatsd n batch, push-aggregate batch, push-aggregate native, batch, push-each -// statsd 1 batch, push-aggregate batch, push-aggregate native, batch, push-each -// graphite 1 batch, push-aggregate batch, push-aggregate synthetic, batch, push-aggregate -// expvar 1 atomic atomic synthetic, batch, in-place expose -// influx n custom custom custom -// prometheus n native native native -// pcp 1 native native native -// cloudwatch n batch push-aggregate batch push-aggregate synthetic, batch, push-aggregate -// -package metrics diff --git a/vendor/github.com/go-kit/kit/metrics/internal/lv/labelvalues.go b/vendor/github.com/go-kit/kit/metrics/internal/lv/labelvalues.go deleted file mode 100644 index 8bb1ba09..00000000 --- a/vendor/github.com/go-kit/kit/metrics/internal/lv/labelvalues.go +++ /dev/null @@ -1,14 +0,0 @@ -package lv - -// LabelValues is a type alias that provides validation on its With method. -// Metrics may include it as a member to help them satisfy With semantics and -// save some code duplication. -type LabelValues []string - -// With validates the input, and returns a new aggregate labelValues. -func (lvs LabelValues) With(labelValues ...string) LabelValues { - if len(labelValues)%2 != 0 { - labelValues = append(labelValues, "unknown") - } - return append(lvs, labelValues...) -} diff --git a/vendor/github.com/go-kit/kit/metrics/internal/lv/space.go b/vendor/github.com/go-kit/kit/metrics/internal/lv/space.go deleted file mode 100644 index 371964a3..00000000 --- a/vendor/github.com/go-kit/kit/metrics/internal/lv/space.go +++ /dev/null @@ -1,145 +0,0 @@ -package lv - -import "sync" - -// NewSpace returns an N-dimensional vector space. -func NewSpace() *Space { - return &Space{} -} - -// Space represents an N-dimensional vector space. Each name and unique label -// value pair establishes a new dimension and point within that dimension. Order -// matters, i.e. [a=1 b=2] identifies a different timeseries than [b=2 a=1]. -type Space struct { - mtx sync.RWMutex - nodes map[string]*node -} - -// Observe locates the time series identified by the name and label values in -// the vector space, and appends the value to the list of observations. -func (s *Space) Observe(name string, lvs LabelValues, value float64) { - s.nodeFor(name).observe(lvs, value) -} - -// Add locates the time series identified by the name and label values in -// the vector space, and appends the delta to the last value in the list of -// observations. -func (s *Space) Add(name string, lvs LabelValues, delta float64) { - s.nodeFor(name).add(lvs, delta) -} - -// Walk traverses the vector space and invokes fn for each non-empty time series -// which is encountered. Return false to abort the traversal. -func (s *Space) Walk(fn func(name string, lvs LabelValues, observations []float64) bool) { - s.mtx.RLock() - defer s.mtx.RUnlock() - for name, node := range s.nodes { - f := func(lvs LabelValues, observations []float64) bool { return fn(name, lvs, observations) } - if !node.walk(LabelValues{}, f) { - return - } - } -} - -// Reset empties the current space and returns a new Space with the old -// contents. Reset a Space to get an immutable copy suitable for walking. -func (s *Space) Reset() *Space { - s.mtx.Lock() - defer s.mtx.Unlock() - n := NewSpace() - n.nodes, s.nodes = s.nodes, n.nodes - return n -} - -func (s *Space) nodeFor(name string) *node { - s.mtx.Lock() - defer s.mtx.Unlock() - if s.nodes == nil { - s.nodes = map[string]*node{} - } - n, ok := s.nodes[name] - if !ok { - n = &node{} - s.nodes[name] = n - } - return n -} - -// node exists at a specific point in the N-dimensional vector space of all -// possible label values. The node collects observations and has child nodes -// with greater specificity. -type node struct { - mtx sync.RWMutex - observations []float64 - children map[pair]*node -} - -type pair struct{ label, value string } - -func (n *node) observe(lvs LabelValues, value float64) { - n.mtx.Lock() - defer n.mtx.Unlock() - if len(lvs) <= 0 { - n.observations = append(n.observations, value) - return - } - if len(lvs) < 2 { - panic("too few LabelValues; programmer error!") - } - head, tail := pair{lvs[0], lvs[1]}, lvs[2:] - if n.children == nil { - n.children = map[pair]*node{} - } - child, ok := n.children[head] - if !ok { - child = &node{} - n.children[head] = child - } - child.observe(tail, value) -} - -func (n *node) add(lvs LabelValues, delta float64) { - n.mtx.Lock() - defer n.mtx.Unlock() - if len(lvs) <= 0 { - var value float64 - if len(n.observations) > 0 { - value = last(n.observations) + delta - } else { - value = delta - } - n.observations = append(n.observations, value) - return - } - if len(lvs) < 2 { - panic("too few LabelValues; programmer error!") - } - head, tail := pair{lvs[0], lvs[1]}, lvs[2:] - if n.children == nil { - n.children = map[pair]*node{} - } - child, ok := n.children[head] - if !ok { - child = &node{} - n.children[head] = child - } - child.add(tail, delta) -} - -func (n *node) walk(lvs LabelValues, fn func(LabelValues, []float64) bool) bool { - n.mtx.RLock() - defer n.mtx.RUnlock() - if len(n.observations) > 0 && !fn(lvs, n.observations) { - return false - } - for p, child := range n.children { - if !child.walk(append(lvs, p.label, p.value), fn) { - return false - } - } - return true -} - -func last(a []float64) float64 { - return a[len(a)-1] -} diff --git a/vendor/github.com/go-kit/kit/metrics/metrics.go b/vendor/github.com/go-kit/kit/metrics/metrics.go deleted file mode 100644 index a7ba1b1f..00000000 --- a/vendor/github.com/go-kit/kit/metrics/metrics.go +++ /dev/null @@ -1,25 +0,0 @@ -package metrics - -// Counter describes a metric that accumulates values monotonically. -// An example of a counter is the number of received HTTP requests. -type Counter interface { - With(labelValues ...string) Counter - Add(delta float64) -} - -// Gauge describes a metric that takes specific values over time. -// An example of a gauge is the current depth of a job queue. -type Gauge interface { - With(labelValues ...string) Gauge - Set(value float64) - Add(delta float64) -} - -// Histogram describes a metric that takes repeated observations of the same -// kind of thing, and produces a statistical summary of those observations, -// typically expressed as quantiles or buckets. An example of a histogram is -// HTTP request latencies. -type Histogram interface { - With(labelValues ...string) Histogram - Observe(value float64) -} diff --git a/vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go b/vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go deleted file mode 100644 index e94ad2a7..00000000 --- a/vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go +++ /dev/null @@ -1,165 +0,0 @@ -// Package prometheus provides Prometheus implementations for metrics. -// Individual metrics are mapped to their Prometheus counterparts, and -// (depending on the constructor used) may be automatically registered in the -// global Prometheus metrics registry. -package prometheus - -import ( - "github.com/prometheus/client_golang/prometheus" - - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/internal/lv" -) - -// Counter implements Counter, via a Prometheus CounterVec. -type Counter struct { - cv *prometheus.CounterVec - lvs lv.LabelValues -} - -// NewCounterFrom constructs and registers a Prometheus CounterVec, -// and returns a usable Counter object. -func NewCounterFrom(opts prometheus.CounterOpts, labelNames []string) *Counter { - cv := prometheus.NewCounterVec(opts, labelNames) - prometheus.MustRegister(cv) - return NewCounter(cv) -} - -// NewCounter wraps the CounterVec and returns a usable Counter object. -func NewCounter(cv *prometheus.CounterVec) *Counter { - return &Counter{ - cv: cv, - } -} - -// With implements Counter. -func (c *Counter) With(labelValues ...string) metrics.Counter { - return &Counter{ - cv: c.cv, - lvs: c.lvs.With(labelValues...), - } -} - -// Add implements Counter. -func (c *Counter) Add(delta float64) { - c.cv.With(makeLabels(c.lvs...)).Add(delta) -} - -// Gauge implements Gauge, via a Prometheus GaugeVec. -type Gauge struct { - gv *prometheus.GaugeVec - lvs lv.LabelValues -} - -// NewGaugeFrom constructs and registers a Prometheus GaugeVec, -// and returns a usable Gauge object. -func NewGaugeFrom(opts prometheus.GaugeOpts, labelNames []string) *Gauge { - gv := prometheus.NewGaugeVec(opts, labelNames) - prometheus.MustRegister(gv) - return NewGauge(gv) -} - -// NewGauge wraps the GaugeVec and returns a usable Gauge object. -func NewGauge(gv *prometheus.GaugeVec) *Gauge { - return &Gauge{ - gv: gv, - } -} - -// With implements Gauge. -func (g *Gauge) With(labelValues ...string) metrics.Gauge { - return &Gauge{ - gv: g.gv, - lvs: g.lvs.With(labelValues...), - } -} - -// Set implements Gauge. -func (g *Gauge) Set(value float64) { - g.gv.With(makeLabels(g.lvs...)).Set(value) -} - -// Add is supported by Prometheus GaugeVecs. -func (g *Gauge) Add(delta float64) { - g.gv.With(makeLabels(g.lvs...)).Add(delta) -} - -// Summary implements Histogram, via a Prometheus SummaryVec. The difference -// between a Summary and a Histogram is that Summaries don't require predefined -// quantile buckets, but cannot be statistically aggregated. -type Summary struct { - sv *prometheus.SummaryVec - lvs lv.LabelValues -} - -// NewSummaryFrom constructs and registers a Prometheus SummaryVec, -// and returns a usable Summary object. -func NewSummaryFrom(opts prometheus.SummaryOpts, labelNames []string) *Summary { - sv := prometheus.NewSummaryVec(opts, labelNames) - prometheus.MustRegister(sv) - return NewSummary(sv) -} - -// NewSummary wraps the SummaryVec and returns a usable Summary object. -func NewSummary(sv *prometheus.SummaryVec) *Summary { - return &Summary{ - sv: sv, - } -} - -// With implements Histogram. -func (s *Summary) With(labelValues ...string) metrics.Histogram { - return &Summary{ - sv: s.sv, - lvs: s.lvs.With(labelValues...), - } -} - -// Observe implements Histogram. -func (s *Summary) Observe(value float64) { - s.sv.With(makeLabels(s.lvs...)).Observe(value) -} - -// Histogram implements Histogram via a Prometheus HistogramVec. The difference -// between a Histogram and a Summary is that Histograms require predefined -// quantile buckets, and can be statistically aggregated. -type Histogram struct { - hv *prometheus.HistogramVec - lvs lv.LabelValues -} - -// NewHistogramFrom constructs and registers a Prometheus HistogramVec, -// and returns a usable Histogram object. -func NewHistogramFrom(opts prometheus.HistogramOpts, labelNames []string) *Histogram { - hv := prometheus.NewHistogramVec(opts, labelNames) - prometheus.MustRegister(hv) - return NewHistogram(hv) -} - -// NewHistogram wraps the HistogramVec and returns a usable Histogram object. -func NewHistogram(hv *prometheus.HistogramVec) *Histogram { - return &Histogram{ - hv: hv, - } -} - -// With implements Histogram. -func (h *Histogram) With(labelValues ...string) metrics.Histogram { - return &Histogram{ - hv: h.hv, - lvs: h.lvs.With(labelValues...), - } -} - -// Observe implements Histogram. -func (h *Histogram) Observe(value float64) { - h.hv.With(makeLabels(h.lvs...)).Observe(value) -} - -func makeLabels(labelValues ...string) prometheus.Labels { - labels := prometheus.Labels{} - for i := 0; i < len(labelValues); i += 2 { - labels[labelValues[i]] = labelValues[i+1] - } - return labels -} diff --git a/vendor/github.com/go-kit/kit/metrics/timer.go b/vendor/github.com/go-kit/kit/metrics/timer.go deleted file mode 100644 index e12d9cd5..00000000 --- a/vendor/github.com/go-kit/kit/metrics/timer.go +++ /dev/null @@ -1,36 +0,0 @@ -package metrics - -import "time" - -// Timer acts as a stopwatch, sending observations to a wrapped histogram. -// It's a bit of helpful syntax sugar for h.Observe(time.Since(x)). -type Timer struct { - h Histogram - t time.Time - u time.Duration -} - -// NewTimer wraps the given histogram and records the current time. -func NewTimer(h Histogram) *Timer { - return &Timer{ - h: h, - t: time.Now(), - u: time.Second, - } -} - -// ObserveDuration captures the number of seconds since the timer was -// constructed, and forwards that observation to the histogram. -func (t *Timer) ObserveDuration() { - d := float64(time.Since(t.t).Nanoseconds()) / float64(t.u) - if d < 0 { - d = 0 - } - t.h.Observe(d) -} - -// Unit sets the unit of the float64 emitted by the timer. -// By default, the timer emits seconds. -func (t *Timer) Unit(u time.Duration) { - t.u = u -} diff --git a/vendor/github.com/go-kit/kit/transport/doc.go b/vendor/github.com/go-kit/kit/transport/doc.go deleted file mode 100644 index f8382ae7..00000000 --- a/vendor/github.com/go-kit/kit/transport/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package transport contains helpers applicable to all supported transports. -package transport diff --git a/vendor/github.com/go-kit/kit/transport/error_handler.go b/vendor/github.com/go-kit/kit/transport/error_handler.go deleted file mode 100644 index 2456df18..00000000 --- a/vendor/github.com/go-kit/kit/transport/error_handler.go +++ /dev/null @@ -1,39 +0,0 @@ -package transport - -import ( - "context" - - "github.com/go-kit/log" -) - -// ErrorHandler receives a transport error to be processed for diagnostic purposes. -// Usually this means logging the error. -type ErrorHandler interface { - Handle(ctx context.Context, err error) -} - -// LogErrorHandler is a transport error handler implementation which logs an error. -type LogErrorHandler struct { - logger log.Logger -} - -func NewLogErrorHandler(logger log.Logger) *LogErrorHandler { - return &LogErrorHandler{ - logger: logger, - } -} - -func (h *LogErrorHandler) Handle(ctx context.Context, err error) { - h.logger.Log("err", err) -} - -// The ErrorHandlerFunc type is an adapter to allow the use of -// ordinary function as ErrorHandler. If f is a function -// with the appropriate signature, ErrorHandlerFunc(f) is a -// ErrorHandler that calls f. -type ErrorHandlerFunc func(ctx context.Context, err error) - -// Handle calls f(ctx, err). -func (f ErrorHandlerFunc) Handle(ctx context.Context, err error) { - f(ctx, err) -} diff --git a/vendor/github.com/go-kit/kit/transport/http/client.go b/vendor/github.com/go-kit/kit/transport/http/client.go deleted file mode 100644 index 7d868eee..00000000 --- a/vendor/github.com/go-kit/kit/transport/http/client.go +++ /dev/null @@ -1,219 +0,0 @@ -package http - -import ( - "bytes" - "context" - "encoding/json" - "encoding/xml" - "io" - "io/ioutil" - "net/http" - "net/url" - - "github.com/go-kit/kit/endpoint" -) - -// HTTPClient is an interface that models *http.Client. -type HTTPClient interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client wraps a URL and provides a method that implements endpoint.Endpoint. -type Client struct { - client HTTPClient - req CreateRequestFunc - dec DecodeResponseFunc - before []RequestFunc - after []ClientResponseFunc - finalizer []ClientFinalizerFunc - bufferedStream bool -} - -// NewClient constructs a usable Client for a single remote method. -func NewClient(method string, tgt *url.URL, enc EncodeRequestFunc, dec DecodeResponseFunc, options ...ClientOption) *Client { - return NewExplicitClient(makeCreateRequestFunc(method, tgt, enc), dec, options...) -} - -// NewExplicitClient is like NewClient but uses a CreateRequestFunc instead of a -// method, target URL, and EncodeRequestFunc, which allows for more control over -// the outgoing HTTP request. -func NewExplicitClient(req CreateRequestFunc, dec DecodeResponseFunc, options ...ClientOption) *Client { - c := &Client{ - client: http.DefaultClient, - req: req, - dec: dec, - } - for _, option := range options { - option(c) - } - return c -} - -// ClientOption sets an optional parameter for clients. -type ClientOption func(*Client) - -// SetClient sets the underlying HTTP client used for requests. -// By default, http.DefaultClient is used. -func SetClient(client HTTPClient) ClientOption { - return func(c *Client) { c.client = client } -} - -// ClientBefore adds one or more RequestFuncs to be applied to the outgoing HTTP -// request before it's invoked. -func ClientBefore(before ...RequestFunc) ClientOption { - return func(c *Client) { c.before = append(c.before, before...) } -} - -// ClientAfter adds one or more ClientResponseFuncs, which are applied to the -// incoming HTTP response prior to it being decoded. This is useful for -// obtaining anything off of the response and adding it into the context prior -// to decoding. -func ClientAfter(after ...ClientResponseFunc) ClientOption { - return func(c *Client) { c.after = append(c.after, after...) } -} - -// ClientFinalizer adds one or more ClientFinalizerFuncs to be executed at the -// end of every HTTP request. Finalizers are executed in the order in which they -// were added. By default, no finalizer is registered. -func ClientFinalizer(f ...ClientFinalizerFunc) ClientOption { - return func(s *Client) { s.finalizer = append(s.finalizer, f...) } -} - -// BufferedStream sets whether the HTTP response body is left open, allowing it -// to be read from later. Useful for transporting a file as a buffered stream. -// That body has to be drained and closed to properly end the request. -func BufferedStream(buffered bool) ClientOption { - return func(c *Client) { c.bufferedStream = buffered } -} - -// Endpoint returns a usable Go kit endpoint that calls the remote HTTP endpoint. -func (c Client) Endpoint() endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - ctx, cancel := context.WithCancel(ctx) - - var ( - resp *http.Response - err error - ) - if c.finalizer != nil { - defer func() { - if resp != nil { - ctx = context.WithValue(ctx, ContextKeyResponseHeaders, resp.Header) - ctx = context.WithValue(ctx, ContextKeyResponseSize, resp.ContentLength) - } - for _, f := range c.finalizer { - f(ctx, err) - } - }() - } - - req, err := c.req(ctx, request) - if err != nil { - cancel() - return nil, err - } - - for _, f := range c.before { - ctx = f(ctx, req) - } - - resp, err = c.client.Do(req.WithContext(ctx)) - if err != nil { - cancel() - return nil, err - } - - // If the caller asked for a buffered stream, we don't cancel the - // context when the endpoint returns. Instead, we should call the - // cancel func when closing the response body. - if c.bufferedStream { - resp.Body = bodyWithCancel{ReadCloser: resp.Body, cancel: cancel} - } else { - defer resp.Body.Close() - defer cancel() - } - - for _, f := range c.after { - ctx = f(ctx, resp) - } - - response, err := c.dec(ctx, resp) - if err != nil { - return nil, err - } - - return response, nil - } -} - -// bodyWithCancel is a wrapper for an io.ReadCloser with also a -// cancel function which is called when the Close is used -type bodyWithCancel struct { - io.ReadCloser - - cancel context.CancelFunc -} - -func (bwc bodyWithCancel) Close() error { - bwc.ReadCloser.Close() - bwc.cancel() - return nil -} - -// ClientFinalizerFunc can be used to perform work at the end of a client HTTP -// request, after the response is returned. The principal -// intended use is for error logging. Additional response parameters are -// provided in the context under keys with the ContextKeyResponse prefix. -// Note: err may be nil. There maybe also no additional response parameters -// depending on when an error occurs. -type ClientFinalizerFunc func(ctx context.Context, err error) - -// EncodeJSONRequest is an EncodeRequestFunc that serializes the request as a -// JSON object to the Request body. Many JSON-over-HTTP services can use it as -// a sensible default. If the request implements Headerer, the provided headers -// will be applied to the request. -func EncodeJSONRequest(c context.Context, r *http.Request, request interface{}) error { - r.Header.Set("Content-Type", "application/json; charset=utf-8") - if headerer, ok := request.(Headerer); ok { - for k := range headerer.Headers() { - r.Header.Set(k, headerer.Headers().Get(k)) - } - } - var b bytes.Buffer - r.Body = ioutil.NopCloser(&b) - return json.NewEncoder(&b).Encode(request) -} - -// EncodeXMLRequest is an EncodeRequestFunc that serializes the request as a -// XML object to the Request body. If the request implements Headerer, -// the provided headers will be applied to the request. -func EncodeXMLRequest(c context.Context, r *http.Request, request interface{}) error { - r.Header.Set("Content-Type", "text/xml; charset=utf-8") - if headerer, ok := request.(Headerer); ok { - for k := range headerer.Headers() { - r.Header.Set(k, headerer.Headers().Get(k)) - } - } - var b bytes.Buffer - r.Body = ioutil.NopCloser(&b) - return xml.NewEncoder(&b).Encode(request) -} - -// -// -// - -func makeCreateRequestFunc(method string, target *url.URL, enc EncodeRequestFunc) CreateRequestFunc { - return func(ctx context.Context, request interface{}) (*http.Request, error) { - req, err := http.NewRequest(method, target.String(), nil) - if err != nil { - return nil, err - } - - if err = enc(ctx, req, request); err != nil { - return nil, err - } - - return req, nil - } -} diff --git a/vendor/github.com/go-kit/kit/transport/http/doc.go b/vendor/github.com/go-kit/kit/transport/http/doc.go deleted file mode 100644 index e6401035..00000000 --- a/vendor/github.com/go-kit/kit/transport/http/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package http provides a general purpose HTTP binding for endpoints. -package http diff --git a/vendor/github.com/go-kit/kit/transport/http/encode_decode.go b/vendor/github.com/go-kit/kit/transport/http/encode_decode.go deleted file mode 100644 index b3de462b..00000000 --- a/vendor/github.com/go-kit/kit/transport/http/encode_decode.go +++ /dev/null @@ -1,36 +0,0 @@ -package http - -import ( - "context" - "net/http" -) - -// DecodeRequestFunc extracts a user-domain request object from an HTTP -// request object. It's designed to be used in HTTP servers, for server-side -// endpoints. One straightforward DecodeRequestFunc could be something that -// JSON decodes from the request body to the concrete request type. -type DecodeRequestFunc func(context.Context, *http.Request) (request interface{}, err error) - -// EncodeRequestFunc encodes the passed request object into the HTTP request -// object. It's designed to be used in HTTP clients, for client-side -// endpoints. One straightforward EncodeRequestFunc could be something that JSON -// encodes the object directly to the request body. -type EncodeRequestFunc func(context.Context, *http.Request, interface{}) error - -// CreateRequestFunc creates an outgoing HTTP request based on the passed -// request object. It's designed to be used in HTTP clients, for client-side -// endpoints. It's a more powerful version of EncodeRequestFunc, and can be used -// if more fine-grained control of the HTTP request is required. -type CreateRequestFunc func(context.Context, interface{}) (*http.Request, error) - -// EncodeResponseFunc encodes the passed response object to the HTTP response -// writer. It's designed to be used in HTTP servers, for server-side -// endpoints. One straightforward EncodeResponseFunc could be something that -// JSON encodes the object directly to the response body. -type EncodeResponseFunc func(context.Context, http.ResponseWriter, interface{}) error - -// DecodeResponseFunc extracts a user-domain response object from an HTTP -// response object. It's designed to be used in HTTP clients, for client-side -// endpoints. One straightforward DecodeResponseFunc could be something that -// JSON decodes from the response body to the concrete response type. -type DecodeResponseFunc func(context.Context, *http.Response) (response interface{}, err error) diff --git a/vendor/github.com/go-kit/kit/transport/http/intercepting_writer.go b/vendor/github.com/go-kit/kit/transport/http/intercepting_writer.go deleted file mode 100644 index 3737b6ea..00000000 --- a/vendor/github.com/go-kit/kit/transport/http/intercepting_writer.go +++ /dev/null @@ -1,257 +0,0 @@ -package http - -import ( - "io" - "net/http" -) - -type interceptingWriter struct { - http.ResponseWriter - code int - written int64 -} - -// WriteHeader may not be explicitly called, so care must be taken to -// initialize w.code to its default value of http.StatusOK. -func (w *interceptingWriter) WriteHeader(code int) { - w.code = code - w.ResponseWriter.WriteHeader(code) -} - -func (w *interceptingWriter) Write(p []byte) (int, error) { - n, err := w.ResponseWriter.Write(p) - w.written += int64(n) - return n, err -} - -// reimplementInterfaces returns a wrapped version of the embedded ResponseWriter -// and selectively implements the same combination of additional interfaces as -// the wrapped one. The interfaces it may implement are: http.Hijacker, -// http.CloseNotifier, http.Pusher, http.Flusher and io.ReaderFrom. The standard -// library is known to assert the existence of these interfaces and behaves -// differently. This implementation is derived from -// https://github.com/felixge/httpsnoop. -func (w *interceptingWriter) reimplementInterfaces() http.ResponseWriter { - var ( - hj, i0 = w.ResponseWriter.(http.Hijacker) - cn, i1 = w.ResponseWriter.(http.CloseNotifier) - pu, i2 = w.ResponseWriter.(http.Pusher) - fl, i3 = w.ResponseWriter.(http.Flusher) - rf, i4 = w.ResponseWriter.(io.ReaderFrom) - ) - - switch { - case !i0 && !i1 && !i2 && !i3 && !i4: - return struct { - http.ResponseWriter - }{w} - case !i0 && !i1 && !i2 && !i3 && i4: - return struct { - http.ResponseWriter - io.ReaderFrom - }{w, rf} - case !i0 && !i1 && !i2 && i3 && !i4: - return struct { - http.ResponseWriter - http.Flusher - }{w, fl} - case !i0 && !i1 && !i2 && i3 && i4: - return struct { - http.ResponseWriter - http.Flusher - io.ReaderFrom - }{w, fl, rf} - case !i0 && !i1 && i2 && !i3 && !i4: - return struct { - http.ResponseWriter - http.Pusher - }{w, pu} - case !i0 && !i1 && i2 && !i3 && i4: - return struct { - http.ResponseWriter - http.Pusher - io.ReaderFrom - }{w, pu, rf} - case !i0 && !i1 && i2 && i3 && !i4: - return struct { - http.ResponseWriter - http.Pusher - http.Flusher - }{w, pu, fl} - case !i0 && !i1 && i2 && i3 && i4: - return struct { - http.ResponseWriter - http.Pusher - http.Flusher - io.ReaderFrom - }{w, pu, fl, rf} - case !i0 && i1 && !i2 && !i3 && !i4: - return struct { - http.ResponseWriter - http.CloseNotifier - }{w, cn} - case !i0 && i1 && !i2 && !i3 && i4: - return struct { - http.ResponseWriter - http.CloseNotifier - io.ReaderFrom - }{w, cn, rf} - case !i0 && i1 && !i2 && i3 && !i4: - return struct { - http.ResponseWriter - http.CloseNotifier - http.Flusher - }{w, cn, fl} - case !i0 && i1 && !i2 && i3 && i4: - return struct { - http.ResponseWriter - http.CloseNotifier - http.Flusher - io.ReaderFrom - }{w, cn, fl, rf} - case !i0 && i1 && i2 && !i3 && !i4: - return struct { - http.ResponseWriter - http.CloseNotifier - http.Pusher - }{w, cn, pu} - case !i0 && i1 && i2 && !i3 && i4: - return struct { - http.ResponseWriter - http.CloseNotifier - http.Pusher - io.ReaderFrom - }{w, cn, pu, rf} - case !i0 && i1 && i2 && i3 && !i4: - return struct { - http.ResponseWriter - http.CloseNotifier - http.Pusher - http.Flusher - }{w, cn, pu, fl} - case !i0 && i1 && i2 && i3 && i4: - return struct { - http.ResponseWriter - http.CloseNotifier - http.Pusher - http.Flusher - io.ReaderFrom - }{w, cn, pu, fl, rf} - case i0 && !i1 && !i2 && !i3 && !i4: - return struct { - http.ResponseWriter - http.Hijacker - }{w, hj} - case i0 && !i1 && !i2 && !i3 && i4: - return struct { - http.ResponseWriter - http.Hijacker - io.ReaderFrom - }{w, hj, rf} - case i0 && !i1 && !i2 && i3 && !i4: - return struct { - http.ResponseWriter - http.Hijacker - http.Flusher - }{w, hj, fl} - case i0 && !i1 && !i2 && i3 && i4: - return struct { - http.ResponseWriter - http.Hijacker - http.Flusher - io.ReaderFrom - }{w, hj, fl, rf} - case i0 && !i1 && i2 && !i3 && !i4: - return struct { - http.ResponseWriter - http.Hijacker - http.Pusher - }{w, hj, pu} - case i0 && !i1 && i2 && !i3 && i4: - return struct { - http.ResponseWriter - http.Hijacker - http.Pusher - io.ReaderFrom - }{w, hj, pu, rf} - case i0 && !i1 && i2 && i3 && !i4: - return struct { - http.ResponseWriter - http.Hijacker - http.Pusher - http.Flusher - }{w, hj, pu, fl} - case i0 && !i1 && i2 && i3 && i4: - return struct { - http.ResponseWriter - http.Hijacker - http.Pusher - http.Flusher - io.ReaderFrom - }{w, hj, pu, fl, rf} - case i0 && i1 && !i2 && !i3 && !i4: - return struct { - http.ResponseWriter - http.Hijacker - http.CloseNotifier - }{w, hj, cn} - case i0 && i1 && !i2 && !i3 && i4: - return struct { - http.ResponseWriter - http.Hijacker - http.CloseNotifier - io.ReaderFrom - }{w, hj, cn, rf} - case i0 && i1 && !i2 && i3 && !i4: - return struct { - http.ResponseWriter - http.Hijacker - http.CloseNotifier - http.Flusher - }{w, hj, cn, fl} - case i0 && i1 && !i2 && i3 && i4: - return struct { - http.ResponseWriter - http.Hijacker - http.CloseNotifier - http.Flusher - io.ReaderFrom - }{w, hj, cn, fl, rf} - case i0 && i1 && i2 && !i3 && !i4: - return struct { - http.ResponseWriter - http.Hijacker - http.CloseNotifier - http.Pusher - }{w, hj, cn, pu} - case i0 && i1 && i2 && !i3 && i4: - return struct { - http.ResponseWriter - http.Hijacker - http.CloseNotifier - http.Pusher - io.ReaderFrom - }{w, hj, cn, pu, rf} - case i0 && i1 && i2 && i3 && !i4: - return struct { - http.ResponseWriter - http.Hijacker - http.CloseNotifier - http.Pusher - http.Flusher - }{w, hj, cn, pu, fl} - case i0 && i1 && i2 && i3 && i4: - return struct { - http.ResponseWriter - http.Hijacker - http.CloseNotifier - http.Pusher - http.Flusher - io.ReaderFrom - }{w, hj, cn, pu, fl, rf} - default: - return struct { - http.ResponseWriter - }{w} - } -} diff --git a/vendor/github.com/go-kit/kit/transport/http/request_response_funcs.go b/vendor/github.com/go-kit/kit/transport/http/request_response_funcs.go deleted file mode 100644 index 8f92b3bc..00000000 --- a/vendor/github.com/go-kit/kit/transport/http/request_response_funcs.go +++ /dev/null @@ -1,133 +0,0 @@ -package http - -import ( - "context" - "net/http" -) - -// RequestFunc may take information from an HTTP request and put it into a -// request context. In Servers, RequestFuncs are executed prior to invoking the -// endpoint. In Clients, RequestFuncs are executed after creating the request -// but prior to invoking the HTTP client. -type RequestFunc func(context.Context, *http.Request) context.Context - -// ServerResponseFunc may take information from a request context and use it to -// manipulate a ResponseWriter. ServerResponseFuncs are only executed in -// servers, after invoking the endpoint but prior to writing a response. -type ServerResponseFunc func(context.Context, http.ResponseWriter) context.Context - -// ClientResponseFunc may take information from an HTTP request and make the -// response available for consumption. ClientResponseFuncs are only executed in -// clients, after a request has been made, but prior to it being decoded. -type ClientResponseFunc func(context.Context, *http.Response) context.Context - -// SetContentType returns a ServerResponseFunc that sets the Content-Type header -// to the provided value. -func SetContentType(contentType string) ServerResponseFunc { - return SetResponseHeader("Content-Type", contentType) -} - -// SetResponseHeader returns a ServerResponseFunc that sets the given header. -func SetResponseHeader(key, val string) ServerResponseFunc { - return func(ctx context.Context, w http.ResponseWriter) context.Context { - w.Header().Set(key, val) - return ctx - } -} - -// SetRequestHeader returns a RequestFunc that sets the given header. -func SetRequestHeader(key, val string) RequestFunc { - return func(ctx context.Context, r *http.Request) context.Context { - r.Header.Set(key, val) - return ctx - } -} - -// PopulateRequestContext is a RequestFunc that populates several values into -// the context from the HTTP request. Those values may be extracted using the -// corresponding ContextKey type in this package. -func PopulateRequestContext(ctx context.Context, r *http.Request) context.Context { - for k, v := range map[contextKey]string{ - ContextKeyRequestMethod: r.Method, - ContextKeyRequestURI: r.RequestURI, - ContextKeyRequestPath: r.URL.Path, - ContextKeyRequestProto: r.Proto, - ContextKeyRequestHost: r.Host, - ContextKeyRequestRemoteAddr: r.RemoteAddr, - ContextKeyRequestXForwardedFor: r.Header.Get("X-Forwarded-For"), - ContextKeyRequestXForwardedProto: r.Header.Get("X-Forwarded-Proto"), - ContextKeyRequestAuthorization: r.Header.Get("Authorization"), - ContextKeyRequestReferer: r.Header.Get("Referer"), - ContextKeyRequestUserAgent: r.Header.Get("User-Agent"), - ContextKeyRequestXRequestID: r.Header.Get("X-Request-Id"), - ContextKeyRequestAccept: r.Header.Get("Accept"), - } { - ctx = context.WithValue(ctx, k, v) - } - return ctx -} - -type contextKey int - -const ( - // ContextKeyRequestMethod is populated in the context by - // PopulateRequestContext. Its value is r.Method. - ContextKeyRequestMethod contextKey = iota - - // ContextKeyRequestURI is populated in the context by - // PopulateRequestContext. Its value is r.RequestURI. - ContextKeyRequestURI - - // ContextKeyRequestPath is populated in the context by - // PopulateRequestContext. Its value is r.URL.Path. - ContextKeyRequestPath - - // ContextKeyRequestProto is populated in the context by - // PopulateRequestContext. Its value is r.Proto. - ContextKeyRequestProto - - // ContextKeyRequestHost is populated in the context by - // PopulateRequestContext. Its value is r.Host. - ContextKeyRequestHost - - // ContextKeyRequestRemoteAddr is populated in the context by - // PopulateRequestContext. Its value is r.RemoteAddr. - ContextKeyRequestRemoteAddr - - // ContextKeyRequestXForwardedFor is populated in the context by - // PopulateRequestContext. Its value is r.Header.Get("X-Forwarded-For"). - ContextKeyRequestXForwardedFor - - // ContextKeyRequestXForwardedProto is populated in the context by - // PopulateRequestContext. Its value is r.Header.Get("X-Forwarded-Proto"). - ContextKeyRequestXForwardedProto - - // ContextKeyRequestAuthorization is populated in the context by - // PopulateRequestContext. Its value is r.Header.Get("Authorization"). - ContextKeyRequestAuthorization - - // ContextKeyRequestReferer is populated in the context by - // PopulateRequestContext. Its value is r.Header.Get("Referer"). - ContextKeyRequestReferer - - // ContextKeyRequestUserAgent is populated in the context by - // PopulateRequestContext. Its value is r.Header.Get("User-Agent"). - ContextKeyRequestUserAgent - - // ContextKeyRequestXRequestID is populated in the context by - // PopulateRequestContext. Its value is r.Header.Get("X-Request-Id"). - ContextKeyRequestXRequestID - - // ContextKeyRequestAccept is populated in the context by - // PopulateRequestContext. Its value is r.Header.Get("Accept"). - ContextKeyRequestAccept - - // ContextKeyResponseHeaders is populated in the context whenever a - // ServerFinalizerFunc is specified. Its value is of type http.Header, and - // is captured only once the entire response has been written. - ContextKeyResponseHeaders - - // ContextKeyResponseSize is populated in the context whenever a - // ServerFinalizerFunc is specified. Its value is of type int64. - ContextKeyResponseSize -) diff --git a/vendor/github.com/go-kit/kit/transport/http/server.go b/vendor/github.com/go-kit/kit/transport/http/server.go deleted file mode 100644 index ab87d4ad..00000000 --- a/vendor/github.com/go-kit/kit/transport/http/server.go +++ /dev/null @@ -1,225 +0,0 @@ -package http - -import ( - "context" - "encoding/json" - "net/http" - - "github.com/go-kit/kit/endpoint" - "github.com/go-kit/kit/transport" - "github.com/go-kit/log" -) - -// Server wraps an endpoint and implements http.Handler. -type Server struct { - e endpoint.Endpoint - dec DecodeRequestFunc - enc EncodeResponseFunc - before []RequestFunc - after []ServerResponseFunc - errorEncoder ErrorEncoder - finalizer []ServerFinalizerFunc - errorHandler transport.ErrorHandler -} - -// NewServer constructs a new server, which implements http.Handler and wraps -// the provided endpoint. -func NewServer( - e endpoint.Endpoint, - dec DecodeRequestFunc, - enc EncodeResponseFunc, - options ...ServerOption, -) *Server { - s := &Server{ - e: e, - dec: dec, - enc: enc, - errorEncoder: DefaultErrorEncoder, - errorHandler: transport.NewLogErrorHandler(log.NewNopLogger()), - } - for _, option := range options { - option(s) - } - return s -} - -// ServerOption sets an optional parameter for servers. -type ServerOption func(*Server) - -// ServerBefore functions are executed on the HTTP request object before the -// request is decoded. -func ServerBefore(before ...RequestFunc) ServerOption { - return func(s *Server) { s.before = append(s.before, before...) } -} - -// ServerAfter functions are executed on the HTTP response writer after the -// endpoint is invoked, but before anything is written to the client. -func ServerAfter(after ...ServerResponseFunc) ServerOption { - return func(s *Server) { s.after = append(s.after, after...) } -} - -// ServerErrorEncoder is used to encode errors to the http.ResponseWriter -// whenever they're encountered in the processing of a request. Clients can -// use this to provide custom error formatting and response codes. By default, -// errors will be written with the DefaultErrorEncoder. -func ServerErrorEncoder(ee ErrorEncoder) ServerOption { - return func(s *Server) { s.errorEncoder = ee } -} - -// ServerErrorLogger is used to log non-terminal errors. By default, no errors -// are logged. This is intended as a diagnostic measure. Finer-grained control -// of error handling, including logging in more detail, should be performed in a -// custom ServerErrorEncoder or ServerFinalizer, both of which have access to -// the context. -// Deprecated: Use ServerErrorHandler instead. -func ServerErrorLogger(logger log.Logger) ServerOption { - return func(s *Server) { s.errorHandler = transport.NewLogErrorHandler(logger) } -} - -// ServerErrorHandler is used to handle non-terminal errors. By default, non-terminal errors -// are ignored. This is intended as a diagnostic measure. Finer-grained control -// of error handling, including logging in more detail, should be performed in a -// custom ServerErrorEncoder or ServerFinalizer, both of which have access to -// the context. -func ServerErrorHandler(errorHandler transport.ErrorHandler) ServerOption { - return func(s *Server) { s.errorHandler = errorHandler } -} - -// ServerFinalizer is executed at the end of every HTTP request. -// By default, no finalizer is registered. -func ServerFinalizer(f ...ServerFinalizerFunc) ServerOption { - return func(s *Server) { s.finalizer = append(s.finalizer, f...) } -} - -// ServeHTTP implements http.Handler. -func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - - if len(s.finalizer) > 0 { - iw := &interceptingWriter{w, http.StatusOK, 0} - defer func() { - ctx = context.WithValue(ctx, ContextKeyResponseHeaders, iw.Header()) - ctx = context.WithValue(ctx, ContextKeyResponseSize, iw.written) - for _, f := range s.finalizer { - f(ctx, iw.code, r) - } - }() - w = iw.reimplementInterfaces() - } - - for _, f := range s.before { - ctx = f(ctx, r) - } - - request, err := s.dec(ctx, r) - if err != nil { - s.errorHandler.Handle(ctx, err) - s.errorEncoder(ctx, err, w) - return - } - - response, err := s.e(ctx, request) - if err != nil { - s.errorHandler.Handle(ctx, err) - s.errorEncoder(ctx, err, w) - return - } - - for _, f := range s.after { - ctx = f(ctx, w) - } - - if err := s.enc(ctx, w, response); err != nil { - s.errorHandler.Handle(ctx, err) - s.errorEncoder(ctx, err, w) - return - } -} - -// ErrorEncoder is responsible for encoding an error to the ResponseWriter. -// Users are encouraged to use custom ErrorEncoders to encode HTTP errors to -// their clients, and will likely want to pass and check for their own error -// types. See the example shipping/handling service. -type ErrorEncoder func(ctx context.Context, err error, w http.ResponseWriter) - -// ServerFinalizerFunc can be used to perform work at the end of an HTTP -// request, after the response has been written to the client. The principal -// intended use is for request logging. In addition to the response code -// provided in the function signature, additional response parameters are -// provided in the context under keys with the ContextKeyResponse prefix. -type ServerFinalizerFunc func(ctx context.Context, code int, r *http.Request) - -// NopRequestDecoder is a DecodeRequestFunc that can be used for requests that do not -// need to be decoded, and simply returns nil, nil. -func NopRequestDecoder(ctx context.Context, r *http.Request) (interface{}, error) { - return nil, nil -} - -// EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a -// JSON object to the ResponseWriter. Many JSON-over-HTTP services can use it as -// a sensible default. If the response implements Headerer, the provided headers -// will be applied to the response. If the response implements StatusCoder, the -// provided StatusCode will be used instead of 200. -func EncodeJSONResponse(_ context.Context, w http.ResponseWriter, response interface{}) error { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - if headerer, ok := response.(Headerer); ok { - for k, values := range headerer.Headers() { - for _, v := range values { - w.Header().Add(k, v) - } - } - } - code := http.StatusOK - if sc, ok := response.(StatusCoder); ok { - code = sc.StatusCode() - } - w.WriteHeader(code) - if code == http.StatusNoContent { - return nil - } - return json.NewEncoder(w).Encode(response) -} - -// DefaultErrorEncoder writes the error to the ResponseWriter, by default a -// content type of text/plain, a body of the plain text of the error, and a -// status code of 500. If the error implements Headerer, the provided headers -// will be applied to the response. If the error implements json.Marshaler, and -// the marshaling succeeds, a content type of application/json and the JSON -// encoded form of the error will be used. If the error implements StatusCoder, -// the provided StatusCode will be used instead of 500. -func DefaultErrorEncoder(_ context.Context, err error, w http.ResponseWriter) { - contentType, body := "text/plain; charset=utf-8", []byte(err.Error()) - if marshaler, ok := err.(json.Marshaler); ok { - if jsonBody, marshalErr := marshaler.MarshalJSON(); marshalErr == nil { - contentType, body = "application/json; charset=utf-8", jsonBody - } - } - w.Header().Set("Content-Type", contentType) - if headerer, ok := err.(Headerer); ok { - for k, values := range headerer.Headers() { - for _, v := range values { - w.Header().Add(k, v) - } - } - } - code := http.StatusInternalServerError - if sc, ok := err.(StatusCoder); ok { - code = sc.StatusCode() - } - w.WriteHeader(code) - w.Write(body) -} - -// StatusCoder is checked by DefaultErrorEncoder. If an error value implements -// StatusCoder, the StatusCode will be used when encoding the error. By default, -// StatusInternalServerError (500) is used. -type StatusCoder interface { - StatusCode() int -} - -// Headerer is checked by DefaultErrorEncoder. If an error value implements -// Headerer, the provided headers will be applied to the response writer, after -// the Content-Type is set. -type Headerer interface { - Headers() http.Header -} diff --git a/vendor/github.com/go-kit/log/.gitignore b/vendor/github.com/go-kit/log/.gitignore deleted file mode 100644 index 66fd13c9..00000000 --- a/vendor/github.com/go-kit/log/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, built with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Dependency directories (remove the comment below to include it) -# vendor/ diff --git a/vendor/github.com/go-kit/log/LICENSE b/vendor/github.com/go-kit/log/LICENSE deleted file mode 100644 index bb5bdb9c..00000000 --- a/vendor/github.com/go-kit/log/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021 Go kit - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-kit/log/README.md b/vendor/github.com/go-kit/log/README.md deleted file mode 100644 index 80677946..00000000 --- a/vendor/github.com/go-kit/log/README.md +++ /dev/null @@ -1,156 +0,0 @@ -# package log - -[![Go Reference](https://pkg.go.dev/badge/github.com/go-kit/log.svg)](https://pkg.go.dev/github.com/go-kit/log) -[![Go Report Card](https://goreportcard.com/badge/go-kit/log)](https://goreportcard.com/report/go-kit/log) -[![GitHub Actions](https://github.com/go-kit/log/actions/workflows/test.yml/badge.svg)](https://github.com/go-kit/log/actions/workflows/test.yml) -[![Coverage Status](https://coveralls.io/repos/github/go-kit/log/badge.svg?branch=main)](https://coveralls.io/github/go-kit/log?branch=main) - -`package log` provides a minimal interface for structured logging in services. -It may be wrapped to encode conventions, enforce type-safety, provide leveled -logging, and so on. It can be used for both typical application log events, -and log-structured data streams. - -## Structured logging - -Structured logging is, basically, conceding to the reality that logs are -_data_, and warrant some level of schematic rigor. Using a stricter, -key/value-oriented message format for our logs, containing contextual and -semantic information, makes it much easier to get insight into the -operational activity of the systems we build. Consequently, `package log` is -of the strong belief that "[the benefits of structured logging outweigh the -minimal effort involved](https://www.thoughtworks.com/radar/techniques/structured-logging)". - -Migrating from unstructured to structured logging is probably a lot easier -than you'd expect. - -```go -// Unstructured -log.Printf("HTTP server listening on %s", addr) - -// Structured -logger.Log("transport", "HTTP", "addr", addr, "msg", "listening") -``` - -## Usage - -### Typical application logging - -```go -w := log.NewSyncWriter(os.Stderr) -logger := log.NewLogfmtLogger(w) -logger.Log("question", "what is the meaning of life?", "answer", 42) - -// Output: -// question="what is the meaning of life?" answer=42 -``` - -### Contextual Loggers - -```go -func main() { - var logger log.Logger - logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) - logger = log.With(logger, "instance_id", 123) - - logger.Log("msg", "starting") - NewWorker(log.With(logger, "component", "worker")).Run() - NewSlacker(log.With(logger, "component", "slacker")).Run() -} - -// Output: -// instance_id=123 msg=starting -// instance_id=123 component=worker msg=running -// instance_id=123 component=slacker msg=running -``` - -### Interact with stdlib logger - -Redirect stdlib logger to Go kit logger. - -```go -import ( - "os" - stdlog "log" - kitlog "github.com/go-kit/log" -) - -func main() { - logger := kitlog.NewJSONLogger(kitlog.NewSyncWriter(os.Stdout)) - stdlog.SetOutput(kitlog.NewStdlibAdapter(logger)) - stdlog.Print("I sure like pie") -} - -// Output: -// {"msg":"I sure like pie","ts":"2016/01/01 12:34:56"} -``` - -Or, if, for legacy reasons, you need to pipe all of your logging through the -stdlib log package, you can redirect Go kit logger to the stdlib logger. - -```go -logger := kitlog.NewLogfmtLogger(kitlog.StdlibWriter{}) -logger.Log("legacy", true, "msg", "at least it's something") - -// Output: -// 2016/01/01 12:34:56 legacy=true msg="at least it's something" -``` - -### Timestamps and callers - -```go -var logger log.Logger -logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) -logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) - -logger.Log("msg", "hello") - -// Output: -// ts=2016-01-01T12:34:56Z caller=main.go:15 msg=hello -``` - -## Levels - -Log levels are supported via the [level package](https://godoc.org/github.com/go-kit/log/level). - -## Supported output formats - -- [Logfmt](https://brandur.org/logfmt) ([see also](https://blog.codeship.com/logfmt-a-log-format-thats-easy-to-read-and-write)) -- JSON - -## Enhancements - -`package log` is centered on the one-method Logger interface. - -```go -type Logger interface { - Log(keyvals ...interface{}) error -} -``` - -This interface, and its supporting code like is the product of much iteration -and evaluation. For more details on the evolution of the Logger interface, -see [The Hunt for a Logger Interface](http://go-talks.appspot.com/github.com/ChrisHines/talks/structured-logging/structured-logging.slide#1), -a talk by [Chris Hines](https://github.com/ChrisHines). -Also, please see -[#63](https://github.com/go-kit/kit/issues/63), -[#76](https://github.com/go-kit/kit/pull/76), -[#131](https://github.com/go-kit/kit/issues/131), -[#157](https://github.com/go-kit/kit/pull/157), -[#164](https://github.com/go-kit/kit/issues/164), and -[#252](https://github.com/go-kit/kit/pull/252) -to review historical conversations about package log and the Logger interface. - -Value-add packages and suggestions, -like improvements to [the leveled logger](https://godoc.org/github.com/go-kit/log/level), -are of course welcome. Good proposals should - -- Be composable with [contextual loggers](https://godoc.org/github.com/go-kit/log#With), -- Not break the behavior of [log.Caller](https://godoc.org/github.com/go-kit/log#Caller) in any wrapped contextual loggers, and -- Be friendly to packages that accept only an unadorned log.Logger. - -## Benchmarks & comparisons - -There are a few Go logging benchmarks and comparisons that include Go kit's package log. - -- [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench) includes kit/log -- [uber-common/zap](https://github.com/uber-common/zap), a zero-alloc logging library, includes a comparison with kit/log diff --git a/vendor/github.com/go-kit/log/doc.go b/vendor/github.com/go-kit/log/doc.go deleted file mode 100644 index f744382f..00000000 --- a/vendor/github.com/go-kit/log/doc.go +++ /dev/null @@ -1,116 +0,0 @@ -// Package log provides a structured logger. -// -// Structured logging produces logs easily consumed later by humans or -// machines. Humans might be interested in debugging errors, or tracing -// specific requests. Machines might be interested in counting interesting -// events, or aggregating information for off-line processing. In both cases, -// it is important that the log messages are structured and actionable. -// Package log is designed to encourage both of these best practices. -// -// Basic Usage -// -// The fundamental interface is Logger. Loggers create log events from -// key/value data. The Logger interface has a single method, Log, which -// accepts a sequence of alternating key/value pairs, which this package names -// keyvals. -// -// type Logger interface { -// Log(keyvals ...interface{}) error -// } -// -// Here is an example of a function using a Logger to create log events. -// -// func RunTask(task Task, logger log.Logger) string { -// logger.Log("taskID", task.ID, "event", "starting task") -// ... -// logger.Log("taskID", task.ID, "event", "task complete") -// } -// -// The keys in the above example are "taskID" and "event". The values are -// task.ID, "starting task", and "task complete". Every key is followed -// immediately by its value. -// -// Keys are usually plain strings. Values may be any type that has a sensible -// encoding in the chosen log format. With structured logging it is a good -// idea to log simple values without formatting them. This practice allows -// the chosen logger to encode values in the most appropriate way. -// -// Contextual Loggers -// -// A contextual logger stores keyvals that it includes in all log events. -// Building appropriate contextual loggers reduces repetition and aids -// consistency in the resulting log output. With, WithPrefix, and WithSuffix -// add context to a logger. We can use With to improve the RunTask example. -// -// func RunTask(task Task, logger log.Logger) string { -// logger = log.With(logger, "taskID", task.ID) -// logger.Log("event", "starting task") -// ... -// taskHelper(task.Cmd, logger) -// ... -// logger.Log("event", "task complete") -// } -// -// The improved version emits the same log events as the original for the -// first and last calls to Log. Passing the contextual logger to taskHelper -// enables each log event created by taskHelper to include the task.ID even -// though taskHelper does not have access to that value. Using contextual -// loggers this way simplifies producing log output that enables tracing the -// life cycle of individual tasks. (See the Contextual example for the full -// code of the above snippet.) -// -// Dynamic Contextual Values -// -// A Valuer function stored in a contextual logger generates a new value each -// time an event is logged. The Valuer example demonstrates how this feature -// works. -// -// Valuers provide the basis for consistently logging timestamps and source -// code location. The log package defines several valuers for that purpose. -// See Timestamp, DefaultTimestamp, DefaultTimestampUTC, Caller, and -// DefaultCaller. A common logger initialization sequence that ensures all log -// entries contain a timestamp and source location looks like this: -// -// logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) -// logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) -// -// Concurrent Safety -// -// Applications with multiple goroutines want each log event written to the -// same logger to remain separate from other log events. Package log provides -// two simple solutions for concurrent safe logging. -// -// NewSyncWriter wraps an io.Writer and serializes each call to its Write -// method. Using a SyncWriter has the benefit that the smallest practical -// portion of the logging logic is performed within a mutex, but it requires -// the formatting Logger to make only one call to Write per log event. -// -// NewSyncLogger wraps any Logger and serializes each call to its Log method. -// Using a SyncLogger has the benefit that it guarantees each log event is -// handled atomically within the wrapped logger, but it typically serializes -// both the formatting and output logic. Use a SyncLogger if the formatting -// logger may perform multiple writes per log event. -// -// Error Handling -// -// This package relies on the practice of wrapping or decorating loggers with -// other loggers to provide composable pieces of functionality. It also means -// that Logger.Log must return an error because some -// implementations—especially those that output log data to an io.Writer—may -// encounter errors that cannot be handled locally. This in turn means that -// Loggers that wrap other loggers should return errors from the wrapped -// logger up the stack. -// -// Fortunately, the decorator pattern also provides a way to avoid the -// necessity to check for errors every time an application calls Logger.Log. -// An application required to panic whenever its Logger encounters -// an error could initialize its logger as follows. -// -// fmtlogger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) -// logger := log.LoggerFunc(func(keyvals ...interface{}) error { -// if err := fmtlogger.Log(keyvals...); err != nil { -// panic(err) -// } -// return nil -// }) -package log diff --git a/vendor/github.com/go-kit/log/json_logger.go b/vendor/github.com/go-kit/log/json_logger.go deleted file mode 100644 index d0faed4f..00000000 --- a/vendor/github.com/go-kit/log/json_logger.go +++ /dev/null @@ -1,91 +0,0 @@ -package log - -import ( - "encoding" - "encoding/json" - "fmt" - "io" - "reflect" -) - -type jsonLogger struct { - io.Writer -} - -// NewJSONLogger returns a Logger that encodes keyvals to the Writer as a -// single JSON object. Each log event produces no more than one call to -// w.Write. The passed Writer must be safe for concurrent use by multiple -// goroutines if the returned Logger will be used concurrently. -func NewJSONLogger(w io.Writer) Logger { - return &jsonLogger{w} -} - -func (l *jsonLogger) Log(keyvals ...interface{}) error { - n := (len(keyvals) + 1) / 2 // +1 to handle case when len is odd - m := make(map[string]interface{}, n) - for i := 0; i < len(keyvals); i += 2 { - k := keyvals[i] - var v interface{} = ErrMissingValue - if i+1 < len(keyvals) { - v = keyvals[i+1] - } - merge(m, k, v) - } - enc := json.NewEncoder(l.Writer) - enc.SetEscapeHTML(false) - return enc.Encode(m) -} - -func merge(dst map[string]interface{}, k, v interface{}) { - var key string - switch x := k.(type) { - case string: - key = x - case fmt.Stringer: - key = safeString(x) - default: - key = fmt.Sprint(x) - } - - // We want json.Marshaler and encoding.TextMarshaller to take priority over - // err.Error() and v.String(). But json.Marshall (called later) does that by - // default so we force a no-op if it's one of those 2 case. - switch x := v.(type) { - case json.Marshaler: - case encoding.TextMarshaler: - case error: - v = safeError(x) - case fmt.Stringer: - v = safeString(x) - } - - dst[key] = v -} - -func safeString(str fmt.Stringer) (s string) { - defer func() { - if panicVal := recover(); panicVal != nil { - if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() { - s = "NULL" - } else { - s = fmt.Sprintf("PANIC in String method: %v", panicVal) - } - } - }() - s = str.String() - return -} - -func safeError(err error) (s interface{}) { - defer func() { - if panicVal := recover(); panicVal != nil { - if v := reflect.ValueOf(err); v.Kind() == reflect.Ptr && v.IsNil() { - s = nil - } else { - s = fmt.Sprintf("PANIC in Error method: %v", panicVal) - } - } - }() - s = err.Error() - return -} diff --git a/vendor/github.com/go-kit/log/log.go b/vendor/github.com/go-kit/log/log.go deleted file mode 100644 index 62e11ada..00000000 --- a/vendor/github.com/go-kit/log/log.go +++ /dev/null @@ -1,179 +0,0 @@ -package log - -import "errors" - -// Logger is the fundamental interface for all log operations. Log creates a -// log event from keyvals, a variadic sequence of alternating keys and values. -// Implementations must be safe for concurrent use by multiple goroutines. In -// particular, any implementation of Logger that appends to keyvals or -// modifies or retains any of its elements must make a copy first. -type Logger interface { - Log(keyvals ...interface{}) error -} - -// ErrMissingValue is appended to keyvals slices with odd length to substitute -// the missing value. -var ErrMissingValue = errors.New("(MISSING)") - -// With returns a new contextual logger with keyvals prepended to those passed -// to calls to Log. If logger is also a contextual logger created by With, -// WithPrefix, or WithSuffix, keyvals is appended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func With(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - kvs := append(l.keyvals, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - return &context{ - logger: l.logger, - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - keyvals: kvs[:len(kvs):len(kvs)], - hasValuer: l.hasValuer || containsValuer(keyvals), - sKeyvals: l.sKeyvals, - sHasValuer: l.sHasValuer, - } -} - -// WithPrefix returns a new contextual logger with keyvals prepended to those -// passed to calls to Log. If logger is also a contextual logger created by -// With, WithPrefix, or WithSuffix, keyvals is prepended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func WithPrefix(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - n := len(l.keyvals) + len(keyvals) - if len(keyvals)%2 != 0 { - n++ - } - kvs := make([]interface{}, 0, n) - kvs = append(kvs, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - kvs = append(kvs, l.keyvals...) - return &context{ - logger: l.logger, - keyvals: kvs, - hasValuer: l.hasValuer || containsValuer(keyvals), - sKeyvals: l.sKeyvals, - sHasValuer: l.sHasValuer, - } -} - -// WithSuffix returns a new contextual logger with keyvals appended to those -// passed to calls to Log. If logger is also a contextual logger created by -// With, WithPrefix, or WithSuffix, keyvals is appended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func WithSuffix(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - n := len(l.sKeyvals) + len(keyvals) - if len(keyvals)%2 != 0 { - n++ - } - kvs := make([]interface{}, 0, n) - kvs = append(kvs, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - kvs = append(l.sKeyvals, kvs...) - return &context{ - logger: l.logger, - keyvals: l.keyvals, - hasValuer: l.hasValuer, - sKeyvals: kvs, - sHasValuer: l.sHasValuer || containsValuer(keyvals), - } -} - -// context is the Logger implementation returned by With, WithPrefix, and -// WithSuffix. It wraps a Logger and holds keyvals that it includes in all -// log events. Its Log method calls bindValues to generate values for each -// Valuer in the context keyvals. -// -// A context must always have the same number of stack frames between calls to -// its Log method and the eventual binding of Valuers to their value. This -// requirement comes from the functional requirement to allow a context to -// resolve application call site information for a Caller stored in the -// context. To do this we must be able to predict the number of logging -// functions on the stack when bindValues is called. -// -// Two implementation details provide the needed stack depth consistency. -// -// 1. newContext avoids introducing an additional layer when asked to -// wrap another context. -// 2. With, WithPrefix, and WithSuffix avoid introducing an additional -// layer by returning a newly constructed context with a merged keyvals -// rather than simply wrapping the existing context. -type context struct { - logger Logger - keyvals []interface{} - sKeyvals []interface{} // suffixes - hasValuer bool - sHasValuer bool -} - -func newContext(logger Logger) *context { - if c, ok := logger.(*context); ok { - return c - } - return &context{logger: logger} -} - -// Log replaces all value elements (odd indexes) containing a Valuer in the -// stored context with their generated value, appends keyvals, and passes the -// result to the wrapped Logger. -func (l *context) Log(keyvals ...interface{}) error { - kvs := append(l.keyvals, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - if l.hasValuer { - // If no keyvals were appended above then we must copy l.keyvals so - // that future log events will reevaluate the stored Valuers. - if len(keyvals) == 0 { - kvs = append([]interface{}{}, l.keyvals...) - } - bindValues(kvs[:(len(l.keyvals))]) - } - kvs = append(kvs, l.sKeyvals...) - if l.sHasValuer { - bindValues(kvs[len(kvs)-len(l.sKeyvals):]) - } - return l.logger.Log(kvs...) -} - -// LoggerFunc is an adapter to allow use of ordinary functions as Loggers. If -// f is a function with the appropriate signature, LoggerFunc(f) is a Logger -// object that calls f. -type LoggerFunc func(...interface{}) error - -// Log implements Logger by calling f(keyvals...). -func (f LoggerFunc) Log(keyvals ...interface{}) error { - return f(keyvals...) -} diff --git a/vendor/github.com/go-kit/log/logfmt_logger.go b/vendor/github.com/go-kit/log/logfmt_logger.go deleted file mode 100644 index a0030529..00000000 --- a/vendor/github.com/go-kit/log/logfmt_logger.go +++ /dev/null @@ -1,62 +0,0 @@ -package log - -import ( - "bytes" - "io" - "sync" - - "github.com/go-logfmt/logfmt" -) - -type logfmtEncoder struct { - *logfmt.Encoder - buf bytes.Buffer -} - -func (l *logfmtEncoder) Reset() { - l.Encoder.Reset() - l.buf.Reset() -} - -var logfmtEncoderPool = sync.Pool{ - New: func() interface{} { - var enc logfmtEncoder - enc.Encoder = logfmt.NewEncoder(&enc.buf) - return &enc - }, -} - -type logfmtLogger struct { - w io.Writer -} - -// NewLogfmtLogger returns a logger that encodes keyvals to the Writer in -// logfmt format. Each log event produces no more than one call to w.Write. -// The passed Writer must be safe for concurrent use by multiple goroutines if -// the returned Logger will be used concurrently. -func NewLogfmtLogger(w io.Writer) Logger { - return &logfmtLogger{w} -} - -func (l logfmtLogger) Log(keyvals ...interface{}) error { - enc := logfmtEncoderPool.Get().(*logfmtEncoder) - enc.Reset() - defer logfmtEncoderPool.Put(enc) - - if err := enc.EncodeKeyvals(keyvals...); err != nil { - return err - } - - // Add newline to the end of the buffer - if err := enc.EndRecord(); err != nil { - return err - } - - // The Logger interface requires implementations to be safe for concurrent - // use by multiple goroutines. For this implementation that means making - // only one call to l.w.Write() for each call to Log. - if _, err := l.w.Write(enc.buf.Bytes()); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-kit/log/nop_logger.go b/vendor/github.com/go-kit/log/nop_logger.go deleted file mode 100644 index 1047d626..00000000 --- a/vendor/github.com/go-kit/log/nop_logger.go +++ /dev/null @@ -1,8 +0,0 @@ -package log - -type nopLogger struct{} - -// NewNopLogger returns a logger that doesn't do anything. -func NewNopLogger() Logger { return nopLogger{} } - -func (nopLogger) Log(...interface{}) error { return nil } diff --git a/vendor/github.com/go-kit/log/staticcheck.conf b/vendor/github.com/go-kit/log/staticcheck.conf deleted file mode 100644 index 528438b9..00000000 --- a/vendor/github.com/go-kit/log/staticcheck.conf +++ /dev/null @@ -1 +0,0 @@ -checks = ["all"] diff --git a/vendor/github.com/go-kit/log/stdlib.go b/vendor/github.com/go-kit/log/stdlib.go deleted file mode 100644 index 0338edbe..00000000 --- a/vendor/github.com/go-kit/log/stdlib.go +++ /dev/null @@ -1,151 +0,0 @@ -package log - -import ( - "bytes" - "io" - "log" - "regexp" - "strings" -) - -// StdlibWriter implements io.Writer by invoking the stdlib log.Print. It's -// designed to be passed to a Go kit logger as the writer, for cases where -// it's necessary to redirect all Go kit log output to the stdlib logger. -// -// If you have any choice in the matter, you shouldn't use this. Prefer to -// redirect the stdlib log to the Go kit logger via NewStdlibAdapter. -type StdlibWriter struct{} - -// Write implements io.Writer. -func (w StdlibWriter) Write(p []byte) (int, error) { - log.Print(strings.TrimSpace(string(p))) - return len(p), nil -} - -// StdlibAdapter wraps a Logger and allows it to be passed to the stdlib -// logger's SetOutput. It will extract date/timestamps, filenames, and -// messages, and place them under relevant keys. -type StdlibAdapter struct { - Logger - timestampKey string - fileKey string - messageKey string - prefix string - joinPrefixToMsg bool -} - -// StdlibAdapterOption sets a parameter for the StdlibAdapter. -type StdlibAdapterOption func(*StdlibAdapter) - -// TimestampKey sets the key for the timestamp field. By default, it's "ts". -func TimestampKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.timestampKey = key } -} - -// FileKey sets the key for the file and line field. By default, it's "caller". -func FileKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.fileKey = key } -} - -// MessageKey sets the key for the actual log message. By default, it's "msg". -func MessageKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.messageKey = key } -} - -// Prefix configures the adapter to parse a prefix from stdlib log events. If -// you provide a non-empty prefix to the stdlib logger, then your should provide -// that same prefix to the adapter via this option. -// -// By default, the prefix isn't included in the msg key. Set joinPrefixToMsg to -// true if you want to include the parsed prefix in the msg. -func Prefix(prefix string, joinPrefixToMsg bool) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.prefix = prefix; a.joinPrefixToMsg = joinPrefixToMsg } -} - -// NewStdlibAdapter returns a new StdlibAdapter wrapper around the passed -// logger. It's designed to be passed to log.SetOutput. -func NewStdlibAdapter(logger Logger, options ...StdlibAdapterOption) io.Writer { - a := StdlibAdapter{ - Logger: logger, - timestampKey: "ts", - fileKey: "caller", - messageKey: "msg", - } - for _, option := range options { - option(&a) - } - return a -} - -func (a StdlibAdapter) Write(p []byte) (int, error) { - p = a.handlePrefix(p) - - result := subexps(p) - keyvals := []interface{}{} - var timestamp string - if date, ok := result["date"]; ok && date != "" { - timestamp = date - } - if time, ok := result["time"]; ok && time != "" { - if timestamp != "" { - timestamp += " " - } - timestamp += time - } - if timestamp != "" { - keyvals = append(keyvals, a.timestampKey, timestamp) - } - if file, ok := result["file"]; ok && file != "" { - keyvals = append(keyvals, a.fileKey, file) - } - if msg, ok := result["msg"]; ok { - msg = a.handleMessagePrefix(msg) - keyvals = append(keyvals, a.messageKey, msg) - } - if err := a.Logger.Log(keyvals...); err != nil { - return 0, err - } - return len(p), nil -} - -func (a StdlibAdapter) handlePrefix(p []byte) []byte { - if a.prefix != "" { - p = bytes.TrimPrefix(p, []byte(a.prefix)) - } - return p -} - -func (a StdlibAdapter) handleMessagePrefix(msg string) string { - if a.prefix == "" { - return msg - } - - msg = strings.TrimPrefix(msg, a.prefix) - if a.joinPrefixToMsg { - msg = a.prefix + msg - } - return msg -} - -const ( - logRegexpDate = `(?P[0-9]{4}/[0-9]{2}/[0-9]{2})?[ ]?` - logRegexpTime = `(?P