From 563768b58a4877dca6af5550c37567fd530216a6 Mon Sep 17 00:00:00 2001 From: Asim Aslam Date: Mon, 27 Jul 2020 13:22:00 +0100 Subject: [PATCH] v3 refactor (#1868) * Move to v3 Co-authored-by: Ben Toogood --- .github/workflows/micro-examples.yml | 37 - .github/workflows/micro-main.yml | 37 - agent/input/discord/conn.go | 4 +- agent/input/discord/discord.go | 2 +- agent/input/slack/conn.go | 2 +- agent/input/slack/slack.go | 2 +- agent/input/telegram/conn.go | 4 +- agent/input/telegram/telegram.go | 2 +- agent/proto/bot.pb.micro.go | 6 +- api/api.go | 4 +- api/handler/api/api.go | 14 +- api/handler/api/util.go | 2 +- api/handler/event/event.go | 6 +- api/handler/http/http.go | 6 +- api/handler/http/http_test.go | 14 +- api/handler/options.go | 6 +- api/handler/rpc/rpc.go | 26 +- api/handler/rpc/rpc_test.go | 2 +- api/handler/rpc/stream.go | 10 +- api/handler/util/router.go | 4 +- api/handler/web/web.go | 6 +- api/resolver/grpc/grpc.go | 2 +- api/resolver/host/host.go | 2 +- api/resolver/options.go | 2 +- api/resolver/path/path.go | 2 +- api/resolver/subdomain/subdomain.go | 4 +- api/resolver/subdomain/subdomain_test.go | 2 +- api/resolver/vpath/vpath.go | 2 +- api/router/options.go | 9 +- api/router/registry/registry.go | 14 +- api/router/registry/registry_test.go | 2 +- api/router/router.go | 2 +- api/router/router_test.go | 24 +- api/router/static/static.go | 14 +- api/router/util/parse.go | 2 +- api/router/util/parse_test.go | 2 +- api/router/util/runtime.go | 2 +- api/server/acme/autocert/autocert.go | 4 +- api/server/acme/certmagic/certmagic.go | 4 +- api/server/acme/certmagic/storage.go | 4 +- api/server/http/http.go | 6 +- api/server/options.go | 4 +- api/service/proto/api.pb.micro.go | 6 +- auth/default.go | 85 - auth/jwt/jwt.go | 6 +- auth/noop/noop.go | 81 + auth/options.go | 18 +- auth/service/proto/auth.pb.go | 1746 ----------------- auth/service/proto/auth.pb.micro.go | 296 --- auth/service/proto/auth.proto | 148 -- auth/service/service.go | 325 --- broker/broker.go | 28 - broker/http.go | 711 ------- broker/http/http.go | 706 ++++++- broker/{ => http}/http_test.go | 18 +- broker/http/options.go | 2 +- broker/memory/memory.go | 8 +- broker/memory/memory_test.go | 2 +- broker/nats/context.go | 2 +- broker/nats/nats.go | 10 +- broker/nats/nats_test.go | 2 +- broker/nats/options.go | 2 +- broker/options.go | 4 +- broker/service/options.go | 22 - broker/service/proto/broker.pb.go | 374 ---- broker/service/proto/broker.pb.micro.go | 185 -- broker/service/proto/broker.proto | 25 - broker/service/service.go | 152 -- broker/service/subscriber.go | 108 - cache/memcache/memcache.go | 2 +- cache/memory/memory.go | 4 +- client/backoff.go | 2 +- client/backoff_test.go | 7 +- client/cache.go | 16 +- client/cache_test.go | 33 +- client/client.go | 39 +- client/grpc/codec.go | 4 +- client/grpc/error.go | 2 +- client/grpc/grpc.go | 12 +- client/grpc/grpc_test.go | 13 +- client/grpc/message.go | 2 +- client/grpc/options.go | 2 +- client/grpc/request.go | 4 +- client/grpc/response.go | 4 +- client/grpc/stream.go | 2 +- client/{ => mucp}/common_test.go | 4 +- client/mucp/mucp.go | 617 +++++- client/{rpc_codec.go => mucp/mucp_codec.go} | 22 +- .../{rpc_message.go => mucp/mucp_message.go} | 10 +- .../{rpc_request.go => mucp/mucp_request.go} | 11 +- .../mucp_request_test.go} | 6 +- .../mucp_response.go} | 6 +- client/{rpc_stream.go => mucp/mucp_stream.go} | 13 +- .../{rpc_client_test.go => mucp/mucp_test.go} | 37 +- client/{ => mucp}/options_test.go | 37 +- client/options.go | 20 +- client/retry.go | 2 +- client/rpc_client.go | 617 ------ client/service/proto/client.pb.micro.go | 6 +- client/test_request.go | 65 + client/util.go | 8 +- client/wrapper.go | 2 +- cmd/cli/cli.go | 50 + cmd/cmd.go | 833 +------- cmd/options.go | 228 --- codec/bytes/bytes.go | 2 +- codec/bytes/marshaler.go | 2 +- codec/grpc/grpc.go | 2 +- codec/json/json.go | 2 +- codec/jsonrpc/client.go | 2 +- codec/jsonrpc/jsonrpc.go | 2 +- codec/jsonrpc/server.go | 2 +- codec/proto/marshaler.go | 2 +- codec/proto/proto.go | 2 +- codec/protorpc/protorpc.go | 2 +- codec/text/text.go | 2 +- config/config.go | 8 +- config/default.go | 10 +- config/default_test.go | 8 +- config/encoder/hcl/hcl.go | 2 +- config/encoder/json/json.go | 2 +- config/encoder/toml/toml.go | 2 +- config/encoder/xml/xml.go | 2 +- config/encoder/yaml/yaml.go | 2 +- config/loader/loader.go | 4 +- config/loader/memory/memory.go | 8 +- config/loader/memory/options.go | 6 +- config/options.go | 6 +- config/reader/json/json.go | 8 +- config/reader/json/json_test.go | 4 +- config/reader/json/values.go | 4 +- config/reader/json/values_test.go | 4 +- config/reader/options.go | 12 +- config/reader/reader.go | 2 +- config/source/cli/README.md | 71 - config/source/cli/cli.go | 145 -- config/source/cli/cli_test.go | 115 -- config/source/cli/options.go | 20 - config/source/cli/util.go | 50 - config/source/env/env.go | 2 +- config/source/env/env_test.go | 2 +- config/source/env/options.go | 2 +- config/source/env/watcher.go | 2 +- config/source/etcd/etcd.go | 2 +- config/source/etcd/options.go | 2 +- config/source/etcd/util.go | 2 +- config/source/etcd/watcher.go | 2 +- config/source/file/file.go | 2 +- config/source/file/file_test.go | 4 +- config/source/file/format.go | 2 +- config/source/file/format_test.go | 2 +- config/source/file/options.go | 2 +- config/source/file/watcher.go | 2 +- config/source/file/watcher_linux.go | 2 +- config/source/flag/flag.go | 2 +- config/source/flag/options.go | 2 +- config/source/memory/memory.go | 2 +- config/source/memory/options.go | 2 +- config/source/memory/watcher.go | 2 +- config/source/options.go | 7 +- config/source/service/options.go | 38 - config/source/service/proto/service.pb.go | 960 --------- .../source/service/proto/service.pb.micro.go | 253 --- config/source/service/proto/service.proto | 69 - config/source/service/service.go | 106 - config/source/service/util.go | 18 - config/source/service/watcher.go | 27 - config/value.go | 2 +- debug/log/kubernetes/kubernetes.go | 6 +- debug/log/kubernetes/kubernetes_test.go | 2 +- debug/log/kubernetes/stream.go | 2 +- debug/log/memory/memory.go | 4 +- debug/log/memory/memory_test.go | 2 +- debug/log/memory/stream.go | 2 +- debug/log/noop/noop.go | 2 +- debug/log/os.go | 2 +- debug/profile/http/http.go | 2 +- debug/profile/pprof/pprof.go | 2 +- debug/service/client.go | 8 +- debug/service/handler/debug.go | 12 +- debug/service/proto/debug.pb.micro.go | 6 +- debug/service/service.go | 4 +- debug/service/stream.go | 2 +- debug/stats/default.go | 2 +- debug/trace/memory/memory.go | 4 +- debug/trace/trace.go | 2 +- defaults.go | 134 -- event.go | 16 - function.go | 81 - function_test.go | 63 - go.mod | 2 +- go.sum | 49 + logger/default.go | 2 +- micro.go | 122 -- model/model.go | 6 +- model/mud/entity.go | 4 +- model/mud/mud.go | 10 +- network/{default.go => mucp/mucp.go} | 279 +-- network/{ => mucp}/node.go | 37 +- network/{ => mucp}/node_test.go | 15 +- network/mucp/proto/network.pb.go | 1102 +++++++++++ network/mucp/proto/network.pb.micro.go | 21 + network/mucp/proto/network.proto | 115 ++ network/network.go | 29 +- network/options.go | 19 +- network/resolver/dns/dns.go | 2 +- network/resolver/dnssrv/dnssrv.go | 2 +- network/resolver/http/http.go | 2 +- network/resolver/registry/registry.go | 7 +- network/resolver/static/static.go | 2 +- network/service/proto/network.pb.go | 1241 ------------ network/service/proto/network.pb.micro.go | 191 -- network/service/proto/network.proto | 131 -- options.go | 340 ---- plugin/default.go | 55 - plugin/plugin.go | 6 - plugin/template.go | 2 +- proxy/grpc/grpc.go | 10 +- proxy/http/http.go | 6 +- proxy/http/http_test.go | 19 +- proxy/mucp/mucp.go | 26 +- proxy/options.go | 4 +- proxy/proxy.go | 2 +- registry/cache/cache.go | 6 +- registry/etcd/etcd.go | 4 +- registry/etcd/options.go | 2 +- registry/etcd/watcher.go | 2 +- registry/mdns/mdns.go | 768 +++++++- registry/{ => mdns}/mdns_test.go | 36 +- registry/mdns/options.go | 18 + registry/mdns_registry.go | 768 -------- registry/memory/memory.go | 4 +- registry/memory/memory_test.go | 2 +- registry/memory/options.go | 2 +- registry/memory/util.go | 2 +- registry/memory/watcher.go | 2 +- registry/memory/watcher_test.go | 2 +- registry/registry.go | 31 - registry/service/options.go | 21 - registry/service/proto/registry.pb.go | 1057 ---------- registry/service/proto/registry.pb.micro.go | 236 --- registry/service/proto/registry.proto | 101 - registry/service/service.go | 216 -- registry/service/util.go | 134 -- registry/service/watcher.go | 47 - router/default.go | 722 ------- router/dns/dns.go | 2 +- router/options.go | 15 +- router/registry/registry.go | 723 ++++++- .../registry_test.go} | 13 +- router/{ => registry}/table.go | 89 +- router/{ => registry}/table_test.go | 96 +- router/registry/watcher.go | 52 + router/router.go | 12 +- router/service/options.go | 22 - router/service/proto/router.pb.go | 1345 ------------- router/service/proto/router.pb.micro.go | 421 ---- router/service/proto/router.proto | 135 -- router/service/service.go | 271 --- router/service/table.go | 123 -- router/service/watcher.go | 118 -- router/static/static.go | 2 +- router/watcher.go | 46 - runtime/default.go | 621 ------ runtime/kubernetes/kubernetes.go | 8 +- runtime/kubernetes/logs.go | 6 +- runtime/kubernetes/service.go | 8 +- runtime/local/build/build.go | 2 +- runtime/local/build/docker/docker.go | 4 +- runtime/local/build/go/golang.go | 2 +- runtime/local/local.go | 621 +++++- runtime/local/process/os/os.go | 2 +- runtime/local/process/os/os_windows.go | 2 +- runtime/local/process/os/process.go | 2 +- runtime/local/process/process.go | 2 +- runtime/{ => local}/service.go | 15 +- runtime/local/source/git/git.go | 2 +- runtime/local/source/go/golang.go | 2 +- runtime/options.go | 2 +- runtime/runtime.go | 5 - runtime/service/proto/runtime.pb.go | 1332 ------------- runtime/service/proto/runtime.pb.micro.go | 236 --- runtime/service/proto/runtime.proto | 139 -- runtime/service/service.go | 301 --- selector/options.go | 2 +- selector/random.go | 2 +- selector/random/random.go | 2 +- selector/random/random_test.go | 2 +- selector/roundrobin/roundrobin.go | 4 +- selector/roundrobin/roundrobin_test.go | 4 +- selector/selector.go | 2 +- selector/tests.go | 2 +- server/context.go | 12 - server/grpc/codec.go | 4 +- server/grpc/context.go | 2 +- server/grpc/error.go | 2 +- server/grpc/extractor.go | 2 +- server/grpc/extractor_test.go | 2 +- server/grpc/grpc.go | 22 +- server/grpc/grpc_test.go | 40 +- server/grpc/handler.go | 4 +- server/grpc/options.go | 16 +- server/grpc/proto/test.pb.micro.go | 6 +- server/grpc/request.go | 4 +- server/grpc/response.go | 2 +- server/grpc/server.go | 4 +- server/grpc/stream.go | 2 +- server/grpc/subscriber.go | 12 +- server/mock/mock.go | 2 +- server/mock/mock_handler.go | 4 +- server/mock/mock_subscriber.go | 4 +- server/mock/mock_test.go | 2 +- server/{ => mucp}/extractor.go | 4 +- server/{ => mucp}/extractor_test.go | 4 +- server/mucp/mucp.go | 8 +- server/mucp/options.go | 56 + server/{ => mucp}/rpc_codec.go | 18 +- server/{ => mucp}/rpc_codec_test.go | 6 +- server/{ => mucp}/rpc_event.go | 6 +- server/{ => mucp}/rpc_handler.go | 13 +- server/{ => mucp}/rpc_request.go | 8 +- server/{ => mucp}/rpc_response.go | 6 +- server/{ => mucp}/rpc_router.go | 45 +- server/{ => mucp}/rpc_server.go | 74 +- server/{ => mucp}/rpc_stream.go | 9 +- server/{ => mucp}/rpc_stream_test.go | 6 +- server/{ => mucp}/rpc_util.go | 2 +- server/{ => mucp}/subscriber.go | 15 +- server/options.go | 22 +- server/proto/server.pb.micro.go | 6 +- server/server.go | 116 +- service.go | 231 --- service/grpc/grpc.go | 12 +- service/grpc/grpc_test.go | 8 +- service/grpc/options.go | 6 +- service/grpc/proto/test.pb.micro.go | 6 +- service/mucp/mucp.go | 12 +- service/options.go | 27 +- service/service.go | 6 +- service_test.go | 175 -- store/cache/cache.go | 4 +- store/cache/cache_test.go | 4 +- store/cockroach/cockroach.go | 4 +- store/cockroach/cockroach_test.go | 2 +- store/file/file.go | 2 +- store/file/file_test.go | 2 +- store/memory/memory.go | 2 +- store/memory/memory_test.go | 2 +- store/options.go | 11 - store/service/proto/store.pb.go | 1236 ------------ store/service/proto/store.pb.micro.go | 253 --- store/service/proto/store.proto | 109 - store/service/service.go | 263 --- sync/etcd/etcd.go | 2 +- sync/memory/memory.go | 2 +- transport/grpc/grpc.go | 10 +- transport/grpc/grpc_test.go | 2 +- transport/grpc/handler.go | 8 +- transport/grpc/proto/transport.pb.micro.go | 6 +- transport/grpc/socket.go | 4 +- transport/http/http.go | 2 +- transport/http/http_test.go | 2 +- transport/http/options.go | 2 +- transport/http_transport.go | 8 +- transport/memory/memory.go | 6 +- transport/memory/memory_test.go | 2 +- transport/options.go | 2 +- transport/quic/quic.go | 4 +- tunnel/broker/broker.go | 6 +- tunnel/default.go | 4 +- tunnel/link.go | 4 +- tunnel/listener.go | 2 +- tunnel/options.go | 6 +- tunnel/session.go | 4 +- tunnel/transport/listener.go | 4 +- tunnel/transport/transport.go | 4 +- tunnel/tunnel.go | 2 +- tunnel/tunnel_test.go | 2 +- util/auth/auth.go | 4 +- util/ctx/ctx.go | 2 +- util/ctx/ctx_test.go | 2 +- util/file/client.go | 4 +- util/file/handler.go | 8 +- util/file/proto/file.pb.micro.go | 6 +- util/http/http.go | 8 +- util/http/http_test.go | 8 +- util/http/options.go | 2 +- util/http/roundtripper.go | 4 +- util/io/io.go | 2 +- util/kubernetes/api/request.go | 2 +- util/kubernetes/client/client.go | 4 +- util/kubernetes/client/watch.go | 2 +- util/log/README.md | 2 +- util/log/log.go | 6 +- util/mdns/server.go | 2 +- util/mux/mux.go | 34 +- util/pool/default.go | 2 +- util/pool/default_test.go | 4 +- util/pool/options.go | 2 +- util/pool/pool.go | 2 +- util/proto/proto.go | 33 - util/registry/util.go | 2 +- util/registry/util_test.go | 2 +- util/scope/scope.go | 2 +- util/socket/socket.go | 2 +- util/stream/stream.go | 11 +- util/sync/manager.go | 2 +- util/sync/options.go | 2 +- util/sync/sync.go | 2 +- util/test/test.go | 2 +- util/token/basic/basic.go | 6 +- util/token/basic/basic_test.go | 6 +- util/token/jwt/jwt.go | 4 +- util/token/jwt/jwt_test.go | 4 +- util/token/options.go | 2 +- util/token/token.go | 2 +- util/wrapper/wrapper.go | 18 +- util/wrapper/wrapper_static_client_test.go | 32 +- util/wrapper/wrapper_test.go | 13 +- web/options.go | 35 +- web/service.go | 108 +- web/service_test.go | 4 +- web/web.go | 1 - web/web_test.go | 37 +- 424 files changed, 6383 insertions(+), 22490 deletions(-) delete mode 100644 .github/workflows/micro-examples.yml delete mode 100644 .github/workflows/micro-main.yml delete mode 100644 auth/default.go create mode 100644 auth/noop/noop.go delete mode 100644 auth/service/proto/auth.pb.go delete mode 100644 auth/service/proto/auth.pb.micro.go delete mode 100644 auth/service/proto/auth.proto delete mode 100644 auth/service/service.go delete mode 100644 broker/http.go rename broker/{ => http}/http_test.go (95%) delete mode 100644 broker/service/options.go delete mode 100644 broker/service/proto/broker.pb.go delete mode 100644 broker/service/proto/broker.pb.micro.go delete mode 100644 broker/service/proto/broker.proto delete mode 100644 broker/service/service.go delete mode 100644 broker/service/subscriber.go rename client/{ => mucp}/common_test.go (94%) rename client/{rpc_codec.go => mucp/mucp_codec.go} (92%) rename client/{rpc_message.go => mucp/mucp_message.go} (78%) rename client/{rpc_request.go => mucp/mucp_request.go} (81%) rename client/{rpc_request_test.go => mucp/mucp_request_test.go} (85%) rename client/{rpc_response.go => mucp/mucp_response.go} (83%) rename client/{rpc_stream.go => mucp/mucp_stream.go} (91%) rename client/{rpc_client_test.go => mucp/mucp_test.go} (70%) rename client/{ => mucp}/options_test.go (61%) delete mode 100644 client/rpc_client.go create mode 100644 client/test_request.go create mode 100644 cmd/cli/cli.go delete mode 100644 cmd/options.go delete mode 100644 config/source/cli/README.md delete mode 100644 config/source/cli/cli.go delete mode 100644 config/source/cli/cli_test.go delete mode 100644 config/source/cli/options.go delete mode 100644 config/source/cli/util.go delete mode 100644 config/source/service/options.go delete mode 100644 config/source/service/proto/service.pb.go delete mode 100644 config/source/service/proto/service.pb.micro.go delete mode 100644 config/source/service/proto/service.proto delete mode 100644 config/source/service/service.go delete mode 100644 config/source/service/util.go delete mode 100644 config/source/service/watcher.go delete mode 100644 defaults.go delete mode 100644 event.go delete mode 100644 function.go delete mode 100644 function_test.go delete mode 100644 micro.go rename network/{default.go => mucp/mucp.go} (87%) rename network/{ => mucp}/node.go (93%) rename network/{ => mucp}/node_test.go (95%) create mode 100644 network/mucp/proto/network.pb.go create mode 100644 network/mucp/proto/network.pb.micro.go create mode 100644 network/mucp/proto/network.proto delete mode 100644 network/service/proto/network.pb.go delete mode 100644 network/service/proto/network.pb.micro.go delete mode 100644 network/service/proto/network.proto delete mode 100644 options.go rename registry/{ => mdns}/mdns_test.go (90%) create mode 100644 registry/mdns/options.go delete mode 100644 registry/mdns_registry.go delete mode 100644 registry/service/options.go delete mode 100644 registry/service/proto/registry.pb.go delete mode 100644 registry/service/proto/registry.pb.micro.go delete mode 100644 registry/service/proto/registry.proto delete mode 100644 registry/service/service.go delete mode 100644 registry/service/util.go delete mode 100644 registry/service/watcher.go delete mode 100644 router/default.go rename router/{default_test.go => registry/registry_test.go} (90%) rename router/{ => registry}/table.go (71%) rename router/{ => registry}/table_test.go (77%) create mode 100644 router/registry/watcher.go delete mode 100644 router/service/options.go delete mode 100644 router/service/proto/router.pb.go delete mode 100644 router/service/proto/router.pb.micro.go delete mode 100644 router/service/proto/router.proto delete mode 100644 router/service/service.go delete mode 100644 router/service/table.go delete mode 100644 router/service/watcher.go delete mode 100644 runtime/default.go rename runtime/{ => local}/service.go (93%) delete mode 100644 runtime/service/proto/runtime.pb.go delete mode 100644 runtime/service/proto/runtime.pb.micro.go delete mode 100644 runtime/service/proto/runtime.proto delete mode 100644 runtime/service/service.go rename server/{ => mucp}/extractor.go (97%) rename server/{ => mucp}/extractor_test.go (96%) create mode 100644 server/mucp/options.go rename server/{ => mucp}/rpc_codec.go (95%) rename server/{ => mucp}/rpc_codec_test.go (95%) rename server/{ => mucp}/rpc_event.go (85%) rename server/{ => mucp}/rpc_handler.go (75%) rename server/{ => mucp}/rpc_request.go (92%) rename server/{ => mucp}/rpc_response.go (84%) rename server/{ => mucp}/rpc_router.go (90%) rename server/{ => mucp}/rpc_server.go (92%) rename server/{ => mucp}/rpc_stream.go (90%) rename server/{ => mucp}/rpc_stream_test.go (95%) rename server/{ => mucp}/rpc_util.go (96%) rename server/{ => mucp}/subscriber.go (90%) delete mode 100644 service.go delete mode 100644 service_test.go delete mode 100644 store/service/proto/store.pb.go delete mode 100644 store/service/proto/store.pb.micro.go delete mode 100644 store/service/proto/store.proto delete mode 100644 store/service/service.go delete mode 100644 util/proto/proto.go diff --git a/.github/workflows/micro-examples.yml b/.github/workflows/micro-examples.yml deleted file mode 100644 index c1743496..00000000 --- a/.github/workflows/micro-examples.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: Build all github.com/micro/examples -on: - pull_request: - branches: - - master - -jobs: - - build: - name: Build repos - runs-on: ubuntu-latest - steps: - - - name: Set up Go 1.13 - uses: actions/setup-go@v1 - with: - go-version: 1.13 - id: go - - - name: Install Protoc - uses: arduino/setup-protoc@master - - - name: Check out this code - uses: actions/checkout@v2 - with: - path: 'go-micro' - - - name: Check out code examples - uses: actions/checkout@v2 - with: - repository: 'micro/examples' - path: 'examples' - - - name: Build all - run: $GITHUB_WORKSPACE/go-micro/.github/workflows/scripts/build-all-examples.sh ${{ github.event.pull_request.head.sha }} ${{ github.event.pull_request.head.repo.full_name }} - working-directory: examples - \ No newline at end of file diff --git a/.github/workflows/micro-main.yml b/.github/workflows/micro-main.yml deleted file mode 100644 index bc08fd84..00000000 --- a/.github/workflows/micro-main.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: Build and test micro -on: - pull_request: - branches: - - master - -jobs: - - build: - name: Build and test micro - runs-on: ubuntu-latest - steps: - - - name: Set up Go 1.13 - uses: actions/setup-go@v2 - with: - go-version: 1.13 - id: go - - - name: Install Protoc - uses: arduino/setup-protoc@master - - - name: Check out this code - uses: actions/checkout@v2 - with: - path: 'go-micro' - - - name: Check out micro - uses: actions/checkout@v2 - with: - repository: 'micro/micro' - path: 'micro' - - - name: Build all - run: $GITHUB_WORKSPACE/go-micro/.github/workflows/scripts/build-micro.sh ${{ github.event.pull_request.head.sha }} ${{ github.event.pull_request.head.repo.full_name }} - working-directory: micro - \ No newline at end of file diff --git a/agent/input/discord/conn.go b/agent/input/discord/conn.go index 4766d442..e1208071 100644 --- a/agent/input/discord/conn.go +++ b/agent/input/discord/conn.go @@ -6,8 +6,8 @@ import ( "sync" "github.com/bwmarrin/discordgo" - "github.com/micro/go-micro/v2/agent/input" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/agent/input" + "github.com/micro/go-micro/v3/logger" ) type discordConn struct { diff --git a/agent/input/discord/discord.go b/agent/input/discord/discord.go index 991fc2d5..c672f325 100644 --- a/agent/input/discord/discord.go +++ b/agent/input/discord/discord.go @@ -9,7 +9,7 @@ import ( "github.com/bwmarrin/discordgo" "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2/agent/input" + "github.com/micro/go-micro/v3/agent/input" ) func init() { diff --git a/agent/input/slack/conn.go b/agent/input/slack/conn.go index 1bc4bbdb..b6422e88 100644 --- a/agent/input/slack/conn.go +++ b/agent/input/slack/conn.go @@ -7,7 +7,7 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/agent/input" + "github.com/micro/go-micro/v3/agent/input" "github.com/nlopes/slack" ) diff --git a/agent/input/slack/slack.go b/agent/input/slack/slack.go index 1475f23a..33e64a87 100644 --- a/agent/input/slack/slack.go +++ b/agent/input/slack/slack.go @@ -5,7 +5,7 @@ import ( "sync" "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2/agent/input" + "github.com/micro/go-micro/v3/agent/input" "github.com/nlopes/slack" ) diff --git a/agent/input/telegram/conn.go b/agent/input/telegram/conn.go index b0cb4f33..61a08c91 100644 --- a/agent/input/telegram/conn.go +++ b/agent/input/telegram/conn.go @@ -6,8 +6,8 @@ import ( "sync" "github.com/forestgiant/sliceutil" - "github.com/micro/go-micro/v2/agent/input" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/agent/input" + "github.com/micro/go-micro/v3/logger" tgbotapi "gopkg.in/telegram-bot-api.v4" ) diff --git a/agent/input/telegram/telegram.go b/agent/input/telegram/telegram.go index c0fff91b..3cec8596 100644 --- a/agent/input/telegram/telegram.go +++ b/agent/input/telegram/telegram.go @@ -6,7 +6,7 @@ import ( "sync" "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2/agent/input" + "github.com/micro/go-micro/v3/agent/input" tgbotapi "gopkg.in/telegram-bot-api.v4" ) diff --git a/agent/proto/bot.pb.micro.go b/agent/proto/bot.pb.micro.go index 7c105aa6..69fd249c 100644 --- a/agent/proto/bot.pb.micro.go +++ b/agent/proto/bot.pb.micro.go @@ -11,9 +11,9 @@ import ( import ( context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" + api "github.com/micro/go-micro/v3/api" + client "github.com/micro/go-micro/v3/client" + server "github.com/micro/go-micro/v3/server" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/api/api.go b/api/api.go index 13465b63..402c938b 100644 --- a/api/api.go +++ b/api/api.go @@ -5,8 +5,8 @@ import ( "regexp" "strings" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/server" ) type Api interface { diff --git a/api/handler/api/api.go b/api/handler/api/api.go index 9cb2865d..7d5a569d 100644 --- a/api/handler/api/api.go +++ b/api/handler/api/api.go @@ -4,13 +4,13 @@ package api import ( "net/http" - goapi "github.com/micro/go-micro/v2/api" - "github.com/micro/go-micro/v2/api/handler" - "github.com/micro/go-micro/v2/api/handler/util" - api "github.com/micro/go-micro/v2/api/proto" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/util/ctx" + goapi "github.com/micro/go-micro/v3/api" + "github.com/micro/go-micro/v3/api/handler" + "github.com/micro/go-micro/v3/api/handler/util" + api "github.com/micro/go-micro/v3/api/proto" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/util/ctx" ) type apiHandler struct { diff --git a/api/handler/api/util.go b/api/handler/api/util.go index 190b8c02..0f0c50db 100644 --- a/api/handler/api/util.go +++ b/api/handler/api/util.go @@ -7,7 +7,7 @@ import ( "net/http" "strings" - api "github.com/micro/go-micro/v2/api/proto" + api "github.com/micro/go-micro/v3/api/proto" "github.com/oxtoacart/bpool" ) diff --git a/api/handler/event/event.go b/api/handler/event/event.go index 98dbfe90..5977b525 100644 --- a/api/handler/event/event.go +++ b/api/handler/event/event.go @@ -11,9 +11,9 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/api/handler" - proto "github.com/micro/go-micro/v2/api/proto" - "github.com/micro/go-micro/v2/util/ctx" + "github.com/micro/go-micro/v3/api/handler" + proto "github.com/micro/go-micro/v3/api/proto" + "github.com/micro/go-micro/v3/util/ctx" "github.com/oxtoacart/bpool" ) diff --git a/api/handler/http/http.go b/api/handler/http/http.go index 53b78c77..5accfab3 100644 --- a/api/handler/http/http.go +++ b/api/handler/http/http.go @@ -9,9 +9,9 @@ import ( "net/http/httputil" "net/url" - "github.com/micro/go-micro/v2/api" - "github.com/micro/go-micro/v2/api/handler" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/api" + "github.com/micro/go-micro/v3/api/handler" + "github.com/micro/go-micro/v3/registry" ) const ( diff --git a/api/handler/http/http_test.go b/api/handler/http/http_test.go index 1cf98d9f..5c5c842f 100644 --- a/api/handler/http/http_test.go +++ b/api/handler/http/http_test.go @@ -6,13 +6,13 @@ import ( "net/http/httptest" "testing" - "github.com/micro/go-micro/v2/api/handler" - "github.com/micro/go-micro/v2/api/resolver" - "github.com/micro/go-micro/v2/api/resolver/vpath" - "github.com/micro/go-micro/v2/api/router" - regRouter "github.com/micro/go-micro/v2/api/router/registry" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/registry/memory" + "github.com/micro/go-micro/v3/api/handler" + "github.com/micro/go-micro/v3/api/resolver" + "github.com/micro/go-micro/v3/api/resolver/vpath" + "github.com/micro/go-micro/v3/api/router" + regRouter "github.com/micro/go-micro/v3/api/router/registry" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/memory" ) func testHttp(t *testing.T, path, service, ns string) { diff --git a/api/handler/options.go b/api/handler/options.go index f41c7303..8e2d058a 100644 --- a/api/handler/options.go +++ b/api/handler/options.go @@ -1,9 +1,9 @@ package handler import ( - "github.com/micro/go-micro/v2/api/router" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/client/grpc" + "github.com/micro/go-micro/v3/api/router" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/client/grpc" ) var ( diff --git a/api/handler/rpc/rpc.go b/api/handler/rpc/rpc.go index 5243c250..f51e7a65 100644 --- a/api/handler/rpc/rpc.go +++ b/api/handler/rpc/rpc.go @@ -9,19 +9,19 @@ import ( "strings" jsonpatch "github.com/evanphx/json-patch/v5" - "github.com/micro/go-micro/v2/api" - "github.com/micro/go-micro/v2/api/handler" - "github.com/micro/go-micro/v2/api/handler/util" - "github.com/micro/go-micro/v2/api/internal/proto" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/codec/jsonrpc" - "github.com/micro/go-micro/v2/codec/protorpc" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/util/ctx" - "github.com/micro/go-micro/v2/util/qson" + "github.com/micro/go-micro/v3/api" + "github.com/micro/go-micro/v3/api/handler" + "github.com/micro/go-micro/v3/api/handler/util" + "github.com/micro/go-micro/v3/api/internal/proto" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/codec/jsonrpc" + "github.com/micro/go-micro/v3/codec/protorpc" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/util/ctx" + "github.com/micro/go-micro/v3/util/qson" "github.com/oxtoacart/bpool" ) diff --git a/api/handler/rpc/rpc_test.go b/api/handler/rpc/rpc_test.go index 1b602f84..8b6cd0b6 100644 --- a/api/handler/rpc/rpc_test.go +++ b/api/handler/rpc/rpc_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/golang/protobuf/proto" - go_api "github.com/micro/go-micro/v2/api/proto" + go_api "github.com/micro/go-micro/v3/api/proto" ) func TestRequestPayloadFromRequest(t *testing.T) { diff --git a/api/handler/rpc/stream.go b/api/handler/rpc/stream.go index b51d59df..1078cdc1 100644 --- a/api/handler/rpc/stream.go +++ b/api/handler/rpc/stream.go @@ -12,11 +12,11 @@ import ( "github.com/gobwas/httphead" "github.com/gobwas/ws" "github.com/gobwas/ws/wsutil" - "github.com/micro/go-micro/v2/api" - "github.com/micro/go-micro/v2/api/handler/util" - "github.com/micro/go-micro/v2/client" - raw "github.com/micro/go-micro/v2/codec/bytes" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/api" + "github.com/micro/go-micro/v3/api/handler/util" + "github.com/micro/go-micro/v3/client" + raw "github.com/micro/go-micro/v3/codec/bytes" + "github.com/micro/go-micro/v3/logger" ) // serveWebsocket will stream rpc back over websockets assuming json diff --git a/api/handler/util/router.go b/api/handler/util/router.go index 7f00b89c..a079e6d4 100644 --- a/api/handler/util/router.go +++ b/api/handler/util/router.go @@ -1,8 +1,8 @@ package util import ( - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/router" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/router" ) // Router is a hack for API routing diff --git a/api/handler/web/web.go b/api/handler/web/web.go index 09567bd5..ace2654e 100644 --- a/api/handler/web/web.go +++ b/api/handler/web/web.go @@ -12,9 +12,9 @@ import ( "net/url" "strings" - "github.com/micro/go-micro/v2/api" - "github.com/micro/go-micro/v2/api/handler" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/api" + "github.com/micro/go-micro/v3/api/handler" + "github.com/micro/go-micro/v3/registry" ) const ( diff --git a/api/resolver/grpc/grpc.go b/api/resolver/grpc/grpc.go index 127a88d2..61d3ae9e 100644 --- a/api/resolver/grpc/grpc.go +++ b/api/resolver/grpc/grpc.go @@ -6,7 +6,7 @@ import ( "net/http" "strings" - "github.com/micro/go-micro/v2/api/resolver" + "github.com/micro/go-micro/v3/api/resolver" ) type Resolver struct { diff --git a/api/resolver/host/host.go b/api/resolver/host/host.go index 6d028961..501f35f8 100644 --- a/api/resolver/host/host.go +++ b/api/resolver/host/host.go @@ -4,7 +4,7 @@ package host import ( "net/http" - "github.com/micro/go-micro/v2/api/resolver" + "github.com/micro/go-micro/v3/api/resolver" ) type Resolver struct { diff --git a/api/resolver/options.go b/api/resolver/options.go index 51a67e6d..68a8774d 100644 --- a/api/resolver/options.go +++ b/api/resolver/options.go @@ -1,7 +1,7 @@ package resolver import ( - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) type Options struct { diff --git a/api/resolver/path/path.go b/api/resolver/path/path.go index 4cdd38ea..b91fefbb 100644 --- a/api/resolver/path/path.go +++ b/api/resolver/path/path.go @@ -5,7 +5,7 @@ import ( "net/http" "strings" - "github.com/micro/go-micro/v2/api/resolver" + "github.com/micro/go-micro/v3/api/resolver" ) type Resolver struct { diff --git a/api/resolver/subdomain/subdomain.go b/api/resolver/subdomain/subdomain.go index f1c4bad7..086ed030 100644 --- a/api/resolver/subdomain/subdomain.go +++ b/api/resolver/subdomain/subdomain.go @@ -7,8 +7,8 @@ import ( "net/http" "strings" - "github.com/micro/go-micro/v2/api/resolver" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/api/resolver" + "github.com/micro/go-micro/v3/logger" "golang.org/x/net/publicsuffix" ) diff --git a/api/resolver/subdomain/subdomain_test.go b/api/resolver/subdomain/subdomain_test.go index dbbbfa82..2a33fa60 100644 --- a/api/resolver/subdomain/subdomain_test.go +++ b/api/resolver/subdomain/subdomain_test.go @@ -5,7 +5,7 @@ import ( "net/url" "testing" - "github.com/micro/go-micro/v2/api/resolver/vpath" + "github.com/micro/go-micro/v3/api/resolver/vpath" "github.com/stretchr/testify/assert" ) diff --git a/api/resolver/vpath/vpath.go b/api/resolver/vpath/vpath.go index 9a2b6cff..d0b6496f 100644 --- a/api/resolver/vpath/vpath.go +++ b/api/resolver/vpath/vpath.go @@ -7,7 +7,7 @@ import ( "regexp" "strings" - "github.com/micro/go-micro/v2/api/resolver" + "github.com/micro/go-micro/v3/api/resolver" ) func NewResolver(opts ...resolver.Option) resolver.Resolver { diff --git a/api/router/options.go b/api/router/options.go index 69b8a504..f5993419 100644 --- a/api/router/options.go +++ b/api/router/options.go @@ -1,9 +1,10 @@ package router import ( - "github.com/micro/go-micro/v2/api/resolver" - "github.com/micro/go-micro/v2/api/resolver/vpath" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/api/resolver" + "github.com/micro/go-micro/v3/api/resolver/vpath" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/mdns" ) type Options struct { @@ -17,7 +18,7 @@ type Option func(o *Options) func NewOptions(opts ...Option) Options { options := Options{ Handler: "meta", - Registry: registry.DefaultRegistry, + Registry: mdns.NewRegistry(), } for _, o := range opts { diff --git a/api/router/registry/registry.go b/api/router/registry/registry.go index 915598b7..202b1b4a 100644 --- a/api/router/registry/registry.go +++ b/api/router/registry/registry.go @@ -10,13 +10,13 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/api" - "github.com/micro/go-micro/v2/api/router" - "github.com/micro/go-micro/v2/api/router/util" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/registry/cache" + "github.com/micro/go-micro/v3/api" + "github.com/micro/go-micro/v3/api/router" + "github.com/micro/go-micro/v3/api/router/util" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/cache" ) // endpoint struct, that holds compiled pcre diff --git a/api/router/registry/registry_test.go b/api/router/registry/registry_test.go index 5d481386..a1ae14d1 100644 --- a/api/router/registry/registry_test.go +++ b/api/router/registry/registry_test.go @@ -3,7 +3,7 @@ package registry import ( "testing" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" "github.com/stretchr/testify/assert" ) diff --git a/api/router/router.go b/api/router/router.go index 18311804..cf119512 100644 --- a/api/router/router.go +++ b/api/router/router.go @@ -4,7 +4,7 @@ package router import ( "net/http" - "github.com/micro/go-micro/v2/api" + "github.com/micro/go-micro/v3/api" ) // Router is used to determine an endpoint for a request diff --git a/api/router/router_test.go b/api/router/router_test.go index a3c01fd2..f56c8d23 100644 --- a/api/router/router_test.go +++ b/api/router/router_test.go @@ -9,18 +9,18 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/api" - "github.com/micro/go-micro/v2/api/handler" - "github.com/micro/go-micro/v2/api/handler/rpc" - "github.com/micro/go-micro/v2/api/router" - rregistry "github.com/micro/go-micro/v2/api/router/registry" - rstatic "github.com/micro/go-micro/v2/api/router/static" - "github.com/micro/go-micro/v2/client" - gcli "github.com/micro/go-micro/v2/client/grpc" - rmemory "github.com/micro/go-micro/v2/registry/memory" - "github.com/micro/go-micro/v2/server" - gsrv "github.com/micro/go-micro/v2/server/grpc" - pb "github.com/micro/go-micro/v2/server/grpc/proto" + "github.com/micro/go-micro/v3/api" + "github.com/micro/go-micro/v3/api/handler" + "github.com/micro/go-micro/v3/api/handler/rpc" + "github.com/micro/go-micro/v3/api/router" + rregistry "github.com/micro/go-micro/v3/api/router/registry" + rstatic "github.com/micro/go-micro/v3/api/router/static" + "github.com/micro/go-micro/v3/client" + gcli "github.com/micro/go-micro/v3/client/grpc" + rmemory "github.com/micro/go-micro/v3/registry/memory" + "github.com/micro/go-micro/v3/server" + gsrv "github.com/micro/go-micro/v3/server/grpc" + pb "github.com/micro/go-micro/v3/server/grpc/proto" ) // server is used to implement helloworld.GreeterServer. diff --git a/api/router/static/static.go b/api/router/static/static.go index 7bcf1d7f..d530f4d4 100644 --- a/api/router/static/static.go +++ b/api/router/static/static.go @@ -8,13 +8,13 @@ import ( "strings" "sync" - "github.com/micro/go-micro/v2/api" - "github.com/micro/go-micro/v2/api/router" - "github.com/micro/go-micro/v2/api/router/util" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/registry" - rutil "github.com/micro/go-micro/v2/util/registry" + "github.com/micro/go-micro/v3/api" + "github.com/micro/go-micro/v3/api/router" + "github.com/micro/go-micro/v3/api/router/util" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/registry" + rutil "github.com/micro/go-micro/v3/util/registry" ) type endpoint struct { diff --git a/api/router/util/parse.go b/api/router/util/parse.go index 83db2d47..155684df 100644 --- a/api/router/util/parse.go +++ b/api/router/util/parse.go @@ -6,7 +6,7 @@ import ( "fmt" "strings" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/logger" ) // InvalidTemplateError indicates that the path template is not valid. diff --git a/api/router/util/parse_test.go b/api/router/util/parse_test.go index b15b6184..43fb5cbe 100644 --- a/api/router/util/parse_test.go +++ b/api/router/util/parse_test.go @@ -8,7 +8,7 @@ import ( "reflect" "testing" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/logger" ) func TestTokenize(t *testing.T) { diff --git a/api/router/util/runtime.go b/api/router/util/runtime.go index 7b615552..a2ba7804 100644 --- a/api/router/util/runtime.go +++ b/api/router/util/runtime.go @@ -7,7 +7,7 @@ import ( "fmt" "strings" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/logger" ) var ( diff --git a/api/server/acme/autocert/autocert.go b/api/server/acme/autocert/autocert.go index 579be51f..ab9be09a 100644 --- a/api/server/acme/autocert/autocert.go +++ b/api/server/acme/autocert/autocert.go @@ -7,8 +7,8 @@ import ( "net" "os" - "github.com/micro/go-micro/v2/api/server/acme" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/api/server/acme" + "github.com/micro/go-micro/v3/logger" "golang.org/x/crypto/acme/autocert" ) diff --git a/api/server/acme/certmagic/certmagic.go b/api/server/acme/certmagic/certmagic.go index 0123325c..3a2803d3 100644 --- a/api/server/acme/certmagic/certmagic.go +++ b/api/server/acme/certmagic/certmagic.go @@ -8,8 +8,8 @@ import ( "time" "github.com/caddyserver/certmagic" - "github.com/micro/go-micro/v2/api/server/acme" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/api/server/acme" + "github.com/micro/go-micro/v3/logger" ) type certmagicProvider struct { diff --git a/api/server/acme/certmagic/storage.go b/api/server/acme/certmagic/storage.go index e9ac1ad1..2a79516f 100644 --- a/api/server/acme/certmagic/storage.go +++ b/api/server/acme/certmagic/storage.go @@ -10,8 +10,8 @@ import ( "time" "github.com/caddyserver/certmagic" - "github.com/micro/go-micro/v2/store" - "github.com/micro/go-micro/v2/sync" + "github.com/micro/go-micro/v3/store" + "github.com/micro/go-micro/v3/sync" ) // File represents a "File" that will be stored in store.Store - the contents and last modified time diff --git a/api/server/http/http.go b/api/server/http/http.go index 518977e6..90eed2fa 100644 --- a/api/server/http/http.go +++ b/api/server/http/http.go @@ -9,9 +9,9 @@ import ( "sync" "github.com/gorilla/handlers" - "github.com/micro/go-micro/v2/api/server" - "github.com/micro/go-micro/v2/api/server/cors" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/api/server" + "github.com/micro/go-micro/v3/api/server/cors" + "github.com/micro/go-micro/v3/logger" ) type httpServer struct { diff --git a/api/server/options.go b/api/server/options.go index 6d87f543..e18117e5 100644 --- a/api/server/options.go +++ b/api/server/options.go @@ -4,8 +4,8 @@ import ( "crypto/tls" "net/http" - "github.com/micro/go-micro/v2/api/resolver" - "github.com/micro/go-micro/v2/api/server/acme" + "github.com/micro/go-micro/v3/api/resolver" + "github.com/micro/go-micro/v3/api/server/acme" ) type Option func(o *Options) diff --git a/api/service/proto/api.pb.micro.go b/api/service/proto/api.pb.micro.go index c2bcfbc6..dd683cf7 100644 --- a/api/service/proto/api.pb.micro.go +++ b/api/service/proto/api.pb.micro.go @@ -11,9 +11,9 @@ import ( import ( context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" + api "github.com/micro/go-micro/v3/api" + client "github.com/micro/go-micro/v3/client" + server "github.com/micro/go-micro/v3/server" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/auth/default.go b/auth/default.go deleted file mode 100644 index 02614936..00000000 --- a/auth/default.go +++ /dev/null @@ -1,85 +0,0 @@ -package auth - -import ( - "github.com/google/uuid" -) - -var ( - DefaultAuth = NewAuth() -) - -func NewAuth(opts ...Option) Auth { - var options Options - - for _, o := range opts { - o(&options) - } - - return &noop{ - opts: options, - } -} - -type noop struct { - opts Options -} - -// String returns the name of the implementation -func (n *noop) String() string { - return "noop" -} - -// Init the auth -func (n *noop) Init(opts ...Option) { - for _, o := range opts { - o(&n.opts) - } -} - -// Options set for auth -func (n *noop) Options() Options { - return n.opts -} - -// Generate a new account -func (n *noop) Generate(id string, opts ...GenerateOption) (*Account, error) { - options := NewGenerateOptions(opts...) - - return &Account{ - ID: id, - Secret: options.Secret, - Metadata: options.Metadata, - Scopes: options.Scopes, - Issuer: n.Options().Issuer, - }, nil -} - -// Grant access to a resource -func (n *noop) Grant(rule *Rule) error { - return nil -} - -// Revoke access to a resource -func (n *noop) Revoke(rule *Rule) error { - return nil -} - -// Rules used to verify requests -func (n *noop) Rules(opts ...RulesOption) ([]*Rule, error) { - return []*Rule{}, nil -} - -// Verify an account has access to a resource -func (n *noop) Verify(acc *Account, res *Resource, opts ...VerifyOption) error { - return nil -} - -// Inspect a token -func (n *noop) Inspect(token string) (*Account, error) { - return &Account{ID: uuid.New().String(), Issuer: n.Options().Issuer}, nil -} - -// Token generation using an account id and secret -func (n *noop) Token(opts ...TokenOption) (*Token, error) { - return &Token{}, nil -} diff --git a/auth/jwt/jwt.go b/auth/jwt/jwt.go index 49fa0b0c..ab14728f 100644 --- a/auth/jwt/jwt.go +++ b/auth/jwt/jwt.go @@ -5,9 +5,9 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/util/token" - "github.com/micro/go-micro/v2/util/token/jwt" + "github.com/micro/go-micro/v3/auth" + "github.com/micro/go-micro/v3/util/token" + "github.com/micro/go-micro/v3/util/token/jwt" ) // NewAuth returns a new instance of the Auth service diff --git a/auth/noop/noop.go b/auth/noop/noop.go new file mode 100644 index 00000000..573f4ca7 --- /dev/null +++ b/auth/noop/noop.go @@ -0,0 +1,81 @@ +package noop + +import ( + "github.com/google/uuid" + "github.com/micro/go-micro/v3/auth" +) + +func NewAuth(opts ...auth.Option) auth.Auth { + var options auth.Options + for _, o := range opts { + o(&options) + } + + return &noop{ + opts: options, + } +} + +type noop struct { + opts auth.Options +} + +// String returns the name of the implementation +func (n *noop) String() string { + return "noop" +} + +// Init the auth +func (n *noop) Init(opts ...auth.Option) { + for _, o := range opts { + o(&n.opts) + } +} + +// Options set for auth +func (n *noop) Options() auth.Options { + return n.opts +} + +// Generate a new account +func (n *noop) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) { + options := auth.NewGenerateOptions(opts...) + + return &auth.Account{ + ID: id, + Secret: options.Secret, + Metadata: options.Metadata, + Scopes: options.Scopes, + Issuer: n.Options().Issuer, + }, nil +} + +// Grant access to a resource +func (n *noop) Grant(rule *auth.Rule) error { + return nil +} + +// Revoke access to a resource +func (n *noop) Revoke(rule *auth.Rule) error { + return nil +} + +// Rules used to verify requests +func (n *noop) Rules(opts ...auth.RulesOption) ([]*auth.Rule, error) { + return []*auth.Rule{}, nil +} + +// Verify an account has access to a resource +func (n *noop) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error { + return nil +} + +// Inspect a token +func (n *noop) Inspect(token string) (*auth.Account, error) { + return &auth.Account{ID: uuid.New().String(), Issuer: n.Options().Issuer}, nil +} + +// Token generation using an account id and secret +func (n *noop) Token(opts ...auth.TokenOption) (*auth.Token, error) { + return &auth.Token{}, nil +} diff --git a/auth/options.go b/auth/options.go index 4c06b854..e1bda400 100644 --- a/auth/options.go +++ b/auth/options.go @@ -4,8 +4,7 @@ import ( "context" "time" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" ) func NewOptions(opts ...Option) Options { @@ -13,10 +12,6 @@ func NewOptions(opts ...Option) Options { for _, o := range opts { o(&options) } - if options.Client == nil { - options.Client = client.DefaultClient - } - return options } @@ -37,10 +32,10 @@ type Options struct { LoginURL string // Store to back auth Store store.Store - // Client to use for RPC - Client client.Client // Addrs sets the addresses of auth Addrs []string + // Context to store other options + Context context.Context } type Option func(o *Options) @@ -102,13 +97,6 @@ func LoginURL(url string) Option { } } -// WithClient sets the client to use when making requests -func WithClient(c client.Client) Option { - return func(o *Options) { - o.Client = c - } -} - type GenerateOptions struct { // Metadata associated with the account Metadata map[string]string diff --git a/auth/service/proto/auth.pb.go b/auth/service/proto/auth.pb.go deleted file mode 100644 index bd913c4a..00000000 --- a/auth/service/proto/auth.pb.go +++ /dev/null @@ -1,1746 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: auth/service/proto/auth.proto - -package go_micro_auth - -import ( - context "context" - fmt "fmt" - proto "github.com/golang/protobuf/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -type Access int32 - -const ( - Access_UNKNOWN Access = 0 - Access_GRANTED Access = 1 - Access_DENIED Access = 2 -) - -var Access_name = map[int32]string{ - 0: "UNKNOWN", - 1: "GRANTED", - 2: "DENIED", -} - -var Access_value = map[string]int32{ - "UNKNOWN": 0, - "GRANTED": 1, - "DENIED": 2, -} - -func (x Access) String() string { - return proto.EnumName(Access_name, int32(x)) -} - -func (Access) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{0} -} - -type ListAccountsRequest struct { - Options *Options `protobuf:"bytes,1,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListAccountsRequest) Reset() { *m = ListAccountsRequest{} } -func (m *ListAccountsRequest) String() string { return proto.CompactTextString(m) } -func (*ListAccountsRequest) ProtoMessage() {} -func (*ListAccountsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{0} -} - -func (m *ListAccountsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListAccountsRequest.Unmarshal(m, b) -} -func (m *ListAccountsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListAccountsRequest.Marshal(b, m, deterministic) -} -func (m *ListAccountsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListAccountsRequest.Merge(m, src) -} -func (m *ListAccountsRequest) XXX_Size() int { - return xxx_messageInfo_ListAccountsRequest.Size(m) -} -func (m *ListAccountsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListAccountsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListAccountsRequest proto.InternalMessageInfo - -func (m *ListAccountsRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type ListAccountsResponse struct { - Accounts []*Account `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListAccountsResponse) Reset() { *m = ListAccountsResponse{} } -func (m *ListAccountsResponse) String() string { return proto.CompactTextString(m) } -func (*ListAccountsResponse) ProtoMessage() {} -func (*ListAccountsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{1} -} - -func (m *ListAccountsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListAccountsResponse.Unmarshal(m, b) -} -func (m *ListAccountsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListAccountsResponse.Marshal(b, m, deterministic) -} -func (m *ListAccountsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListAccountsResponse.Merge(m, src) -} -func (m *ListAccountsResponse) XXX_Size() int { - return xxx_messageInfo_ListAccountsResponse.Size(m) -} -func (m *ListAccountsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListAccountsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListAccountsResponse proto.InternalMessageInfo - -func (m *ListAccountsResponse) GetAccounts() []*Account { - if m != nil { - return m.Accounts - } - return nil -} - -type DeleteAccountRequest struct { - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Options *Options `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteAccountRequest) Reset() { *m = DeleteAccountRequest{} } -func (m *DeleteAccountRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteAccountRequest) ProtoMessage() {} -func (*DeleteAccountRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{2} -} - -func (m *DeleteAccountRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteAccountRequest.Unmarshal(m, b) -} -func (m *DeleteAccountRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteAccountRequest.Marshal(b, m, deterministic) -} -func (m *DeleteAccountRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteAccountRequest.Merge(m, src) -} -func (m *DeleteAccountRequest) XXX_Size() int { - return xxx_messageInfo_DeleteAccountRequest.Size(m) -} -func (m *DeleteAccountRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteAccountRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteAccountRequest proto.InternalMessageInfo - -func (m *DeleteAccountRequest) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *DeleteAccountRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type DeleteAccountResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteAccountResponse) Reset() { *m = DeleteAccountResponse{} } -func (m *DeleteAccountResponse) String() string { return proto.CompactTextString(m) } -func (*DeleteAccountResponse) ProtoMessage() {} -func (*DeleteAccountResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{3} -} - -func (m *DeleteAccountResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteAccountResponse.Unmarshal(m, b) -} -func (m *DeleteAccountResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteAccountResponse.Marshal(b, m, deterministic) -} -func (m *DeleteAccountResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteAccountResponse.Merge(m, src) -} -func (m *DeleteAccountResponse) XXX_Size() int { - return xxx_messageInfo_DeleteAccountResponse.Size(m) -} -func (m *DeleteAccountResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteAccountResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteAccountResponse proto.InternalMessageInfo - -type Token struct { - AccessToken string `protobuf:"bytes,1,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"` - RefreshToken string `protobuf:"bytes,2,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - Created int64 `protobuf:"varint,3,opt,name=created,proto3" json:"created,omitempty"` - Expiry int64 `protobuf:"varint,4,opt,name=expiry,proto3" json:"expiry,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Token) Reset() { *m = Token{} } -func (m *Token) String() string { return proto.CompactTextString(m) } -func (*Token) ProtoMessage() {} -func (*Token) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{4} -} - -func (m *Token) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Token.Unmarshal(m, b) -} -func (m *Token) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Token.Marshal(b, m, deterministic) -} -func (m *Token) XXX_Merge(src proto.Message) { - xxx_messageInfo_Token.Merge(m, src) -} -func (m *Token) XXX_Size() int { - return xxx_messageInfo_Token.Size(m) -} -func (m *Token) XXX_DiscardUnknown() { - xxx_messageInfo_Token.DiscardUnknown(m) -} - -var xxx_messageInfo_Token proto.InternalMessageInfo - -func (m *Token) GetAccessToken() string { - if m != nil { - return m.AccessToken - } - return "" -} - -func (m *Token) GetRefreshToken() string { - if m != nil { - return m.RefreshToken - } - return "" -} - -func (m *Token) GetCreated() int64 { - if m != nil { - return m.Created - } - return 0 -} - -func (m *Token) GetExpiry() int64 { - if m != nil { - return m.Expiry - } - return 0 -} - -type Account struct { - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` - Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Scopes []string `protobuf:"bytes,5,rep,name=scopes,proto3" json:"scopes,omitempty"` - Issuer string `protobuf:"bytes,6,opt,name=issuer,proto3" json:"issuer,omitempty"` - Secret string `protobuf:"bytes,7,opt,name=secret,proto3" json:"secret,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Account) Reset() { *m = Account{} } -func (m *Account) String() string { return proto.CompactTextString(m) } -func (*Account) ProtoMessage() {} -func (*Account) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{5} -} - -func (m *Account) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Account.Unmarshal(m, b) -} -func (m *Account) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Account.Marshal(b, m, deterministic) -} -func (m *Account) XXX_Merge(src proto.Message) { - xxx_messageInfo_Account.Merge(m, src) -} -func (m *Account) XXX_Size() int { - return xxx_messageInfo_Account.Size(m) -} -func (m *Account) XXX_DiscardUnknown() { - xxx_messageInfo_Account.DiscardUnknown(m) -} - -var xxx_messageInfo_Account proto.InternalMessageInfo - -func (m *Account) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *Account) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *Account) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Account) GetScopes() []string { - if m != nil { - return m.Scopes - } - return nil -} - -func (m *Account) GetIssuer() string { - if m != nil { - return m.Issuer - } - return "" -} - -func (m *Account) GetSecret() string { - if m != nil { - return m.Secret - } - return "" -} - -type Resource struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` - Endpoint string `protobuf:"bytes,3,opt,name=endpoint,proto3" json:"endpoint,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Resource) Reset() { *m = Resource{} } -func (m *Resource) String() string { return proto.CompactTextString(m) } -func (*Resource) ProtoMessage() {} -func (*Resource) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{6} -} - -func (m *Resource) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Resource.Unmarshal(m, b) -} -func (m *Resource) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Resource.Marshal(b, m, deterministic) -} -func (m *Resource) XXX_Merge(src proto.Message) { - xxx_messageInfo_Resource.Merge(m, src) -} -func (m *Resource) XXX_Size() int { - return xxx_messageInfo_Resource.Size(m) -} -func (m *Resource) XXX_DiscardUnknown() { - xxx_messageInfo_Resource.DiscardUnknown(m) -} - -var xxx_messageInfo_Resource proto.InternalMessageInfo - -func (m *Resource) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Resource) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *Resource) GetEndpoint() string { - if m != nil { - return m.Endpoint - } - return "" -} - -type GenerateRequest struct { - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Metadata map[string]string `protobuf:"bytes,3,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Scopes []string `protobuf:"bytes,4,rep,name=scopes,proto3" json:"scopes,omitempty"` - Secret string `protobuf:"bytes,5,opt,name=secret,proto3" json:"secret,omitempty"` - Type string `protobuf:"bytes,6,opt,name=type,proto3" json:"type,omitempty"` - Provider string `protobuf:"bytes,7,opt,name=provider,proto3" json:"provider,omitempty"` - Options *Options `protobuf:"bytes,8,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GenerateRequest) Reset() { *m = GenerateRequest{} } -func (m *GenerateRequest) String() string { return proto.CompactTextString(m) } -func (*GenerateRequest) ProtoMessage() {} -func (*GenerateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{7} -} - -func (m *GenerateRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GenerateRequest.Unmarshal(m, b) -} -func (m *GenerateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GenerateRequest.Marshal(b, m, deterministic) -} -func (m *GenerateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenerateRequest.Merge(m, src) -} -func (m *GenerateRequest) XXX_Size() int { - return xxx_messageInfo_GenerateRequest.Size(m) -} -func (m *GenerateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GenerateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GenerateRequest proto.InternalMessageInfo - -func (m *GenerateRequest) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *GenerateRequest) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *GenerateRequest) GetScopes() []string { - if m != nil { - return m.Scopes - } - return nil -} - -func (m *GenerateRequest) GetSecret() string { - if m != nil { - return m.Secret - } - return "" -} - -func (m *GenerateRequest) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *GenerateRequest) GetProvider() string { - if m != nil { - return m.Provider - } - return "" -} - -func (m *GenerateRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type GenerateResponse struct { - Account *Account `protobuf:"bytes,1,opt,name=account,proto3" json:"account,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GenerateResponse) Reset() { *m = GenerateResponse{} } -func (m *GenerateResponse) String() string { return proto.CompactTextString(m) } -func (*GenerateResponse) ProtoMessage() {} -func (*GenerateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{8} -} - -func (m *GenerateResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GenerateResponse.Unmarshal(m, b) -} -func (m *GenerateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GenerateResponse.Marshal(b, m, deterministic) -} -func (m *GenerateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenerateResponse.Merge(m, src) -} -func (m *GenerateResponse) XXX_Size() int { - return xxx_messageInfo_GenerateResponse.Size(m) -} -func (m *GenerateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GenerateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GenerateResponse proto.InternalMessageInfo - -func (m *GenerateResponse) GetAccount() *Account { - if m != nil { - return m.Account - } - return nil -} - -type GrantRequest struct { - Scope string `protobuf:"bytes,1,opt,name=scope,proto3" json:"scope,omitempty"` - Resource *Resource `protobuf:"bytes,2,opt,name=resource,proto3" json:"resource,omitempty"` - Options *Options `protobuf:"bytes,3,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GrantRequest) Reset() { *m = GrantRequest{} } -func (m *GrantRequest) String() string { return proto.CompactTextString(m) } -func (*GrantRequest) ProtoMessage() {} -func (*GrantRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{9} -} - -func (m *GrantRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GrantRequest.Unmarshal(m, b) -} -func (m *GrantRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GrantRequest.Marshal(b, m, deterministic) -} -func (m *GrantRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GrantRequest.Merge(m, src) -} -func (m *GrantRequest) XXX_Size() int { - return xxx_messageInfo_GrantRequest.Size(m) -} -func (m *GrantRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GrantRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GrantRequest proto.InternalMessageInfo - -func (m *GrantRequest) GetScope() string { - if m != nil { - return m.Scope - } - return "" -} - -func (m *GrantRequest) GetResource() *Resource { - if m != nil { - return m.Resource - } - return nil -} - -func (m *GrantRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type GrantResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GrantResponse) Reset() { *m = GrantResponse{} } -func (m *GrantResponse) String() string { return proto.CompactTextString(m) } -func (*GrantResponse) ProtoMessage() {} -func (*GrantResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{10} -} - -func (m *GrantResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GrantResponse.Unmarshal(m, b) -} -func (m *GrantResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GrantResponse.Marshal(b, m, deterministic) -} -func (m *GrantResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GrantResponse.Merge(m, src) -} -func (m *GrantResponse) XXX_Size() int { - return xxx_messageInfo_GrantResponse.Size(m) -} -func (m *GrantResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GrantResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GrantResponse proto.InternalMessageInfo - -type RevokeRequest struct { - Scope string `protobuf:"bytes,1,opt,name=scope,proto3" json:"scope,omitempty"` - Resource *Resource `protobuf:"bytes,2,opt,name=resource,proto3" json:"resource,omitempty"` - Options *Options `protobuf:"bytes,3,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RevokeRequest) Reset() { *m = RevokeRequest{} } -func (m *RevokeRequest) String() string { return proto.CompactTextString(m) } -func (*RevokeRequest) ProtoMessage() {} -func (*RevokeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{11} -} - -func (m *RevokeRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RevokeRequest.Unmarshal(m, b) -} -func (m *RevokeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RevokeRequest.Marshal(b, m, deterministic) -} -func (m *RevokeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_RevokeRequest.Merge(m, src) -} -func (m *RevokeRequest) XXX_Size() int { - return xxx_messageInfo_RevokeRequest.Size(m) -} -func (m *RevokeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_RevokeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_RevokeRequest proto.InternalMessageInfo - -func (m *RevokeRequest) GetScope() string { - if m != nil { - return m.Scope - } - return "" -} - -func (m *RevokeRequest) GetResource() *Resource { - if m != nil { - return m.Resource - } - return nil -} - -func (m *RevokeRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type RevokeResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RevokeResponse) Reset() { *m = RevokeResponse{} } -func (m *RevokeResponse) String() string { return proto.CompactTextString(m) } -func (*RevokeResponse) ProtoMessage() {} -func (*RevokeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{12} -} - -func (m *RevokeResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RevokeResponse.Unmarshal(m, b) -} -func (m *RevokeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RevokeResponse.Marshal(b, m, deterministic) -} -func (m *RevokeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_RevokeResponse.Merge(m, src) -} -func (m *RevokeResponse) XXX_Size() int { - return xxx_messageInfo_RevokeResponse.Size(m) -} -func (m *RevokeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_RevokeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_RevokeResponse proto.InternalMessageInfo - -type InspectRequest struct { - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - Options *Options `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InspectRequest) Reset() { *m = InspectRequest{} } -func (m *InspectRequest) String() string { return proto.CompactTextString(m) } -func (*InspectRequest) ProtoMessage() {} -func (*InspectRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{13} -} - -func (m *InspectRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InspectRequest.Unmarshal(m, b) -} -func (m *InspectRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InspectRequest.Marshal(b, m, deterministic) -} -func (m *InspectRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_InspectRequest.Merge(m, src) -} -func (m *InspectRequest) XXX_Size() int { - return xxx_messageInfo_InspectRequest.Size(m) -} -func (m *InspectRequest) XXX_DiscardUnknown() { - xxx_messageInfo_InspectRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_InspectRequest proto.InternalMessageInfo - -func (m *InspectRequest) GetToken() string { - if m != nil { - return m.Token - } - return "" -} - -func (m *InspectRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type InspectResponse struct { - Account *Account `protobuf:"bytes,1,opt,name=account,proto3" json:"account,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InspectResponse) Reset() { *m = InspectResponse{} } -func (m *InspectResponse) String() string { return proto.CompactTextString(m) } -func (*InspectResponse) ProtoMessage() {} -func (*InspectResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{14} -} - -func (m *InspectResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InspectResponse.Unmarshal(m, b) -} -func (m *InspectResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InspectResponse.Marshal(b, m, deterministic) -} -func (m *InspectResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_InspectResponse.Merge(m, src) -} -func (m *InspectResponse) XXX_Size() int { - return xxx_messageInfo_InspectResponse.Size(m) -} -func (m *InspectResponse) XXX_DiscardUnknown() { - xxx_messageInfo_InspectResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_InspectResponse proto.InternalMessageInfo - -func (m *InspectResponse) GetAccount() *Account { - if m != nil { - return m.Account - } - return nil -} - -type TokenRequest struct { - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Secret string `protobuf:"bytes,2,opt,name=secret,proto3" json:"secret,omitempty"` - RefreshToken string `protobuf:"bytes,3,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - TokenExpiry int64 `protobuf:"varint,4,opt,name=token_expiry,json=tokenExpiry,proto3" json:"token_expiry,omitempty"` - Options *Options `protobuf:"bytes,5,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TokenRequest) Reset() { *m = TokenRequest{} } -func (m *TokenRequest) String() string { return proto.CompactTextString(m) } -func (*TokenRequest) ProtoMessage() {} -func (*TokenRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{15} -} - -func (m *TokenRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TokenRequest.Unmarshal(m, b) -} -func (m *TokenRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TokenRequest.Marshal(b, m, deterministic) -} -func (m *TokenRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_TokenRequest.Merge(m, src) -} -func (m *TokenRequest) XXX_Size() int { - return xxx_messageInfo_TokenRequest.Size(m) -} -func (m *TokenRequest) XXX_DiscardUnknown() { - xxx_messageInfo_TokenRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_TokenRequest proto.InternalMessageInfo - -func (m *TokenRequest) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *TokenRequest) GetSecret() string { - if m != nil { - return m.Secret - } - return "" -} - -func (m *TokenRequest) GetRefreshToken() string { - if m != nil { - return m.RefreshToken - } - return "" -} - -func (m *TokenRequest) GetTokenExpiry() int64 { - if m != nil { - return m.TokenExpiry - } - return 0 -} - -func (m *TokenRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type TokenResponse struct { - Token *Token `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TokenResponse) Reset() { *m = TokenResponse{} } -func (m *TokenResponse) String() string { return proto.CompactTextString(m) } -func (*TokenResponse) ProtoMessage() {} -func (*TokenResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{16} -} - -func (m *TokenResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TokenResponse.Unmarshal(m, b) -} -func (m *TokenResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TokenResponse.Marshal(b, m, deterministic) -} -func (m *TokenResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TokenResponse.Merge(m, src) -} -func (m *TokenResponse) XXX_Size() int { - return xxx_messageInfo_TokenResponse.Size(m) -} -func (m *TokenResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TokenResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TokenResponse proto.InternalMessageInfo - -func (m *TokenResponse) GetToken() *Token { - if m != nil { - return m.Token - } - return nil -} - -type Rule struct { - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Scope string `protobuf:"bytes,2,opt,name=scope,proto3" json:"scope,omitempty"` - Resource *Resource `protobuf:"bytes,3,opt,name=resource,proto3" json:"resource,omitempty"` - Access Access `protobuf:"varint,4,opt,name=access,proto3,enum=go.micro.auth.Access" json:"access,omitempty"` - Priority int32 `protobuf:"varint,5,opt,name=priority,proto3" json:"priority,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Rule) Reset() { *m = Rule{} } -func (m *Rule) String() string { return proto.CompactTextString(m) } -func (*Rule) ProtoMessage() {} -func (*Rule) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{17} -} - -func (m *Rule) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Rule.Unmarshal(m, b) -} -func (m *Rule) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Rule.Marshal(b, m, deterministic) -} -func (m *Rule) XXX_Merge(src proto.Message) { - xxx_messageInfo_Rule.Merge(m, src) -} -func (m *Rule) XXX_Size() int { - return xxx_messageInfo_Rule.Size(m) -} -func (m *Rule) XXX_DiscardUnknown() { - xxx_messageInfo_Rule.DiscardUnknown(m) -} - -var xxx_messageInfo_Rule proto.InternalMessageInfo - -func (m *Rule) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *Rule) GetScope() string { - if m != nil { - return m.Scope - } - return "" -} - -func (m *Rule) GetResource() *Resource { - if m != nil { - return m.Resource - } - return nil -} - -func (m *Rule) GetAccess() Access { - if m != nil { - return m.Access - } - return Access_UNKNOWN -} - -func (m *Rule) GetPriority() int32 { - if m != nil { - return m.Priority - } - return 0 -} - -type Options struct { - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Options) Reset() { *m = Options{} } -func (m *Options) String() string { return proto.CompactTextString(m) } -func (*Options) ProtoMessage() {} -func (*Options) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{18} -} - -func (m *Options) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Options.Unmarshal(m, b) -} -func (m *Options) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Options.Marshal(b, m, deterministic) -} -func (m *Options) XXX_Merge(src proto.Message) { - xxx_messageInfo_Options.Merge(m, src) -} -func (m *Options) XXX_Size() int { - return xxx_messageInfo_Options.Size(m) -} -func (m *Options) XXX_DiscardUnknown() { - xxx_messageInfo_Options.DiscardUnknown(m) -} - -var xxx_messageInfo_Options proto.InternalMessageInfo - -func (m *Options) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -type CreateRequest struct { - Rule *Rule `protobuf:"bytes,1,opt,name=rule,proto3" json:"rule,omitempty"` - Options *Options `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateRequest) Reset() { *m = CreateRequest{} } -func (m *CreateRequest) String() string { return proto.CompactTextString(m) } -func (*CreateRequest) ProtoMessage() {} -func (*CreateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{19} -} - -func (m *CreateRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateRequest.Unmarshal(m, b) -} -func (m *CreateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateRequest.Marshal(b, m, deterministic) -} -func (m *CreateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateRequest.Merge(m, src) -} -func (m *CreateRequest) XXX_Size() int { - return xxx_messageInfo_CreateRequest.Size(m) -} -func (m *CreateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_CreateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateRequest proto.InternalMessageInfo - -func (m *CreateRequest) GetRule() *Rule { - if m != nil { - return m.Rule - } - return nil -} - -func (m *CreateRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type CreateResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateResponse) Reset() { *m = CreateResponse{} } -func (m *CreateResponse) String() string { return proto.CompactTextString(m) } -func (*CreateResponse) ProtoMessage() {} -func (*CreateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{20} -} - -func (m *CreateResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateResponse.Unmarshal(m, b) -} -func (m *CreateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateResponse.Marshal(b, m, deterministic) -} -func (m *CreateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateResponse.Merge(m, src) -} -func (m *CreateResponse) XXX_Size() int { - return xxx_messageInfo_CreateResponse.Size(m) -} -func (m *CreateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CreateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateResponse proto.InternalMessageInfo - -type DeleteRequest struct { - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Options *Options `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteRequest) Reset() { *m = DeleteRequest{} } -func (m *DeleteRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteRequest) ProtoMessage() {} -func (*DeleteRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{21} -} - -func (m *DeleteRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteRequest.Unmarshal(m, b) -} -func (m *DeleteRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteRequest.Marshal(b, m, deterministic) -} -func (m *DeleteRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteRequest.Merge(m, src) -} -func (m *DeleteRequest) XXX_Size() int { - return xxx_messageInfo_DeleteRequest.Size(m) -} -func (m *DeleteRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteRequest proto.InternalMessageInfo - -func (m *DeleteRequest) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *DeleteRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type DeleteResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteResponse) Reset() { *m = DeleteResponse{} } -func (m *DeleteResponse) String() string { return proto.CompactTextString(m) } -func (*DeleteResponse) ProtoMessage() {} -func (*DeleteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{22} -} - -func (m *DeleteResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteResponse.Unmarshal(m, b) -} -func (m *DeleteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteResponse.Marshal(b, m, deterministic) -} -func (m *DeleteResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteResponse.Merge(m, src) -} -func (m *DeleteResponse) XXX_Size() int { - return xxx_messageInfo_DeleteResponse.Size(m) -} -func (m *DeleteResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteResponse proto.InternalMessageInfo - -type ListRequest struct { - Options *Options `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListRequest) Reset() { *m = ListRequest{} } -func (m *ListRequest) String() string { return proto.CompactTextString(m) } -func (*ListRequest) ProtoMessage() {} -func (*ListRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{23} -} - -func (m *ListRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListRequest.Unmarshal(m, b) -} -func (m *ListRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListRequest.Marshal(b, m, deterministic) -} -func (m *ListRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListRequest.Merge(m, src) -} -func (m *ListRequest) XXX_Size() int { - return xxx_messageInfo_ListRequest.Size(m) -} -func (m *ListRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListRequest proto.InternalMessageInfo - -func (m *ListRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type ListResponse struct { - Rules []*Rule `protobuf:"bytes,1,rep,name=rules,proto3" json:"rules,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListResponse) Reset() { *m = ListResponse{} } -func (m *ListResponse) String() string { return proto.CompactTextString(m) } -func (*ListResponse) ProtoMessage() {} -func (*ListResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_21300bfacc51fc2a, []int{24} -} - -func (m *ListResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListResponse.Unmarshal(m, b) -} -func (m *ListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListResponse.Marshal(b, m, deterministic) -} -func (m *ListResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListResponse.Merge(m, src) -} -func (m *ListResponse) XXX_Size() int { - return xxx_messageInfo_ListResponse.Size(m) -} -func (m *ListResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListResponse proto.InternalMessageInfo - -func (m *ListResponse) GetRules() []*Rule { - if m != nil { - return m.Rules - } - return nil -} - -func init() { - proto.RegisterEnum("go.micro.auth.Access", Access_name, Access_value) - proto.RegisterType((*ListAccountsRequest)(nil), "go.micro.auth.ListAccountsRequest") - proto.RegisterType((*ListAccountsResponse)(nil), "go.micro.auth.ListAccountsResponse") - proto.RegisterType((*DeleteAccountRequest)(nil), "go.micro.auth.DeleteAccountRequest") - proto.RegisterType((*DeleteAccountResponse)(nil), "go.micro.auth.DeleteAccountResponse") - proto.RegisterType((*Token)(nil), "go.micro.auth.Token") - proto.RegisterType((*Account)(nil), "go.micro.auth.Account") - proto.RegisterMapType((map[string]string)(nil), "go.micro.auth.Account.MetadataEntry") - proto.RegisterType((*Resource)(nil), "go.micro.auth.Resource") - proto.RegisterType((*GenerateRequest)(nil), "go.micro.auth.GenerateRequest") - proto.RegisterMapType((map[string]string)(nil), "go.micro.auth.GenerateRequest.MetadataEntry") - proto.RegisterType((*GenerateResponse)(nil), "go.micro.auth.GenerateResponse") - proto.RegisterType((*GrantRequest)(nil), "go.micro.auth.GrantRequest") - proto.RegisterType((*GrantResponse)(nil), "go.micro.auth.GrantResponse") - proto.RegisterType((*RevokeRequest)(nil), "go.micro.auth.RevokeRequest") - proto.RegisterType((*RevokeResponse)(nil), "go.micro.auth.RevokeResponse") - proto.RegisterType((*InspectRequest)(nil), "go.micro.auth.InspectRequest") - proto.RegisterType((*InspectResponse)(nil), "go.micro.auth.InspectResponse") - proto.RegisterType((*TokenRequest)(nil), "go.micro.auth.TokenRequest") - proto.RegisterType((*TokenResponse)(nil), "go.micro.auth.TokenResponse") - proto.RegisterType((*Rule)(nil), "go.micro.auth.Rule") - proto.RegisterType((*Options)(nil), "go.micro.auth.Options") - proto.RegisterType((*CreateRequest)(nil), "go.micro.auth.CreateRequest") - proto.RegisterType((*CreateResponse)(nil), "go.micro.auth.CreateResponse") - proto.RegisterType((*DeleteRequest)(nil), "go.micro.auth.DeleteRequest") - proto.RegisterType((*DeleteResponse)(nil), "go.micro.auth.DeleteResponse") - proto.RegisterType((*ListRequest)(nil), "go.micro.auth.ListRequest") - proto.RegisterType((*ListResponse)(nil), "go.micro.auth.ListResponse") -} - -func init() { proto.RegisterFile("auth/service/proto/auth.proto", fileDescriptor_21300bfacc51fc2a) } - -var fileDescriptor_21300bfacc51fc2a = []byte{ - // 976 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x57, 0xcd, 0x6e, 0xdb, 0x46, - 0x10, 0x36, 0xf5, 0xef, 0xd1, 0x8f, 0x85, 0x8d, 0x92, 0x08, 0x8a, 0x9d, 0x3a, 0x4c, 0x80, 0xb8, - 0x41, 0x2b, 0x07, 0xca, 0xa5, 0x6d, 0x0e, 0xad, 0x11, 0x09, 0x6a, 0xd2, 0x46, 0x41, 0x88, 0x04, - 0xcd, 0xcd, 0x60, 0xa9, 0x69, 0xcd, 0x5a, 0x26, 0xd9, 0xdd, 0xa5, 0x51, 0x1d, 0x7b, 0x6e, 0x1f, - 0xa5, 0x87, 0x1e, 0x7a, 0xea, 0xb3, 0xf4, 0xde, 0x17, 0xe8, 0x03, 0x14, 0xdc, 0x9d, 0xa5, 0x29, - 0x9a, 0x32, 0x04, 0xb7, 0x87, 0xdc, 0x38, 0x3f, 0x3b, 0xfb, 0xcd, 0xb7, 0x33, 0xb3, 0x4b, 0xd8, - 0x73, 0x63, 0x79, 0x72, 0x28, 0x90, 0x9f, 0xfb, 0x1e, 0x1e, 0x46, 0x3c, 0x94, 0xe1, 0x61, 0xa2, - 0x1a, 0xaa, 0x4f, 0xd6, 0xfe, 0x3e, 0x1c, 0x9e, 0xf9, 0x1e, 0x0f, 0x87, 0x89, 0xd2, 0x9e, 0xc2, - 0x8d, 0xaf, 0x7d, 0x21, 0x8f, 0x3c, 0x2f, 0x8c, 0x03, 0x29, 0x1c, 0xfc, 0x31, 0x46, 0x21, 0xd9, - 0x63, 0xa8, 0x87, 0x91, 0xf4, 0xc3, 0x40, 0xf4, 0xad, 0x7d, 0xeb, 0xa0, 0x39, 0xba, 0x35, 0x5c, - 0x59, 0x37, 0x7c, 0xa5, 0xad, 0x8e, 0x71, 0xb3, 0x5f, 0x40, 0x6f, 0x35, 0x90, 0x88, 0xc2, 0x40, - 0x20, 0x1b, 0x41, 0xc3, 0x25, 0x5d, 0xdf, 0xda, 0x2f, 0x17, 0x84, 0xa2, 0x25, 0x4e, 0xea, 0x67, - 0xbf, 0x83, 0xde, 0x18, 0x17, 0x28, 0xd1, 0x98, 0x08, 0x55, 0x07, 0x4a, 0xfe, 0x5c, 0x01, 0xda, - 0x76, 0x4a, 0xfe, 0x3c, 0x8b, 0xb2, 0xb4, 0x19, 0xca, 0xdb, 0x70, 0x33, 0x17, 0x59, 0xc3, 0xb4, - 0x7f, 0xb6, 0xa0, 0xfa, 0x26, 0x3c, 0xc5, 0x80, 0xdd, 0x83, 0x96, 0xeb, 0x79, 0x28, 0xc4, 0xb1, - 0x4c, 0x64, 0xda, 0xae, 0xa9, 0x75, 0xda, 0xe5, 0x3e, 0xb4, 0x39, 0x7e, 0xc7, 0x51, 0x9c, 0x90, - 0x4f, 0x49, 0xf9, 0xb4, 0x48, 0xa9, 0x9d, 0xfa, 0x50, 0xf7, 0x38, 0xba, 0x12, 0xe7, 0xfd, 0xf2, - 0xbe, 0x75, 0x50, 0x76, 0x8c, 0xc8, 0x6e, 0x41, 0x0d, 0x7f, 0x8a, 0x7c, 0xbe, 0xec, 0x57, 0x94, - 0x81, 0x24, 0xfb, 0x1f, 0x0b, 0xea, 0x84, 0xeb, 0x52, 0xaa, 0x0c, 0x2a, 0x72, 0x19, 0x21, 0xed, - 0xa4, 0xbe, 0xd9, 0x17, 0xd0, 0x38, 0x43, 0xe9, 0xce, 0x5d, 0xe9, 0xf6, 0x2b, 0x8a, 0xda, 0x07, - 0xc5, 0xd4, 0x0e, 0x5f, 0x92, 0xdb, 0x24, 0x90, 0x7c, 0xe9, 0xa4, 0xab, 0x12, 0x24, 0xc2, 0x0b, - 0x23, 0x14, 0xfd, 0xea, 0x7e, 0xf9, 0x60, 0xdb, 0x21, 0x29, 0xd1, 0xfb, 0x42, 0xc4, 0xc8, 0xfb, - 0x35, 0xb5, 0x1f, 0x49, 0xca, 0x1f, 0x3d, 0x8e, 0xb2, 0x5f, 0xd7, 0x7a, 0x2d, 0x0d, 0x9e, 0x42, - 0x7b, 0x65, 0x0b, 0xd6, 0x85, 0xf2, 0x29, 0x2e, 0x09, 0x7f, 0xf2, 0xc9, 0x7a, 0x50, 0x3d, 0x77, - 0x17, 0xb1, 0xc9, 0x40, 0x0b, 0x9f, 0x95, 0x3e, 0xb1, 0xec, 0x19, 0x34, 0x1c, 0x14, 0x61, 0xcc, - 0x3d, 0x4c, 0xd2, 0x0c, 0xdc, 0x33, 0xa4, 0x85, 0xea, 0xbb, 0x30, 0xf5, 0x01, 0x34, 0x30, 0x98, - 0x47, 0xa1, 0x1f, 0x48, 0xc5, 0xee, 0xb6, 0x93, 0xca, 0xf6, 0x9f, 0x25, 0xd8, 0x99, 0x62, 0x80, - 0xdc, 0x95, 0xb8, 0xae, 0x72, 0xbe, 0xcc, 0x50, 0x57, 0x56, 0xd4, 0x7d, 0x94, 0xa3, 0x2e, 0x17, - 0x61, 0x03, 0x0a, 0x2b, 0x79, 0x0a, 0x89, 0xaa, 0x6a, 0x96, 0xaa, 0x34, 0x9b, 0xda, 0x6a, 0x36, - 0x11, 0x0f, 0xcf, 0xfd, 0x39, 0x72, 0x22, 0x36, 0x95, 0xb3, 0x35, 0xde, 0xd8, 0xa8, 0xc6, 0xff, - 0xdb, 0x61, 0x8c, 0xa1, 0x7b, 0x91, 0x39, 0xb5, 0xf0, 0x63, 0xa8, 0x53, 0x6b, 0xae, 0x19, 0x06, - 0xa6, 0x99, 0x8c, 0x9b, 0xfd, 0x8b, 0x05, 0xad, 0x29, 0x77, 0x2f, 0x3a, 0xb7, 0x07, 0x55, 0xc5, - 0x0b, 0x81, 0xd0, 0x02, 0x7b, 0x02, 0x0d, 0x4e, 0x27, 0x4f, 0x0d, 0x7c, 0x3b, 0x17, 0xd9, 0x14, - 0x86, 0x93, 0x3a, 0x66, 0x09, 0x29, 0x6f, 0xd6, 0xf4, 0x3b, 0xd0, 0x26, 0x30, 0xd4, 0xec, 0xbf, - 0x5a, 0xd0, 0x76, 0xf0, 0x3c, 0x3c, 0xc5, 0xf7, 0x02, 0x5f, 0x17, 0x3a, 0x06, 0x0d, 0x01, 0x7c, - 0x07, 0x9d, 0xe7, 0x81, 0x88, 0xd0, 0xcb, 0x12, 0x98, 0x1d, 0x47, 0x5a, 0xb8, 0xc6, 0x00, 0x7c, - 0x06, 0x3b, 0x69, 0xe4, 0x6b, 0x1f, 0xef, 0xef, 0x16, 0xb4, 0xd4, 0x90, 0x5b, 0xd7, 0x5e, 0x17, - 0xc5, 0x5f, 0x5a, 0x29, 0xfe, 0x4b, 0x83, 0xb3, 0x5c, 0x30, 0x38, 0xef, 0x41, 0x4b, 0x19, 0x8f, - 0x57, 0x86, 0x64, 0x53, 0xe9, 0x26, 0x4a, 0x95, 0xcd, 0xbb, 0xba, 0x59, 0xde, 0x4f, 0xa1, 0x4d, - 0x88, 0x29, 0xeb, 0x47, 0x59, 0x42, 0x9b, 0xa3, 0x5e, 0x2e, 0x80, 0x76, 0xd6, 0x2e, 0xf6, 0x6f, - 0x16, 0x54, 0x9c, 0x78, 0x81, 0x97, 0xf2, 0x4c, 0xcb, 0xa6, 0xb4, 0xae, 0x6c, 0xca, 0x9b, 0x96, - 0xcd, 0xc7, 0x50, 0xd3, 0x57, 0x8c, 0xca, 0xb7, 0x33, 0xba, 0x79, 0xf9, 0x10, 0x50, 0x08, 0x87, - 0x9c, 0xf4, 0xc8, 0xf0, 0x43, 0xee, 0xcb, 0xa5, 0xa2, 0xa0, 0xea, 0xa4, 0xb2, 0xfd, 0x10, 0xea, - 0x94, 0x3f, 0xdb, 0x85, 0xed, 0x64, 0x86, 0x8a, 0xc8, 0xf5, 0x4c, 0x6d, 0x5f, 0x28, 0xec, 0x1f, - 0xa0, 0xfd, 0x4c, 0xdd, 0x49, 0xe6, 0x1c, 0x1f, 0x42, 0x85, 0xc7, 0x0b, 0x24, 0x4e, 0x6e, 0xe4, - 0x51, 0xc7, 0x0b, 0x74, 0x94, 0xc3, 0x35, 0x0a, 0xaf, 0x0b, 0x1d, 0xb3, 0x17, 0x15, 0xf9, 0x6b, - 0x68, 0xeb, 0xbb, 0xf8, 0xff, 0xbb, 0xde, 0xbb, 0xd0, 0x31, 0x21, 0x69, 0x93, 0xcf, 0xa1, 0x99, - 0x3c, 0x4b, 0x0a, 0xde, 0x35, 0x1b, 0x86, 0xfc, 0x14, 0x5a, 0x3a, 0x00, 0xd5, 0xcd, 0x87, 0x50, - 0x4d, 0x18, 0x30, 0x8f, 0x99, 0x42, 0x8e, 0xb4, 0xc7, 0xa3, 0x21, 0xd4, 0xf4, 0xa9, 0xb1, 0x26, - 0xd4, 0xdf, 0xce, 0xbe, 0x9a, 0xbd, 0xfa, 0x66, 0xd6, 0xdd, 0x4a, 0x84, 0xa9, 0x73, 0x34, 0x7b, - 0x33, 0x19, 0x77, 0x2d, 0x06, 0x50, 0x1b, 0x4f, 0x66, 0xcf, 0x27, 0xe3, 0x6e, 0x69, 0xf4, 0xb7, - 0x05, 0x95, 0xa3, 0x58, 0x9e, 0xb0, 0x97, 0xd0, 0x30, 0x43, 0x98, 0xdd, 0xbd, 0xfa, 0x5e, 0x1a, - 0x7c, 0xb0, 0xd6, 0x4e, 0x0c, 0x6c, 0xb1, 0x17, 0x50, 0xa7, 0x9e, 0x67, 0x7b, 0x39, 0xef, 0xd5, - 0x29, 0x33, 0xb8, 0xbb, 0xce, 0x9c, 0xc6, 0x1a, 0x9b, 0x67, 0xd2, 0x9d, 0xc2, 0x86, 0xa1, 0x38, - 0xbb, 0xc5, 0x46, 0x13, 0x65, 0xf4, 0x87, 0x05, 0x0d, 0xf3, 0x52, 0x64, 0xaf, 0xa1, 0x92, 0x30, - 0xcc, 0xec, 0xdc, 0xa2, 0x82, 0x77, 0xe9, 0xe0, 0xfe, 0x95, 0x3e, 0x29, 0xca, 0xb7, 0x50, 0xd3, - 0x75, 0xc0, 0xf2, 0x0b, 0x8a, 0xde, 0x95, 0x83, 0x07, 0x57, 0x3b, 0xa5, 0xb0, 0xff, 0xb2, 0xa0, - 0x9a, 0x1c, 0xb0, 0x60, 0x53, 0xa8, 0xe9, 0x6a, 0x66, 0xf9, 0x54, 0x57, 0x1a, 0x6a, 0xb0, 0xb7, - 0xc6, 0x9a, 0x22, 0x9d, 0xa6, 0x48, 0x77, 0x0b, 0x41, 0xac, 0x0b, 0x94, 0x2b, 0xf3, 0x2d, 0x76, - 0x44, 0x2c, 0x0e, 0x0a, 0x18, 0x32, 0x41, 0xee, 0x14, 0xda, 0x4c, 0x88, 0x6f, 0x6b, 0xea, 0x0f, - 0xe1, 0xc9, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x6a, 0xc6, 0x9f, 0x04, 0x42, 0x0c, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// AuthClient is the client API for Auth service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type AuthClient interface { - Generate(ctx context.Context, in *GenerateRequest, opts ...grpc.CallOption) (*GenerateResponse, error) - Inspect(ctx context.Context, in *InspectRequest, opts ...grpc.CallOption) (*InspectResponse, error) - Token(ctx context.Context, in *TokenRequest, opts ...grpc.CallOption) (*TokenResponse, error) -} - -type authClient struct { - cc *grpc.ClientConn -} - -func NewAuthClient(cc *grpc.ClientConn) AuthClient { - return &authClient{cc} -} - -func (c *authClient) Generate(ctx context.Context, in *GenerateRequest, opts ...grpc.CallOption) (*GenerateResponse, error) { - out := new(GenerateResponse) - err := c.cc.Invoke(ctx, "/go.micro.auth.Auth/Generate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authClient) Inspect(ctx context.Context, in *InspectRequest, opts ...grpc.CallOption) (*InspectResponse, error) { - out := new(InspectResponse) - err := c.cc.Invoke(ctx, "/go.micro.auth.Auth/Inspect", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authClient) Token(ctx context.Context, in *TokenRequest, opts ...grpc.CallOption) (*TokenResponse, error) { - out := new(TokenResponse) - err := c.cc.Invoke(ctx, "/go.micro.auth.Auth/Token", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AuthServer is the server API for Auth service. -type AuthServer interface { - Generate(context.Context, *GenerateRequest) (*GenerateResponse, error) - Inspect(context.Context, *InspectRequest) (*InspectResponse, error) - Token(context.Context, *TokenRequest) (*TokenResponse, error) -} - -// UnimplementedAuthServer can be embedded to have forward compatible implementations. -type UnimplementedAuthServer struct { -} - -func (*UnimplementedAuthServer) Generate(ctx context.Context, req *GenerateRequest) (*GenerateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Generate not implemented") -} -func (*UnimplementedAuthServer) Inspect(ctx context.Context, req *InspectRequest) (*InspectResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Inspect not implemented") -} -func (*UnimplementedAuthServer) Token(ctx context.Context, req *TokenRequest) (*TokenResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Token not implemented") -} - -func RegisterAuthServer(s *grpc.Server, srv AuthServer) { - s.RegisterService(&_Auth_serviceDesc, srv) -} - -func _Auth_Generate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GenerateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServer).Generate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.auth.Auth/Generate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServer).Generate(ctx, req.(*GenerateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Auth_Inspect_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(InspectRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServer).Inspect(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.auth.Auth/Inspect", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServer).Inspect(ctx, req.(*InspectRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Auth_Token_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(TokenRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServer).Token(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.auth.Auth/Token", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServer).Token(ctx, req.(*TokenRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Auth_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.auth.Auth", - HandlerType: (*AuthServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Generate", - Handler: _Auth_Generate_Handler, - }, - { - MethodName: "Inspect", - Handler: _Auth_Inspect_Handler, - }, - { - MethodName: "Token", - Handler: _Auth_Token_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "auth/service/proto/auth.proto", -} - -// AccountsClient is the client API for Accounts service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type AccountsClient interface { - List(ctx context.Context, in *ListAccountsRequest, opts ...grpc.CallOption) (*ListAccountsResponse, error) - Delete(ctx context.Context, in *DeleteAccountRequest, opts ...grpc.CallOption) (*DeleteAccountResponse, error) -} - -type accountsClient struct { - cc *grpc.ClientConn -} - -func NewAccountsClient(cc *grpc.ClientConn) AccountsClient { - return &accountsClient{cc} -} - -func (c *accountsClient) List(ctx context.Context, in *ListAccountsRequest, opts ...grpc.CallOption) (*ListAccountsResponse, error) { - out := new(ListAccountsResponse) - err := c.cc.Invoke(ctx, "/go.micro.auth.Accounts/List", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *accountsClient) Delete(ctx context.Context, in *DeleteAccountRequest, opts ...grpc.CallOption) (*DeleteAccountResponse, error) { - out := new(DeleteAccountResponse) - err := c.cc.Invoke(ctx, "/go.micro.auth.Accounts/Delete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AccountsServer is the server API for Accounts service. -type AccountsServer interface { - List(context.Context, *ListAccountsRequest) (*ListAccountsResponse, error) - Delete(context.Context, *DeleteAccountRequest) (*DeleteAccountResponse, error) -} - -// UnimplementedAccountsServer can be embedded to have forward compatible implementations. -type UnimplementedAccountsServer struct { -} - -func (*UnimplementedAccountsServer) List(ctx context.Context, req *ListAccountsRequest) (*ListAccountsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method List not implemented") -} -func (*UnimplementedAccountsServer) Delete(ctx context.Context, req *DeleteAccountRequest) (*DeleteAccountResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") -} - -func RegisterAccountsServer(s *grpc.Server, srv AccountsServer) { - s.RegisterService(&_Accounts_serviceDesc, srv) -} - -func _Accounts_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListAccountsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AccountsServer).List(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.auth.Accounts/List", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AccountsServer).List(ctx, req.(*ListAccountsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Accounts_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteAccountRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AccountsServer).Delete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.auth.Accounts/Delete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AccountsServer).Delete(ctx, req.(*DeleteAccountRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Accounts_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.auth.Accounts", - HandlerType: (*AccountsServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "List", - Handler: _Accounts_List_Handler, - }, - { - MethodName: "Delete", - Handler: _Accounts_Delete_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "auth/service/proto/auth.proto", -} - -// RulesClient is the client API for Rules service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type RulesClient interface { - Create(ctx context.Context, in *CreateRequest, opts ...grpc.CallOption) (*CreateResponse, error) - Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) - List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) -} - -type rulesClient struct { - cc *grpc.ClientConn -} - -func NewRulesClient(cc *grpc.ClientConn) RulesClient { - return &rulesClient{cc} -} - -func (c *rulesClient) Create(ctx context.Context, in *CreateRequest, opts ...grpc.CallOption) (*CreateResponse, error) { - out := new(CreateResponse) - err := c.cc.Invoke(ctx, "/go.micro.auth.Rules/Create", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *rulesClient) Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) { - out := new(DeleteResponse) - err := c.cc.Invoke(ctx, "/go.micro.auth.Rules/Delete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *rulesClient) List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) { - out := new(ListResponse) - err := c.cc.Invoke(ctx, "/go.micro.auth.Rules/List", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// RulesServer is the server API for Rules service. -type RulesServer interface { - Create(context.Context, *CreateRequest) (*CreateResponse, error) - Delete(context.Context, *DeleteRequest) (*DeleteResponse, error) - List(context.Context, *ListRequest) (*ListResponse, error) -} - -// UnimplementedRulesServer can be embedded to have forward compatible implementations. -type UnimplementedRulesServer struct { -} - -func (*UnimplementedRulesServer) Create(ctx context.Context, req *CreateRequest) (*CreateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Create not implemented") -} -func (*UnimplementedRulesServer) Delete(ctx context.Context, req *DeleteRequest) (*DeleteResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") -} -func (*UnimplementedRulesServer) List(ctx context.Context, req *ListRequest) (*ListResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method List not implemented") -} - -func RegisterRulesServer(s *grpc.Server, srv RulesServer) { - s.RegisterService(&_Rules_serviceDesc, srv) -} - -func _Rules_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CreateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RulesServer).Create(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.auth.Rules/Create", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RulesServer).Create(ctx, req.(*CreateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Rules_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RulesServer).Delete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.auth.Rules/Delete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RulesServer).Delete(ctx, req.(*DeleteRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Rules_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RulesServer).List(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.auth.Rules/List", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RulesServer).List(ctx, req.(*ListRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Rules_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.auth.Rules", - HandlerType: (*RulesServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Create", - Handler: _Rules_Create_Handler, - }, - { - MethodName: "Delete", - Handler: _Rules_Delete_Handler, - }, - { - MethodName: "List", - Handler: _Rules_List_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "auth/service/proto/auth.proto", -} diff --git a/auth/service/proto/auth.pb.micro.go b/auth/service/proto/auth.pb.micro.go deleted file mode 100644 index 0a69c871..00000000 --- a/auth/service/proto/auth.pb.micro.go +++ /dev/null @@ -1,296 +0,0 @@ -// Code generated by protoc-gen-micro. DO NOT EDIT. -// source: auth/service/proto/auth.proto - -package go_micro_auth - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -import ( - context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ api.Endpoint -var _ context.Context -var _ client.Option -var _ server.Option - -// Api Endpoints for Auth service - -func NewAuthEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Auth service - -type AuthService interface { - Generate(ctx context.Context, in *GenerateRequest, opts ...client.CallOption) (*GenerateResponse, error) - Inspect(ctx context.Context, in *InspectRequest, opts ...client.CallOption) (*InspectResponse, error) - Token(ctx context.Context, in *TokenRequest, opts ...client.CallOption) (*TokenResponse, error) -} - -type authService struct { - c client.Client - name string -} - -func NewAuthService(name string, c client.Client) AuthService { - return &authService{ - c: c, - name: name, - } -} - -func (c *authService) Generate(ctx context.Context, in *GenerateRequest, opts ...client.CallOption) (*GenerateResponse, error) { - req := c.c.NewRequest(c.name, "Auth.Generate", in) - out := new(GenerateResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authService) Inspect(ctx context.Context, in *InspectRequest, opts ...client.CallOption) (*InspectResponse, error) { - req := c.c.NewRequest(c.name, "Auth.Inspect", in) - out := new(InspectResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authService) Token(ctx context.Context, in *TokenRequest, opts ...client.CallOption) (*TokenResponse, error) { - req := c.c.NewRequest(c.name, "Auth.Token", in) - out := new(TokenResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Auth service - -type AuthHandler interface { - Generate(context.Context, *GenerateRequest, *GenerateResponse) error - Inspect(context.Context, *InspectRequest, *InspectResponse) error - Token(context.Context, *TokenRequest, *TokenResponse) error -} - -func RegisterAuthHandler(s server.Server, hdlr AuthHandler, opts ...server.HandlerOption) error { - type auth interface { - Generate(ctx context.Context, in *GenerateRequest, out *GenerateResponse) error - Inspect(ctx context.Context, in *InspectRequest, out *InspectResponse) error - Token(ctx context.Context, in *TokenRequest, out *TokenResponse) error - } - type Auth struct { - auth - } - h := &authHandler{hdlr} - return s.Handle(s.NewHandler(&Auth{h}, opts...)) -} - -type authHandler struct { - AuthHandler -} - -func (h *authHandler) Generate(ctx context.Context, in *GenerateRequest, out *GenerateResponse) error { - return h.AuthHandler.Generate(ctx, in, out) -} - -func (h *authHandler) Inspect(ctx context.Context, in *InspectRequest, out *InspectResponse) error { - return h.AuthHandler.Inspect(ctx, in, out) -} - -func (h *authHandler) Token(ctx context.Context, in *TokenRequest, out *TokenResponse) error { - return h.AuthHandler.Token(ctx, in, out) -} - -// Api Endpoints for Accounts service - -func NewAccountsEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Accounts service - -type AccountsService interface { - List(ctx context.Context, in *ListAccountsRequest, opts ...client.CallOption) (*ListAccountsResponse, error) - Delete(ctx context.Context, in *DeleteAccountRequest, opts ...client.CallOption) (*DeleteAccountResponse, error) -} - -type accountsService struct { - c client.Client - name string -} - -func NewAccountsService(name string, c client.Client) AccountsService { - return &accountsService{ - c: c, - name: name, - } -} - -func (c *accountsService) List(ctx context.Context, in *ListAccountsRequest, opts ...client.CallOption) (*ListAccountsResponse, error) { - req := c.c.NewRequest(c.name, "Accounts.List", in) - out := new(ListAccountsResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *accountsService) Delete(ctx context.Context, in *DeleteAccountRequest, opts ...client.CallOption) (*DeleteAccountResponse, error) { - req := c.c.NewRequest(c.name, "Accounts.Delete", in) - out := new(DeleteAccountResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Accounts service - -type AccountsHandler interface { - List(context.Context, *ListAccountsRequest, *ListAccountsResponse) error - Delete(context.Context, *DeleteAccountRequest, *DeleteAccountResponse) error -} - -func RegisterAccountsHandler(s server.Server, hdlr AccountsHandler, opts ...server.HandlerOption) error { - type accounts interface { - List(ctx context.Context, in *ListAccountsRequest, out *ListAccountsResponse) error - Delete(ctx context.Context, in *DeleteAccountRequest, out *DeleteAccountResponse) error - } - type Accounts struct { - accounts - } - h := &accountsHandler{hdlr} - return s.Handle(s.NewHandler(&Accounts{h}, opts...)) -} - -type accountsHandler struct { - AccountsHandler -} - -func (h *accountsHandler) List(ctx context.Context, in *ListAccountsRequest, out *ListAccountsResponse) error { - return h.AccountsHandler.List(ctx, in, out) -} - -func (h *accountsHandler) Delete(ctx context.Context, in *DeleteAccountRequest, out *DeleteAccountResponse) error { - return h.AccountsHandler.Delete(ctx, in, out) -} - -// Api Endpoints for Rules service - -func NewRulesEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Rules service - -type RulesService interface { - Create(ctx context.Context, in *CreateRequest, opts ...client.CallOption) (*CreateResponse, error) - Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) - List(ctx context.Context, in *ListRequest, opts ...client.CallOption) (*ListResponse, error) -} - -type rulesService struct { - c client.Client - name string -} - -func NewRulesService(name string, c client.Client) RulesService { - return &rulesService{ - c: c, - name: name, - } -} - -func (c *rulesService) Create(ctx context.Context, in *CreateRequest, opts ...client.CallOption) (*CreateResponse, error) { - req := c.c.NewRequest(c.name, "Rules.Create", in) - out := new(CreateResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *rulesService) Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) { - req := c.c.NewRequest(c.name, "Rules.Delete", in) - out := new(DeleteResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *rulesService) List(ctx context.Context, in *ListRequest, opts ...client.CallOption) (*ListResponse, error) { - req := c.c.NewRequest(c.name, "Rules.List", in) - out := new(ListResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Rules service - -type RulesHandler interface { - Create(context.Context, *CreateRequest, *CreateResponse) error - Delete(context.Context, *DeleteRequest, *DeleteResponse) error - List(context.Context, *ListRequest, *ListResponse) error -} - -func RegisterRulesHandler(s server.Server, hdlr RulesHandler, opts ...server.HandlerOption) error { - type rules interface { - Create(ctx context.Context, in *CreateRequest, out *CreateResponse) error - Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error - List(ctx context.Context, in *ListRequest, out *ListResponse) error - } - type Rules struct { - rules - } - h := &rulesHandler{hdlr} - return s.Handle(s.NewHandler(&Rules{h}, opts...)) -} - -type rulesHandler struct { - RulesHandler -} - -func (h *rulesHandler) Create(ctx context.Context, in *CreateRequest, out *CreateResponse) error { - return h.RulesHandler.Create(ctx, in, out) -} - -func (h *rulesHandler) Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error { - return h.RulesHandler.Delete(ctx, in, out) -} - -func (h *rulesHandler) List(ctx context.Context, in *ListRequest, out *ListResponse) error { - return h.RulesHandler.List(ctx, in, out) -} diff --git a/auth/service/proto/auth.proto b/auth/service/proto/auth.proto deleted file mode 100644 index 0c701d81..00000000 --- a/auth/service/proto/auth.proto +++ /dev/null @@ -1,148 +0,0 @@ -syntax = "proto3"; - -package go.micro.auth; - -service Auth { - rpc Generate(GenerateRequest) returns (GenerateResponse) {}; - rpc Inspect(InspectRequest) returns (InspectResponse) {}; - rpc Token(TokenRequest) returns (TokenResponse) {}; -} - -service Accounts { - rpc List(ListAccountsRequest) returns (ListAccountsResponse) {}; - rpc Delete(DeleteAccountRequest) returns (DeleteAccountResponse) {}; -} - -service Rules { - rpc Create(CreateRequest) returns (CreateResponse) {}; - rpc Delete(DeleteRequest) returns (DeleteResponse) {}; - rpc List(ListRequest) returns (ListResponse) {}; -} - -message ListAccountsRequest { - Options options = 1; -} - -message ListAccountsResponse { - repeated Account accounts = 1; -} - -message DeleteAccountRequest { - string id = 1; - Options options = 2; -} - -message DeleteAccountResponse {} - -message Token { - string access_token = 1; - string refresh_token = 2; - int64 created = 3; - int64 expiry = 4; -} - -message Account { - string id = 1; - string type = 2; - map metadata = 4; - repeated string scopes = 5; - string issuer = 6; - string secret = 7; -} - -message Resource{ - string name = 1; - string type = 2; - string endpoint = 3; -} - -message GenerateRequest { - string id = 1; - map metadata = 3; - repeated string scopes = 4; - string secret = 5; - string type = 6; - string provider = 7; - Options options = 8; -} - -message GenerateResponse { - Account account = 1; -} - -message GrantRequest { - string scope = 1; - Resource resource = 2; - Options options = 3; -} - -message GrantResponse {} - -message RevokeRequest { - string scope = 1; - Resource resource = 2; - Options options = 3; -} - -message RevokeResponse {} - -message InspectRequest { - string token = 1; - Options options = 2; -} - -message InspectResponse { - Account account = 1; -} - -message TokenRequest { - string id = 1; - string secret = 2; - string refresh_token = 3; - int64 token_expiry = 4; - Options options = 5; -} - -message TokenResponse { - Token token = 1; -} - -enum Access { - UNKNOWN = 0; - GRANTED = 1; - DENIED = 2; -} - -message Rule { - string id = 1; - string scope = 2; - Resource resource = 3; - Access access = 4; - int32 priority = 5; -} - -message Options { - string namespace = 1; -} - -message CreateRequest { - Rule rule = 1; - Options options = 2; -} - -message CreateResponse {} - -message DeleteRequest { - string id = 1; - Options options = 2; -} - -message DeleteResponse {} - -message ListRequest { - Options options = 2; -} - -message ListResponse { - repeated Rule rules = 1; -} diff --git a/auth/service/service.go b/auth/service/service.go deleted file mode 100644 index efd94980..00000000 --- a/auth/service/service.go +++ /dev/null @@ -1,325 +0,0 @@ -// Package servie is a micro service implementation of the auth interface -package service - -import ( - "context" - "strings" - "time" - - "github.com/micro/go-micro/v2/auth" - pb "github.com/micro/go-micro/v2/auth/service/proto" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/util/token" - "github.com/micro/go-micro/v2/util/token/jwt" -) - -// svc is the service implementation of the Auth interface -type svcAuth struct { - options auth.Options - auth pb.AuthService - rules pb.RulesService - token token.Provider -} - -func (s *svcAuth) String() string { - return "service" -} - -func (s *svcAuth) Init(opts ...auth.Option) { - for _, o := range opts { - o(&s.options) - } - - s.auth = pb.NewAuthService("go.micro.auth", s.options.Client) - s.rules = pb.NewRulesService("go.micro.auth", s.options.Client) - - s.setupJWT() -} - -func (s *svcAuth) Options() auth.Options { - return s.options -} - -// Generate a new account -func (s *svcAuth) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) { - options := auth.NewGenerateOptions(opts...) - if len(options.Issuer) == 0 { - options.Issuer = s.options.Issuer - } - - // we have the JWT private key and generate ourselves an account - if len(s.options.PrivateKey) > 0 { - acc := &auth.Account{ - ID: id, - Type: options.Type, - Scopes: options.Scopes, - Metadata: options.Metadata, - Issuer: options.Issuer, - } - - tok, err := s.token.Generate(acc, token.WithExpiry(time.Hour*24*365)) - if err != nil { - return nil, err - } - - // when using JWTs, the account secret is the JWT's token. This - // can be used as an argument in the Token method. - acc.Secret = tok.Token - return acc, nil - } - - rsp, err := s.auth.Generate(context.TODO(), &pb.GenerateRequest{ - Id: id, - Type: options.Type, - Secret: options.Secret, - Scopes: options.Scopes, - Metadata: options.Metadata, - Provider: options.Provider, - Options: &pb.Options{ - Namespace: options.Issuer, - }, - }, s.callOpts()...) - if err != nil { - return nil, err - } - - return serializeAccount(rsp.Account), nil -} - -// Grant access to a resource -func (s *svcAuth) Grant(rule *auth.Rule) error { - access := pb.Access_UNKNOWN - if rule.Access == auth.AccessGranted { - access = pb.Access_GRANTED - } else if rule.Access == auth.AccessDenied { - access = pb.Access_DENIED - } - - _, err := s.rules.Create(context.TODO(), &pb.CreateRequest{ - Rule: &pb.Rule{ - Id: rule.ID, - Scope: rule.Scope, - Priority: rule.Priority, - Access: access, - Resource: &pb.Resource{ - Type: rule.Resource.Type, - Name: rule.Resource.Name, - Endpoint: rule.Resource.Endpoint, - }, - }, - Options: &pb.Options{ - Namespace: s.Options().Issuer, - }, - }, s.callOpts()...) - - return err -} - -// Revoke access to a resource -func (s *svcAuth) Revoke(rule *auth.Rule) error { - _, err := s.rules.Delete(context.TODO(), &pb.DeleteRequest{ - Id: rule.ID, Options: &pb.Options{ - Namespace: s.Options().Issuer, - }, - }, s.callOpts()...) - - return err -} - -func (s *svcAuth) Rules(opts ...auth.RulesOption) ([]*auth.Rule, error) { - var options auth.RulesOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.TODO() - } - if len(options.Namespace) == 0 { - options.Namespace = s.options.Issuer - } - - callOpts := append(s.callOpts(), client.WithCache(time.Second*30)) - rsp, err := s.rules.List(options.Context, &pb.ListRequest{ - Options: &pb.Options{Namespace: options.Namespace}, - }, callOpts...) - if err != nil { - return nil, err - } - - rules := make([]*auth.Rule, len(rsp.Rules)) - for i, r := range rsp.Rules { - rules[i] = serializeRule(r) - } - - return rules, nil -} - -// Verify an account has access to a resource -func (s *svcAuth) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error { - var options auth.VerifyOptions - for _, o := range opts { - o(&options) - } - - rs, err := s.Rules( - auth.RulesContext(options.Context), - auth.RulesNamespace(options.Namespace), - ) - if err != nil { - return err - } - - return auth.VerifyAccess(rs, acc, res) -} - -// Inspect a token -func (s *svcAuth) Inspect(token string) (*auth.Account, error) { - // try to decode JWT locally and fall back to srv if an error occurs - if len(strings.Split(token, ".")) == 3 && len(s.options.PublicKey) > 0 { - return s.token.Inspect(token) - } - - // the token is not a JWT or we do not have the keys to decode it, - // fall back to the auth service - rsp, err := s.auth.Inspect(context.TODO(), &pb.InspectRequest{ - Token: token, Options: &pb.Options{Namespace: s.Options().Issuer}, - }, s.callOpts()...) - if err != nil { - return nil, err - } - return serializeAccount(rsp.Account), nil -} - -// Token generation using an account ID and secret -func (s *svcAuth) Token(opts ...auth.TokenOption) (*auth.Token, error) { - options := auth.NewTokenOptions(opts...) - if len(options.Issuer) == 0 { - options.Issuer = s.options.Issuer - } - - // we have the JWT private key and refresh accounts locally - if len(s.options.PrivateKey) > 0 { - tok := options.RefreshToken - if len(options.Secret) > 0 { - tok = options.Secret - } - - acc, err := s.token.Inspect(tok) - if err != nil { - return nil, err - } - - token, err := s.token.Generate(acc, token.WithExpiry(options.Expiry)) - if err != nil { - return nil, err - } - - return &auth.Token{ - Expiry: token.Expiry, - AccessToken: token.Token, - RefreshToken: tok, - }, nil - } - - rsp, err := s.auth.Token(context.Background(), &pb.TokenRequest{ - Id: options.ID, - Secret: options.Secret, - RefreshToken: options.RefreshToken, - TokenExpiry: int64(options.Expiry.Seconds()), - Options: &pb.Options{ - Namespace: options.Issuer, - }, - }, s.callOpts()...) - if err != nil { - return nil, err - } - - return serializeToken(rsp.Token), nil -} - -func serializeToken(t *pb.Token) *auth.Token { - return &auth.Token{ - AccessToken: t.AccessToken, - RefreshToken: t.RefreshToken, - Created: time.Unix(t.Created, 0), - Expiry: time.Unix(t.Expiry, 0), - } -} - -func serializeAccount(a *pb.Account) *auth.Account { - return &auth.Account{ - ID: a.Id, - Secret: a.Secret, - Issuer: a.Issuer, - Metadata: a.Metadata, - Scopes: a.Scopes, - } -} - -func serializeRule(r *pb.Rule) *auth.Rule { - var access auth.Access - if r.Access == pb.Access_GRANTED { - access = auth.AccessGranted - } else { - access = auth.AccessDenied - } - - return &auth.Rule{ - ID: r.Id, - Scope: r.Scope, - Access: access, - Priority: r.Priority, - Resource: &auth.Resource{ - Type: r.Resource.Type, - Name: r.Resource.Name, - Endpoint: r.Resource.Endpoint, - }, - } -} - -func (s *svcAuth) callOpts() []client.CallOption { - return []client.CallOption{ - client.WithAddress(s.options.Addrs...), - } -} - -// NewAuth returns a new instance of the Auth service -func NewAuth(opts ...auth.Option) auth.Auth { - options := auth.NewOptions(opts...) - if options.Client == nil { - options.Client = client.DefaultClient - } - if len(options.Addrs) == 0 { - options.Addrs = []string{"127.0.0.1:8010"} - } - - service := &svcAuth{ - auth: pb.NewAuthService("go.micro.auth", options.Client), - rules: pb.NewRulesService("go.micro.auth", options.Client), - options: options, - } - service.setupJWT() - - return service -} - -func (s *svcAuth) setupJWT() { - tokenOpts := []token.Option{} - - // if we have a JWT public key passed as an option, - // we can decode tokens with the type "JWT" locally - // and not have to make an RPC call - if key := s.options.PublicKey; len(key) > 0 { - tokenOpts = append(tokenOpts, token.WithPublicKey(key)) - } - - // if we have a JWT private key passed as an option, - // we can generate accounts locally and not have to make - // an RPC call, this is used for micro clients such as - // api, web, proxy. - if key := s.options.PrivateKey; len(key) > 0 { - tokenOpts = append(tokenOpts, token.WithPrivateKey(key)) - } - - s.token = jwt.NewTokenProvider(tokenOpts...) -} diff --git a/broker/broker.go b/broker/broker.go index b1ce35bd..4095a3a9 100644 --- a/broker/broker.go +++ b/broker/broker.go @@ -37,31 +37,3 @@ type Subscriber interface { Topic() string Unsubscribe() error } - -var ( - DefaultBroker Broker = NewBroker() -) - -func Init(opts ...Option) error { - return DefaultBroker.Init(opts...) -} - -func Connect() error { - return DefaultBroker.Connect() -} - -func Disconnect() error { - return DefaultBroker.Disconnect() -} - -func Publish(topic string, msg *Message, opts ...PublishOption) error { - return DefaultBroker.Publish(topic, msg, opts...) -} - -func Subscribe(topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) { - return DefaultBroker.Subscribe(topic, handler, opts...) -} - -func String() string { - return DefaultBroker.String() -} diff --git a/broker/http.go b/broker/http.go deleted file mode 100644 index ef06a182..00000000 --- a/broker/http.go +++ /dev/null @@ -1,711 +0,0 @@ -// Package http provides a http based message broker -package broker - -import ( - "bytes" - "context" - "crypto/tls" - "errors" - "fmt" - "io" - "io/ioutil" - "math/rand" - "net" - "net/http" - "net/url" - "runtime" - "sync" - "time" - - "github.com/google/uuid" - "github.com/micro/go-micro/v2/codec/json" - merr "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/registry/cache" - maddr "github.com/micro/go-micro/v2/util/addr" - mnet "github.com/micro/go-micro/v2/util/net" - mls "github.com/micro/go-micro/v2/util/tls" - "golang.org/x/net/http2" -) - -// HTTP Broker is a point to point async broker -type httpBroker struct { - id string - address string - opts Options - - mux *http.ServeMux - - c *http.Client - r registry.Registry - - sync.RWMutex - subscribers map[string][]*httpSubscriber - running bool - exit chan chan error - - // offline message inbox - mtx sync.RWMutex - inbox map[string][][]byte -} - -type httpSubscriber struct { - opts SubscribeOptions - id string - topic string - fn Handler - svc *registry.Service - hb *httpBroker -} - -type httpEvent struct { - m *Message - t string - err error -} - -var ( - DefaultPath = "/" - DefaultAddress = "127.0.0.1:0" - serviceName = "micro.http.broker" - broadcastVersion = "ff.http.broadcast" - registerTTL = time.Minute - registerInterval = time.Second * 30 -) - -func init() { - rand.Seed(time.Now().Unix()) -} - -func newTransport(config *tls.Config) *http.Transport { - if config == nil { - config = &tls.Config{ - InsecureSkipVerify: true, - } - } - - dialTLS := func(network string, addr string) (net.Conn, error) { - return tls.Dial(network, addr, config) - } - - t := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - TLSHandshakeTimeout: 10 * time.Second, - DialTLS: dialTLS, - } - runtime.SetFinalizer(&t, func(tr **http.Transport) { - (*tr).CloseIdleConnections() - }) - - // setup http2 - http2.ConfigureTransport(t) - - return t -} - -func newHttpBroker(opts ...Option) Broker { - options := Options{ - Codec: json.Marshaler{}, - Context: context.TODO(), - Registry: registry.DefaultRegistry, - } - - for _, o := range opts { - o(&options) - } - - // set address - addr := DefaultAddress - - if len(options.Addrs) > 0 && len(options.Addrs[0]) > 0 { - addr = options.Addrs[0] - } - - h := &httpBroker{ - id: uuid.New().String(), - address: addr, - opts: options, - r: options.Registry, - c: &http.Client{Transport: newTransport(options.TLSConfig)}, - subscribers: make(map[string][]*httpSubscriber), - exit: make(chan chan error), - mux: http.NewServeMux(), - inbox: make(map[string][][]byte), - } - - // specify the message handler - h.mux.Handle(DefaultPath, h) - - // get optional handlers - if h.opts.Context != nil { - handlers, ok := h.opts.Context.Value("http_handlers").(map[string]http.Handler) - if ok { - for pattern, handler := range handlers { - h.mux.Handle(pattern, handler) - } - } - } - - return h -} - -func (h *httpEvent) Ack() error { - return nil -} - -func (h *httpEvent) Error() error { - return h.err -} - -func (h *httpEvent) Message() *Message { - return h.m -} - -func (h *httpEvent) Topic() string { - return h.t -} - -func (h *httpSubscriber) Options() SubscribeOptions { - return h.opts -} - -func (h *httpSubscriber) Topic() string { - return h.topic -} - -func (h *httpSubscriber) Unsubscribe() error { - return h.hb.unsubscribe(h) -} - -func (h *httpBroker) saveMessage(topic string, msg []byte) { - h.mtx.Lock() - defer h.mtx.Unlock() - - // get messages - c := h.inbox[topic] - - // save message - c = append(c, msg) - - // max length 64 - if len(c) > 64 { - c = c[:64] - } - - // save inbox - h.inbox[topic] = c -} - -func (h *httpBroker) getMessage(topic string, num int) [][]byte { - h.mtx.Lock() - defer h.mtx.Unlock() - - // get messages - c, ok := h.inbox[topic] - if !ok { - return nil - } - - // more message than requests - if len(c) >= num { - msg := c[:num] - h.inbox[topic] = c[num:] - return msg - } - - // reset inbox - h.inbox[topic] = nil - - // return all messages - return c -} - -func (h *httpBroker) subscribe(s *httpSubscriber) error { - h.Lock() - defer h.Unlock() - - if err := h.r.Register(s.svc, registry.RegisterTTL(registerTTL)); err != nil { - return err - } - - h.subscribers[s.topic] = append(h.subscribers[s.topic], s) - return nil -} - -func (h *httpBroker) unsubscribe(s *httpSubscriber) error { - h.Lock() - defer h.Unlock() - - //nolint:prealloc - var subscribers []*httpSubscriber - - // look for subscriber - for _, sub := range h.subscribers[s.topic] { - // deregister and skip forward - if sub == s { - _ = h.r.Deregister(sub.svc) - continue - } - // keep subscriber - subscribers = append(subscribers, sub) - } - - // set subscribers - h.subscribers[s.topic] = subscribers - - return nil -} - -func (h *httpBroker) run(l net.Listener) { - t := time.NewTicker(registerInterval) - defer t.Stop() - - for { - select { - // heartbeat for each subscriber - case <-t.C: - h.RLock() - for _, subs := range h.subscribers { - for _, sub := range subs { - _ = h.r.Register(sub.svc, registry.RegisterTTL(registerTTL)) - } - } - h.RUnlock() - // received exit signal - case ch := <-h.exit: - ch <- l.Close() - h.RLock() - for _, subs := range h.subscribers { - for _, sub := range subs { - _ = h.r.Deregister(sub.svc) - } - } - h.RUnlock() - return - } - } -} - -func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) { - if req.Method != "POST" { - err := merr.BadRequest("go.micro.broker", "Method not allowed") - http.Error(w, err.Error(), http.StatusMethodNotAllowed) - return - } - defer req.Body.Close() - - req.ParseForm() - - b, err := ioutil.ReadAll(req.Body) - if err != nil { - errr := merr.InternalServerError("go.micro.broker", "Error reading request body: %v", err) - w.WriteHeader(500) - w.Write([]byte(errr.Error())) - return - } - - var m *Message - if err = h.opts.Codec.Unmarshal(b, &m); err != nil { - errr := merr.InternalServerError("go.micro.broker", "Error parsing request body: %v", err) - w.WriteHeader(500) - w.Write([]byte(errr.Error())) - return - } - - topic := m.Header["Micro-Topic"] - //delete(m.Header, ":topic") - - if len(topic) == 0 { - errr := merr.InternalServerError("go.micro.broker", "Topic not found") - w.WriteHeader(500) - w.Write([]byte(errr.Error())) - return - } - - p := &httpEvent{m: m, t: topic} - id := req.Form.Get("id") - - //nolint:prealloc - var subs []Handler - - h.RLock() - for _, subscriber := range h.subscribers[topic] { - if id != subscriber.id { - continue - } - subs = append(subs, subscriber.fn) - } - h.RUnlock() - - // execute the handler - for _, fn := range subs { - p.err = fn(p) - } -} - -func (h *httpBroker) Address() string { - h.RLock() - defer h.RUnlock() - return h.address -} - -func (h *httpBroker) Connect() error { - h.RLock() - if h.running { - h.RUnlock() - return nil - } - h.RUnlock() - - h.Lock() - defer h.Unlock() - - var l net.Listener - var err error - - if h.opts.Secure || h.opts.TLSConfig != nil { - config := h.opts.TLSConfig - - fn := func(addr string) (net.Listener, error) { - if config == nil { - hosts := []string{addr} - - // check if its a valid host:port - if host, _, err := net.SplitHostPort(addr); err == nil { - if len(host) == 0 { - hosts = maddr.IPs() - } else { - hosts = []string{host} - } - } - - // generate a certificate - cert, err := mls.Certificate(hosts...) - if err != nil { - return nil, err - } - config = &tls.Config{Certificates: []tls.Certificate{cert}} - } - return tls.Listen("tcp", addr, config) - } - - l, err = mnet.Listen(h.address, fn) - } else { - fn := func(addr string) (net.Listener, error) { - return net.Listen("tcp", addr) - } - - l, err = mnet.Listen(h.address, fn) - } - - if err != nil { - return err - } - - addr := h.address - h.address = l.Addr().String() - - go http.Serve(l, h.mux) - go func() { - h.run(l) - h.Lock() - h.opts.Addrs = []string{addr} - h.address = addr - h.Unlock() - }() - - // get registry - reg := h.opts.Registry - if reg == nil { - reg = registry.DefaultRegistry - } - // set cache - h.r = cache.New(reg) - - // set running - h.running = true - return nil -} - -func (h *httpBroker) Disconnect() error { - h.RLock() - if !h.running { - h.RUnlock() - return nil - } - h.RUnlock() - - h.Lock() - defer h.Unlock() - - // stop cache - rc, ok := h.r.(cache.Cache) - if ok { - rc.Stop() - } - - // exit and return err - ch := make(chan error) - h.exit <- ch - err := <-ch - - // set not running - h.running = false - return err -} - -func (h *httpBroker) Init(opts ...Option) error { - h.RLock() - if h.running { - h.RUnlock() - return errors.New("cannot init while connected") - } - h.RUnlock() - - h.Lock() - defer h.Unlock() - - for _, o := range opts { - o(&h.opts) - } - - if len(h.opts.Addrs) > 0 && len(h.opts.Addrs[0]) > 0 { - h.address = h.opts.Addrs[0] - } - - if len(h.id) == 0 { - h.id = "go.micro.http.broker-" + uuid.New().String() - } - - // get registry - reg := h.opts.Registry - if reg == nil { - reg = registry.DefaultRegistry - } - - // get cache - if rc, ok := h.r.(cache.Cache); ok { - rc.Stop() - } - - // set registry - h.r = cache.New(reg) - - // reconfigure tls config - if c := h.opts.TLSConfig; c != nil { - h.c = &http.Client{ - Transport: newTransport(c), - } - } - - return nil -} - -func (h *httpBroker) Options() Options { - return h.opts -} - -func (h *httpBroker) Publish(topic string, msg *Message, opts ...PublishOption) error { - // create the message first - m := &Message{ - Header: make(map[string]string), - Body: msg.Body, - } - - for k, v := range msg.Header { - m.Header[k] = v - } - - m.Header["Micro-Topic"] = topic - - // encode the message - b, err := h.opts.Codec.Marshal(m) - if err != nil { - return err - } - - // save the message - h.saveMessage(topic, b) - - // now attempt to get the service - h.RLock() - s, err := h.r.GetService(serviceName) - if err != nil { - h.RUnlock() - return err - } - h.RUnlock() - - pub := func(node *registry.Node, t string, b []byte) error { - scheme := "http" - - // check if secure is added in metadata - if node.Metadata["secure"] == "true" { - scheme = "https" - } - - vals := url.Values{} - vals.Add("id", node.Id) - - uri := fmt.Sprintf("%s://%s%s?%s", scheme, node.Address, DefaultPath, vals.Encode()) - r, err := h.c.Post(uri, "application/json", bytes.NewReader(b)) - if err != nil { - return err - } - - // discard response body - io.Copy(ioutil.Discard, r.Body) - r.Body.Close() - return nil - } - - srv := func(s []*registry.Service, b []byte) { - for _, service := range s { - var nodes []*registry.Node - - for _, node := range service.Nodes { - // only use nodes tagged with broker http - if node.Metadata["broker"] != "http" { - continue - } - - // look for nodes for the topic - if node.Metadata["topic"] != topic { - continue - } - - nodes = append(nodes, node) - } - - // only process if we have nodes - if len(nodes) == 0 { - continue - } - - switch service.Version { - // broadcast version means broadcast to all nodes - case broadcastVersion: - var success bool - - // publish to all nodes - for _, node := range nodes { - // publish async - if err := pub(node, topic, b); err == nil { - success = true - } - } - - // save if it failed to publish at least once - if !success { - h.saveMessage(topic, b) - } - default: - // select node to publish to - node := nodes[rand.Int()%len(nodes)] - - // publish async to one node - if err := pub(node, topic, b); err != nil { - // if failed save it - h.saveMessage(topic, b) - } - } - } - } - - // do the rest async - go func() { - // get a third of the backlog - messages := h.getMessage(topic, 8) - delay := (len(messages) > 1) - - // publish all the messages - for _, msg := range messages { - // serialize here - srv(s, msg) - - // sending a backlog of messages - if delay { - time.Sleep(time.Millisecond * 100) - } - } - }() - - return nil -} - -func (h *httpBroker) Subscribe(topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) { - var err error - var host, port string - options := NewSubscribeOptions(opts...) - - // parse address for host, port - host, port, err = net.SplitHostPort(h.Address()) - if err != nil { - return nil, err - } - - addr, err := maddr.Extract(host) - if err != nil { - return nil, err - } - - var secure bool - - if h.opts.Secure || h.opts.TLSConfig != nil { - secure = true - } - - // register service - node := ®istry.Node{ - Id: topic + "-" + h.id, - Address: mnet.HostPort(addr, port), - Metadata: map[string]string{ - "secure": fmt.Sprintf("%t", secure), - "broker": "http", - "topic": topic, - }, - } - - // check for queue group or broadcast queue - version := options.Queue - if len(version) == 0 { - version = broadcastVersion - } - - service := ®istry.Service{ - Name: serviceName, - Version: version, - Nodes: []*registry.Node{node}, - } - - // generate subscriber - subscriber := &httpSubscriber{ - opts: options, - hb: h, - id: node.Id, - topic: topic, - fn: handler, - svc: service, - } - - // subscribe now - if err := h.subscribe(subscriber); err != nil { - return nil, err - } - - // return the subscriber - return subscriber, nil -} - -func (h *httpBroker) String() string { - return "http" -} - -// NewBroker returns a new http broker -func NewBroker(opts ...Option) Broker { - return newHttpBroker(opts...) -} diff --git a/broker/http/http.go b/broker/http/http.go index ff28a41d..4b0c26c4 100644 --- a/broker/http/http.go +++ b/broker/http/http.go @@ -2,10 +2,712 @@ package http import ( - "github.com/micro/go-micro/v2/broker" + "bytes" + "context" + "crypto/tls" + "errors" + "fmt" + "io" + "io/ioutil" + "math/rand" + "net" + "net/http" + "net/url" + "runtime" + "sync" + "time" + + "github.com/google/uuid" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/codec/json" + merr "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/cache" + "github.com/micro/go-micro/v3/registry/mdns" + maddr "github.com/micro/go-micro/v3/util/addr" + mnet "github.com/micro/go-micro/v3/util/net" + mls "github.com/micro/go-micro/v3/util/tls" + "golang.org/x/net/http2" ) +// HTTP Broker is a point to point async broker +type httpBroker struct { + id string + address string + opts broker.Options + + mux *http.ServeMux + + c *http.Client + r registry.Registry + + sync.RWMutex + subscribers map[string][]*httpSubscriber + running bool + exit chan chan error + + // offline message inbox + mtx sync.RWMutex + inbox map[string][][]byte +} + +type httpSubscriber struct { + opts broker.SubscribeOptions + id string + topic string + fn broker.Handler + svc *registry.Service + hb *httpBroker +} + +type httpEvent struct { + m *broker.Message + t string + err error +} + +var ( + DefaultPath = "/" + DefaultAddress = "127.0.0.1:0" + serviceName = "micro.http.broker" + broadcastVersion = "ff.http.broadcast" + registerTTL = time.Minute + registerInterval = time.Second * 30 +) + +func init() { + rand.Seed(time.Now().Unix()) +} + +func newTransport(config *tls.Config) *http.Transport { + if config == nil { + config = &tls.Config{ + InsecureSkipVerify: true, + } + } + + dialTLS := func(network string, addr string) (net.Conn, error) { + return tls.Dial(network, addr, config) + } + + t := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + Dial: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).Dial, + TLSHandshakeTimeout: 10 * time.Second, + DialTLS: dialTLS, + } + runtime.SetFinalizer(&t, func(tr **http.Transport) { + (*tr).CloseIdleConnections() + }) + + // setup http2 + http2.ConfigureTransport(t) + + return t +} + +func newHttpBroker(opts ...broker.Option) broker.Broker { + options := broker.Options{ + Codec: json.Marshaler{}, + Context: context.TODO(), + Registry: mdns.NewRegistry(), + } + + for _, o := range opts { + o(&options) + } + + // set address + addr := DefaultAddress + + if len(options.Addrs) > 0 && len(options.Addrs[0]) > 0 { + addr = options.Addrs[0] + } + + h := &httpBroker{ + id: uuid.New().String(), + address: addr, + opts: options, + r: options.Registry, + c: &http.Client{Transport: newTransport(options.TLSConfig)}, + subscribers: make(map[string][]*httpSubscriber), + exit: make(chan chan error), + mux: http.NewServeMux(), + inbox: make(map[string][][]byte), + } + + // specify the message handler + h.mux.Handle(DefaultPath, h) + + // get optional handlers + if h.opts.Context != nil { + handlers, ok := h.opts.Context.Value("http_handlers").(map[string]http.Handler) + if ok { + for pattern, handler := range handlers { + h.mux.Handle(pattern, handler) + } + } + } + + return h +} + +func (h *httpEvent) Ack() error { + return nil +} + +func (h *httpEvent) Error() error { + return h.err +} + +func (h *httpEvent) Message() *broker.Message { + return h.m +} + +func (h *httpEvent) Topic() string { + return h.t +} + +func (h *httpSubscriber) Options() broker.SubscribeOptions { + return h.opts +} + +func (h *httpSubscriber) Topic() string { + return h.topic +} + +func (h *httpSubscriber) Unsubscribe() error { + return h.hb.unsubscribe(h) +} + +func (h *httpBroker) saveMessage(topic string, msg []byte) { + h.mtx.Lock() + defer h.mtx.Unlock() + + // get messages + c := h.inbox[topic] + + // save message + c = append(c, msg) + + // max length 64 + if len(c) > 64 { + c = c[:64] + } + + // save inbox + h.inbox[topic] = c +} + +func (h *httpBroker) getMessage(topic string, num int) [][]byte { + h.mtx.Lock() + defer h.mtx.Unlock() + + // get messages + c, ok := h.inbox[topic] + if !ok { + return nil + } + + // more message than requests + if len(c) >= num { + msg := c[:num] + h.inbox[topic] = c[num:] + return msg + } + + // reset inbox + h.inbox[topic] = nil + + // return all messages + return c +} + +func (h *httpBroker) subscribe(s *httpSubscriber) error { + h.Lock() + defer h.Unlock() + + if err := h.r.Register(s.svc, registry.RegisterTTL(registerTTL)); err != nil { + return err + } + + h.subscribers[s.topic] = append(h.subscribers[s.topic], s) + return nil +} + +func (h *httpBroker) unsubscribe(s *httpSubscriber) error { + h.Lock() + defer h.Unlock() + + //nolint:prealloc + var subscribers []*httpSubscriber + + // look for subscriber + for _, sub := range h.subscribers[s.topic] { + // deregister and skip forward + if sub == s { + _ = h.r.Deregister(sub.svc) + continue + } + // keep subscriber + subscribers = append(subscribers, sub) + } + + // set subscribers + h.subscribers[s.topic] = subscribers + + return nil +} + +func (h *httpBroker) run(l net.Listener) { + t := time.NewTicker(registerInterval) + defer t.Stop() + + for { + select { + // heartbeat for each subscriber + case <-t.C: + h.RLock() + for _, subs := range h.subscribers { + for _, sub := range subs { + _ = h.r.Register(sub.svc, registry.RegisterTTL(registerTTL)) + } + } + h.RUnlock() + // received exit signal + case ch := <-h.exit: + ch <- l.Close() + h.RLock() + for _, subs := range h.subscribers { + for _, sub := range subs { + _ = h.r.Deregister(sub.svc) + } + } + h.RUnlock() + return + } + } +} + +func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) { + if req.Method != "POST" { + err := merr.BadRequest("go.micro.broker", "Method not allowed") + http.Error(w, err.Error(), http.StatusMethodNotAllowed) + return + } + defer req.Body.Close() + + req.ParseForm() + + b, err := ioutil.ReadAll(req.Body) + if err != nil { + errr := merr.InternalServerError("go.micro.broker", "Error reading request body: %v", err) + w.WriteHeader(500) + w.Write([]byte(errr.Error())) + return + } + + var m *broker.Message + if err = h.opts.Codec.Unmarshal(b, &m); err != nil { + errr := merr.InternalServerError("go.micro.broker", "Error parsing request body: %v", err) + w.WriteHeader(500) + w.Write([]byte(errr.Error())) + return + } + + topic := m.Header["Micro-Topic"] + //delete(m.Header, ":topic") + + if len(topic) == 0 { + errr := merr.InternalServerError("go.micro.broker", "Topic not found") + w.WriteHeader(500) + w.Write([]byte(errr.Error())) + return + } + + p := &httpEvent{m: m, t: topic} + id := req.Form.Get("id") + + //nolint:prealloc + var subs []broker.Handler + + h.RLock() + for _, subscriber := range h.subscribers[topic] { + if id != subscriber.id { + continue + } + subs = append(subs, subscriber.fn) + } + h.RUnlock() + + // execute the handler + for _, fn := range subs { + p.err = fn(p) + } +} + +func (h *httpBroker) Address() string { + h.RLock() + defer h.RUnlock() + return h.address +} + +func (h *httpBroker) Connect() error { + h.RLock() + if h.running { + h.RUnlock() + return nil + } + h.RUnlock() + + h.Lock() + defer h.Unlock() + + var l net.Listener + var err error + + if h.opts.Secure || h.opts.TLSConfig != nil { + config := h.opts.TLSConfig + + fn := func(addr string) (net.Listener, error) { + if config == nil { + hosts := []string{addr} + + // check if its a valid host:port + if host, _, err := net.SplitHostPort(addr); err == nil { + if len(host) == 0 { + hosts = maddr.IPs() + } else { + hosts = []string{host} + } + } + + // generate a certificate + cert, err := mls.Certificate(hosts...) + if err != nil { + return nil, err + } + config = &tls.Config{Certificates: []tls.Certificate{cert}} + } + return tls.Listen("tcp", addr, config) + } + + l, err = mnet.Listen(h.address, fn) + } else { + fn := func(addr string) (net.Listener, error) { + return net.Listen("tcp", addr) + } + + l, err = mnet.Listen(h.address, fn) + } + + if err != nil { + return err + } + + addr := h.address + h.address = l.Addr().String() + + go http.Serve(l, h.mux) + go func() { + h.run(l) + h.Lock() + h.opts.Addrs = []string{addr} + h.address = addr + h.Unlock() + }() + + // get registry + reg := h.opts.Registry + if reg == nil { + reg = mdns.NewRegistry() + } + // set cache + h.r = cache.New(reg) + + // set running + h.running = true + return nil +} + +func (h *httpBroker) Disconnect() error { + h.RLock() + if !h.running { + h.RUnlock() + return nil + } + h.RUnlock() + + h.Lock() + defer h.Unlock() + + // stop cache + rc, ok := h.r.(cache.Cache) + if ok { + rc.Stop() + } + + // exit and return err + ch := make(chan error) + h.exit <- ch + err := <-ch + + // set not running + h.running = false + return err +} + +func (h *httpBroker) Init(opts ...broker.Option) error { + h.RLock() + if h.running { + h.RUnlock() + return errors.New("cannot init while connected") + } + h.RUnlock() + + h.Lock() + defer h.Unlock() + + for _, o := range opts { + o(&h.opts) + } + + if len(h.opts.Addrs) > 0 && len(h.opts.Addrs[0]) > 0 { + h.address = h.opts.Addrs[0] + } + + if len(h.id) == 0 { + h.id = "go.micro.http.broker-" + uuid.New().String() + } + + // get registry + reg := h.opts.Registry + if reg == nil { + reg = mdns.NewRegistry() + } + + // get cache + if rc, ok := h.r.(cache.Cache); ok { + rc.Stop() + } + + // set registry + h.r = cache.New(reg) + + // reconfigure tls config + if c := h.opts.TLSConfig; c != nil { + h.c = &http.Client{ + Transport: newTransport(c), + } + } + + return nil +} + +func (h *httpBroker) Options() broker.Options { + return h.opts +} + +func (h *httpBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { + // create the message first + m := &broker.Message{ + Header: make(map[string]string), + Body: msg.Body, + } + + for k, v := range msg.Header { + m.Header[k] = v + } + + m.Header["Micro-Topic"] = topic + + // encode the message + b, err := h.opts.Codec.Marshal(m) + if err != nil { + return err + } + + // save the message + h.saveMessage(topic, b) + + // now attempt to get the service + h.RLock() + s, err := h.r.GetService(serviceName) + if err != nil { + h.RUnlock() + return err + } + h.RUnlock() + + pub := func(node *registry.Node, t string, b []byte) error { + scheme := "http" + + // check if secure is added in metadata + if node.Metadata["secure"] == "true" { + scheme = "https" + } + + vals := url.Values{} + vals.Add("id", node.Id) + + uri := fmt.Sprintf("%s://%s%s?%s", scheme, node.Address, DefaultPath, vals.Encode()) + r, err := h.c.Post(uri, "application/json", bytes.NewReader(b)) + if err != nil { + return err + } + + // discard response body + io.Copy(ioutil.Discard, r.Body) + r.Body.Close() + return nil + } + + srv := func(s []*registry.Service, b []byte) { + for _, service := range s { + var nodes []*registry.Node + + for _, node := range service.Nodes { + // only use nodes tagged with broker http + if node.Metadata["broker"] != "http" { + continue + } + + // look for nodes for the topic + if node.Metadata["topic"] != topic { + continue + } + + nodes = append(nodes, node) + } + + // only process if we have nodes + if len(nodes) == 0 { + continue + } + + switch service.Version { + // broadcast version means broadcast to all nodes + case broadcastVersion: + var success bool + + // publish to all nodes + for _, node := range nodes { + // publish async + if err := pub(node, topic, b); err == nil { + success = true + } + } + + // save if it failed to publish at least once + if !success { + h.saveMessage(topic, b) + } + default: + // select node to publish to + node := nodes[rand.Int()%len(nodes)] + + // publish async to one node + if err := pub(node, topic, b); err != nil { + // if failed save it + h.saveMessage(topic, b) + } + } + } + } + + // do the rest async + go func() { + // get a third of the backlog + messages := h.getMessage(topic, 8) + delay := (len(messages) > 1) + + // publish all the messages + for _, msg := range messages { + // serialize here + srv(s, msg) + + // sending a backlog of messages + if delay { + time.Sleep(time.Millisecond * 100) + } + } + }() + + return nil +} + +func (h *httpBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { + var err error + var host, port string + options := broker.NewSubscribeOptions(opts...) + + // parse address for host, port + host, port, err = net.SplitHostPort(h.Address()) + if err != nil { + return nil, err + } + + addr, err := maddr.Extract(host) + if err != nil { + return nil, err + } + + var secure bool + + if h.opts.Secure || h.opts.TLSConfig != nil { + secure = true + } + + // register service + node := ®istry.Node{ + Id: topic + "-" + h.id, + Address: mnet.HostPort(addr, port), + Metadata: map[string]string{ + "secure": fmt.Sprintf("%t", secure), + "broker": "http", + "topic": topic, + }, + } + + // check for queue group or broadcast queue + version := options.Queue + if len(version) == 0 { + version = broadcastVersion + } + + service := ®istry.Service{ + Name: serviceName, + Version: version, + Nodes: []*registry.Node{node}, + } + + // generate subscriber + subscriber := &httpSubscriber{ + opts: options, + hb: h, + id: node.Id, + topic: topic, + fn: handler, + svc: service, + } + + // subscribe now + if err := h.subscribe(subscriber); err != nil { + return nil, err + } + + // return the subscriber + return subscriber, nil +} + +func (h *httpBroker) String() string { + return "http" +} + // NewBroker returns a new http broker func NewBroker(opts ...broker.Option) broker.Broker { - return broker.NewBroker(opts...) + return newHttpBroker(opts...) } diff --git a/broker/http_test.go b/broker/http/http_test.go similarity index 95% rename from broker/http_test.go rename to broker/http/http_test.go index 7d5309ae..335e820c 100644 --- a/broker/http_test.go +++ b/broker/http/http_test.go @@ -1,4 +1,4 @@ -package broker_test +package http import ( "sync" @@ -6,9 +6,9 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/registry/memory" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/memory" ) var ( @@ -61,7 +61,7 @@ func sub(be *testing.B, c int) { be.StopTimer() m := newTestRegistry() - b := broker.NewBroker(broker.Registry(m)) + b := NewBroker(broker.Registry(m)) topic := uuid.New().String() if err := b.Init(); err != nil { @@ -120,7 +120,7 @@ func sub(be *testing.B, c int) { func pub(be *testing.B, c int) { be.StopTimer() m := newTestRegistry() - b := broker.NewBroker(broker.Registry(m)) + b := NewBroker(broker.Registry(m)) topic := uuid.New().String() if err := b.Init(); err != nil { @@ -189,7 +189,7 @@ func pub(be *testing.B, c int) { func TestBroker(t *testing.T) { m := newTestRegistry() - b := broker.NewBroker(broker.Registry(m)) + b := NewBroker(broker.Registry(m)) if err := b.Init(); err != nil { t.Fatalf("Unexpected init error: %v", err) @@ -236,7 +236,7 @@ func TestBroker(t *testing.T) { func TestConcurrentSubBroker(t *testing.T) { m := newTestRegistry() - b := broker.NewBroker(broker.Registry(m)) + b := NewBroker(broker.Registry(m)) if err := b.Init(); err != nil { t.Fatalf("Unexpected init error: %v", err) @@ -293,7 +293,7 @@ func TestConcurrentSubBroker(t *testing.T) { func TestConcurrentPubBroker(t *testing.T) { m := newTestRegistry() - b := broker.NewBroker(broker.Registry(m)) + b := NewBroker(broker.Registry(m)) if err := b.Init(); err != nil { t.Fatalf("Unexpected init error: %v", err) diff --git a/broker/http/options.go b/broker/http/options.go index c9825e1d..89a10f6f 100644 --- a/broker/http/options.go +++ b/broker/http/options.go @@ -4,7 +4,7 @@ import ( "context" "net/http" - "github.com/micro/go-micro/v2/broker" + "github.com/micro/go-micro/v3/broker" ) // Handle registers the handler for the given pattern. diff --git a/broker/memory/memory.go b/broker/memory/memory.go index 2938402c..a093c4ec 100644 --- a/broker/memory/memory.go +++ b/broker/memory/memory.go @@ -9,10 +9,10 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/logger" - maddr "github.com/micro/go-micro/v2/util/addr" - mnet "github.com/micro/go-micro/v2/util/net" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/logger" + maddr "github.com/micro/go-micro/v3/util/addr" + mnet "github.com/micro/go-micro/v3/util/net" ) type memoryBroker struct { diff --git a/broker/memory/memory_test.go b/broker/memory/memory_test.go index 74e7941a..1abe782d 100644 --- a/broker/memory/memory_test.go +++ b/broker/memory/memory_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/micro/go-micro/v2/broker" + "github.com/micro/go-micro/v3/broker" ) func TestMemoryBroker(t *testing.T) { diff --git a/broker/nats/context.go b/broker/nats/context.go index 8284b557..2432291a 100644 --- a/broker/nats/context.go +++ b/broker/nats/context.go @@ -3,7 +3,7 @@ package nats import ( "context" - "github.com/micro/go-micro/v2/broker" + "github.com/micro/go-micro/v3/broker" ) // setBrokerOption returns a function to setup a context with given value diff --git a/broker/nats/nats.go b/broker/nats/nats.go index 3f161829..17c12411 100644 --- a/broker/nats/nats.go +++ b/broker/nats/nats.go @@ -7,10 +7,10 @@ import ( "strings" "sync" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/codec/json" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/codec/json" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/registry/mdns" nats "github.com/nats-io/nats.go" ) @@ -310,7 +310,7 @@ func NewBroker(opts ...broker.Option) broker.Broker { // Default codec Codec: json.Marshaler{}, Context: context.Background(), - Registry: registry.DefaultRegistry, + Registry: mdns.NewRegistry(), } n := &natsBroker{ diff --git a/broker/nats/nats_test.go b/broker/nats/nats_test.go index 109c192c..2c3f0f0d 100644 --- a/broker/nats/nats_test.go +++ b/broker/nats/nats_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/micro/go-micro/v2/broker" + "github.com/micro/go-micro/v3/broker" nats "github.com/nats-io/nats.go" ) diff --git a/broker/nats/options.go b/broker/nats/options.go index 78708c0b..debd7e65 100644 --- a/broker/nats/options.go +++ b/broker/nats/options.go @@ -1,7 +1,7 @@ package nats import ( - "github.com/micro/go-micro/v2/broker" + "github.com/micro/go-micro/v3/broker" nats "github.com/nats-io/nats.go" ) diff --git a/broker/options.go b/broker/options.go index 674b3e2e..8d1f2c22 100644 --- a/broker/options.go +++ b/broker/options.go @@ -4,8 +4,8 @@ import ( "context" "crypto/tls" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/registry" ) type Options struct { diff --git a/broker/service/options.go b/broker/service/options.go deleted file mode 100644 index 41e5b403..00000000 --- a/broker/service/options.go +++ /dev/null @@ -1,22 +0,0 @@ -package service - -import ( - "context" - - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/client" -) - -type clientKey struct{} - -// Client to call broker service -func Client(c client.Client) broker.Option { - return func(o *broker.Options) { - if o.Context == nil { - o.Context = context.WithValue(context.Background(), clientKey{}, c) - return - } - - o.Context = context.WithValue(o.Context, clientKey{}, c) - } -} diff --git a/broker/service/proto/broker.pb.go b/broker/service/proto/broker.pb.go deleted file mode 100644 index cb561cc9..00000000 --- a/broker/service/proto/broker.pb.go +++ /dev/null @@ -1,374 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: broker/service/proto/broker.proto - -package go_micro_broker - -import ( - context "context" - fmt "fmt" - proto "github.com/golang/protobuf/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -type Empty struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { - return fileDescriptor_df4d8f04292cf3fe, []int{0} -} - -func (m *Empty) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Empty.Unmarshal(m, b) -} -func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Empty.Marshal(b, m, deterministic) -} -func (m *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(m, src) -} -func (m *Empty) XXX_Size() int { - return xxx_messageInfo_Empty.Size(m) -} -func (m *Empty) XXX_DiscardUnknown() { - xxx_messageInfo_Empty.DiscardUnknown(m) -} - -var xxx_messageInfo_Empty proto.InternalMessageInfo - -type PublishRequest struct { - Topic string `protobuf:"bytes,1,opt,name=topic,proto3" json:"topic,omitempty"` - Message *Message `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PublishRequest) Reset() { *m = PublishRequest{} } -func (m *PublishRequest) String() string { return proto.CompactTextString(m) } -func (*PublishRequest) ProtoMessage() {} -func (*PublishRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_df4d8f04292cf3fe, []int{1} -} - -func (m *PublishRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PublishRequest.Unmarshal(m, b) -} -func (m *PublishRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PublishRequest.Marshal(b, m, deterministic) -} -func (m *PublishRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_PublishRequest.Merge(m, src) -} -func (m *PublishRequest) XXX_Size() int { - return xxx_messageInfo_PublishRequest.Size(m) -} -func (m *PublishRequest) XXX_DiscardUnknown() { - xxx_messageInfo_PublishRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_PublishRequest proto.InternalMessageInfo - -func (m *PublishRequest) GetTopic() string { - if m != nil { - return m.Topic - } - return "" -} - -func (m *PublishRequest) GetMessage() *Message { - if m != nil { - return m.Message - } - return nil -} - -type SubscribeRequest struct { - Topic string `protobuf:"bytes,1,opt,name=topic,proto3" json:"topic,omitempty"` - Queue string `protobuf:"bytes,2,opt,name=queue,proto3" json:"queue,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SubscribeRequest) Reset() { *m = SubscribeRequest{} } -func (m *SubscribeRequest) String() string { return proto.CompactTextString(m) } -func (*SubscribeRequest) ProtoMessage() {} -func (*SubscribeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_df4d8f04292cf3fe, []int{2} -} - -func (m *SubscribeRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SubscribeRequest.Unmarshal(m, b) -} -func (m *SubscribeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SubscribeRequest.Marshal(b, m, deterministic) -} -func (m *SubscribeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SubscribeRequest.Merge(m, src) -} -func (m *SubscribeRequest) XXX_Size() int { - return xxx_messageInfo_SubscribeRequest.Size(m) -} -func (m *SubscribeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SubscribeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SubscribeRequest proto.InternalMessageInfo - -func (m *SubscribeRequest) GetTopic() string { - if m != nil { - return m.Topic - } - return "" -} - -func (m *SubscribeRequest) GetQueue() string { - if m != nil { - return m.Queue - } - return "" -} - -type Message struct { - Header map[string]string `protobuf:"bytes,1,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Body []byte `protobuf:"bytes,2,opt,name=body,proto3" json:"body,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_df4d8f04292cf3fe, []int{3} -} - -func (m *Message) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Message.Unmarshal(m, b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return xxx_messageInfo_Message.Size(m) -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -func (m *Message) GetHeader() map[string]string { - if m != nil { - return m.Header - } - return nil -} - -func (m *Message) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -func init() { - proto.RegisterType((*Empty)(nil), "go.micro.broker.Empty") - proto.RegisterType((*PublishRequest)(nil), "go.micro.broker.PublishRequest") - proto.RegisterType((*SubscribeRequest)(nil), "go.micro.broker.SubscribeRequest") - proto.RegisterType((*Message)(nil), "go.micro.broker.Message") - proto.RegisterMapType((map[string]string)(nil), "go.micro.broker.Message.HeaderEntry") -} - -func init() { proto.RegisterFile("broker/service/proto/broker.proto", fileDescriptor_df4d8f04292cf3fe) } - -var fileDescriptor_df4d8f04292cf3fe = []byte{ - // 299 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x51, 0x4d, 0x4b, 0xc3, 0x40, - 0x14, 0xec, 0xb6, 0xb6, 0xa1, 0xaf, 0xa2, 0x65, 0x29, 0x12, 0x7a, 0x31, 0x0d, 0x1e, 0x72, 0xda, - 0x48, 0xbc, 0xa8, 0x88, 0x07, 0xb1, 0xe0, 0x41, 0x41, 0xd6, 0x9b, 0xb7, 0x6c, 0xfa, 0x68, 0x43, - 0x1b, 0x37, 0xdd, 0x4d, 0x0a, 0xf9, 0x23, 0x9e, 0xfc, 0xb1, 0xd2, 0xdd, 0xf8, 0xd5, 0x50, 0x6f, - 0x6f, 0xde, 0xce, 0xce, 0x1b, 0x66, 0x60, 0x22, 0x94, 0x5c, 0xa2, 0x0a, 0x35, 0xaa, 0x4d, 0x9a, - 0x60, 0x98, 0x2b, 0x59, 0xc8, 0xd0, 0x2e, 0x99, 0x01, 0xf4, 0x78, 0x2e, 0x59, 0x96, 0x26, 0x4a, - 0x32, 0xbb, 0xf6, 0x1d, 0xe8, 0x4e, 0xb3, 0xbc, 0xa8, 0xfc, 0x57, 0x38, 0x7a, 0x2e, 0xc5, 0x2a, - 0xd5, 0x0b, 0x8e, 0xeb, 0x12, 0x75, 0x41, 0x47, 0xd0, 0x2d, 0x64, 0x9e, 0x26, 0x2e, 0xf1, 0x48, - 0xd0, 0xe7, 0x16, 0xd0, 0x08, 0x9c, 0x0c, 0xb5, 0x8e, 0xe7, 0xe8, 0xb6, 0x3d, 0x12, 0x0c, 0x22, - 0x97, 0xed, 0x68, 0xb2, 0x27, 0xfb, 0xce, 0xbf, 0x88, 0xfe, 0x2d, 0x0c, 0x5f, 0x4a, 0xa1, 0x13, - 0x95, 0x0a, 0xfc, 0x5f, 0x7d, 0x04, 0xdd, 0x75, 0x89, 0xa5, 0xd5, 0xee, 0x73, 0x0b, 0xfc, 0x77, - 0x02, 0x4e, 0x2d, 0x4a, 0x6f, 0xa0, 0xb7, 0xc0, 0x78, 0x86, 0xca, 0x25, 0x5e, 0x27, 0x18, 0x44, - 0x67, 0xfb, 0xce, 0xb3, 0x07, 0x43, 0x9b, 0xbe, 0x15, 0xaa, 0xe2, 0xf5, 0x1f, 0x4a, 0xe1, 0x40, - 0xc8, 0x59, 0x65, 0xe4, 0x0f, 0xb9, 0x99, 0xc7, 0x57, 0x30, 0xf8, 0x45, 0xa5, 0x43, 0xe8, 0x2c, - 0xb1, 0xaa, 0x6d, 0x6d, 0xc7, 0xad, 0xa9, 0x4d, 0xbc, 0xfa, 0x31, 0x65, 0xc0, 0x75, 0xfb, 0x92, - 0x44, 0x1f, 0x04, 0x7a, 0x77, 0xe6, 0x2a, 0xbd, 0x07, 0xa7, 0xce, 0x8f, 0x9e, 0x36, 0x2c, 0xfd, - 0x4d, 0x76, 0x7c, 0xd2, 0x20, 0xd8, 0x0e, 0x5a, 0xf4, 0x11, 0xfa, 0xdf, 0x49, 0xd1, 0x49, 0x83, - 0xb6, 0x9b, 0xe2, 0x78, 0x6f, 0xf8, 0x7e, 0xeb, 0x9c, 0x88, 0x9e, 0x29, 0xfd, 0xe2, 0x33, 0x00, - 0x00, 0xff, 0xff, 0x19, 0x9f, 0x10, 0x75, 0x19, 0x02, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// BrokerClient is the client API for Broker service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type BrokerClient interface { - Publish(ctx context.Context, in *PublishRequest, opts ...grpc.CallOption) (*Empty, error) - Subscribe(ctx context.Context, in *SubscribeRequest, opts ...grpc.CallOption) (Broker_SubscribeClient, error) -} - -type brokerClient struct { - cc *grpc.ClientConn -} - -func NewBrokerClient(cc *grpc.ClientConn) BrokerClient { - return &brokerClient{cc} -} - -func (c *brokerClient) Publish(ctx context.Context, in *PublishRequest, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/go.micro.broker.Broker/Publish", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *brokerClient) Subscribe(ctx context.Context, in *SubscribeRequest, opts ...grpc.CallOption) (Broker_SubscribeClient, error) { - stream, err := c.cc.NewStream(ctx, &_Broker_serviceDesc.Streams[0], "/go.micro.broker.Broker/Subscribe", opts...) - if err != nil { - return nil, err - } - x := &brokerSubscribeClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Broker_SubscribeClient interface { - Recv() (*Message, error) - grpc.ClientStream -} - -type brokerSubscribeClient struct { - grpc.ClientStream -} - -func (x *brokerSubscribeClient) Recv() (*Message, error) { - m := new(Message) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// BrokerServer is the server API for Broker service. -type BrokerServer interface { - Publish(context.Context, *PublishRequest) (*Empty, error) - Subscribe(*SubscribeRequest, Broker_SubscribeServer) error -} - -// UnimplementedBrokerServer can be embedded to have forward compatible implementations. -type UnimplementedBrokerServer struct { -} - -func (*UnimplementedBrokerServer) Publish(ctx context.Context, req *PublishRequest) (*Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method Publish not implemented") -} -func (*UnimplementedBrokerServer) Subscribe(req *SubscribeRequest, srv Broker_SubscribeServer) error { - return status.Errorf(codes.Unimplemented, "method Subscribe not implemented") -} - -func RegisterBrokerServer(s *grpc.Server, srv BrokerServer) { - s.RegisterService(&_Broker_serviceDesc, srv) -} - -func _Broker_Publish_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(PublishRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BrokerServer).Publish(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.broker.Broker/Publish", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BrokerServer).Publish(ctx, req.(*PublishRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Broker_Subscribe_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(SubscribeRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(BrokerServer).Subscribe(m, &brokerSubscribeServer{stream}) -} - -type Broker_SubscribeServer interface { - Send(*Message) error - grpc.ServerStream -} - -type brokerSubscribeServer struct { - grpc.ServerStream -} - -func (x *brokerSubscribeServer) Send(m *Message) error { - return x.ServerStream.SendMsg(m) -} - -var _Broker_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.broker.Broker", - HandlerType: (*BrokerServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Publish", - Handler: _Broker_Publish_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Subscribe", - Handler: _Broker_Subscribe_Handler, - ServerStreams: true, - }, - }, - Metadata: "broker/service/proto/broker.proto", -} diff --git a/broker/service/proto/broker.pb.micro.go b/broker/service/proto/broker.pb.micro.go deleted file mode 100644 index 01e6f938..00000000 --- a/broker/service/proto/broker.pb.micro.go +++ /dev/null @@ -1,185 +0,0 @@ -// Code generated by protoc-gen-micro. DO NOT EDIT. -// source: broker/service/proto/broker.proto - -package go_micro_broker - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -import ( - context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ api.Endpoint -var _ context.Context -var _ client.Option -var _ server.Option - -// Api Endpoints for Broker service - -func NewBrokerEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Broker service - -type BrokerService interface { - Publish(ctx context.Context, in *PublishRequest, opts ...client.CallOption) (*Empty, error) - Subscribe(ctx context.Context, in *SubscribeRequest, opts ...client.CallOption) (Broker_SubscribeService, error) -} - -type brokerService struct { - c client.Client - name string -} - -func NewBrokerService(name string, c client.Client) BrokerService { - return &brokerService{ - c: c, - name: name, - } -} - -func (c *brokerService) Publish(ctx context.Context, in *PublishRequest, opts ...client.CallOption) (*Empty, error) { - req := c.c.NewRequest(c.name, "Broker.Publish", in) - out := new(Empty) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *brokerService) Subscribe(ctx context.Context, in *SubscribeRequest, opts ...client.CallOption) (Broker_SubscribeService, error) { - req := c.c.NewRequest(c.name, "Broker.Subscribe", &SubscribeRequest{}) - stream, err := c.c.Stream(ctx, req, opts...) - if err != nil { - return nil, err - } - if err := stream.Send(in); err != nil { - return nil, err - } - return &brokerServiceSubscribe{stream}, nil -} - -type Broker_SubscribeService interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Recv() (*Message, error) -} - -type brokerServiceSubscribe struct { - stream client.Stream -} - -func (x *brokerServiceSubscribe) Close() error { - return x.stream.Close() -} - -func (x *brokerServiceSubscribe) Context() context.Context { - return x.stream.Context() -} - -func (x *brokerServiceSubscribe) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *brokerServiceSubscribe) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *brokerServiceSubscribe) Recv() (*Message, error) { - m := new(Message) - err := x.stream.Recv(m) - if err != nil { - return nil, err - } - return m, nil -} - -// Server API for Broker service - -type BrokerHandler interface { - Publish(context.Context, *PublishRequest, *Empty) error - Subscribe(context.Context, *SubscribeRequest, Broker_SubscribeStream) error -} - -func RegisterBrokerHandler(s server.Server, hdlr BrokerHandler, opts ...server.HandlerOption) error { - type broker interface { - Publish(ctx context.Context, in *PublishRequest, out *Empty) error - Subscribe(ctx context.Context, stream server.Stream) error - } - type Broker struct { - broker - } - h := &brokerHandler{hdlr} - return s.Handle(s.NewHandler(&Broker{h}, opts...)) -} - -type brokerHandler struct { - BrokerHandler -} - -func (h *brokerHandler) Publish(ctx context.Context, in *PublishRequest, out *Empty) error { - return h.BrokerHandler.Publish(ctx, in, out) -} - -func (h *brokerHandler) Subscribe(ctx context.Context, stream server.Stream) error { - m := new(SubscribeRequest) - if err := stream.Recv(m); err != nil { - return err - } - return h.BrokerHandler.Subscribe(ctx, m, &brokerSubscribeStream{stream}) -} - -type Broker_SubscribeStream interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Send(*Message) error -} - -type brokerSubscribeStream struct { - stream server.Stream -} - -func (x *brokerSubscribeStream) Close() error { - return x.stream.Close() -} - -func (x *brokerSubscribeStream) Context() context.Context { - return x.stream.Context() -} - -func (x *brokerSubscribeStream) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *brokerSubscribeStream) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *brokerSubscribeStream) Send(m *Message) error { - return x.stream.Send(m) -} diff --git a/broker/service/proto/broker.proto b/broker/service/proto/broker.proto deleted file mode 100644 index 3fc877e6..00000000 --- a/broker/service/proto/broker.proto +++ /dev/null @@ -1,25 +0,0 @@ -syntax = "proto3"; - -package go.micro.broker; - -service Broker { - rpc Publish(PublishRequest) returns (Empty) {}; - rpc Subscribe(SubscribeRequest) returns (stream Message) {}; -} - -message Empty {} - -message PublishRequest { - string topic = 1; - Message message = 2; -} - -message SubscribeRequest { - string topic = 1; - string queue = 2; -} - -message Message { - map header = 1; - bytes body = 2; -} diff --git a/broker/service/service.go b/broker/service/service.go deleted file mode 100644 index f5708746..00000000 --- a/broker/service/service.go +++ /dev/null @@ -1,152 +0,0 @@ -// Package service provides the broker service client -package service - -import ( - "context" - "time" - - "github.com/micro/go-micro/v2/broker" - pb "github.com/micro/go-micro/v2/broker/service/proto" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/logger" -) - -type serviceBroker struct { - Addrs []string - Client pb.BrokerService - options broker.Options -} - -var ( - DefaultName = "go.micro.broker" -) - -func (b *serviceBroker) Address() string { - return b.Addrs[0] -} - -func (b *serviceBroker) Connect() error { - return nil -} - -func (b *serviceBroker) Disconnect() error { - return nil -} - -func (b *serviceBroker) Init(opts ...broker.Option) error { - for _, o := range opts { - o(&b.options) - } - return nil -} - -func (b *serviceBroker) Options() broker.Options { - return b.options -} - -func (b *serviceBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Publishing to topic %s broker %v", topic, b.Addrs) - } - _, err := b.Client.Publish(context.TODO(), &pb.PublishRequest{ - Topic: topic, - Message: &pb.Message{ - Header: msg.Header, - Body: msg.Body, - }, - }, client.WithAddress(b.Addrs...)) - return err -} - -func (b *serviceBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { - var options broker.SubscribeOptions - for _, o := range opts { - o(&options) - } - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Subscribing to topic %s queue %s broker %v", topic, options.Queue, b.Addrs) - } - stream, err := b.Client.Subscribe(context.TODO(), &pb.SubscribeRequest{ - Topic: topic, - Queue: options.Queue, - }, client.WithAddress(b.Addrs...), client.WithRequestTimeout(time.Hour)) - if err != nil { - return nil, err - } - - sub := &serviceSub{ - topic: topic, - queue: options.Queue, - handler: handler, - stream: stream, - closed: make(chan bool), - options: options, - } - - go func() { - for { - select { - case <-sub.closed: - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Unsubscribed from topic %s", topic) - } - return - default: - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - // run the subscriber - logger.Debugf("Streaming from broker %v to topic [%s] queue [%s]", b.Addrs, topic, options.Queue) - } - if err := sub.run(); err != nil { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Resubscribing to topic %s broker %v", topic, b.Addrs) - } - stream, err := b.Client.Subscribe(context.TODO(), &pb.SubscribeRequest{ - Topic: topic, - Queue: options.Queue, - }, client.WithAddress(b.Addrs...), client.WithRequestTimeout(time.Hour)) - if err != nil { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Failed to resubscribe to topic %s: %v", topic, err) - } - time.Sleep(time.Second) - continue - } - // new stream - sub.stream = stream - } - } - } - }() - - return sub, nil -} - -func (b *serviceBroker) String() string { - return "service" -} - -func NewBroker(opts ...broker.Option) broker.Broker { - var options broker.Options - for _, o := range opts { - o(&options) - } - - addrs := options.Addrs - if len(addrs) == 0 { - addrs = []string{"127.0.0.1:8001"} - } - - cli := client.DefaultClient - - // get options client from the context. We set this in the context to prevent an import loop, as - // the client depends on the broker - if c, ok := options.Context.Value(clientKey{}).(client.Client); ok { - cli = c - } - - return &serviceBroker{ - Addrs: addrs, - Client: pb.NewBrokerService(DefaultName, cli), - options: options, - } -} diff --git a/broker/service/subscriber.go b/broker/service/subscriber.go deleted file mode 100644 index c11ec962..00000000 --- a/broker/service/subscriber.go +++ /dev/null @@ -1,108 +0,0 @@ -package service - -import ( - "github.com/micro/go-micro/v2/broker" - pb "github.com/micro/go-micro/v2/broker/service/proto" - "github.com/micro/go-micro/v2/logger" -) - -type serviceSub struct { - topic string - queue string - handler broker.Handler - stream pb.Broker_SubscribeService - closed chan bool - options broker.SubscribeOptions -} - -type serviceEvent struct { - topic string - err error - message *broker.Message -} - -func (s *serviceEvent) Topic() string { - return s.topic -} - -func (s *serviceEvent) Message() *broker.Message { - return s.message -} - -func (s *serviceEvent) Ack() error { - return nil -} - -func (s *serviceEvent) Error() error { - return s.err -} - -func (s *serviceSub) isClosed() bool { - select { - case <-s.closed: - return true - default: - return false - } -} - -func (s *serviceSub) run() error { - exit := make(chan bool) - go func() { - select { - case <-exit: - case <-s.closed: - } - - // close the stream - s.stream.Close() - }() - - for { - // TODO: do not fail silently - msg, err := s.stream.Recv() - if err != nil { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Streaming error for subcription to topic %s: %v", s.Topic(), err) - } - - // close the exit channel - close(exit) - - // don't return an error if we unsubscribed - if s.isClosed() { - return nil - } - - // return stream error - return err - } - - p := &serviceEvent{ - topic: s.topic, - message: &broker.Message{ - Header: msg.Header, - Body: msg.Body, - }, - } - p.err = s.handler(p) - } -} - -func (s *serviceSub) Options() broker.SubscribeOptions { - return s.options -} - -func (s *serviceSub) Topic() string { - return s.topic -} - -func (s *serviceSub) Unsubscribe() error { - select { - case <-s.closed: - return nil - default: - close(s.closed) - } - return nil -} diff --git a/cache/memcache/memcache.go b/cache/memcache/memcache.go index c94aab41..8536924c 100644 --- a/cache/memcache/memcache.go +++ b/cache/memcache/memcache.go @@ -5,7 +5,7 @@ import ( "encoding/json" "github.com/bradfitz/gomemcache/memcache" - "github.com/micro/go-micro/v2/cache" + "github.com/micro/go-micro/v3/cache" ) type memcacheCache struct { diff --git a/cache/memory/memory.go b/cache/memory/memory.go index d4246b77..5769707a 100644 --- a/cache/memory/memory.go +++ b/cache/memory/memory.go @@ -4,8 +4,8 @@ package memory import ( "sync" - "github.com/micro/go-micro/v2/cache" - "github.com/micro/go-micro/v2/errors" + "github.com/micro/go-micro/v3/cache" + "github.com/micro/go-micro/v3/errors" ) type memoryCache struct { diff --git a/client/backoff.go b/client/backoff.go index 7281f4a8..d20ec778 100644 --- a/client/backoff.go +++ b/client/backoff.go @@ -4,7 +4,7 @@ import ( "context" "time" - "github.com/micro/go-micro/v2/util/backoff" + "github.com/micro/go-micro/v3/util/backoff" ) type BackoffFunc func(ctx context.Context, req Request, attempts int) (time.Duration, error) diff --git a/client/backoff_test.go b/client/backoff_test.go index 7e1e1990..5b9b60b8 100644 --- a/client/backoff_test.go +++ b/client/backoff_test.go @@ -16,10 +16,13 @@ func TestBackoff(t *testing.T) { 7900 * time.Millisecond, } - c := NewClient() + r := &testRequest{ + service: "test", + method: "test", + } for i := 0; i < 5; i++ { - d, err := exponentialBackoff(context.TODO(), c.NewRequest("test", "test", nil), i) + d, err := exponentialBackoff(context.TODO(), r, i) if err != nil { t.Fatal(err) } diff --git a/client/cache.go b/client/cache.go index a6ab71c1..dfcff812 100644 --- a/client/cache.go +++ b/client/cache.go @@ -7,7 +7,7 @@ import ( "hash/fnv" "time" - "github.com/micro/go-micro/v2/metadata" + "github.com/micro/go-micro/v3/metadata" cache "github.com/patrickmn/go-cache" ) @@ -24,12 +24,12 @@ type Cache struct { } // Get a response from the cache -func (c *Cache) Get(ctx context.Context, req *Request) (interface{}, bool) { +func (c *Cache) Get(ctx context.Context, req Request) (interface{}, bool) { return c.cache.Get(key(ctx, req)) } // Set a response in the cache -func (c *Cache) Set(ctx context.Context, req *Request, rsp interface{}, expiry time.Duration) { +func (c *Cache) Set(ctx context.Context, req Request, rsp interface{}, expiry time.Duration) { c.cache.Set(key(ctx, req), rsp, expiry) } @@ -47,16 +47,16 @@ func (c *Cache) List() map[string]string { } // key returns a hash for the context and request -func key(ctx context.Context, req *Request) string { +func key(ctx context.Context, req Request) string { ns, _ := metadata.Get(ctx, "Micro-Namespace") bytes, _ := json.Marshal(map[string]interface{}{ "namespace": ns, "request": map[string]interface{}{ - "service": (*req).Service(), - "endpoint": (*req).Endpoint(), - "method": (*req).Method(), - "body": (*req).Body(), + "service": req.Service(), + "endpoint": req.Endpoint(), + "method": req.Method(), + "body": req.Body(), }, }) diff --git a/client/cache_test.go b/client/cache_test.go index 70721a23..8125e67e 100644 --- a/client/cache_test.go +++ b/client/cache_test.go @@ -5,15 +5,15 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/metadata" + "github.com/micro/go-micro/v3/metadata" ) func TestCache(t *testing.T) { ctx := context.TODO() - req := NewRequest("go.micro.service.foo", "Foo.Bar", nil) + req := &testRequest{service: "go.micro.service.foo", method: "Foo.Bar"} t.Run("CacheMiss", func(t *testing.T) { - if _, ok := NewCache().Get(ctx, &req); ok { + if _, ok := NewCache().Get(ctx, req); ok { t.Errorf("Expected to get no result from Get") } }) @@ -22,9 +22,9 @@ func TestCache(t *testing.T) { c := NewCache() rsp := "theresponse" - c.Set(ctx, &req, rsp, time.Minute) + c.Set(ctx, req, rsp, time.Minute) - if res, ok := c.Get(ctx, &req); !ok { + if res, ok := c.Get(ctx, req); !ok { t.Errorf("Expected a result, got nothing") } else if res != rsp { t.Errorf("Expected '%v' result, got '%v'", rsp, res) @@ -34,21 +34,22 @@ func TestCache(t *testing.T) { func TestCacheKey(t *testing.T) { ctx := context.TODO() - req1 := NewRequest("go.micro.service.foo", "Foo.Bar", nil) - req2 := NewRequest("go.micro.service.foo", "Foo.Baz", nil) - req3 := NewRequest("go.micro.service.foo", "Foo.Baz", "customquery") + + req1 := &testRequest{service: "go.micro.service.foo", method: "Foo.Bar"} + req2 := &testRequest{service: "go.micro.service.foo", method: "Foo.Baz"} + req3 := &testRequest{service: "go.micro.service.foo", method: "Foo.Bar", body: "customquery"} t.Run("IdenticalRequests", func(t *testing.T) { - key1 := key(ctx, &req1) - key2 := key(ctx, &req1) + key1 := key(ctx, req1) + key2 := key(ctx, req1) if key1 != key2 { t.Errorf("Expected the keys to match for identical requests and context") } }) t.Run("DifferentRequestEndpoints", func(t *testing.T) { - key1 := key(ctx, &req1) - key2 := key(ctx, &req2) + key1 := key(ctx, req1) + key2 := key(ctx, req2) if key1 == key2 { t.Errorf("Expected the keys to differ for different request endpoints") @@ -56,8 +57,8 @@ func TestCacheKey(t *testing.T) { }) t.Run("DifferentRequestBody", func(t *testing.T) { - key1 := key(ctx, &req2) - key2 := key(ctx, &req3) + key1 := key(ctx, req2) + key2 := key(ctx, req3) if key1 == key2 { t.Errorf("Expected the keys to differ for different request bodies") @@ -66,8 +67,8 @@ func TestCacheKey(t *testing.T) { t.Run("DifferentMetadata", func(t *testing.T) { mdCtx := metadata.Set(context.TODO(), "Micro-Namespace", "bar") - key1 := key(mdCtx, &req1) - key2 := key(ctx, &req1) + key1 := key(mdCtx, req1) + key2 := key(ctx, req1) if key1 == key2 { t.Errorf("Expected the keys to differ for different metadata") diff --git a/client/client.go b/client/client.go index 7ab0a5e1..2b18f279 100644 --- a/client/client.go +++ b/client/client.go @@ -5,7 +5,7 @@ import ( "context" "time" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) // Client is the interface used to make requests to services. @@ -91,8 +91,6 @@ type MessageOption func(*MessageOptions) type RequestOption func(*RequestOptions) var ( - // DefaultClient is a default client to use out of the box - DefaultClient Client = newRpcClient() // DefaultBackoff is the default backoff function for retries DefaultBackoff = exponentialBackoff // DefaultRetry is the default check-for-retry function for retries @@ -105,39 +103,4 @@ var ( DefaultPoolSize = 100 // DefaultPoolTTL sets the connection pool ttl DefaultPoolTTL = time.Minute - - // NewClient returns a new client - NewClient func(...Option) Client = newRpcClient ) - -// Makes a synchronous call to a service using the default client -func Call(ctx context.Context, request Request, response interface{}, opts ...CallOption) error { - return DefaultClient.Call(ctx, request, response, opts...) -} - -// Publishes a publication using the default client. Using the underlying broker -// set within the options. -func Publish(ctx context.Context, msg Message, opts ...PublishOption) error { - return DefaultClient.Publish(ctx, msg, opts...) -} - -// Creates a new message using the default client -func NewMessage(topic string, payload interface{}, opts ...MessageOption) Message { - return DefaultClient.NewMessage(topic, payload, opts...) -} - -// Creates a new request using the default client. Content Type will -// be set to the default within options and use the appropriate codec -func NewRequest(service, endpoint string, request interface{}, reqOpts ...RequestOption) Request { - return DefaultClient.NewRequest(service, endpoint, request, reqOpts...) -} - -// Creates a streaming connection with a service and returns responses on the -// channel passed in. It's up to the user to close the streamer. -func NewStream(ctx context.Context, request Request, opts ...CallOption) (Stream, error) { - return DefaultClient.Stream(ctx, request, opts...) -} - -func String() string { - return DefaultClient.String() -} diff --git a/client/grpc/codec.go b/client/grpc/codec.go index e5a6730e..c3775455 100644 --- a/client/grpc/codec.go +++ b/client/grpc/codec.go @@ -9,8 +9,8 @@ import ( "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/codec/bytes" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/codec/bytes" "github.com/oxtoacart/bpool" "google.golang.org/grpc" "google.golang.org/grpc/encoding" diff --git a/client/grpc/error.go b/client/grpc/error.go index 8088c552..7b690b38 100644 --- a/client/grpc/error.go +++ b/client/grpc/error.go @@ -1,7 +1,7 @@ package grpc import ( - "github.com/micro/go-micro/v2/errors" + "github.com/micro/go-micro/v3/errors" "google.golang.org/grpc/status" ) diff --git a/client/grpc/grpc.go b/client/grpc/grpc.go index 85b21255..2ed71bd9 100644 --- a/client/grpc/grpc.go +++ b/client/grpc/grpc.go @@ -11,12 +11,12 @@ import ( "sync/atomic" "time" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/client" - raw "github.com/micro/go-micro/v2/codec/bytes" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/client" + raw "github.com/micro/go-micro/v3/codec/bytes" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/registry" "google.golang.org/grpc" "google.golang.org/grpc/credentials" diff --git a/client/grpc/grpc_test.go b/client/grpc/grpc_test.go index bbec1b40..1b05ae83 100644 --- a/client/grpc/grpc_test.go +++ b/client/grpc/grpc_test.go @@ -5,11 +5,12 @@ import ( "net" "testing" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/registry/memory" - "github.com/micro/go-micro/v2/router" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/memory" + "github.com/micro/go-micro/v3/router" + regRouter "github.com/micro/go-micro/v3/router/registry" pgrpc "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" ) @@ -57,7 +58,7 @@ func TestGRPCClient(t *testing.T) { }) // create router - rtr := router.NewRouter(router.Registry(r)) + rtr := regRouter.NewRouter(router.Registry(r)) // create client c := NewClient(client.Router(rtr)) diff --git a/client/grpc/message.go b/client/grpc/message.go index ddc8b926..cdcc3bd0 100644 --- a/client/grpc/message.go +++ b/client/grpc/message.go @@ -1,7 +1,7 @@ package grpc import ( - "github.com/micro/go-micro/v2/client" + "github.com/micro/go-micro/v3/client" ) type grpcEvent struct { diff --git a/client/grpc/options.go b/client/grpc/options.go index 28222f85..220f7583 100644 --- a/client/grpc/options.go +++ b/client/grpc/options.go @@ -5,7 +5,7 @@ import ( "context" "crypto/tls" - "github.com/micro/go-micro/v2/client" + "github.com/micro/go-micro/v3/client" "google.golang.org/grpc" "google.golang.org/grpc/encoding" ) diff --git a/client/grpc/request.go b/client/grpc/request.go index d7555727..e957eb19 100644 --- a/client/grpc/request.go +++ b/client/grpc/request.go @@ -4,8 +4,8 @@ import ( "fmt" "strings" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/codec" ) type grpcRequest struct { diff --git a/client/grpc/response.go b/client/grpc/response.go index cd4d319c..1a871c92 100644 --- a/client/grpc/response.go +++ b/client/grpc/response.go @@ -3,8 +3,8 @@ package grpc import ( "strings" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/codec/bytes" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/codec/bytes" "google.golang.org/grpc" "google.golang.org/grpc/encoding" ) diff --git a/client/grpc/stream.go b/client/grpc/stream.go index ae13bbcf..5051718d 100644 --- a/client/grpc/stream.go +++ b/client/grpc/stream.go @@ -5,7 +5,7 @@ import ( "io" "sync" - "github.com/micro/go-micro/v2/client" + "github.com/micro/go-micro/v3/client" "google.golang.org/grpc" ) diff --git a/client/common_test.go b/client/mucp/common_test.go similarity index 94% rename from client/common_test.go rename to client/mucp/common_test.go index d1b347e6..24837dd2 100644 --- a/client/common_test.go +++ b/client/mucp/common_test.go @@ -1,7 +1,7 @@ -package client +package mucp import ( - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) var ( diff --git a/client/mucp/mucp.go b/client/mucp/mucp.go index ddd1f7cb..997f273b 100644 --- a/client/mucp/mucp.go +++ b/client/mucp/mucp.go @@ -2,10 +2,623 @@ package mucp import ( - "github.com/micro/go-micro/v2/client" + "context" + "fmt" + "sync/atomic" + "time" + + "github.com/google/uuid" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/codec" + raw "github.com/micro/go-micro/v3/codec/bytes" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/transport" + "github.com/micro/go-micro/v3/util/buf" + "github.com/micro/go-micro/v3/util/net" + "github.com/micro/go-micro/v3/util/pool" ) // NewClient returns a new micro client interface func NewClient(opts ...client.Option) client.Client { - return client.NewClient(opts...) + return newClient(opts...) +} + +type rpcClient struct { + once atomic.Value + opts client.Options + pool pool.Pool + seq uint64 +} + +func newClient(opt ...client.Option) client.Client { + opts := client.NewOptions(opt...) + + p := pool.NewPool( + pool.Size(opts.PoolSize), + pool.TTL(opts.PoolTTL), + pool.Transport(opts.Transport), + ) + + rc := &rpcClient{ + opts: opts, + pool: p, + seq: 0, + } + rc.once.Store(false) + + c := client.Client(rc) + + // wrap in reverse + for i := len(opts.Wrappers); i > 0; i-- { + c = opts.Wrappers[i-1](c) + } + + return c +} + +func (r *rpcClient) newCodec(contentType string) (codec.NewCodec, error) { + if c, ok := r.opts.Codecs[contentType]; ok { + return c, nil + } + if cf, ok := DefaultCodecs[contentType]; ok { + return cf, nil + } + return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType) +} + +func (r *rpcClient) call(ctx context.Context, node *registry.Node, req client.Request, resp interface{}, opts client.CallOptions) error { + msg := &transport.Message{ + Header: make(map[string]string), + } + + md, ok := metadata.FromContext(ctx) + if ok { + for k, v := range md { + // don't copy Micro-Topic header, that used for pub/sub + // this fix case then client uses the same context that received in subscriber + if k == "Micro-Topic" { + continue + } + msg.Header[k] = v + } + } + + // set timeout in nanoseconds + msg.Header["Timeout"] = fmt.Sprintf("%d", opts.RequestTimeout) + // set the content type for the request + msg.Header["Content-Type"] = req.ContentType() + // set the accept header + msg.Header["Accept"] = req.ContentType() + + // setup old protocol + cf := setupProtocol(msg, node) + + // no codec specified + if cf == nil { + var err error + cf, err = r.newCodec(req.ContentType()) + if err != nil { + return errors.InternalServerError("go.micro.client", err.Error()) + } + } + + dOpts := []transport.DialOption{ + transport.WithStream(), + } + + if opts.DialTimeout >= 0 { + dOpts = append(dOpts, transport.WithTimeout(opts.DialTimeout)) + } + + c, err := r.pool.Get(node.Address, dOpts...) + if err != nil { + return errors.InternalServerError("go.micro.client", "connection error: %v", err) + } + + seq := atomic.AddUint64(&r.seq, 1) - 1 + codec := newRpcCodec(msg, c, cf, "") + + rsp := &rpcResponse{ + socket: c, + codec: codec, + } + + stream := &rpcStream{ + id: fmt.Sprintf("%v", seq), + context: ctx, + request: req, + response: rsp, + codec: codec, + closed: make(chan bool), + release: func(err error) { r.pool.Release(c, err) }, + sendEOS: false, + } + // close the stream on exiting this function + defer stream.Close() + + // wait for error response + ch := make(chan error, 1) + + go func() { + defer func() { + if r := recover(); r != nil { + ch <- errors.InternalServerError("go.micro.client", "panic recovered: %v", r) + } + }() + + // send request + if err := stream.Send(req.Body()); err != nil { + ch <- err + return + } + + // recv request + if err := stream.Recv(resp); err != nil { + ch <- err + return + } + + // success + ch <- nil + }() + + var grr error + + select { + case err := <-ch: + return err + case <-ctx.Done(): + grr = errors.Timeout("go.micro.client", fmt.Sprintf("%v", ctx.Err())) + } + + // set the stream error + if grr != nil { + stream.Lock() + stream.err = grr + stream.Unlock() + + return grr + } + + return nil +} + +func (r *rpcClient) stream(ctx context.Context, node *registry.Node, req client.Request, opts client.CallOptions) (client.Stream, error) { + msg := &transport.Message{ + Header: make(map[string]string), + } + + md, ok := metadata.FromContext(ctx) + if ok { + for k, v := range md { + msg.Header[k] = v + } + } + + // set timeout in nanoseconds + if opts.StreamTimeout > time.Duration(0) { + msg.Header["Timeout"] = fmt.Sprintf("%d", opts.StreamTimeout) + } + // set the content type for the request + msg.Header["Content-Type"] = req.ContentType() + // set the accept header + msg.Header["Accept"] = req.ContentType() + + // set old codecs + cf := setupProtocol(msg, node) + + // no codec specified + if cf == nil { + var err error + cf, err = r.newCodec(req.ContentType()) + if err != nil { + return nil, errors.InternalServerError("go.micro.client", err.Error()) + } + } + + dOpts := []transport.DialOption{ + transport.WithStream(), + } + + if opts.DialTimeout >= 0 { + dOpts = append(dOpts, transport.WithTimeout(opts.DialTimeout)) + } + + c, err := r.opts.Transport.Dial(node.Address, dOpts...) + if err != nil { + return nil, errors.InternalServerError("go.micro.client", "connection error: %v", err) + } + + // increment the sequence number + seq := atomic.AddUint64(&r.seq, 1) - 1 + id := fmt.Sprintf("%v", seq) + + // create codec with stream id + codec := newRpcCodec(msg, c, cf, id) + + rsp := &rpcResponse{ + socket: c, + codec: codec, + } + + // set request codec + if r, ok := req.(*rpcRequest); ok { + r.codec = codec + } + + stream := &rpcStream{ + id: id, + context: ctx, + request: req, + response: rsp, + codec: codec, + // used to close the stream + closed: make(chan bool), + // signal the end of stream, + sendEOS: true, + // release func + release: func(err error) { c.Close() }, + } + + // wait for error response + ch := make(chan error, 1) + + go func() { + // send the first message + ch <- stream.Send(req.Body()) + }() + + var grr error + + select { + case err := <-ch: + grr = err + case <-ctx.Done(): + grr = errors.Timeout("go.micro.client", fmt.Sprintf("%v", ctx.Err())) + } + + if grr != nil { + // set the error + stream.Lock() + stream.err = grr + stream.Unlock() + + // close the stream + stream.Close() + return nil, grr + } + + return stream, nil +} + +func (r *rpcClient) Init(opts ...client.Option) error { + size := r.opts.PoolSize + ttl := r.opts.PoolTTL + tr := r.opts.Transport + + for _, o := range opts { + o(&r.opts) + } + + // update pool configuration if the options changed + if size != r.opts.PoolSize || ttl != r.opts.PoolTTL || tr != r.opts.Transport { + // close existing pool + r.pool.Close() + // create new pool + r.pool = pool.NewPool( + pool.Size(r.opts.PoolSize), + pool.TTL(r.opts.PoolTTL), + pool.Transport(r.opts.Transport), + ) + } + + return nil +} + +func (r *rpcClient) Options() client.Options { + return r.opts +} + +func (r *rpcClient) Call(ctx context.Context, request client.Request, response interface{}, opts ...client.CallOption) error { + // make a copy of call opts + callOpts := r.opts.CallOptions + for _, opt := range opts { + opt(&callOpts) + } + + // check if we already have a deadline + if d, ok := ctx.Deadline(); !ok { + // no deadline so we create a new one + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, callOpts.RequestTimeout) + defer cancel() + } else { + // got a deadline so no need to setup context + // but we need to set the timeout we pass along + remaining := d.Sub(time.Now()) + client.WithRequestTimeout(remaining)(&callOpts) + } + + // should we noop right here? + select { + case <-ctx.Done(): + return errors.Timeout("go.micro.client", fmt.Sprintf("%v", ctx.Err())) + default: + } + + // make copy of call method + rcall := r.call + + // wrap the call in reverse + for i := len(callOpts.CallWrappers); i > 0; i-- { + rcall = callOpts.CallWrappers[i-1](rcall) + } + + // return errors.New("go.micro.client", "request timeout", 408) + call := func(i int) error { + // call backoff first. Someone may want an initial start delay + t, err := callOpts.Backoff(ctx, request, i) + if err != nil { + return errors.InternalServerError("go.micro.client", "backoff error: %v", err.Error()) + } + + // only sleep if greater than 0 + if t.Seconds() > 0 { + time.Sleep(t) + } + + // use the router passed as a call option, or fallback to the rpc clients router + if callOpts.Router == nil { + callOpts.Router = r.opts.Router + } + // use the selector passed as a call option, or fallback to the rpc clients selector + if callOpts.Selector == nil { + callOpts.Selector = r.opts.Selector + } + + // lookup the route to send the request via + route, err := client.LookupRoute(request, callOpts) + if err != nil { + return err + } + + // pass a node to enable backwards comparability as changing the + // call func would be a breaking change. + // todo v3: change the call func to accept a route + node := ®istry.Node{Address: route.Address, Metadata: route.Metadata} + + // make the call + err = rcall(ctx, node, request, response, callOpts) + + // record the result of the call to inform future routing decisions + r.opts.Selector.Record(*route, err) + + return err + } + + // get the retries + retries := callOpts.Retries + + // disable retries when using a proxy + if _, _, ok := net.Proxy(request.Service(), callOpts.Address); ok { + retries = 0 + } + + ch := make(chan error, retries+1) + var gerr error + + for i := 0; i <= retries; i++ { + go func(i int) { + ch <- call(i) + }(i) + + select { + case <-ctx.Done(): + return errors.Timeout("go.micro.client", fmt.Sprintf("call timeout: %v", ctx.Err())) + case err := <-ch: + // if the call succeeded lets bail early + if err == nil { + return nil + } + + retry, rerr := callOpts.Retry(ctx, request, i, err) + if rerr != nil { + return rerr + } + + if !retry { + return err + } + + gerr = err + } + } + + return gerr +} + +func (r *rpcClient) Stream(ctx context.Context, request client.Request, opts ...client.CallOption) (client.Stream, error) { + // make a copy of call opts + callOpts := r.opts.CallOptions + for _, opt := range opts { + opt(&callOpts) + } + + // should we noop right here? + select { + case <-ctx.Done(): + return nil, errors.Timeout("go.micro.client", fmt.Sprintf("%v", ctx.Err())) + default: + } + + call := func(i int) (client.Stream, error) { + // call backoff first. Someone may want an initial start delay + t, err := callOpts.Backoff(ctx, request, i) + if err != nil { + return nil, errors.InternalServerError("go.micro.client", "backoff error: %v", err.Error()) + } + + // only sleep if greater than 0 + if t.Seconds() > 0 { + time.Sleep(t) + } + + // use the router passed as a call option, or fallback to the rpc clients router + if callOpts.Router == nil { + callOpts.Router = r.opts.Router + } + // use the selector passed as a call option, or fallback to the rpc clients selector + if callOpts.Selector == nil { + callOpts.Selector = r.opts.Selector + } + + // lookup the route to send the request via + route, err := client.LookupRoute(request, callOpts) + if err != nil { + return nil, err + } + + // pass a node to enable backwards compatability as changing the + // call func would be a breaking change. + // todo v3: change the call func to accept a route + node := ®istry.Node{Address: route.Address, Metadata: route.Metadata} + + // perform the call + stream, err := r.stream(ctx, node, request, callOpts) + + // record the result of the call to inform future routing decisions + r.opts.Selector.Record(*route, err) + + return stream, err + } + + type response struct { + stream client.Stream + err error + } + + // get the retries + retries := callOpts.Retries + + // disable retries when using a proxy + if _, _, ok := net.Proxy(request.Service(), callOpts.Address); ok { + retries = 0 + } + + ch := make(chan response, retries+1) + var grr error + + for i := 0; i <= retries; i++ { + go func(i int) { + s, err := call(i) + ch <- response{s, err} + }(i) + + select { + case <-ctx.Done(): + return nil, errors.Timeout("go.micro.client", fmt.Sprintf("call timeout: %v", ctx.Err())) + case rsp := <-ch: + // if the call succeeded lets bail early + if rsp.err == nil { + return rsp.stream, nil + } + + retry, rerr := callOpts.Retry(ctx, request, i, rsp.err) + if rerr != nil { + return nil, rerr + } + + if !retry { + return nil, rsp.err + } + + grr = rsp.err + } + } + + return nil, grr +} + +func (r *rpcClient) Publish(ctx context.Context, msg client.Message, opts ...client.PublishOption) error { + options := client.PublishOptions{ + Context: context.Background(), + } + for _, o := range opts { + o(&options) + } + + md, ok := metadata.FromContext(ctx) + if !ok { + md = make(map[string]string) + } + + id := uuid.New().String() + md["Content-Type"] = msg.ContentType() + md["Micro-Topic"] = msg.Topic() + md["Micro-Id"] = id + + // set the topic + topic := msg.Topic() + + // get the exchange + if len(options.Exchange) > 0 { + topic = options.Exchange + } + + // encode message body + cf, err := r.newCodec(msg.ContentType()) + if err != nil { + return errors.InternalServerError("go.micro.client", err.Error()) + } + + var body []byte + + // passed in raw data + if d, ok := msg.Payload().(*raw.Frame); ok { + body = d.Data + } else { + // new buffer + b := buf.New(nil) + + if err := cf(b).Write(&codec.Message{ + Target: topic, + Type: codec.Event, + Header: map[string]string{ + "Micro-Id": id, + "Micro-Topic": msg.Topic(), + }, + }, msg.Payload()); err != nil { + return errors.InternalServerError("go.micro.client", err.Error()) + } + + // set the body + body = b.Bytes() + } + + if !r.once.Load().(bool) { + if err = r.opts.Broker.Connect(); err != nil { + return errors.InternalServerError("go.micro.client", err.Error()) + } + r.once.Store(true) + } + + return r.opts.Broker.Publish(topic, &broker.Message{ + Header: md, + Body: body, + }, broker.PublishContext(options.Context)) +} + +func (r *rpcClient) NewMessage(topic string, message interface{}, opts ...client.MessageOption) client.Message { + return newMessage(topic, message, r.opts.ContentType, opts...) +} + +func (r *rpcClient) NewRequest(service, method string, request interface{}, reqOpts ...client.RequestOption) client.Request { + return newRequest(service, method, request, r.opts.ContentType, reqOpts...) +} + +func (r *rpcClient) String() string { + return "mucp" } diff --git a/client/rpc_codec.go b/client/mucp/mucp_codec.go similarity index 92% rename from client/rpc_codec.go rename to client/mucp/mucp_codec.go index 35a392b5..14754f76 100644 --- a/client/rpc_codec.go +++ b/client/mucp/mucp_codec.go @@ -1,19 +1,19 @@ -package client +package mucp import ( "bytes" errs "errors" - "github.com/micro/go-micro/v2/codec" - raw "github.com/micro/go-micro/v2/codec/bytes" - "github.com/micro/go-micro/v2/codec/grpc" - "github.com/micro/go-micro/v2/codec/json" - "github.com/micro/go-micro/v2/codec/jsonrpc" - "github.com/micro/go-micro/v2/codec/proto" - "github.com/micro/go-micro/v2/codec/protorpc" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/codec" + raw "github.com/micro/go-micro/v3/codec/bytes" + "github.com/micro/go-micro/v3/codec/grpc" + "github.com/micro/go-micro/v3/codec/json" + "github.com/micro/go-micro/v3/codec/jsonrpc" + "github.com/micro/go-micro/v3/codec/proto" + "github.com/micro/go-micro/v3/codec/protorpc" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/transport" ) const ( diff --git a/client/rpc_message.go b/client/mucp/mucp_message.go similarity index 78% rename from client/rpc_message.go rename to client/mucp/mucp_message.go index 418c756f..9336f2fd 100644 --- a/client/rpc_message.go +++ b/client/mucp/mucp_message.go @@ -1,4 +1,8 @@ -package client +package mucp + +import ( + "github.com/micro/go-micro/v3/client" +) type message struct { topic string @@ -6,8 +10,8 @@ type message struct { payload interface{} } -func newMessage(topic string, payload interface{}, contentType string, opts ...MessageOption) Message { - var options MessageOptions +func newMessage(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message { + var options client.MessageOptions for _, o := range opts { o(&options) } diff --git a/client/rpc_request.go b/client/mucp/mucp_request.go similarity index 81% rename from client/rpc_request.go rename to client/mucp/mucp_request.go index 97ca50f7..35b30e1e 100644 --- a/client/rpc_request.go +++ b/client/mucp/mucp_request.go @@ -1,7 +1,8 @@ -package client +package mucp import ( - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/codec" ) type rpcRequest struct { @@ -11,11 +12,11 @@ type rpcRequest struct { contentType string codec codec.Codec body interface{} - opts RequestOptions + opts client.RequestOptions } -func newRequest(service, endpoint string, request interface{}, contentType string, reqOpts ...RequestOption) Request { - var opts RequestOptions +func newRequest(service, endpoint string, request interface{}, contentType string, reqOpts ...client.RequestOption) client.Request { + var opts client.RequestOptions for _, o := range reqOpts { o(&opts) diff --git a/client/rpc_request_test.go b/client/mucp/mucp_request_test.go similarity index 85% rename from client/rpc_request_test.go rename to client/mucp/mucp_request_test.go index e3516794..f3f975c2 100644 --- a/client/rpc_request_test.go +++ b/client/mucp/mucp_request_test.go @@ -1,7 +1,9 @@ -package client +package mucp import ( "testing" + + "github.com/micro/go-micro/v3/client" ) func TestRequestOptions(t *testing.T) { @@ -16,7 +18,7 @@ func TestRequestOptions(t *testing.T) { t.Fatalf("expected 'endpoint' got %s", r.ContentType()) } - r2 := newRequest("service", "endpoint", nil, "application/json", WithContentType("application/protobuf")) + r2 := newRequest("service", "endpoint", nil, "application/json", client.WithContentType("application/protobuf")) if r2.ContentType() != "application/protobuf" { t.Fatalf("expected 'endpoint' got %s", r2.ContentType()) } diff --git a/client/rpc_response.go b/client/mucp/mucp_response.go similarity index 83% rename from client/rpc_response.go rename to client/mucp/mucp_response.go index d7faaea6..0925e5f0 100644 --- a/client/rpc_response.go +++ b/client/mucp/mucp_response.go @@ -1,8 +1,8 @@ -package client +package mucp import ( - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/transport" ) type rpcResponse struct { diff --git a/client/rpc_stream.go b/client/mucp/mucp_stream.go similarity index 91% rename from client/rpc_stream.go rename to client/mucp/mucp_stream.go index 426aafc4..04a630c1 100644 --- a/client/rpc_stream.go +++ b/client/mucp/mucp_stream.go @@ -1,11 +1,12 @@ -package client +package mucp import ( "context" "io" "sync" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/codec" ) // Implements the streamer interface @@ -14,8 +15,8 @@ type rpcStream struct { id string closed chan bool err error - request Request - response Response + request client.Request + response client.Response codec codec.Codec context context.Context @@ -39,11 +40,11 @@ func (r *rpcStream) Context() context.Context { return r.context } -func (r *rpcStream) Request() Request { +func (r *rpcStream) Request() client.Request { return r.request } -func (r *rpcStream) Response() Response { +func (r *rpcStream) Response() client.Response { return r.response } diff --git a/client/rpc_client_test.go b/client/mucp/mucp_test.go similarity index 70% rename from client/rpc_client_test.go rename to client/mucp/mucp_test.go index 73b671b3..5c81c9ed 100644 --- a/client/rpc_client_test.go +++ b/client/mucp/mucp_test.go @@ -1,13 +1,14 @@ -package client +package mucp import ( "context" "fmt" "testing" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/registry/memory" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/memory" ) func newTestRegistry() registry.Registry { @@ -20,8 +21,8 @@ func TestCallAddress(t *testing.T) { endpoint := "Test.Endpoint" address := "10.1.10.1:8080" - wrap := func(cf CallFunc) CallFunc { - return func(ctx context.Context, node *registry.Node, req Request, rsp interface{}, opts CallOptions) error { + wrap := func(cf client.CallFunc) client.CallFunc { + return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error { called = true if req.Service() != service { @@ -43,14 +44,14 @@ func TestCallAddress(t *testing.T) { r := newTestRegistry() c := NewClient( - Registry(r), - WrapCall(wrap), + client.Registry(r), + client.WrapCall(wrap), ) req := c.NewRequest(service, endpoint, nil) // test calling remote address - if err := c.Call(context.Background(), req, nil, WithAddress(address)); err != nil { + if err := c.Call(context.Background(), req, nil, client.WithAddress(address)); err != nil { t.Fatal("call with address error", err) } @@ -67,8 +68,8 @@ func TestCallRetry(t *testing.T) { var called int - wrap := func(cf CallFunc) CallFunc { - return func(ctx context.Context, node *registry.Node, req Request, rsp interface{}, opts CallOptions) error { + wrap := func(cf client.CallFunc) client.CallFunc { + return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error { called++ if called == 1 { return errors.InternalServerError("test.error", "retry request") @@ -81,14 +82,14 @@ func TestCallRetry(t *testing.T) { r := newTestRegistry() c := NewClient( - Registry(r), - WrapCall(wrap), + client.Registry(r), + client.WrapCall(wrap), ) req := c.NewRequest(service, endpoint, nil) // test calling remote address - if err := c.Call(context.Background(), req, nil, WithAddress(address)); err != nil { + if err := c.Call(context.Background(), req, nil, client.WithAddress(address)); err != nil { t.Fatal("call with address error", err) } @@ -105,8 +106,8 @@ func TestCallWrapper(t *testing.T) { endpoint := "Test.Endpoint" address := "10.1.10.1:8080" - wrap := func(cf CallFunc) CallFunc { - return func(ctx context.Context, node *registry.Node, req Request, rsp interface{}, opts CallOptions) error { + wrap := func(cf client.CallFunc) client.CallFunc { + return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error { called = true if req.Service() != service { @@ -128,8 +129,8 @@ func TestCallWrapper(t *testing.T) { r := newTestRegistry() c := NewClient( - Registry(r), - WrapCall(wrap), + client.Registry(r), + client.WrapCall(wrap), ) r.Register(®istry.Service{ diff --git a/client/options_test.go b/client/mucp/options_test.go similarity index 61% rename from client/options_test.go rename to client/mucp/options_test.go index 83c3a557..29b76791 100644 --- a/client/options_test.go +++ b/client/mucp/options_test.go @@ -1,10 +1,11 @@ -package client +package mucp import ( "testing" "time" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/transport" ) func TestCallOptions(t *testing.T) { @@ -14,33 +15,33 @@ func TestCallOptions(t *testing.T) { rtimeout time.Duration dtimeout time.Duration }{ - {false, DefaultRetries, DefaultRequestTimeout, transport.DefaultDialTimeout}, + {false, client.DefaultRetries, client.DefaultRequestTimeout, transport.DefaultDialTimeout}, {true, 10, time.Second, time.Second * 2}, } for _, d := range testData { - var opts Options - var cl Client + var opts client.Options + var cl client.Client if d.set { - opts = NewOptions( - Retries(d.retries), - RequestTimeout(d.rtimeout), - DialTimeout(d.dtimeout), + opts = client.NewOptions( + client.Retries(d.retries), + client.RequestTimeout(d.rtimeout), + client.DialTimeout(d.dtimeout), ) cl = NewClient( - Retries(d.retries), - RequestTimeout(d.rtimeout), - DialTimeout(d.dtimeout), + client.Retries(d.retries), + client.RequestTimeout(d.rtimeout), + client.DialTimeout(d.dtimeout), ) } else { - opts = NewOptions() + opts = client.NewOptions() cl = NewClient() } // test options and those set in client - for _, o := range []Options{opts, cl.Options()} { + for _, o := range []client.Options{opts, cl.Options()} { if o.CallOptions.Retries != d.retries { t.Fatalf("Expected retries %v got %v", d.retries, o.CallOptions.Retries) } @@ -57,12 +58,12 @@ func TestCallOptions(t *testing.T) { callOpts := o.CallOptions // create new opts - cretries := WithRetries(o.CallOptions.Retries * 10) - crtimeout := WithRequestTimeout(o.CallOptions.RequestTimeout * (time.Second * 10)) - cdtimeout := WithDialTimeout(o.CallOptions.DialTimeout * (time.Second * 10)) + cretries := client.WithRetries(o.CallOptions.Retries * 10) + crtimeout := client.WithRequestTimeout(o.CallOptions.RequestTimeout * (time.Second * 10)) + cdtimeout := client.WithDialTimeout(o.CallOptions.DialTimeout * (time.Second * 10)) // set call options - for _, opt := range []CallOption{cretries, crtimeout, cdtimeout} { + for _, opt := range []client.CallOption{cretries, crtimeout, cdtimeout} { opt(&callOpts) } diff --git a/client/options.go b/client/options.go index 5058983d..4106393f 100644 --- a/client/options.go +++ b/client/options.go @@ -4,12 +4,14 @@ import ( "context" "time" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/selector" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/broker/http" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/router" + regRouter "github.com/micro/go-micro/v3/router/registry" + "github.com/micro/go-micro/v3/selector" + "github.com/micro/go-micro/v3/transport" ) type Options struct { @@ -102,7 +104,7 @@ func NewOptions(options ...Option) Options { opts := Options{ Cache: NewCache(), Context: context.Background(), - ContentType: DefaultContentType, + ContentType: "application/protobuf", Codecs: make(map[string]codec.NewCodec), CallOptions: CallOptions{ Backoff: DefaultBackoff, @@ -113,8 +115,8 @@ func NewOptions(options ...Option) Options { }, PoolSize: DefaultPoolSize, PoolTTL: DefaultPoolTTL, - Broker: broker.DefaultBroker, - Router: router.DefaultRouter, + Broker: http.NewBroker(), + Router: regRouter.NewRouter(), Selector: selector.DefaultSelector, Transport: transport.DefaultTransport, } diff --git a/client/retry.go b/client/retry.go index 92ba4c07..e23dc1aa 100644 --- a/client/retry.go +++ b/client/retry.go @@ -3,7 +3,7 @@ package client import ( "context" - "github.com/micro/go-micro/v2/errors" + "github.com/micro/go-micro/v3/errors" ) // note that returning either false or a non-nil error will result in the call not being retried diff --git a/client/rpc_client.go b/client/rpc_client.go deleted file mode 100644 index 71c74cca..00000000 --- a/client/rpc_client.go +++ /dev/null @@ -1,617 +0,0 @@ -package client - -import ( - "context" - "fmt" - "sync/atomic" - "time" - - "github.com/google/uuid" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/codec" - raw "github.com/micro/go-micro/v2/codec/bytes" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/transport" - "github.com/micro/go-micro/v2/util/buf" - "github.com/micro/go-micro/v2/util/net" - "github.com/micro/go-micro/v2/util/pool" -) - -type rpcClient struct { - once atomic.Value - opts Options - pool pool.Pool - seq uint64 -} - -func newRpcClient(opt ...Option) Client { - opts := NewOptions(opt...) - - p := pool.NewPool( - pool.Size(opts.PoolSize), - pool.TTL(opts.PoolTTL), - pool.Transport(opts.Transport), - ) - - rc := &rpcClient{ - opts: opts, - pool: p, - seq: 0, - } - rc.once.Store(false) - - c := Client(rc) - - // wrap in reverse - for i := len(opts.Wrappers); i > 0; i-- { - c = opts.Wrappers[i-1](c) - } - - return c -} - -func (r *rpcClient) newCodec(contentType string) (codec.NewCodec, error) { - if c, ok := r.opts.Codecs[contentType]; ok { - return c, nil - } - if cf, ok := DefaultCodecs[contentType]; ok { - return cf, nil - } - return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType) -} - -func (r *rpcClient) call(ctx context.Context, node *registry.Node, req Request, resp interface{}, opts CallOptions) error { - msg := &transport.Message{ - Header: make(map[string]string), - } - - md, ok := metadata.FromContext(ctx) - if ok { - for k, v := range md { - // don't copy Micro-Topic header, that used for pub/sub - // this fix case then client uses the same context that received in subscriber - if k == "Micro-Topic" { - continue - } - msg.Header[k] = v - } - } - - // set timeout in nanoseconds - msg.Header["Timeout"] = fmt.Sprintf("%d", opts.RequestTimeout) - // set the content type for the request - msg.Header["Content-Type"] = req.ContentType() - // set the accept header - msg.Header["Accept"] = req.ContentType() - - // setup old protocol - cf := setupProtocol(msg, node) - - // no codec specified - if cf == nil { - var err error - cf, err = r.newCodec(req.ContentType()) - if err != nil { - return errors.InternalServerError("go.micro.client", err.Error()) - } - } - - dOpts := []transport.DialOption{ - transport.WithStream(), - } - - if opts.DialTimeout >= 0 { - dOpts = append(dOpts, transport.WithTimeout(opts.DialTimeout)) - } - - c, err := r.pool.Get(node.Address, dOpts...) - if err != nil { - return errors.InternalServerError("go.micro.client", "connection error: %v", err) - } - - seq := atomic.AddUint64(&r.seq, 1) - 1 - codec := newRpcCodec(msg, c, cf, "") - - rsp := &rpcResponse{ - socket: c, - codec: codec, - } - - stream := &rpcStream{ - id: fmt.Sprintf("%v", seq), - context: ctx, - request: req, - response: rsp, - codec: codec, - closed: make(chan bool), - release: func(err error) { r.pool.Release(c, err) }, - sendEOS: false, - } - // close the stream on exiting this function - defer stream.Close() - - // wait for error response - ch := make(chan error, 1) - - go func() { - defer func() { - if r := recover(); r != nil { - ch <- errors.InternalServerError("go.micro.client", "panic recovered: %v", r) - } - }() - - // send request - if err := stream.Send(req.Body()); err != nil { - ch <- err - return - } - - // recv request - if err := stream.Recv(resp); err != nil { - ch <- err - return - } - - // success - ch <- nil - }() - - var grr error - - select { - case err := <-ch: - return err - case <-ctx.Done(): - grr = errors.Timeout("go.micro.client", fmt.Sprintf("%v", ctx.Err())) - } - - // set the stream error - if grr != nil { - stream.Lock() - stream.err = grr - stream.Unlock() - - return grr - } - - return nil -} - -func (r *rpcClient) stream(ctx context.Context, node *registry.Node, req Request, opts CallOptions) (Stream, error) { - msg := &transport.Message{ - Header: make(map[string]string), - } - - md, ok := metadata.FromContext(ctx) - if ok { - for k, v := range md { - msg.Header[k] = v - } - } - - // set timeout in nanoseconds - if opts.StreamTimeout > time.Duration(0) { - msg.Header["Timeout"] = fmt.Sprintf("%d", opts.StreamTimeout) - } - // set the content type for the request - msg.Header["Content-Type"] = req.ContentType() - // set the accept header - msg.Header["Accept"] = req.ContentType() - - // set old codecs - cf := setupProtocol(msg, node) - - // no codec specified - if cf == nil { - var err error - cf, err = r.newCodec(req.ContentType()) - if err != nil { - return nil, errors.InternalServerError("go.micro.client", err.Error()) - } - } - - dOpts := []transport.DialOption{ - transport.WithStream(), - } - - if opts.DialTimeout >= 0 { - dOpts = append(dOpts, transport.WithTimeout(opts.DialTimeout)) - } - - c, err := r.opts.Transport.Dial(node.Address, dOpts...) - if err != nil { - return nil, errors.InternalServerError("go.micro.client", "connection error: %v", err) - } - - // increment the sequence number - seq := atomic.AddUint64(&r.seq, 1) - 1 - id := fmt.Sprintf("%v", seq) - - // create codec with stream id - codec := newRpcCodec(msg, c, cf, id) - - rsp := &rpcResponse{ - socket: c, - codec: codec, - } - - // set request codec - if r, ok := req.(*rpcRequest); ok { - r.codec = codec - } - - stream := &rpcStream{ - id: id, - context: ctx, - request: req, - response: rsp, - codec: codec, - // used to close the stream - closed: make(chan bool), - // signal the end of stream, - sendEOS: true, - // release func - release: func(err error) { c.Close() }, - } - - // wait for error response - ch := make(chan error, 1) - - go func() { - // send the first message - ch <- stream.Send(req.Body()) - }() - - var grr error - - select { - case err := <-ch: - grr = err - case <-ctx.Done(): - grr = errors.Timeout("go.micro.client", fmt.Sprintf("%v", ctx.Err())) - } - - if grr != nil { - // set the error - stream.Lock() - stream.err = grr - stream.Unlock() - - // close the stream - stream.Close() - return nil, grr - } - - return stream, nil -} - -func (r *rpcClient) Init(opts ...Option) error { - size := r.opts.PoolSize - ttl := r.opts.PoolTTL - tr := r.opts.Transport - - for _, o := range opts { - o(&r.opts) - } - - // update pool configuration if the options changed - if size != r.opts.PoolSize || ttl != r.opts.PoolTTL || tr != r.opts.Transport { - // close existing pool - r.pool.Close() - // create new pool - r.pool = pool.NewPool( - pool.Size(r.opts.PoolSize), - pool.TTL(r.opts.PoolTTL), - pool.Transport(r.opts.Transport), - ) - } - - return nil -} - -func (r *rpcClient) Options() Options { - return r.opts -} - -func (r *rpcClient) Call(ctx context.Context, request Request, response interface{}, opts ...CallOption) error { - // make a copy of call opts - callOpts := r.opts.CallOptions - for _, opt := range opts { - opt(&callOpts) - } - - // check if we already have a deadline - if d, ok := ctx.Deadline(); !ok { - // no deadline so we create a new one - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, callOpts.RequestTimeout) - defer cancel() - } else { - // got a deadline so no need to setup context - // but we need to set the timeout we pass along - remaining := d.Sub(time.Now()) - WithRequestTimeout(remaining)(&callOpts) - } - - // should we noop right here? - select { - case <-ctx.Done(): - return errors.Timeout("go.micro.client", fmt.Sprintf("%v", ctx.Err())) - default: - } - - // make copy of call method - rcall := r.call - - // wrap the call in reverse - for i := len(callOpts.CallWrappers); i > 0; i-- { - rcall = callOpts.CallWrappers[i-1](rcall) - } - - // return errors.New("go.micro.client", "request timeout", 408) - call := func(i int) error { - // call backoff first. Someone may want an initial start delay - t, err := callOpts.Backoff(ctx, request, i) - if err != nil { - return errors.InternalServerError("go.micro.client", "backoff error: %v", err.Error()) - } - - // only sleep if greater than 0 - if t.Seconds() > 0 { - time.Sleep(t) - } - - // use the router passed as a call option, or fallback to the rpc clients router - if callOpts.Router == nil { - callOpts.Router = r.opts.Router - } - // use the selector passed as a call option, or fallback to the rpc clients selector - if callOpts.Selector == nil { - callOpts.Selector = r.opts.Selector - } - - // lookup the route to send the request via - route, err := LookupRoute(request, callOpts) - if err != nil { - return err - } - - // pass a node to enable backwards comparability as changing the - // call func would be a breaking change. - // todo v3: change the call func to accept a route - node := ®istry.Node{Address: route.Address, Metadata: route.Metadata} - - // make the call - err = rcall(ctx, node, request, response, callOpts) - - // record the result of the call to inform future routing decisions - r.opts.Selector.Record(*route, err) - - return err - } - - // get the retries - retries := callOpts.Retries - - // disable retries when using a proxy - if _, _, ok := net.Proxy(request.Service(), callOpts.Address); ok { - retries = 0 - } - - ch := make(chan error, retries+1) - var gerr error - - for i := 0; i <= retries; i++ { - go func(i int) { - ch <- call(i) - }(i) - - select { - case <-ctx.Done(): - return errors.Timeout("go.micro.client", fmt.Sprintf("call timeout: %v", ctx.Err())) - case err := <-ch: - // if the call succeeded lets bail early - if err == nil { - return nil - } - - retry, rerr := callOpts.Retry(ctx, request, i, err) - if rerr != nil { - return rerr - } - - if !retry { - return err - } - - gerr = err - } - } - - return gerr -} - -func (r *rpcClient) Stream(ctx context.Context, request Request, opts ...CallOption) (Stream, error) { - // make a copy of call opts - callOpts := r.opts.CallOptions - for _, opt := range opts { - opt(&callOpts) - } - - // should we noop right here? - select { - case <-ctx.Done(): - return nil, errors.Timeout("go.micro.client", fmt.Sprintf("%v", ctx.Err())) - default: - } - - call := func(i int) (Stream, error) { - // call backoff first. Someone may want an initial start delay - t, err := callOpts.Backoff(ctx, request, i) - if err != nil { - return nil, errors.InternalServerError("go.micro.client", "backoff error: %v", err.Error()) - } - - // only sleep if greater than 0 - if t.Seconds() > 0 { - time.Sleep(t) - } - - // use the router passed as a call option, or fallback to the rpc clients router - if callOpts.Router == nil { - callOpts.Router = r.opts.Router - } - // use the selector passed as a call option, or fallback to the rpc clients selector - if callOpts.Selector == nil { - callOpts.Selector = r.opts.Selector - } - - // lookup the route to send the request via - route, err := LookupRoute(request, callOpts) - if err != nil { - return nil, err - } - - // pass a node to enable backwards compatability as changing the - // call func would be a breaking change. - // todo v3: change the call func to accept a route - node := ®istry.Node{Address: route.Address, Metadata: route.Metadata} - - // perform the call - stream, err := r.stream(ctx, node, request, callOpts) - - // record the result of the call to inform future routing decisions - r.opts.Selector.Record(*route, err) - - return stream, err - } - - type response struct { - stream Stream - err error - } - - // get the retries - retries := callOpts.Retries - - // disable retries when using a proxy - if _, _, ok := net.Proxy(request.Service(), callOpts.Address); ok { - retries = 0 - } - - ch := make(chan response, retries+1) - var grr error - - for i := 0; i <= retries; i++ { - go func(i int) { - s, err := call(i) - ch <- response{s, err} - }(i) - - select { - case <-ctx.Done(): - return nil, errors.Timeout("go.micro.client", fmt.Sprintf("call timeout: %v", ctx.Err())) - case rsp := <-ch: - // if the call succeeded lets bail early - if rsp.err == nil { - return rsp.stream, nil - } - - retry, rerr := callOpts.Retry(ctx, request, i, rsp.err) - if rerr != nil { - return nil, rerr - } - - if !retry { - return nil, rsp.err - } - - grr = rsp.err - } - } - - return nil, grr -} - -func (r *rpcClient) Publish(ctx context.Context, msg Message, opts ...PublishOption) error { - options := PublishOptions{ - Context: context.Background(), - } - for _, o := range opts { - o(&options) - } - - md, ok := metadata.FromContext(ctx) - if !ok { - md = make(map[string]string) - } - - id := uuid.New().String() - md["Content-Type"] = msg.ContentType() - md["Micro-Topic"] = msg.Topic() - md["Micro-Id"] = id - - // set the topic - topic := msg.Topic() - - // get the exchange - if len(options.Exchange) > 0 { - topic = options.Exchange - } - - // encode message body - cf, err := r.newCodec(msg.ContentType()) - if err != nil { - return errors.InternalServerError("go.micro.client", err.Error()) - } - - var body []byte - - // passed in raw data - if d, ok := msg.Payload().(*raw.Frame); ok { - body = d.Data - } else { - // new buffer - b := buf.New(nil) - - if err := cf(b).Write(&codec.Message{ - Target: topic, - Type: codec.Event, - Header: map[string]string{ - "Micro-Id": id, - "Micro-Topic": msg.Topic(), - }, - }, msg.Payload()); err != nil { - return errors.InternalServerError("go.micro.client", err.Error()) - } - - // set the body - body = b.Bytes() - } - - if !r.once.Load().(bool) { - if err = r.opts.Broker.Connect(); err != nil { - return errors.InternalServerError("go.micro.client", err.Error()) - } - r.once.Store(true) - } - - return r.opts.Broker.Publish(topic, &broker.Message{ - Header: md, - Body: body, - }, broker.PublishContext(options.Context)) -} - -func (r *rpcClient) NewMessage(topic string, message interface{}, opts ...MessageOption) Message { - return newMessage(topic, message, r.opts.ContentType, opts...) -} - -func (r *rpcClient) NewRequest(service, method string, request interface{}, reqOpts ...RequestOption) Request { - return newRequest(service, method, request, r.opts.ContentType, reqOpts...) -} - -func (r *rpcClient) String() string { - return "mucp" -} diff --git a/client/service/proto/client.pb.micro.go b/client/service/proto/client.pb.micro.go index 0f3094bb..bdfe1081 100644 --- a/client/service/proto/client.pb.micro.go +++ b/client/service/proto/client.pb.micro.go @@ -11,9 +11,9 @@ import ( import ( context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" + api "github.com/micro/go-micro/v3/api" + client "github.com/micro/go-micro/v3/client" + server "github.com/micro/go-micro/v3/server" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/client/test_request.go b/client/test_request.go new file mode 100644 index 00000000..80e1d175 --- /dev/null +++ b/client/test_request.go @@ -0,0 +1,65 @@ +package client + +import ( + "github.com/micro/go-micro/v3/codec" +) + +type testRequest struct { + service string + method string + endpoint string + contentType string + codec codec.Codec + body interface{} + opts RequestOptions +} + +func newRequest(service, endpoint string, request interface{}, contentType string, reqOpts ...RequestOption) Request { + var opts RequestOptions + + for _, o := range reqOpts { + o(&opts) + } + + // set the content-type specified + if len(opts.ContentType) > 0 { + contentType = opts.ContentType + } + + return &testRequest{ + service: service, + method: endpoint, + endpoint: endpoint, + body: request, + contentType: contentType, + opts: opts, + } +} + +func (r *testRequest) ContentType() string { + return r.contentType +} + +func (r *testRequest) Service() string { + return r.service +} + +func (r *testRequest) Method() string { + return r.method +} + +func (r *testRequest) Endpoint() string { + return r.endpoint +} + +func (r *testRequest) Body() interface{} { + return r.body +} + +func (r *testRequest) Codec() codec.Writer { + return r.codec +} + +func (r *testRequest) Stream() bool { + return r.opts.Stream +} diff --git a/client/util.go b/client/util.go index f5d505a7..41946bba 100644 --- a/client/util.go +++ b/client/util.go @@ -3,10 +3,10 @@ package client import ( "math/rand" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/selector" - pnet "github.com/micro/go-micro/v2/util/net" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/router" + "github.com/micro/go-micro/v3/selector" + pnet "github.com/micro/go-micro/v3/util/net" ) // LookupRoute for a request using the router and then choose one using the selector diff --git a/client/wrapper.go b/client/wrapper.go index d5138bcc..e68c31e6 100644 --- a/client/wrapper.go +++ b/client/wrapper.go @@ -3,7 +3,7 @@ package client import ( "context" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) // CallFunc represents the individual call func diff --git a/cmd/cli/cli.go b/cmd/cli/cli.go new file mode 100644 index 00000000..46a28050 --- /dev/null +++ b/cmd/cli/cli.go @@ -0,0 +1,50 @@ +// Package cli is a urfave/cli implementation of the command +package cli + +import ( + "os" + + "github.com/micro/cli/v2" + "github.com/micro/go-micro/v3/cmd" +) + +type cliCmd struct { + opts cmd.Options + app *cli.App +} + +func (c *cliCmd) Init(opts ...cmd.Option) error { + for _, o := range opts { + o(&c.opts) + } + c.app.Name = c.opts.Name + c.app.Description = c.opts.Description + c.app.Version = c.opts.Version + c.app.Flags = c.opts.Flags + c.app.Commands = c.opts.Commands + c.app.Action = c.opts.Action + return nil +} + +func (c *cliCmd) Options() cmd.Options { + return c.opts +} + +func (c *cliCmd) App() *cli.App { + return c.app +} + +func (c *cliCmd) Run() error { + return c.app.Run(os.Args) +} + +func (c *cliCmd) String() string { + return "cli" +} + +func NewCmd(opts ...cmd.Option) cmd.Cmd { + c := new(cliCmd) + c.app = cli.NewApp() + c.Init(opts...) + return c +} diff --git a/cmd/cmd.go b/cmd/cmd.go index de87b686..68b6bd31 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -2,40 +2,12 @@ package cmd import ( - "crypto/tls" - "crypto/x509" - "io/ioutil" - "math/rand" - "os" - "strings" - "time" + "context" "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/broker" - brokerSrv "github.com/micro/go-micro/v2/broker/service" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/client/grpc" - "github.com/micro/go-micro/v2/config" - "github.com/micro/go-micro/v2/debug/profile" - "github.com/micro/go-micro/v2/debug/trace" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/registry" - registrySrv "github.com/micro/go-micro/v2/registry/service" - "github.com/micro/go-micro/v2/router" - srvRouter "github.com/micro/go-micro/v2/router/service" - "github.com/micro/go-micro/v2/runtime" - "github.com/micro/go-micro/v2/selector" - "github.com/micro/go-micro/v2/server" - "github.com/micro/go-micro/v2/store" - "github.com/micro/go-micro/v2/transport" - authutil "github.com/micro/go-micro/v2/util/auth" - "github.com/micro/go-micro/v2/util/wrapper" - - configSrc "github.com/micro/go-micro/v2/config/source" - configSrv "github.com/micro/go-micro/v2/config/source/service" ) +// TODO: replace App with RegisterCommand/RegisterFlags type Cmd interface { // Init initialises options // Note: Use Run to parse command line @@ -50,776 +22,65 @@ type Cmd interface { String() string } -type cmd struct { - opts Options - app *cli.App -} - type Option func(o *Options) -var ( - DefaultCmd = newCmd() - - DefaultFlags = []cli.Flag{ - &cli.StringFlag{ - Name: "client", - EnvVars: []string{"MICRO_CLIENT"}, - Usage: "Client for go-micro; rpc", - }, - &cli.StringFlag{ - Name: "client_request_timeout", - EnvVars: []string{"MICRO_CLIENT_REQUEST_TIMEOUT"}, - Usage: "Sets the client request timeout. e.g 500ms, 5s, 1m. Default: 5s", - }, - &cli.IntFlag{ - Name: "client_retries", - EnvVars: []string{"MICRO_CLIENT_RETRIES"}, - Value: client.DefaultRetries, - Usage: "Sets the client retries. Default: 1", - }, - &cli.IntFlag{ - Name: "client_pool_size", - EnvVars: []string{"MICRO_CLIENT_POOL_SIZE"}, - Usage: "Sets the client connection pool size. Default: 1", - }, - &cli.StringFlag{ - Name: "client_pool_ttl", - EnvVars: []string{"MICRO_CLIENT_POOL_TTL"}, - Usage: "Sets the client connection pool ttl. e.g 500ms, 5s, 1m. Default: 1m", - }, - &cli.IntFlag{ - Name: "register_ttl", - EnvVars: []string{"MICRO_REGISTER_TTL"}, - Value: 60, - Usage: "Register TTL in seconds", - }, - &cli.IntFlag{ - Name: "register_interval", - EnvVars: []string{"MICRO_REGISTER_INTERVAL"}, - Value: 30, - Usage: "Register interval in seconds", - }, - &cli.StringFlag{ - Name: "server", - EnvVars: []string{"MICRO_SERVER"}, - Usage: "Server for go-micro; rpc", - }, - &cli.StringFlag{ - Name: "server_name", - EnvVars: []string{"MICRO_SERVER_NAME"}, - Usage: "Name of the server. go.micro.srv.example", - }, - &cli.StringFlag{ - Name: "server_version", - EnvVars: []string{"MICRO_SERVER_VERSION"}, - Usage: "Version of the server. 1.1.0", - }, - &cli.StringFlag{ - Name: "server_id", - EnvVars: []string{"MICRO_SERVER_ID"}, - Usage: "Id of the server. Auto-generated if not specified", - }, - &cli.StringFlag{ - Name: "server_address", - EnvVars: []string{"MICRO_SERVER_ADDRESS"}, - Usage: "Bind address for the server. 127.0.0.1:8080", - }, - &cli.StringFlag{ - Name: "server_advertise", - EnvVars: []string{"MICRO_SERVER_ADVERTISE"}, - Usage: "Used instead of the server_address when registering with discovery. 127.0.0.1:8080", - }, - &cli.StringSliceFlag{ - Name: "server_metadata", - EnvVars: []string{"MICRO_SERVER_METADATA"}, - Value: &cli.StringSlice{}, - Usage: "A list of key-value pairs defining metadata. version=1.0.0", - }, - &cli.StringFlag{ - Name: "broker", - EnvVars: []string{"MICRO_BROKER"}, - Usage: "Broker for pub/sub. http, nats, rabbitmq", - }, - &cli.StringFlag{ - Name: "broker_address", - EnvVars: []string{"MICRO_BROKER_ADDRESS"}, - Usage: "Comma-separated list of broker addresses", - }, - &cli.StringFlag{ - Name: "broker_tls_ca", - Usage: "Certificate authority for TLS with broker", - EnvVars: []string{"MICRO_BROKER_TLS_CA"}, - }, - &cli.StringFlag{ - Name: "broker_tls_cert", - Usage: "Client cert for TLS with broker", - EnvVars: []string{"MICRO_BROKER_TLS_CERT"}, - }, - &cli.StringFlag{ - Name: "broker_tls_key", - Usage: "Client key for TLS with broker", - EnvVars: []string{"MICRO_BROKER_TLS_KEY"}, - }, - &cli.StringFlag{ - Name: "profile", - Usage: "Debug profiler for cpu and memory stats", - EnvVars: []string{"MICRO_DEBUG_PROFILE"}, - }, - &cli.StringFlag{ - Name: "registry", - EnvVars: []string{"MICRO_REGISTRY"}, - Usage: "Registry for discovery. etcd, mdns", - }, - &cli.StringFlag{ - Name: "registry_address", - EnvVars: []string{"MICRO_REGISTRY_ADDRESS"}, - Usage: "Comma-separated list of registry addresses", - }, - &cli.StringFlag{ - Name: "registry_tls_ca", - Usage: "Certificate authority for TLS with registry", - EnvVars: []string{"MICRO_REGISTRY_TLS_CA"}, - }, - &cli.StringFlag{ - Name: "registry_tls_cert", - Usage: "Client cert for TLS with registry", - EnvVars: []string{"MICRO_REGISTRY_TLS_CERT"}, - }, - &cli.StringFlag{ - Name: "registry_tls_key", - Usage: "Client key for TLS with registry", - EnvVars: []string{"MICRO_REGISTRY_TLS_KEY"}, - }, &cli.StringFlag{ - Name: "runtime", - Usage: "Runtime for building and running services e.g local, kubernetes", - EnvVars: []string{"MICRO_RUNTIME"}, - Value: "local", - }, - &cli.StringFlag{ - Name: "runtime_source", - Usage: "Runtime source for building and running services e.g github.com/micro/service", - EnvVars: []string{"MICRO_RUNTIME_SOURCE"}, - Value: "github.com/micro/services", - }, - &cli.StringFlag{ - Name: "selector", - EnvVars: []string{"MICRO_SELECTOR"}, - Usage: "Selector used to pick nodes for querying", - }, - &cli.StringFlag{ - Name: "store", - EnvVars: []string{"MICRO_STORE"}, - Usage: "Store used for key-value storage", - }, - &cli.StringFlag{ - Name: "store_address", - EnvVars: []string{"MICRO_STORE_ADDRESS"}, - Usage: "Comma-separated list of store addresses", - }, - &cli.StringFlag{ - Name: "store_database", - EnvVars: []string{"MICRO_STORE_DATABASE"}, - Usage: "Database option for the underlying store", - }, - &cli.StringFlag{ - Name: "store_table", - EnvVars: []string{"MICRO_STORE_TABLE"}, - Usage: "Table option for the underlying store", - }, - &cli.StringFlag{ - Name: "transport", - EnvVars: []string{"MICRO_TRANSPORT"}, - Usage: "Transport mechanism used; http", - }, - &cli.StringFlag{ - Name: "transport_address", - EnvVars: []string{"MICRO_TRANSPORT_ADDRESS"}, - Usage: "Comma-separated list of transport addresses", - }, - &cli.StringFlag{ - Name: "tracer", - EnvVars: []string{"MICRO_TRACER"}, - Usage: "Tracer for distributed tracing, e.g. memory, jaeger", - }, - &cli.StringFlag{ - Name: "tracer_address", - EnvVars: []string{"MICRO_TRACER_ADDRESS"}, - Usage: "Comma-separated list of tracer addresses", - }, - &cli.StringFlag{ - Name: "auth", - EnvVars: []string{"MICRO_AUTH"}, - Usage: "Auth for role based access control, e.g. service", - }, - &cli.StringFlag{ - Name: "auth_address", - EnvVars: []string{"MICRO_AUTH_ADDRESS"}, - Usage: "Comma-separated list of auth addresses", - }, - &cli.StringFlag{ - Name: "auth_id", - EnvVars: []string{"MICRO_AUTH_ID"}, - Usage: "Account ID used for client authentication", - }, - &cli.StringFlag{ - Name: "auth_secret", - EnvVars: []string{"MICRO_AUTH_SECRET"}, - Usage: "Account secret used for client authentication", - }, - &cli.StringFlag{ - Name: "service_namespace", - EnvVars: []string{"MICRO_NAMESPACE"}, - Usage: "Namespace the service is operating in", - Value: "micro", - }, - &cli.StringFlag{ - Name: "auth_public_key", - EnvVars: []string{"MICRO_AUTH_PUBLIC_KEY"}, - Usage: "Public key for JWT auth (base64 encoded PEM)", - }, - &cli.StringFlag{ - Name: "auth_private_key", - EnvVars: []string{"MICRO_AUTH_PRIVATE_KEY"}, - Usage: "Private key for JWT auth (base64 encoded PEM)", - }, - &cli.StringFlag{ - Name: "config", - EnvVars: []string{"MICRO_CONFIG"}, - Usage: "The source of the config to be used to get configuration", - }, - &cli.StringFlag{ - Name: "router", - EnvVars: []string{"MICRO_ROUTER"}, - Usage: "Router used for client requests", - }, - &cli.StringFlag{ - Name: "router_address", - Usage: "Comma-separated list of router addresses", - EnvVars: []string{"MICRO_ROUTER_ADDRESS"}, - }, - } - - DefaultBrokers = map[string]func(...broker.Option) broker.Broker{} - - DefaultClients = map[string]func(...client.Option) client.Client{} - - DefaultRegistries = map[string]func(...registry.Option) registry.Registry{} - - DefaultRouters = map[string]func(...router.Option) router.Router{} - - DefaultSelectors = map[string]func(...selector.Option) selector.Selector{} - - DefaultServers = map[string]func(...server.Option) server.Server{} - - DefaultTransports = map[string]func(...transport.Option) transport.Transport{} - - DefaultRuntimes = map[string]func(...runtime.Option) runtime.Runtime{} - - DefaultStores = map[string]func(...store.Option) store.Store{} - - DefaultTracers = map[string]func(...trace.Option) trace.Tracer{} - - DefaultAuths = map[string]func(...auth.Option) auth.Auth{} - - DefaultProfiles = map[string]func(...profile.Option) profile.Profile{} - - DefaultConfigs = map[string]func(...config.Option) (config.Config, error){} -) - -func init() { - rand.Seed(time.Now().Unix()) +type Options struct { + // Name of the application + Name string + // Description of the application + Description string + // Version of the application + Version string + // Action to execute when Run is called and there is no subcommand + // TODO replace with a build in context + Action func(*cli.Context) error + // TODO replace with built in command definition + Commands []*cli.Command + // TODO replace with built in flags definition + Flags []cli.Flag + // Other options for implementations of the interface + // can be stored in a context + Context context.Context } -func newCmd(opts ...Option) Cmd { - options := Options{ - Auth: &auth.DefaultAuth, - Broker: &broker.DefaultBroker, - Client: &client.DefaultClient, - Registry: ®istry.DefaultRegistry, - Server: &server.DefaultServer, - Selector: &selector.DefaultSelector, - Transport: &transport.DefaultTransport, - Router: &router.DefaultRouter, - Runtime: &runtime.DefaultRuntime, - Store: &store.DefaultStore, - Tracer: &trace.DefaultTracer, - Profile: &profile.DefaultProfile, - Config: &config.DefaultConfig, - - Brokers: DefaultBrokers, - Clients: DefaultClients, - Registries: DefaultRegistries, - Selectors: DefaultSelectors, - Servers: DefaultServers, - Transports: DefaultTransports, - Routers: DefaultRouters, - Runtimes: DefaultRuntimes, - Stores: DefaultStores, - Tracers: DefaultTracers, - Auths: DefaultAuths, - Profiles: DefaultProfiles, - Configs: DefaultConfigs, +// Command line Name +func Name(n string) Option { + return func(o *Options) { + o.Name = n } - - for _, o := range opts { - o(&options) - } - - if len(options.Description) == 0 { - options.Description = "a go-micro service" - } - - cmd := new(cmd) - cmd.opts = options - cmd.app = cli.NewApp() - cmd.app.Name = cmd.opts.Name - cmd.app.Version = cmd.opts.Version - cmd.app.Usage = cmd.opts.Description - cmd.app.Before = cmd.Before - cmd.app.Flags = DefaultFlags - cmd.app.Action = func(c *cli.Context) error { - return nil - } - - if len(options.Version) == 0 { - cmd.app.HideVersion = true - } - - return cmd } -func (c *cmd) App() *cli.App { - return c.app +// Command line Description +func Description(d string) Option { + return func(o *Options) { + o.Description = d + } } -func (c *cmd) Options() Options { - return c.opts +// Command line Version +func Version(v string) Option { + return func(o *Options) { + o.Version = v + } } -func (c *cmd) Before(ctx *cli.Context) error { - // Setup client options - var clientOpts []client.Option - - if r := ctx.Int("client_retries"); r >= 0 { - clientOpts = append(clientOpts, client.Retries(r)) +// Commands to add +func Commands(c ...*cli.Command) Option { + return func(o *Options) { + o.Commands = c } - - if t := ctx.String("client_request_timeout"); len(t) > 0 { - d, err := time.ParseDuration(t) - if err != nil { - logger.Fatalf("failed to parse client_request_timeout: %v", t) - } - clientOpts = append(clientOpts, client.RequestTimeout(d)) - } - - if r := ctx.Int("client_pool_size"); r > 0 { - clientOpts = append(clientOpts, client.PoolSize(r)) - } - - if t := ctx.String("client_pool_ttl"); len(t) > 0 { - d, err := time.ParseDuration(t) - if err != nil { - logger.Fatalf("failed to parse client_pool_ttl: %v", t) - } - clientOpts = append(clientOpts, client.PoolTTL(d)) - } - - // Setup server options - var serverOpts []server.Option - - metadata := make(map[string]string) - for _, d := range ctx.StringSlice("server_metadata") { - var key, val string - parts := strings.Split(d, "=") - key = parts[0] - if len(parts) > 1 { - val = strings.Join(parts[1:], "=") - } - metadata[key] = val - } - - if len(metadata) > 0 { - serverOpts = append(serverOpts, server.Metadata(metadata)) - } - - if len(ctx.String("server_name")) > 0 { - serverOpts = append(serverOpts, server.Name(ctx.String("server_name"))) - } - - if len(ctx.String("server_version")) > 0 { - serverOpts = append(serverOpts, server.Version(ctx.String("server_version"))) - } - - if len(ctx.String("server_id")) > 0 { - serverOpts = append(serverOpts, server.Id(ctx.String("server_id"))) - } - - if len(ctx.String("server_address")) > 0 { - serverOpts = append(serverOpts, server.Address(ctx.String("server_address"))) - } - - if len(ctx.String("server_advertise")) > 0 { - serverOpts = append(serverOpts, server.Advertise(ctx.String("server_advertise"))) - } - - if ttl := time.Duration(ctx.Int("register_ttl")); ttl >= 0 { - serverOpts = append(serverOpts, server.RegisterTTL(ttl*time.Second)) - } - - if val := time.Duration(ctx.Int("register_interval")); val >= 0 { - serverOpts = append(serverOpts, server.RegisterInterval(val*time.Second)) - } - - // setup a client to use when calling the runtime. It is important the auth client is wrapped - // after the cache client since the wrappers are applied in reverse order and the cache will use - // some of the headers set by the auth client. - authFn := func() auth.Auth { return *c.opts.Auth } - cacheFn := func() *client.Cache { return (*c.opts.Client).Options().Cache } - microClient := wrapper.CacheClient(cacheFn, grpc.NewClient()) - microClient = wrapper.AuthClient(authFn, microClient) - - // Setup auth options - authOpts := []auth.Option{auth.WithClient(microClient)} - if len(ctx.String("auth_address")) > 0 { - authOpts = append(authOpts, auth.Addrs(ctx.String("auth_address"))) - } - if len(ctx.String("auth_id")) > 0 || len(ctx.String("auth_secret")) > 0 { - authOpts = append(authOpts, auth.Credentials( - ctx.String("auth_id"), ctx.String("auth_secret"), - )) - } - if len(ctx.String("auth_public_key")) > 0 { - authOpts = append(authOpts, auth.PublicKey(ctx.String("auth_public_key"))) - } - if len(ctx.String("auth_private_key")) > 0 { - authOpts = append(authOpts, auth.PrivateKey(ctx.String("auth_private_key"))) - } - if ns := ctx.String("service_namespace"); len(ns) > 0 { - serverOpts = append(serverOpts, server.Namespace(ns)) - authOpts = append(authOpts, auth.Issuer(ns)) - } - - // Set the auth - if name := ctx.String("auth"); len(name) > 0 { - a, ok := c.opts.Auths[name] - if !ok { - logger.Fatalf("Unsupported auth: %s", name) - } - *c.opts.Auth = a(authOpts...) - serverOpts = append(serverOpts, server.Auth(*c.opts.Auth)) - } else if len(authOpts) > 0 { - (*c.opts.Auth).Init(authOpts...) - } - - // verify the auth's service account - if err := authutil.Verify(*c.opts.Auth); err != nil { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Auth [%v] Error generating auth account: %v", (*c.opts.Auth), err) - } - } - - // Setup broker options. - brokerOpts := []broker.Option{brokerSrv.Client(microClient)} - - if len(ctx.String("broker_address")) > 0 { - brokerOpts = append(brokerOpts, broker.Addrs(ctx.String("broker_address"))) - } - - // Parse broker TLS certs - if ctx.IsSet("broker_tls_cert") || ctx.IsSet("broker_tls_key") { - cert, err := tls.LoadX509KeyPair(ctx.String("broker_tls_cert"), ctx.String("broker_tls_key")) - if err != nil { - logger.Fatalf("Error loading broker TLS cert: %v", err) - } - - // load custom certificate authority - caCertPool := x509.NewCertPool() - if ctx.IsSet("broker_tls_ca") { - crt, err := ioutil.ReadFile(ctx.String("broker_tls_ca")) - if err != nil { - logger.Fatalf("Error loading broker TLS certificate authority: %v", err) - } - caCertPool.AppendCertsFromPEM(crt) - } - - cfg := &tls.Config{Certificates: []tls.Certificate{cert}, RootCAs: caCertPool} - brokerOpts = append(brokerOpts, broker.TLSConfig(cfg)) - } - - // Setup registry options - registryOpts := []registry.Option{registrySrv.WithClient(microClient)} - - // Parse registry TLS certs - if ctx.IsSet("registry_tls_cert") || ctx.IsSet("registry_tls_key") { - cert, err := tls.LoadX509KeyPair(ctx.String("registry_tls_cert"), ctx.String("registry_tls_key")) - if err != nil { - logger.Fatalf("Error loading registry tls cert: %v", err) - } - - // load custom certificate authority - caCertPool := x509.NewCertPool() - if ctx.IsSet("registry_tls_ca") { - crt, err := ioutil.ReadFile(ctx.String("registry_tls_ca")) - if err != nil { - logger.Fatalf("Error loading registry tls certificate authority: %v", err) - } - caCertPool.AppendCertsFromPEM(crt) - } - - cfg := &tls.Config{Certificates: []tls.Certificate{cert}, RootCAs: caCertPool} - registryOpts = append(registryOpts, registry.TLSConfig(cfg)) - } - - if len(ctx.String("registry_address")) > 0 { - addresses := strings.Split(ctx.String("registry_address"), ",") - registryOpts = append(registryOpts, registry.Addrs(addresses...)) - } - - // Set the registry - if name := ctx.String("registry"); len(name) > 0 && (*c.opts.Registry).String() != name { - r, ok := c.opts.Registries[name] - if !ok { - logger.Fatalf("Registry %s not found", name) - } - - *c.opts.Registry = r(registryOpts...) - serverOpts = append(serverOpts, server.Registry(*c.opts.Registry)) - brokerOpts = append(brokerOpts, broker.Registry(*c.opts.Registry)) - } else if len(registryOpts) > 0 { - if err := (*c.opts.Registry).Init(registryOpts...); err != nil { - logger.Fatalf("Error configuring registry: %v", err) - } - } - - // Set the selector - if name := ctx.String("selector"); len(name) > 0 && (*c.opts.Selector).String() != name { - s, ok := c.opts.Selectors[name] - if !ok { - logger.Fatalf("Selector %s not found", name) - } - - *c.opts.Selector = s() - clientOpts = append(clientOpts, client.Selector(*c.opts.Selector)) - } - - // Set the router, this must happen before the rest of the server as it'll route server requests - // such as go.micro.config if no address is specified - routerOpts := []router.Option{ - srvRouter.Client(microClient), - router.Network(ctx.String("service_namespace")), - router.Registry(*c.opts.Registry), - router.Id((*c.opts.Server).Options().Id), - } - if len(ctx.String("router_address")) > 0 { - routerOpts = append(routerOpts, router.Address(ctx.String("router_address"))) - } - if name := ctx.String("router"); len(name) > 0 && (*c.opts.Router).String() != name { - r, ok := c.opts.Routers[name] - if !ok { - logger.Fatalf("Router %s not found", name) - } - - // close the default router before replacing it - if err := (*c.opts.Router).Close(); err != nil { - logger.Fatalf("Error closing default router: %s", name) - } - - *c.opts.Router = r(routerOpts...) - clientOpts = append(clientOpts, client.Router(*c.opts.Router)) - } else if len(routerOpts) > 0 { - if err := (*c.opts.Router).Init(routerOpts...); err != nil { - logger.Fatalf("Error configuring router: %v", err) - } - } - - // Setup store options - storeOpts := []store.Option{store.WithClient(microClient)} - if len(ctx.String("store_address")) > 0 { - storeOpts = append(storeOpts, store.Nodes(strings.Split(ctx.String("store_address"), ",")...)) - } - if len(ctx.String("store_database")) > 0 { - storeOpts = append(storeOpts, store.Database(ctx.String("store_database"))) - } else if len(ctx.String("service_namespace")) > 0 { - storeOpts = append(storeOpts, store.Database(ctx.String("service_namespace"))) - } - if len(ctx.String("store_table")) > 0 { - storeOpts = append(storeOpts, store.Table(ctx.String("store_table"))) - } - - // Set the store - if name := ctx.String("store"); len(name) > 0 { - s, ok := c.opts.Stores[name] - if !ok { - logger.Fatalf("Unsupported store: %s", name) - } - - *c.opts.Store = s(storeOpts...) - } else if len(storeOpts) > 0 { - if err := (*c.opts.Store).Init(storeOpts...); err != nil { - logger.Fatalf("Error configuring store: %v", err) - } - } - - // Setup the runtime options - runtimeOpts := []runtime.Option{runtime.WithClient(microClient)} - if len(ctx.String("runtime_source")) > 0 { - runtimeOpts = append(runtimeOpts, runtime.WithSource(ctx.String("runtime_source"))) - } - - // Set the runtime - if name := ctx.String("runtime"); len(name) > 0 { - r, ok := c.opts.Runtimes[name] - if !ok { - logger.Fatalf("Unsupported runtime: %s", name) - } - - *c.opts.Runtime = r(runtimeOpts...) - } else if len(runtimeOpts) > 0 { - if err := (*c.opts.Runtime).Init(runtimeOpts...); err != nil { - logger.Fatalf("Error configuring runtime: %v", err) - } - } - - // Set the tracer - if name := ctx.String("tracer"); len(name) > 0 { - r, ok := c.opts.Tracers[name] - if !ok { - logger.Fatalf("Unsupported tracer: %s", name) - } - - *c.opts.Tracer = r() - } - - // Set the profile - if name := ctx.String("profile"); len(name) > 0 { - p, ok := c.opts.Profiles[name] - if !ok { - logger.Fatalf("Unsupported profile: %s", name) - } - - *c.opts.Profile = p() - } - - // Set the broker - if name := ctx.String("broker"); len(name) > 0 && (*c.opts.Broker).String() != name { - b, ok := c.opts.Brokers[name] - if !ok { - logger.Fatalf("Broker %s not found", name) - } - - *c.opts.Broker = b(brokerOpts...) - serverOpts = append(serverOpts, server.Broker(*c.opts.Broker)) - clientOpts = append(clientOpts, client.Broker(*c.opts.Broker)) - } else if len(brokerOpts) > 0 { - if err := (*c.opts.Broker).Init(brokerOpts...); err != nil { - logger.Fatalf("Error configuring broker: %v", err) - } - } - - // Setup the transport options - var transportOpts []transport.Option - if len(ctx.String("transport_address")) > 0 { - addresses := strings.Split(ctx.String("transport_address"), ",") - transportOpts = append(transportOpts, transport.Addrs(addresses...)) - } - - // Set the transport - if name := ctx.String("transport"); len(name) > 0 && (*c.opts.Transport).String() != name { - t, ok := c.opts.Transports[name] - if !ok { - logger.Fatalf("Transport %s not found", name) - } - - *c.opts.Transport = t(transportOpts...) - serverOpts = append(serverOpts, server.Transport(*c.opts.Transport)) - clientOpts = append(clientOpts, client.Transport(*c.opts.Transport)) - } else if len(transportOpts) > 0 { - if err := (*c.opts.Transport).Init(transportOpts...); err != nil { - logger.Fatalf("Error configuring transport: %v", err) - } - } - - // Setup config sources - if ctx.String("config") == "service" { - opt := config.WithSource(configSrv.NewSource( - configSrc.WithClient(microClient), - configSrv.Namespace(ctx.String("service_namespace")), - )) - - if err := (*c.opts.Config).Init(opt); err != nil { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Error configuring config: %v", err) - } - } - } - - // Set the client - if name := ctx.String("client"); len(name) > 0 && (*c.opts.Client).String() != name { - cl, ok := c.opts.Clients[name] - if !ok { - logger.Fatalf("Client %s not found", name) - } - - *c.opts.Client = cl(clientOpts...) - } else if len(clientOpts) > 0 { - if err := (*c.opts.Client).Init(clientOpts...); err != nil { - logger.Fatalf("Error configuring client: %v", err) - } - } - - // Set the server - if name := ctx.String("server"); len(name) > 0 && (*c.opts.Server).String() != name { - s, ok := c.opts.Servers[name] - if !ok { - logger.Fatalf("Server %s not found", name) - } - - *c.opts.Server = s(serverOpts...) - } else if len(serverOpts) > 0 { - if err := (*c.opts.Server).Init(serverOpts...); err != nil { - logger.Fatalf("Error configuring server: %v", err) - } - } - - return nil } -func (c *cmd) Init(opts ...Option) error { - for _, o := range opts { - o(&c.opts) +// Flags to add +func Flags(f ...cli.Flag) Option { + return func(o *Options) { + o.Flags = f } - if len(c.opts.Name) > 0 { - c.app.Name = c.opts.Name +} + +// Action to execute +func Action(a func(*cli.Context) error) Option { + return func(o *Options) { + o.Action = a } - if len(c.opts.Version) > 0 { - c.app.Version = c.opts.Version - } - c.app.HideVersion = len(c.opts.Version) == 0 - c.app.Usage = c.opts.Description - return nil -} - -func (c *cmd) Run() error { - return c.app.Run(os.Args) -} - -func (c *cmd) String() string { - return "micro/cli" -} - -func App() *cli.App { - return DefaultCmd.App() -} - -func Init(opts ...Option) error { - return DefaultCmd.Init(opts...) -} - -func NewCmd(opts ...Option) Cmd { - return newCmd(opts...) -} - -// Run the default command -func Run() error { - return DefaultCmd.Run() } diff --git a/cmd/options.go b/cmd/options.go deleted file mode 100644 index 127a93e7..00000000 --- a/cmd/options.go +++ /dev/null @@ -1,228 +0,0 @@ -package cmd - -import ( - "context" - - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/config" - "github.com/micro/go-micro/v2/debug/profile" - "github.com/micro/go-micro/v2/debug/trace" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/runtime" - "github.com/micro/go-micro/v2/selector" - "github.com/micro/go-micro/v2/server" - "github.com/micro/go-micro/v2/store" - "github.com/micro/go-micro/v2/transport" -) - -type Options struct { - // For the Command Line itself - Name string - Description string - Version string - - // We need pointers to things so we can swap them out if needed. - Broker *broker.Broker - Registry *registry.Registry - Selector *selector.Selector - Transport *transport.Transport - Config *config.Config - Client *client.Client - Server *server.Server - Router *router.Router - Runtime *runtime.Runtime - Store *store.Store - Tracer *trace.Tracer - Auth *auth.Auth - Profile *profile.Profile - - Brokers map[string]func(...broker.Option) broker.Broker - Configs map[string]func(...config.Option) (config.Config, error) - Clients map[string]func(...client.Option) client.Client - Registries map[string]func(...registry.Option) registry.Registry - Selectors map[string]func(...selector.Option) selector.Selector - Servers map[string]func(...server.Option) server.Server - Transports map[string]func(...transport.Option) transport.Transport - Routers map[string]func(...router.Option) router.Router - Runtimes map[string]func(...runtime.Option) runtime.Runtime - Stores map[string]func(...store.Option) store.Store - Tracers map[string]func(...trace.Option) trace.Tracer - Auths map[string]func(...auth.Option) auth.Auth - Profiles map[string]func(...profile.Option) profile.Profile - - // Other options for implementations of the interface - // can be stored in a context - Context context.Context -} - -// Command line Name -func Name(n string) Option { - return func(o *Options) { - o.Name = n - } -} - -// Command line Description -func Description(d string) Option { - return func(o *Options) { - o.Description = d - } -} - -// Command line Version -func Version(v string) Option { - return func(o *Options) { - o.Version = v - } -} - -func Broker(b *broker.Broker) Option { - return func(o *Options) { - o.Broker = b - } -} - -func Config(c *config.Config) Option { - return func(o *Options) { - o.Config = c - } -} - -func Selector(s *selector.Selector) Option { - return func(o *Options) { - o.Selector = s - } -} - -func Registry(r *registry.Registry) Option { - return func(o *Options) { - o.Registry = r - } -} - -func Router(r *router.Router) Option { - return func(o *Options) { - o.Router = r - } -} - -func Runtime(r *runtime.Runtime) Option { - return func(o *Options) { - o.Runtime = r - } -} - -func Transport(t *transport.Transport) Option { - return func(o *Options) { - o.Transport = t - } -} - -func Client(c *client.Client) Option { - return func(o *Options) { - o.Client = c - } -} - -func Server(s *server.Server) Option { - return func(o *Options) { - o.Server = s - } -} - -func Store(s *store.Store) Option { - return func(o *Options) { - o.Store = s - } -} - -func Tracer(t *trace.Tracer) Option { - return func(o *Options) { - o.Tracer = t - } -} - -func Auth(a *auth.Auth) Option { - return func(o *Options) { - o.Auth = a - } -} - -func Profile(p *profile.Profile) Option { - return func(o *Options) { - o.Profile = p - } -} - -// New broker func -func NewBroker(name string, b func(...broker.Option) broker.Broker) Option { - return func(o *Options) { - o.Brokers[name] = b - } -} - -// New client func -func NewClient(name string, b func(...client.Option) client.Client) Option { - return func(o *Options) { - o.Clients[name] = b - } -} - -// New registry func -func NewRegistry(name string, r func(...registry.Option) registry.Registry) Option { - return func(o *Options) { - o.Registries[name] = r - } -} - -// New selector func -func NewSelector(name string, s func(...selector.Option) selector.Selector) Option { - return func(o *Options) { - o.Selectors[name] = s - } -} - -// New server func -func NewServer(name string, s func(...server.Option) server.Server) Option { - return func(o *Options) { - o.Servers[name] = s - } -} - -// New transport func -func NewTransport(name string, t func(...transport.Option) transport.Transport) Option { - return func(o *Options) { - o.Transports[name] = t - } -} - -// New router func -func NewRouter(name string, r func(...router.Option) router.Router) Option { - return func(o *Options) { - o.Routers[name] = r - } -} - -// New runtime func -func NewRuntime(name string, r func(...runtime.Option) runtime.Runtime) Option { - return func(o *Options) { - o.Runtimes[name] = r - } -} - -// New tracer func -func NewTracer(name string, t func(...trace.Option) trace.Tracer) Option { - return func(o *Options) { - o.Tracers[name] = t - } -} - -// New auth func -func NewAuth(name string, t func(...auth.Option) auth.Auth) Option { - return func(o *Options) { - o.Auths[name] = t - } -} diff --git a/codec/bytes/bytes.go b/codec/bytes/bytes.go index 23a6c6fc..73fc4a97 100644 --- a/codec/bytes/bytes.go +++ b/codec/bytes/bytes.go @@ -6,7 +6,7 @@ import ( "io" "io/ioutil" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type Codec struct { diff --git a/codec/bytes/marshaler.go b/codec/bytes/marshaler.go index d15e8d75..76cdd954 100644 --- a/codec/bytes/marshaler.go +++ b/codec/bytes/marshaler.go @@ -1,7 +1,7 @@ package bytes import ( - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type Marshaler struct{} diff --git a/codec/grpc/grpc.go b/codec/grpc/grpc.go index 90bf4eb6..6f8db3a0 100644 --- a/codec/grpc/grpc.go +++ b/codec/grpc/grpc.go @@ -9,7 +9,7 @@ import ( "strings" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type Codec struct { diff --git a/codec/json/json.go b/codec/json/json.go index 7db36a50..49103e1c 100644 --- a/codec/json/json.go +++ b/codec/json/json.go @@ -7,7 +7,7 @@ import ( "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type Codec struct { diff --git a/codec/jsonrpc/client.go b/codec/jsonrpc/client.go index f1e320a0..6e43cde5 100644 --- a/codec/jsonrpc/client.go +++ b/codec/jsonrpc/client.go @@ -6,7 +6,7 @@ import ( "io" "sync" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type clientCodec struct { diff --git a/codec/jsonrpc/jsonrpc.go b/codec/jsonrpc/jsonrpc.go index fcf2ac65..7c378daf 100644 --- a/codec/jsonrpc/jsonrpc.go +++ b/codec/jsonrpc/jsonrpc.go @@ -7,7 +7,7 @@ import ( "fmt" "io" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type jsonCodec struct { diff --git a/codec/jsonrpc/server.go b/codec/jsonrpc/server.go index 48b71e64..cdbd3fa1 100644 --- a/codec/jsonrpc/server.go +++ b/codec/jsonrpc/server.go @@ -5,7 +5,7 @@ import ( "fmt" "io" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type serverCodec struct { diff --git a/codec/proto/marshaler.go b/codec/proto/marshaler.go index 82acc4b2..23184fdb 100644 --- a/codec/proto/marshaler.go +++ b/codec/proto/marshaler.go @@ -4,7 +4,7 @@ import ( "bytes" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" "github.com/oxtoacart/bpool" ) diff --git a/codec/proto/proto.go b/codec/proto/proto.go index 87073619..f13786ae 100644 --- a/codec/proto/proto.go +++ b/codec/proto/proto.go @@ -6,7 +6,7 @@ import ( "io/ioutil" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type Codec struct { diff --git a/codec/protorpc/protorpc.go b/codec/protorpc/protorpc.go index ce945693..3460a835 100644 --- a/codec/protorpc/protorpc.go +++ b/codec/protorpc/protorpc.go @@ -9,7 +9,7 @@ import ( "sync" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type flusher interface { diff --git a/codec/text/text.go b/codec/text/text.go index 86be2068..3df7c338 100644 --- a/codec/text/text.go +++ b/codec/text/text.go @@ -6,7 +6,7 @@ import ( "io" "io/ioutil" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type Codec struct { diff --git a/config/config.go b/config/config.go index cd30f8b2..77a9fdc1 100644 --- a/config/config.go +++ b/config/config.go @@ -4,10 +4,10 @@ package config import ( "context" - "github.com/micro/go-micro/v2/config/loader" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/source" - "github.com/micro/go-micro/v2/config/source/file" + "github.com/micro/go-micro/v3/config/loader" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/source" + "github.com/micro/go-micro/v3/config/source/file" ) // Config is an interface abstraction for dynamic configuration diff --git a/config/default.go b/config/default.go index ae80e1f9..bd946f03 100644 --- a/config/default.go +++ b/config/default.go @@ -5,11 +5,11 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/config/loader" - "github.com/micro/go-micro/v2/config/loader/memory" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/reader/json" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/loader" + "github.com/micro/go-micro/v3/config/loader/memory" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/reader/json" + "github.com/micro/go-micro/v3/config/source" ) type config struct { diff --git a/config/default_test.go b/config/default_test.go index 0250a546..46350963 100644 --- a/config/default_test.go +++ b/config/default_test.go @@ -9,10 +9,10 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/config/source" - "github.com/micro/go-micro/v2/config/source/env" - "github.com/micro/go-micro/v2/config/source/file" - "github.com/micro/go-micro/v2/config/source/memory" + "github.com/micro/go-micro/v3/config/source" + "github.com/micro/go-micro/v3/config/source/env" + "github.com/micro/go-micro/v3/config/source/file" + "github.com/micro/go-micro/v3/config/source/memory" ) func createFileForIssue18(t *testing.T, content string) *os.File { diff --git a/config/encoder/hcl/hcl.go b/config/encoder/hcl/hcl.go index efde9d92..72fad9df 100644 --- a/config/encoder/hcl/hcl.go +++ b/config/encoder/hcl/hcl.go @@ -4,7 +4,7 @@ import ( "encoding/json" "github.com/hashicorp/hcl" - "github.com/micro/go-micro/v2/config/encoder" + "github.com/micro/go-micro/v3/config/encoder" ) type hclEncoder struct{} diff --git a/config/encoder/json/json.go b/config/encoder/json/json.go index 67714dfe..13f179f9 100644 --- a/config/encoder/json/json.go +++ b/config/encoder/json/json.go @@ -3,7 +3,7 @@ package json import ( "encoding/json" - "github.com/micro/go-micro/v2/config/encoder" + "github.com/micro/go-micro/v3/config/encoder" ) type jsonEncoder struct{} diff --git a/config/encoder/toml/toml.go b/config/encoder/toml/toml.go index baca12e4..91109073 100644 --- a/config/encoder/toml/toml.go +++ b/config/encoder/toml/toml.go @@ -4,7 +4,7 @@ import ( "bytes" "github.com/BurntSushi/toml" - "github.com/micro/go-micro/v2/config/encoder" + "github.com/micro/go-micro/v3/config/encoder" ) type tomlEncoder struct{} diff --git a/config/encoder/xml/xml.go b/config/encoder/xml/xml.go index 7b9c55f4..8e32a14e 100644 --- a/config/encoder/xml/xml.go +++ b/config/encoder/xml/xml.go @@ -3,7 +3,7 @@ package xml import ( "encoding/xml" - "github.com/micro/go-micro/v2/config/encoder" + "github.com/micro/go-micro/v3/config/encoder" ) type xmlEncoder struct{} diff --git a/config/encoder/yaml/yaml.go b/config/encoder/yaml/yaml.go index b671fcab..b3da7ba5 100644 --- a/config/encoder/yaml/yaml.go +++ b/config/encoder/yaml/yaml.go @@ -2,7 +2,7 @@ package yaml import ( "github.com/ghodss/yaml" - "github.com/micro/go-micro/v2/config/encoder" + "github.com/micro/go-micro/v3/config/encoder" ) type yamlEncoder struct{} diff --git a/config/loader/loader.go b/config/loader/loader.go index 1dcb1450..1e2dc13a 100644 --- a/config/loader/loader.go +++ b/config/loader/loader.go @@ -4,8 +4,8 @@ package loader import ( "context" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/source" ) // Loader manages loading sources diff --git a/config/loader/memory/memory.go b/config/loader/memory/memory.go index 5af7d5c4..0081f193 100644 --- a/config/loader/memory/memory.go +++ b/config/loader/memory/memory.go @@ -9,10 +9,10 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/config/loader" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/reader/json" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/loader" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/reader/json" + "github.com/micro/go-micro/v3/config/source" ) type memory struct { diff --git a/config/loader/memory/options.go b/config/loader/memory/options.go index cbf9d497..34a8441c 100644 --- a/config/loader/memory/options.go +++ b/config/loader/memory/options.go @@ -1,9 +1,9 @@ package memory import ( - "github.com/micro/go-micro/v2/config/loader" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/loader" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/source" ) // WithSource appends a source to list of sources diff --git a/config/options.go b/config/options.go index 34e176a4..d29f8f86 100644 --- a/config/options.go +++ b/config/options.go @@ -1,9 +1,9 @@ package config import ( - "github.com/micro/go-micro/v2/config/loader" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/loader" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/source" ) // WithLoader sets the loader for manager config diff --git a/config/reader/json/json.go b/config/reader/json/json.go index db96cb39..f356fe94 100644 --- a/config/reader/json/json.go +++ b/config/reader/json/json.go @@ -5,10 +5,10 @@ import ( "time" "github.com/imdario/mergo" - "github.com/micro/go-micro/v2/config/encoder" - "github.com/micro/go-micro/v2/config/encoder/json" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/encoder" + "github.com/micro/go-micro/v3/config/encoder/json" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/source" ) type jsonReader struct { diff --git a/config/reader/json/json_test.go b/config/reader/json/json_test.go index 75d1bf7e..6c0818ba 100644 --- a/config/reader/json/json_test.go +++ b/config/reader/json/json_test.go @@ -3,8 +3,8 @@ package json import ( "testing" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/source" ) func TestReader(t *testing.T) { diff --git a/config/reader/json/values.go b/config/reader/json/values.go index 3ff9118a..7f0fe13c 100644 --- a/config/reader/json/values.go +++ b/config/reader/json/values.go @@ -8,8 +8,8 @@ import ( "time" simple "github.com/bitly/go-simplejson" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/source" ) type jsonValues struct { diff --git a/config/reader/json/values_test.go b/config/reader/json/values_test.go index 7d3ccaeb..2f86b003 100644 --- a/config/reader/json/values_test.go +++ b/config/reader/json/values_test.go @@ -4,8 +4,8 @@ import ( "reflect" "testing" - "github.com/micro/go-micro/v2/config/reader" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/reader" + "github.com/micro/go-micro/v3/config/source" ) func TestValues(t *testing.T) { diff --git a/config/reader/options.go b/config/reader/options.go index 716dfcac..51fecd05 100644 --- a/config/reader/options.go +++ b/config/reader/options.go @@ -1,12 +1,12 @@ package reader import ( - "github.com/micro/go-micro/v2/config/encoder" - "github.com/micro/go-micro/v2/config/encoder/hcl" - "github.com/micro/go-micro/v2/config/encoder/json" - "github.com/micro/go-micro/v2/config/encoder/toml" - "github.com/micro/go-micro/v2/config/encoder/xml" - "github.com/micro/go-micro/v2/config/encoder/yaml" + "github.com/micro/go-micro/v3/config/encoder" + "github.com/micro/go-micro/v3/config/encoder/hcl" + "github.com/micro/go-micro/v3/config/encoder/json" + "github.com/micro/go-micro/v3/config/encoder/toml" + "github.com/micro/go-micro/v3/config/encoder/xml" + "github.com/micro/go-micro/v3/config/encoder/yaml" ) type Options struct { diff --git a/config/reader/reader.go b/config/reader/reader.go index e10ff6df..abc3ad94 100644 --- a/config/reader/reader.go +++ b/config/reader/reader.go @@ -4,7 +4,7 @@ package reader import ( "time" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) // Reader is an interface for merging changesets diff --git a/config/source/cli/README.md b/config/source/cli/README.md deleted file mode 100644 index 0b482d58..00000000 --- a/config/source/cli/README.md +++ /dev/null @@ -1,71 +0,0 @@ -# cli Source - -The cli source reads config from parsed flags via a cli.Context. - -## Format - -We expect the use of the `micro/cli` package. Upper case flags will be lower cased. Dashes will be used as delimiters for nesting. - -### Example - -```go -micro.Flags( - cli.StringFlag{ - Name: "database-address", - Value: "127.0.0.1", - Usage: "the db address", - }, - cli.IntFlag{ - Name: "database-port", - Value: 3306, - Usage: "the db port", - }, -) -``` - -Becomes - -```json -{ - "database": { - "address": "127.0.0.1", - "port": 3306 - } -} -``` - -## New and Load Source - -Because a cli.Context is needed to retrieve the flags and their values, it is recommended to build your source from within a cli.Action. - -```go - -func main() { - // New Service - service := micro.NewService( - micro.Name("example"), - micro.Flags( - cli.StringFlag{ - Name: "database-address", - Value: "127.0.0.1", - Usage: "the db address", - }, - ), - ) - - var clisrc source.Source - - service.Init( - micro.Action(func(c *cli.Context) { - clisrc = cli.NewSource( - cli.Context(c), - ) - // Alternatively, just setup your config right here - }), - ) - - // ... Load and use that source ... - conf := config.NewConfig() - conf.Load(clisrc) -} -``` diff --git a/config/source/cli/cli.go b/config/source/cli/cli.go deleted file mode 100644 index 6c065cb5..00000000 --- a/config/source/cli/cli.go +++ /dev/null @@ -1,145 +0,0 @@ -package cli - -import ( - "flag" - "io/ioutil" - "os" - "strings" - "time" - - "github.com/imdario/mergo" - "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2/cmd" - "github.com/micro/go-micro/v2/config/source" -) - -type cliSource struct { - opts source.Options - ctx *cli.Context -} - -func (c *cliSource) Read() (*source.ChangeSet, error) { - var changes map[string]interface{} - - // directly using app cli flags, to access default values of not specified options - for _, f := range c.ctx.App.Flags { - name := f.Names()[0] - tmp := toEntry(name, c.ctx.Generic(name)) - mergo.Map(&changes, tmp) // need to sort error handling - } - - b, err := c.opts.Encoder.Encode(changes) - if err != nil { - return nil, err - } - - cs := &source.ChangeSet{ - Format: c.opts.Encoder.String(), - Data: b, - Timestamp: time.Now(), - Source: c.String(), - } - cs.Checksum = cs.Sum() - - return cs, nil -} - -func toEntry(name string, v interface{}) map[string]interface{} { - n := strings.ToLower(name) - keys := strings.FieldsFunc(n, split) - reverse(keys) - tmp := make(map[string]interface{}) - for i, k := range keys { - if i == 0 { - tmp[k] = v - continue - } - - tmp = map[string]interface{}{k: tmp} - } - return tmp -} - -func reverse(ss []string) { - for i := len(ss)/2 - 1; i >= 0; i-- { - opp := len(ss) - 1 - i - ss[i], ss[opp] = ss[opp], ss[i] - } -} - -func split(r rune) bool { - return r == '-' || r == '_' -} - -func (c *cliSource) Watch() (source.Watcher, error) { - return source.NewNoopWatcher() -} - -// Write is unsupported -func (c *cliSource) Write(cs *source.ChangeSet) error { - return nil -} - -func (c *cliSource) String() string { - return "cli" -} - -// NewSource returns a config source for integrating parsed flags from a micro/cli.Context. -// Hyphens are delimiters for nesting, and all keys are lowercased. The assumption is that -// command line flags have already been parsed. -// -// Example: -// cli.StringFlag{Name: "db-host"}, -// -// -// { -// "database": { -// "host": "localhost" -// } -// } -func NewSource(opts ...source.Option) source.Source { - options := source.NewOptions(opts...) - - var ctx *cli.Context - - if c, ok := options.Context.Value(contextKey{}).(*cli.Context); ok { - ctx = c - } else { - // no context - // get the default app/flags - app := cmd.App() - flags := app.Flags - - // create flagset - set := flag.NewFlagSet(app.Name, flag.ContinueOnError) - - // apply flags to set - for _, f := range flags { - f.Apply(set) - } - - // parse flags - set.SetOutput(ioutil.Discard) - set.Parse(os.Args[1:]) - - // normalise flags - normalizeFlags(app.Flags, set) - - // create context - ctx = cli.NewContext(app, set, nil) - } - - return &cliSource{ - ctx: ctx, - opts: options, - } -} - -// WithContext returns a new source with the context specified. -// The assumption is that Context is retrieved within an app.Action function. -func WithContext(ctx *cli.Context, opts ...source.Option) source.Source { - return &cliSource{ - ctx: ctx, - opts: source.NewOptions(opts...), - } -} diff --git a/config/source/cli/cli_test.go b/config/source/cli/cli_test.go deleted file mode 100644 index 154faeab..00000000 --- a/config/source/cli/cli_test.go +++ /dev/null @@ -1,115 +0,0 @@ -package cli - -import ( - "encoding/json" - "os" - "testing" - - "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2" - "github.com/micro/go-micro/v2/cmd" - "github.com/micro/go-micro/v2/config" - "github.com/micro/go-micro/v2/config/source" -) - -func TestCliSourceDefault(t *testing.T) { - const expVal string = "flagvalue" - - service := micro.NewService( - micro.Flags( - // to be able to run inside go test - &cli.StringFlag{ - Name: "test.timeout", - }, - &cli.BoolFlag{ - Name: "test.v", - }, - &cli.StringFlag{ - Name: "test.run", - }, - &cli.StringFlag{ - Name: "test.testlogfile", - }, - &cli.StringFlag{ - Name: "flag", - Usage: "It changes something", - EnvVars: []string{"flag"}, - Value: expVal, - }, - ), - ) - var cliSrc source.Source - service.Init( - // Loads CLI configuration - micro.Action(func(c *cli.Context) error { - cliSrc = NewSource( - Context(c), - ) - return nil - }), - ) - - config.Load(cliSrc) - if fval := config.Get("flag").String("default"); fval != expVal { - t.Fatalf("default flag value not loaded %v != %v", fval, expVal) - } -} - -func test(t *testing.T, withContext bool) { - var src source.Source - - // setup app - app := cmd.App() - app.Name = "testapp" - app.Flags = []cli.Flag{ - &cli.StringFlag{ - Name: "db-host", - EnvVars: []string{"db-host"}, - Value: "myval", - }, - } - - // with context - if withContext { - // set action - app.Action = func(c *cli.Context) error { - src = WithContext(c) - return nil - } - - // run app - app.Run([]string{"run", "-db-host", "localhost"}) - // no context - } else { - // set args - os.Args = []string{"run", "-db-host", "localhost"} - src = NewSource() - } - - // test config - c, err := src.Read() - if err != nil { - t.Error(err) - } - - var actual map[string]interface{} - if err := json.Unmarshal(c.Data, &actual); err != nil { - t.Error(err) - } - - actualDB := actual["db"].(map[string]interface{}) - if actualDB["host"] != "localhost" { - t.Errorf("expected localhost, got %v", actualDB["name"]) - } - -} - -func TestCliSource(t *testing.T) { - // without context - test(t, false) -} - -func TestCliSourceWithContext(t *testing.T) { - // with context - test(t, true) -} diff --git a/config/source/cli/options.go b/config/source/cli/options.go deleted file mode 100644 index 28d28720..00000000 --- a/config/source/cli/options.go +++ /dev/null @@ -1,20 +0,0 @@ -package cli - -import ( - "context" - - "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2/config/source" -) - -type contextKey struct{} - -// Context sets the cli context -func Context(c *cli.Context) source.Option { - return func(o *source.Options) { - if o.Context == nil { - o.Context = context.Background() - } - o.Context = context.WithValue(o.Context, contextKey{}, c) - } -} diff --git a/config/source/cli/util.go b/config/source/cli/util.go deleted file mode 100644 index 1eb9a8b0..00000000 --- a/config/source/cli/util.go +++ /dev/null @@ -1,50 +0,0 @@ -package cli - -import ( - "errors" - "flag" - "strings" - - "github.com/micro/cli/v2" -) - -func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) { - switch ff.Value.(type) { - case *cli.StringSlice: - default: - set.Set(name, ff.Value.String()) - } -} - -func normalizeFlags(flags []cli.Flag, set *flag.FlagSet) error { - visited := make(map[string]bool) - set.Visit(func(f *flag.Flag) { - visited[f.Name] = true - }) - for _, f := range flags { - parts := f.Names() - if len(parts) == 1 { - continue - } - var ff *flag.Flag - for _, name := range parts { - name = strings.Trim(name, " ") - if visited[name] { - if ff != nil { - return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name) - } - ff = set.Lookup(name) - } - } - if ff == nil { - continue - } - for _, name := range parts { - name = strings.Trim(name, " ") - if !visited[name] { - copyFlag(name, ff, set) - } - } - } - return nil -} diff --git a/config/source/env/env.go b/config/source/env/env.go index 25f5b827..1d0ed295 100644 --- a/config/source/env/env.go +++ b/config/source/env/env.go @@ -7,7 +7,7 @@ import ( "time" "github.com/imdario/mergo" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) var ( diff --git a/config/source/env/env_test.go b/config/source/env/env_test.go index 7b0f99d4..50b1bce7 100644 --- a/config/source/env/env_test.go +++ b/config/source/env/env_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) func TestEnv_Read(t *testing.T) { diff --git a/config/source/env/options.go b/config/source/env/options.go index 27f99241..dd362610 100644 --- a/config/source/env/options.go +++ b/config/source/env/options.go @@ -5,7 +5,7 @@ import ( "strings" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type strippedPrefixKey struct{} diff --git a/config/source/env/watcher.go b/config/source/env/watcher.go index bf7fb481..f698bb8f 100644 --- a/config/source/env/watcher.go +++ b/config/source/env/watcher.go @@ -1,7 +1,7 @@ package env import ( - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type watcher struct { diff --git a/config/source/etcd/etcd.go b/config/source/etcd/etcd.go index db9c50f0..08ae4e0c 100644 --- a/config/source/etcd/etcd.go +++ b/config/source/etcd/etcd.go @@ -8,7 +8,7 @@ import ( cetcd "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/mvcc/mvccpb" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) // Currently a single etcd reader diff --git a/config/source/etcd/options.go b/config/source/etcd/options.go index 79e0ab61..3d2c1e69 100644 --- a/config/source/etcd/options.go +++ b/config/source/etcd/options.go @@ -4,7 +4,7 @@ import ( "context" "time" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type addressKey struct{} diff --git a/config/source/etcd/util.go b/config/source/etcd/util.go index 6186befa..e495b64c 100644 --- a/config/source/etcd/util.go +++ b/config/source/etcd/util.go @@ -5,7 +5,7 @@ import ( "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/mvcc/mvccpb" - "github.com/micro/go-micro/v2/config/encoder" + "github.com/micro/go-micro/v3/config/encoder" ) func makeEvMap(e encoder.Encoder, data map[string]interface{}, kv []*clientv3.Event, stripPrefix string) map[string]interface{} { diff --git a/config/source/etcd/watcher.go b/config/source/etcd/watcher.go index d43f2987..0d4fbf8b 100644 --- a/config/source/etcd/watcher.go +++ b/config/source/etcd/watcher.go @@ -7,7 +7,7 @@ import ( "time" cetcd "github.com/coreos/etcd/clientv3" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type watcher struct { diff --git a/config/source/file/file.go b/config/source/file/file.go index f04d67c6..17067447 100644 --- a/config/source/file/file.go +++ b/config/source/file/file.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "os" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type file struct { diff --git a/config/source/file/file_test.go b/config/source/file/file_test.go index e388a88a..fb725496 100644 --- a/config/source/file/file_test.go +++ b/config/source/file/file_test.go @@ -7,8 +7,8 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/config" - "github.com/micro/go-micro/v2/config/source/file" + "github.com/micro/go-micro/v3/config" + "github.com/micro/go-micro/v3/config/source/file" ) func TestConfig(t *testing.T) { diff --git a/config/source/file/format.go b/config/source/file/format.go index 09f10071..4bd9dd22 100644 --- a/config/source/file/format.go +++ b/config/source/file/format.go @@ -3,7 +3,7 @@ package file import ( "strings" - "github.com/micro/go-micro/v2/config/encoder" + "github.com/micro/go-micro/v3/config/encoder" ) func format(p string, e encoder.Encoder) string { diff --git a/config/source/file/format_test.go b/config/source/file/format_test.go index 8383f84a..dca78cee 100644 --- a/config/source/file/format_test.go +++ b/config/source/file/format_test.go @@ -3,7 +3,7 @@ package file import ( "testing" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) func TestFormat(t *testing.T) { diff --git a/config/source/file/options.go b/config/source/file/options.go index e2f67bb4..f9721cb4 100644 --- a/config/source/file/options.go +++ b/config/source/file/options.go @@ -3,7 +3,7 @@ package file import ( "context" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type filePathKey struct{} diff --git a/config/source/file/watcher.go b/config/source/file/watcher.go index f26cc6e4..39c20a71 100644 --- a/config/source/file/watcher.go +++ b/config/source/file/watcher.go @@ -6,7 +6,7 @@ import ( "os" "github.com/fsnotify/fsnotify" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type watcher struct { diff --git a/config/source/file/watcher_linux.go b/config/source/file/watcher_linux.go index 13efbde5..b8957bf9 100644 --- a/config/source/file/watcher_linux.go +++ b/config/source/file/watcher_linux.go @@ -6,7 +6,7 @@ import ( "os" "github.com/fsnotify/fsnotify" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type watcher struct { diff --git a/config/source/flag/flag.go b/config/source/flag/flag.go index 3cd3dcf6..1eef5fc7 100644 --- a/config/source/flag/flag.go +++ b/config/source/flag/flag.go @@ -4,7 +4,7 @@ import ( "errors" "flag" "github.com/imdario/mergo" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" "strings" "time" ) diff --git a/config/source/flag/options.go b/config/source/flag/options.go index 85ccfd83..b770d2dd 100644 --- a/config/source/flag/options.go +++ b/config/source/flag/options.go @@ -3,7 +3,7 @@ package flag import ( "context" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type includeUnsetKey struct{} diff --git a/config/source/memory/memory.go b/config/source/memory/memory.go index 0bb78d23..a48d0e29 100644 --- a/config/source/memory/memory.go +++ b/config/source/memory/memory.go @@ -6,7 +6,7 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type memory struct { diff --git a/config/source/memory/options.go b/config/source/memory/options.go index d7ec6309..46f98e05 100644 --- a/config/source/memory/options.go +++ b/config/source/memory/options.go @@ -3,7 +3,7 @@ package memory import ( "context" - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type changeSetKey struct{} diff --git a/config/source/memory/watcher.go b/config/source/memory/watcher.go index c04714b1..c44ff110 100644 --- a/config/source/memory/watcher.go +++ b/config/source/memory/watcher.go @@ -1,7 +1,7 @@ package memory import ( - "github.com/micro/go-micro/v2/config/source" + "github.com/micro/go-micro/v3/config/source" ) type watcher struct { diff --git a/config/source/options.go b/config/source/options.go index cd694a77..34090b03 100644 --- a/config/source/options.go +++ b/config/source/options.go @@ -3,9 +3,9 @@ package source import ( "context" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/config/encoder" - "github.com/micro/go-micro/v2/config/encoder/json" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/config/encoder" + "github.com/micro/go-micro/v3/config/encoder/json" ) type Options struct { @@ -25,7 +25,6 @@ func NewOptions(opts ...Option) Options { options := Options{ Encoder: json.NewEncoder(), Context: context.Background(), - Client: client.DefaultClient, } for _, o := range opts { diff --git a/config/source/service/options.go b/config/source/service/options.go deleted file mode 100644 index 27565a79..00000000 --- a/config/source/service/options.go +++ /dev/null @@ -1,38 +0,0 @@ -package service - -import ( - "context" - - "github.com/micro/go-micro/v2/config/source" -) - -type serviceNameKey struct{} -type namespaceKey struct{} -type pathKey struct{} - -func ServiceName(name string) source.Option { - return func(o *source.Options) { - if o.Context == nil { - o.Context = context.Background() - } - o.Context = context.WithValue(o.Context, serviceNameKey{}, name) - } -} - -func Namespace(namespace string) source.Option { - return func(o *source.Options) { - if o.Context == nil { - o.Context = context.Background() - } - o.Context = context.WithValue(o.Context, namespaceKey{}, namespace) - } -} - -func Path(path string) source.Option { - return func(o *source.Options) { - if o.Context == nil { - o.Context = context.Background() - } - o.Context = context.WithValue(o.Context, pathKey{}, path) - } -} diff --git a/config/source/service/proto/service.pb.go b/config/source/service/proto/service.pb.go deleted file mode 100644 index 6cce6174..00000000 --- a/config/source/service/proto/service.pb.go +++ /dev/null @@ -1,960 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: config/source/service/proto/service.proto - -package service - -import ( - context "context" - fmt "fmt" - proto "github.com/golang/protobuf/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -type ChangeSet struct { - Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` - Checksum string `protobuf:"bytes,2,opt,name=checksum,proto3" json:"checksum,omitempty"` - Format string `protobuf:"bytes,3,opt,name=format,proto3" json:"format,omitempty"` - Source string `protobuf:"bytes,4,opt,name=source,proto3" json:"source,omitempty"` - Timestamp int64 `protobuf:"varint,5,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ChangeSet) Reset() { *m = ChangeSet{} } -func (m *ChangeSet) String() string { return proto.CompactTextString(m) } -func (*ChangeSet) ProtoMessage() {} -func (*ChangeSet) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{0} -} - -func (m *ChangeSet) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ChangeSet.Unmarshal(m, b) -} -func (m *ChangeSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ChangeSet.Marshal(b, m, deterministic) -} -func (m *ChangeSet) XXX_Merge(src proto.Message) { - xxx_messageInfo_ChangeSet.Merge(m, src) -} -func (m *ChangeSet) XXX_Size() int { - return xxx_messageInfo_ChangeSet.Size(m) -} -func (m *ChangeSet) XXX_DiscardUnknown() { - xxx_messageInfo_ChangeSet.DiscardUnknown(m) -} - -var xxx_messageInfo_ChangeSet proto.InternalMessageInfo - -func (m *ChangeSet) GetData() string { - if m != nil { - return m.Data - } - return "" -} - -func (m *ChangeSet) GetChecksum() string { - if m != nil { - return m.Checksum - } - return "" -} - -func (m *ChangeSet) GetFormat() string { - if m != nil { - return m.Format - } - return "" -} - -func (m *ChangeSet) GetSource() string { - if m != nil { - return m.Source - } - return "" -} - -func (m *ChangeSet) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -type Change struct { - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` - ChangeSet *ChangeSet `protobuf:"bytes,3,opt,name=changeSet,proto3" json:"changeSet,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Change) Reset() { *m = Change{} } -func (m *Change) String() string { return proto.CompactTextString(m) } -func (*Change) ProtoMessage() {} -func (*Change) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{1} -} - -func (m *Change) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Change.Unmarshal(m, b) -} -func (m *Change) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Change.Marshal(b, m, deterministic) -} -func (m *Change) XXX_Merge(src proto.Message) { - xxx_messageInfo_Change.Merge(m, src) -} -func (m *Change) XXX_Size() int { - return xxx_messageInfo_Change.Size(m) -} -func (m *Change) XXX_DiscardUnknown() { - xxx_messageInfo_Change.DiscardUnknown(m) -} - -var xxx_messageInfo_Change proto.InternalMessageInfo - -func (m *Change) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -func (m *Change) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -func (m *Change) GetChangeSet() *ChangeSet { - if m != nil { - return m.ChangeSet - } - return nil -} - -type CreateRequest struct { - Change *Change `protobuf:"bytes,1,opt,name=change,proto3" json:"change,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateRequest) Reset() { *m = CreateRequest{} } -func (m *CreateRequest) String() string { return proto.CompactTextString(m) } -func (*CreateRequest) ProtoMessage() {} -func (*CreateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{2} -} - -func (m *CreateRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateRequest.Unmarshal(m, b) -} -func (m *CreateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateRequest.Marshal(b, m, deterministic) -} -func (m *CreateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateRequest.Merge(m, src) -} -func (m *CreateRequest) XXX_Size() int { - return xxx_messageInfo_CreateRequest.Size(m) -} -func (m *CreateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_CreateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateRequest proto.InternalMessageInfo - -func (m *CreateRequest) GetChange() *Change { - if m != nil { - return m.Change - } - return nil -} - -type CreateResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateResponse) Reset() { *m = CreateResponse{} } -func (m *CreateResponse) String() string { return proto.CompactTextString(m) } -func (*CreateResponse) ProtoMessage() {} -func (*CreateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{3} -} - -func (m *CreateResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateResponse.Unmarshal(m, b) -} -func (m *CreateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateResponse.Marshal(b, m, deterministic) -} -func (m *CreateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateResponse.Merge(m, src) -} -func (m *CreateResponse) XXX_Size() int { - return xxx_messageInfo_CreateResponse.Size(m) -} -func (m *CreateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CreateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateResponse proto.InternalMessageInfo - -type UpdateRequest struct { - Change *Change `protobuf:"bytes,1,opt,name=change,proto3" json:"change,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpdateRequest) Reset() { *m = UpdateRequest{} } -func (m *UpdateRequest) String() string { return proto.CompactTextString(m) } -func (*UpdateRequest) ProtoMessage() {} -func (*UpdateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{4} -} - -func (m *UpdateRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpdateRequest.Unmarshal(m, b) -} -func (m *UpdateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpdateRequest.Marshal(b, m, deterministic) -} -func (m *UpdateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateRequest.Merge(m, src) -} -func (m *UpdateRequest) XXX_Size() int { - return xxx_messageInfo_UpdateRequest.Size(m) -} -func (m *UpdateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateRequest proto.InternalMessageInfo - -func (m *UpdateRequest) GetChange() *Change { - if m != nil { - return m.Change - } - return nil -} - -type UpdateResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpdateResponse) Reset() { *m = UpdateResponse{} } -func (m *UpdateResponse) String() string { return proto.CompactTextString(m) } -func (*UpdateResponse) ProtoMessage() {} -func (*UpdateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{5} -} - -func (m *UpdateResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpdateResponse.Unmarshal(m, b) -} -func (m *UpdateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpdateResponse.Marshal(b, m, deterministic) -} -func (m *UpdateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateResponse.Merge(m, src) -} -func (m *UpdateResponse) XXX_Size() int { - return xxx_messageInfo_UpdateResponse.Size(m) -} -func (m *UpdateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateResponse proto.InternalMessageInfo - -type DeleteRequest struct { - Change *Change `protobuf:"bytes,1,opt,name=change,proto3" json:"change,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteRequest) Reset() { *m = DeleteRequest{} } -func (m *DeleteRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteRequest) ProtoMessage() {} -func (*DeleteRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{6} -} - -func (m *DeleteRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteRequest.Unmarshal(m, b) -} -func (m *DeleteRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteRequest.Marshal(b, m, deterministic) -} -func (m *DeleteRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteRequest.Merge(m, src) -} -func (m *DeleteRequest) XXX_Size() int { - return xxx_messageInfo_DeleteRequest.Size(m) -} -func (m *DeleteRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteRequest proto.InternalMessageInfo - -func (m *DeleteRequest) GetChange() *Change { - if m != nil { - return m.Change - } - return nil -} - -type DeleteResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteResponse) Reset() { *m = DeleteResponse{} } -func (m *DeleteResponse) String() string { return proto.CompactTextString(m) } -func (*DeleteResponse) ProtoMessage() {} -func (*DeleteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{7} -} - -func (m *DeleteResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteResponse.Unmarshal(m, b) -} -func (m *DeleteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteResponse.Marshal(b, m, deterministic) -} -func (m *DeleteResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteResponse.Merge(m, src) -} -func (m *DeleteResponse) XXX_Size() int { - return xxx_messageInfo_DeleteResponse.Size(m) -} -func (m *DeleteResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteResponse proto.InternalMessageInfo - -type ListRequest struct { - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListRequest) Reset() { *m = ListRequest{} } -func (m *ListRequest) String() string { return proto.CompactTextString(m) } -func (*ListRequest) ProtoMessage() {} -func (*ListRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{8} -} - -func (m *ListRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListRequest.Unmarshal(m, b) -} -func (m *ListRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListRequest.Marshal(b, m, deterministic) -} -func (m *ListRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListRequest.Merge(m, src) -} -func (m *ListRequest) XXX_Size() int { - return xxx_messageInfo_ListRequest.Size(m) -} -func (m *ListRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListRequest proto.InternalMessageInfo - -func (m *ListRequest) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -type ListResponse struct { - Values []*Change `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListResponse) Reset() { *m = ListResponse{} } -func (m *ListResponse) String() string { return proto.CompactTextString(m) } -func (*ListResponse) ProtoMessage() {} -func (*ListResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{9} -} - -func (m *ListResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListResponse.Unmarshal(m, b) -} -func (m *ListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListResponse.Marshal(b, m, deterministic) -} -func (m *ListResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListResponse.Merge(m, src) -} -func (m *ListResponse) XXX_Size() int { - return xxx_messageInfo_ListResponse.Size(m) -} -func (m *ListResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListResponse proto.InternalMessageInfo - -func (m *ListResponse) GetValues() []*Change { - if m != nil { - return m.Values - } - return nil -} - -type ReadRequest struct { - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadRequest) Reset() { *m = ReadRequest{} } -func (m *ReadRequest) String() string { return proto.CompactTextString(m) } -func (*ReadRequest) ProtoMessage() {} -func (*ReadRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{10} -} - -func (m *ReadRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadRequest.Unmarshal(m, b) -} -func (m *ReadRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadRequest.Marshal(b, m, deterministic) -} -func (m *ReadRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadRequest.Merge(m, src) -} -func (m *ReadRequest) XXX_Size() int { - return xxx_messageInfo_ReadRequest.Size(m) -} -func (m *ReadRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ReadRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadRequest proto.InternalMessageInfo - -func (m *ReadRequest) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -func (m *ReadRequest) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -type ReadResponse struct { - Change *Change `protobuf:"bytes,1,opt,name=change,proto3" json:"change,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadResponse) Reset() { *m = ReadResponse{} } -func (m *ReadResponse) String() string { return proto.CompactTextString(m) } -func (*ReadResponse) ProtoMessage() {} -func (*ReadResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{11} -} - -func (m *ReadResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadResponse.Unmarshal(m, b) -} -func (m *ReadResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadResponse.Marshal(b, m, deterministic) -} -func (m *ReadResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadResponse.Merge(m, src) -} -func (m *ReadResponse) XXX_Size() int { - return xxx_messageInfo_ReadResponse.Size(m) -} -func (m *ReadResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ReadResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadResponse proto.InternalMessageInfo - -func (m *ReadResponse) GetChange() *Change { - if m != nil { - return m.Change - } - return nil -} - -type WatchRequest struct { - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *WatchRequest) Reset() { *m = WatchRequest{} } -func (m *WatchRequest) String() string { return proto.CompactTextString(m) } -func (*WatchRequest) ProtoMessage() {} -func (*WatchRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{12} -} - -func (m *WatchRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_WatchRequest.Unmarshal(m, b) -} -func (m *WatchRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_WatchRequest.Marshal(b, m, deterministic) -} -func (m *WatchRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_WatchRequest.Merge(m, src) -} -func (m *WatchRequest) XXX_Size() int { - return xxx_messageInfo_WatchRequest.Size(m) -} -func (m *WatchRequest) XXX_DiscardUnknown() { - xxx_messageInfo_WatchRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_WatchRequest proto.InternalMessageInfo - -func (m *WatchRequest) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -func (m *WatchRequest) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -type WatchResponse struct { - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - ChangeSet *ChangeSet `protobuf:"bytes,2,opt,name=changeSet,proto3" json:"changeSet,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *WatchResponse) Reset() { *m = WatchResponse{} } -func (m *WatchResponse) String() string { return proto.CompactTextString(m) } -func (*WatchResponse) ProtoMessage() {} -func (*WatchResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e67338fe1f659d14, []int{13} -} - -func (m *WatchResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_WatchResponse.Unmarshal(m, b) -} -func (m *WatchResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_WatchResponse.Marshal(b, m, deterministic) -} -func (m *WatchResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_WatchResponse.Merge(m, src) -} -func (m *WatchResponse) XXX_Size() int { - return xxx_messageInfo_WatchResponse.Size(m) -} -func (m *WatchResponse) XXX_DiscardUnknown() { - xxx_messageInfo_WatchResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_WatchResponse proto.InternalMessageInfo - -func (m *WatchResponse) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -func (m *WatchResponse) GetChangeSet() *ChangeSet { - if m != nil { - return m.ChangeSet - } - return nil -} - -func init() { - proto.RegisterType((*ChangeSet)(nil), "ChangeSet") - proto.RegisterType((*Change)(nil), "Change") - proto.RegisterType((*CreateRequest)(nil), "CreateRequest") - proto.RegisterType((*CreateResponse)(nil), "CreateResponse") - proto.RegisterType((*UpdateRequest)(nil), "UpdateRequest") - proto.RegisterType((*UpdateResponse)(nil), "UpdateResponse") - proto.RegisterType((*DeleteRequest)(nil), "DeleteRequest") - proto.RegisterType((*DeleteResponse)(nil), "DeleteResponse") - proto.RegisterType((*ListRequest)(nil), "ListRequest") - proto.RegisterType((*ListResponse)(nil), "ListResponse") - proto.RegisterType((*ReadRequest)(nil), "ReadRequest") - proto.RegisterType((*ReadResponse)(nil), "ReadResponse") - proto.RegisterType((*WatchRequest)(nil), "WatchRequest") - proto.RegisterType((*WatchResponse)(nil), "WatchResponse") -} - -func init() { - proto.RegisterFile("config/source/service/proto/service.proto", fileDescriptor_e67338fe1f659d14) -} - -var fileDescriptor_e67338fe1f659d14 = []byte{ - // 440 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4d, 0x6b, 0xdb, 0x40, - 0x10, 0xb5, 0x6c, 0x47, 0xad, 0xc7, 0x96, 0x5c, 0xe6, 0x50, 0x84, 0x28, 0xd4, 0x2c, 0x14, 0xdc, - 0x06, 0xd6, 0xc1, 0xfd, 0x01, 0x2d, 0xb8, 0xc7, 0x9e, 0x54, 0x4a, 0xce, 0xdb, 0xf5, 0x24, 0x36, - 0x8d, 0x2c, 0x55, 0xbb, 0xca, 0x7f, 0xc8, 0xbf, 0x2e, 0xfb, 0xa1, 0x48, 0x32, 0x45, 0xd4, 0xb9, - 0x69, 0xde, 0xce, 0xbc, 0x37, 0xbb, 0xef, 0xd9, 0xf0, 0x51, 0x16, 0xa7, 0xbb, 0xe3, 0xfd, 0x46, - 0x15, 0x75, 0x25, 0x69, 0xa3, 0xa8, 0x7a, 0x3c, 0x4a, 0xda, 0x94, 0x55, 0xa1, 0x8b, 0xa6, 0xe2, - 0xb6, 0x62, 0x4f, 0x01, 0xcc, 0x76, 0x07, 0x71, 0xba, 0xa7, 0x1f, 0xa4, 0x11, 0x61, 0xba, 0x17, - 0x5a, 0x24, 0xc1, 0x2a, 0x58, 0xcf, 0x32, 0xfb, 0x8d, 0x29, 0xbc, 0x96, 0x07, 0x92, 0xbf, 0x55, - 0x9d, 0x27, 0x63, 0x8b, 0x3f, 0xd7, 0xf8, 0x16, 0xc2, 0xbb, 0xa2, 0xca, 0x85, 0x4e, 0x26, 0xf6, - 0xc4, 0x57, 0x06, 0x77, 0xda, 0xc9, 0xd4, 0xe1, 0xae, 0xc2, 0x77, 0x30, 0xd3, 0xc7, 0x9c, 0x94, - 0x16, 0x79, 0x99, 0x5c, 0xad, 0x82, 0xf5, 0x24, 0x6b, 0x01, 0xb6, 0x87, 0xd0, 0xad, 0x62, 0xfa, - 0x4e, 0x22, 0x27, 0x55, 0x0a, 0x49, 0x7e, 0x99, 0x16, 0x30, 0x5b, 0x96, 0x42, 0x1f, 0xfc, 0x36, - 0xf6, 0x1b, 0xd7, 0x30, 0x93, 0xcd, 0x35, 0xec, 0x32, 0xf3, 0x2d, 0xf0, 0xe7, 0x8b, 0x65, 0xed, - 0x21, 0xbb, 0x81, 0x68, 0x57, 0x91, 0xd0, 0x94, 0xd1, 0x9f, 0x9a, 0x94, 0xc6, 0xf7, 0x10, 0xba, - 0x53, 0xab, 0x34, 0xdf, 0xbe, 0xf2, 0x73, 0x99, 0x87, 0xd9, 0x1b, 0x88, 0x9b, 0x09, 0x55, 0x16, - 0x27, 0x45, 0x86, 0xe3, 0x67, 0xb9, 0xbf, 0x90, 0xa3, 0x99, 0x68, 0x39, 0xbe, 0xd1, 0x03, 0x5d, - 0xc6, 0xd1, 0x4c, 0x78, 0x8e, 0x6b, 0x98, 0x7f, 0x3f, 0x2a, 0xdd, 0x30, 0x0c, 0x3e, 0x1b, 0xdb, - 0xc0, 0xc2, 0x35, 0xbb, 0x61, 0xa3, 0xf7, 0x28, 0x1e, 0x6a, 0x52, 0x49, 0xb0, 0x9a, 0xf4, 0xf4, - 0x1c, 0xcc, 0xbe, 0xc0, 0x3c, 0x23, 0xb1, 0xff, 0x2f, 0xf6, 0x7f, 0x99, 0x62, 0x14, 0x1d, 0x41, - 0xab, 0x38, 0x7c, 0xc3, 0xaf, 0xb0, 0xb8, 0x15, 0x5a, 0x1e, 0x5e, 0x2e, 0x79, 0x0b, 0x91, 0x67, - 0xf0, 0x9a, 0xc3, 0x14, 0xbd, 0xd8, 0x8c, 0x07, 0x62, 0xb3, 0x7d, 0x1a, 0x43, 0xb8, 0xb3, 0x3f, - 0x2b, 0xbc, 0x86, 0xd0, 0xe5, 0x01, 0x63, 0xde, 0x8b, 0x52, 0xba, 0xe4, 0x67, 0x41, 0x19, 0x99, - 0x66, 0x67, 0x3c, 0xc6, 0xbc, 0x97, 0x99, 0x74, 0xc9, 0xcf, 0x12, 0x61, 0x9b, 0x9d, 0xc3, 0x18, - 0xf3, 0x5e, 0x38, 0xd2, 0x25, 0x3f, 0xb3, 0x7e, 0x84, 0x1f, 0x60, 0x6a, 0xfc, 0xc4, 0x05, 0xef, - 0x64, 0x20, 0x8d, 0x78, 0xd7, 0x64, 0xd7, 0x66, 0x4c, 0xc0, 0x05, 0xef, 0x98, 0x99, 0x46, 0xbc, - 0xeb, 0x0c, 0x1b, 0xe1, 0x27, 0xb8, 0xb2, 0x0f, 0x87, 0x11, 0xef, 0x5a, 0x90, 0xc6, 0xbc, 0xf7, - 0x9e, 0x6c, 0x74, 0x13, 0xfc, 0x0a, 0xed, 0x7f, 0xc7, 0xe7, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, - 0xb7, 0x06, 0x45, 0x6a, 0x68, 0x04, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// ConfigClient is the client API for Config service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type ConfigClient interface { - Create(ctx context.Context, in *CreateRequest, opts ...grpc.CallOption) (*CreateResponse, error) - Update(ctx context.Context, in *UpdateRequest, opts ...grpc.CallOption) (*UpdateResponse, error) - Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) - List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) - Read(ctx context.Context, in *ReadRequest, opts ...grpc.CallOption) (*ReadResponse, error) - Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (Config_WatchClient, error) -} - -type configClient struct { - cc *grpc.ClientConn -} - -func NewConfigClient(cc *grpc.ClientConn) ConfigClient { - return &configClient{cc} -} - -func (c *configClient) Create(ctx context.Context, in *CreateRequest, opts ...grpc.CallOption) (*CreateResponse, error) { - out := new(CreateResponse) - err := c.cc.Invoke(ctx, "/Config/Create", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configClient) Update(ctx context.Context, in *UpdateRequest, opts ...grpc.CallOption) (*UpdateResponse, error) { - out := new(UpdateResponse) - err := c.cc.Invoke(ctx, "/Config/Update", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configClient) Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) { - out := new(DeleteResponse) - err := c.cc.Invoke(ctx, "/Config/Delete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configClient) List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) { - out := new(ListResponse) - err := c.cc.Invoke(ctx, "/Config/List", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configClient) Read(ctx context.Context, in *ReadRequest, opts ...grpc.CallOption) (*ReadResponse, error) { - out := new(ReadResponse) - err := c.cc.Invoke(ctx, "/Config/Read", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configClient) Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (Config_WatchClient, error) { - stream, err := c.cc.NewStream(ctx, &_Config_serviceDesc.Streams[0], "/Config/Watch", opts...) - if err != nil { - return nil, err - } - x := &configWatchClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Config_WatchClient interface { - Recv() (*WatchResponse, error) - grpc.ClientStream -} - -type configWatchClient struct { - grpc.ClientStream -} - -func (x *configWatchClient) Recv() (*WatchResponse, error) { - m := new(WatchResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// ConfigServer is the server API for Config service. -type ConfigServer interface { - Create(context.Context, *CreateRequest) (*CreateResponse, error) - Update(context.Context, *UpdateRequest) (*UpdateResponse, error) - Delete(context.Context, *DeleteRequest) (*DeleteResponse, error) - List(context.Context, *ListRequest) (*ListResponse, error) - Read(context.Context, *ReadRequest) (*ReadResponse, error) - Watch(*WatchRequest, Config_WatchServer) error -} - -// UnimplementedConfigServer can be embedded to have forward compatible implementations. -type UnimplementedConfigServer struct { -} - -func (*UnimplementedConfigServer) Create(ctx context.Context, req *CreateRequest) (*CreateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Create not implemented") -} -func (*UnimplementedConfigServer) Update(ctx context.Context, req *UpdateRequest) (*UpdateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Update not implemented") -} -func (*UnimplementedConfigServer) Delete(ctx context.Context, req *DeleteRequest) (*DeleteResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") -} -func (*UnimplementedConfigServer) List(ctx context.Context, req *ListRequest) (*ListResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method List not implemented") -} -func (*UnimplementedConfigServer) Read(ctx context.Context, req *ReadRequest) (*ReadResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Read not implemented") -} -func (*UnimplementedConfigServer) Watch(req *WatchRequest, srv Config_WatchServer) error { - return status.Errorf(codes.Unimplemented, "method Watch not implemented") -} - -func RegisterConfigServer(s *grpc.Server, srv ConfigServer) { - s.RegisterService(&_Config_serviceDesc, srv) -} - -func _Config_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CreateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ConfigServer).Create(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/Config/Create", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ConfigServer).Create(ctx, req.(*CreateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Config_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpdateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ConfigServer).Update(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/Config/Update", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ConfigServer).Update(ctx, req.(*UpdateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Config_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ConfigServer).Delete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/Config/Delete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ConfigServer).Delete(ctx, req.(*DeleteRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Config_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ConfigServer).List(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/Config/List", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ConfigServer).List(ctx, req.(*ListRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Config_Read_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ReadRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ConfigServer).Read(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/Config/Read", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ConfigServer).Read(ctx, req.(*ReadRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Config_Watch_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(WatchRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(ConfigServer).Watch(m, &configWatchServer{stream}) -} - -type Config_WatchServer interface { - Send(*WatchResponse) error - grpc.ServerStream -} - -type configWatchServer struct { - grpc.ServerStream -} - -func (x *configWatchServer) Send(m *WatchResponse) error { - return x.ServerStream.SendMsg(m) -} - -var _Config_serviceDesc = grpc.ServiceDesc{ - ServiceName: "Config", - HandlerType: (*ConfigServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Create", - Handler: _Config_Create_Handler, - }, - { - MethodName: "Update", - Handler: _Config_Update_Handler, - }, - { - MethodName: "Delete", - Handler: _Config_Delete_Handler, - }, - { - MethodName: "List", - Handler: _Config_List_Handler, - }, - { - MethodName: "Read", - Handler: _Config_Read_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Watch", - Handler: _Config_Watch_Handler, - ServerStreams: true, - }, - }, - Metadata: "config/source/service/proto/service.proto", -} diff --git a/config/source/service/proto/service.pb.micro.go b/config/source/service/proto/service.pb.micro.go deleted file mode 100644 index d37fc283..00000000 --- a/config/source/service/proto/service.pb.micro.go +++ /dev/null @@ -1,253 +0,0 @@ -// Code generated by protoc-gen-micro. DO NOT EDIT. -// source: config/source/service/proto/service.proto - -package service - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -import ( - context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ api.Endpoint -var _ context.Context -var _ client.Option -var _ server.Option - -// Api Endpoints for Config service - -func NewConfigEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Config service - -type ConfigService interface { - Create(ctx context.Context, in *CreateRequest, opts ...client.CallOption) (*CreateResponse, error) - Update(ctx context.Context, in *UpdateRequest, opts ...client.CallOption) (*UpdateResponse, error) - Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) - List(ctx context.Context, in *ListRequest, opts ...client.CallOption) (*ListResponse, error) - Read(ctx context.Context, in *ReadRequest, opts ...client.CallOption) (*ReadResponse, error) - Watch(ctx context.Context, in *WatchRequest, opts ...client.CallOption) (Config_WatchService, error) -} - -type configService struct { - c client.Client - name string -} - -func NewConfigService(name string, c client.Client) ConfigService { - return &configService{ - c: c, - name: name, - } -} - -func (c *configService) Create(ctx context.Context, in *CreateRequest, opts ...client.CallOption) (*CreateResponse, error) { - req := c.c.NewRequest(c.name, "Config.Create", in) - out := new(CreateResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configService) Update(ctx context.Context, in *UpdateRequest, opts ...client.CallOption) (*UpdateResponse, error) { - req := c.c.NewRequest(c.name, "Config.Update", in) - out := new(UpdateResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configService) Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) { - req := c.c.NewRequest(c.name, "Config.Delete", in) - out := new(DeleteResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configService) List(ctx context.Context, in *ListRequest, opts ...client.CallOption) (*ListResponse, error) { - req := c.c.NewRequest(c.name, "Config.List", in) - out := new(ListResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configService) Read(ctx context.Context, in *ReadRequest, opts ...client.CallOption) (*ReadResponse, error) { - req := c.c.NewRequest(c.name, "Config.Read", in) - out := new(ReadResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *configService) Watch(ctx context.Context, in *WatchRequest, opts ...client.CallOption) (Config_WatchService, error) { - req := c.c.NewRequest(c.name, "Config.Watch", &WatchRequest{}) - stream, err := c.c.Stream(ctx, req, opts...) - if err != nil { - return nil, err - } - if err := stream.Send(in); err != nil { - return nil, err - } - return &configServiceWatch{stream}, nil -} - -type Config_WatchService interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Recv() (*WatchResponse, error) -} - -type configServiceWatch struct { - stream client.Stream -} - -func (x *configServiceWatch) Close() error { - return x.stream.Close() -} - -func (x *configServiceWatch) Context() context.Context { - return x.stream.Context() -} - -func (x *configServiceWatch) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *configServiceWatch) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *configServiceWatch) Recv() (*WatchResponse, error) { - m := new(WatchResponse) - err := x.stream.Recv(m) - if err != nil { - return nil, err - } - return m, nil -} - -// Server API for Config service - -type ConfigHandler interface { - Create(context.Context, *CreateRequest, *CreateResponse) error - Update(context.Context, *UpdateRequest, *UpdateResponse) error - Delete(context.Context, *DeleteRequest, *DeleteResponse) error - List(context.Context, *ListRequest, *ListResponse) error - Read(context.Context, *ReadRequest, *ReadResponse) error - Watch(context.Context, *WatchRequest, Config_WatchStream) error -} - -func RegisterConfigHandler(s server.Server, hdlr ConfigHandler, opts ...server.HandlerOption) error { - type config interface { - Create(ctx context.Context, in *CreateRequest, out *CreateResponse) error - Update(ctx context.Context, in *UpdateRequest, out *UpdateResponse) error - Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error - List(ctx context.Context, in *ListRequest, out *ListResponse) error - Read(ctx context.Context, in *ReadRequest, out *ReadResponse) error - Watch(ctx context.Context, stream server.Stream) error - } - type Config struct { - config - } - h := &configHandler{hdlr} - return s.Handle(s.NewHandler(&Config{h}, opts...)) -} - -type configHandler struct { - ConfigHandler -} - -func (h *configHandler) Create(ctx context.Context, in *CreateRequest, out *CreateResponse) error { - return h.ConfigHandler.Create(ctx, in, out) -} - -func (h *configHandler) Update(ctx context.Context, in *UpdateRequest, out *UpdateResponse) error { - return h.ConfigHandler.Update(ctx, in, out) -} - -func (h *configHandler) Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error { - return h.ConfigHandler.Delete(ctx, in, out) -} - -func (h *configHandler) List(ctx context.Context, in *ListRequest, out *ListResponse) error { - return h.ConfigHandler.List(ctx, in, out) -} - -func (h *configHandler) Read(ctx context.Context, in *ReadRequest, out *ReadResponse) error { - return h.ConfigHandler.Read(ctx, in, out) -} - -func (h *configHandler) Watch(ctx context.Context, stream server.Stream) error { - m := new(WatchRequest) - if err := stream.Recv(m); err != nil { - return err - } - return h.ConfigHandler.Watch(ctx, m, &configWatchStream{stream}) -} - -type Config_WatchStream interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Send(*WatchResponse) error -} - -type configWatchStream struct { - stream server.Stream -} - -func (x *configWatchStream) Close() error { - return x.stream.Close() -} - -func (x *configWatchStream) Context() context.Context { - return x.stream.Context() -} - -func (x *configWatchStream) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *configWatchStream) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *configWatchStream) Send(m *WatchResponse) error { - return x.stream.Send(m) -} diff --git a/config/source/service/proto/service.proto b/config/source/service/proto/service.proto deleted file mode 100644 index 5e0a3389..00000000 --- a/config/source/service/proto/service.proto +++ /dev/null @@ -1,69 +0,0 @@ -syntax = "proto3"; - -service Config { - rpc Create (CreateRequest) returns (CreateResponse) {} - rpc Update (UpdateRequest) returns (UpdateResponse) {} - rpc Delete (DeleteRequest) returns (DeleteResponse) {} - rpc List (ListRequest) returns (ListResponse) {} - rpc Read (ReadRequest) returns (ReadResponse) {} - rpc Watch (WatchRequest) returns (stream WatchResponse) {} -} - -message ChangeSet { - string data = 1; - string checksum = 2; - string format = 3; - string source = 4; - int64 timestamp = 5; -} - -message Change { - string namespace = 1; - string path = 2; - ChangeSet changeSet = 3; -} - -message CreateRequest { - Change change = 1; -} - -message CreateResponse {} - -message UpdateRequest { - Change change = 1; -} - -message UpdateResponse {} - -message DeleteRequest { - Change change = 1; -} - -message DeleteResponse {} - -message ListRequest { - string namespace = 1; -} - -message ListResponse { - repeated Change values = 1; -} - -message ReadRequest { - string namespace = 1; - string path = 2; -} - -message ReadResponse { - Change change = 1; -} - -message WatchRequest { - string namespace = 1; - string path = 2; -} - -message WatchResponse { - string namespace = 1; - ChangeSet changeSet = 2; -} diff --git a/config/source/service/service.go b/config/source/service/service.go deleted file mode 100644 index 8776853c..00000000 --- a/config/source/service/service.go +++ /dev/null @@ -1,106 +0,0 @@ -package service - -import ( - "context" - "net/http" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/config/source" - proto "github.com/micro/go-micro/v2/config/source/service/proto" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/logger" -) - -var ( - DefaultName = "go.micro.config" - DefaultNamespace = "micro" - DefaultPath = "" -) - -type service struct { - serviceName string - namespace string - path string - opts source.Options - client proto.ConfigService -} - -func (m *service) Read() (set *source.ChangeSet, err error) { - client := proto.NewConfigService(m.serviceName, m.opts.Client) - req, err := client.Read(context.Background(), &proto.ReadRequest{ - Namespace: m.namespace, - Path: m.path, - }) - if verr, ok := err.(*errors.Error); ok && verr.Code == http.StatusNotFound { - return nil, nil - } else if err != nil { - return nil, err - } - - return toChangeSet(req.Change.ChangeSet), nil -} - -func (m *service) Watch() (w source.Watcher, err error) { - client := proto.NewConfigService(m.serviceName, m.opts.Client) - stream, err := client.Watch(context.Background(), &proto.WatchRequest{ - Namespace: m.namespace, - Path: m.path, - }) - if err != nil { - if logger.V(logger.ErrorLevel, logger.DefaultLogger) { - logger.Error("watch err: ", err) - } - return - } - return newWatcher(stream) -} - -// Write is unsupported -func (m *service) Write(cs *source.ChangeSet) error { - return nil -} - -func (m *service) String() string { - return "service" -} - -func NewSource(opts ...source.Option) source.Source { - var options source.Options - for _, o := range opts { - o(&options) - } - - addr := DefaultName - namespace := DefaultNamespace - path := DefaultPath - - if options.Context != nil { - a, ok := options.Context.Value(serviceNameKey{}).(string) - if ok { - addr = a - } - - k, ok := options.Context.Value(namespaceKey{}).(string) - if ok { - namespace = k - } - - p, ok := options.Context.Value(pathKey{}).(string) - if ok { - path = p - } - } - - if options.Client == nil { - options.Client = client.DefaultClient - } - - s := &service{ - serviceName: addr, - opts: options, - namespace: namespace, - path: path, - } - - return s -} diff --git a/config/source/service/util.go b/config/source/service/util.go deleted file mode 100644 index ad301918..00000000 --- a/config/source/service/util.go +++ /dev/null @@ -1,18 +0,0 @@ -package service - -import ( - "time" - - "github.com/micro/go-micro/v2/config/source" - proto "github.com/micro/go-micro/v2/config/source/service/proto" -) - -func toChangeSet(c *proto.ChangeSet) *source.ChangeSet { - return &source.ChangeSet{ - Data: []byte(c.Data), - Checksum: c.Checksum, - Format: c.Format, - Timestamp: time.Unix(c.Timestamp, 0), - Source: c.Source, - } -} diff --git a/config/source/service/watcher.go b/config/source/service/watcher.go deleted file mode 100644 index c99e5f7c..00000000 --- a/config/source/service/watcher.go +++ /dev/null @@ -1,27 +0,0 @@ -package service - -import ( - "github.com/micro/go-micro/v2/config/source" - proto "github.com/micro/go-micro/v2/config/source/service/proto" -) - -type watcher struct { - stream proto.Config_WatchService -} - -func newWatcher(stream proto.Config_WatchService) (source.Watcher, error) { - return &watcher{stream: stream}, nil -} - -func (w *watcher) Next() (*source.ChangeSet, error) { - var rsp proto.WatchResponse - err := w.stream.RecvMsg(&rsp) - if err != nil { - return nil, err - } - return toChangeSet(rsp.ChangeSet), nil -} - -func (w *watcher) Stop() error { - return w.stream.Close() -} diff --git a/config/value.go b/config/value.go index 90710bad..3cf1a2e4 100644 --- a/config/value.go +++ b/config/value.go @@ -3,7 +3,7 @@ package config import ( "time" - "github.com/micro/go-micro/v2/config/reader" + "github.com/micro/go-micro/v3/config/reader" ) type value struct{} diff --git a/debug/log/kubernetes/kubernetes.go b/debug/log/kubernetes/kubernetes.go index 882066be..5731a2bf 100644 --- a/debug/log/kubernetes/kubernetes.go +++ b/debug/log/kubernetes/kubernetes.go @@ -1,4 +1,4 @@ -// Package kubernetes is a logger implementing (github.com/micro/go-micro/v2/debug/log).Log +// Package kubernetes is a logger implementing (github.com/micro/go-micro/v3/debug/log).Log package kubernetes import ( @@ -10,8 +10,8 @@ import ( "strconv" "time" - "github.com/micro/go-micro/v2/debug/log" - "github.com/micro/go-micro/v2/util/kubernetes/client" + "github.com/micro/go-micro/v3/debug/log" + "github.com/micro/go-micro/v3/util/kubernetes/client" ) type klog struct { diff --git a/debug/log/kubernetes/kubernetes_test.go b/debug/log/kubernetes/kubernetes_test.go index 97749869..0036a0e9 100644 --- a/debug/log/kubernetes/kubernetes_test.go +++ b/debug/log/kubernetes/kubernetes_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/debug/log" + "github.com/micro/go-micro/v3/debug/log" "github.com/stretchr/testify/assert" ) diff --git a/debug/log/kubernetes/stream.go b/debug/log/kubernetes/stream.go index 50d18100..e82ed6bb 100644 --- a/debug/log/kubernetes/stream.go +++ b/debug/log/kubernetes/stream.go @@ -6,7 +6,7 @@ import ( "os" "sync" - "github.com/micro/go-micro/v2/debug/log" + "github.com/micro/go-micro/v3/debug/log" ) func write(l log.Record) error { diff --git a/debug/log/memory/memory.go b/debug/log/memory/memory.go index b168addd..a6025169 100644 --- a/debug/log/memory/memory.go +++ b/debug/log/memory/memory.go @@ -4,8 +4,8 @@ package memory import ( "fmt" - "github.com/micro/go-micro/v2/debug/log" - "github.com/micro/go-micro/v2/util/ring" + "github.com/micro/go-micro/v3/debug/log" + "github.com/micro/go-micro/v3/util/ring" ) var ( diff --git a/debug/log/memory/memory_test.go b/debug/log/memory/memory_test.go index 8fc861ac..304c296f 100644 --- a/debug/log/memory/memory_test.go +++ b/debug/log/memory/memory_test.go @@ -4,7 +4,7 @@ import ( "reflect" "testing" - "github.com/micro/go-micro/v2/debug/log" + "github.com/micro/go-micro/v3/debug/log" ) func TestLogger(t *testing.T) { diff --git a/debug/log/memory/stream.go b/debug/log/memory/stream.go index ae6493ae..cd1d8568 100644 --- a/debug/log/memory/stream.go +++ b/debug/log/memory/stream.go @@ -1,7 +1,7 @@ package memory import ( - "github.com/micro/go-micro/v2/debug/log" + "github.com/micro/go-micro/v3/debug/log" ) type logStream struct { diff --git a/debug/log/noop/noop.go b/debug/log/noop/noop.go index 1cbeba6a..1e0d23c4 100644 --- a/debug/log/noop/noop.go +++ b/debug/log/noop/noop.go @@ -1,7 +1,7 @@ package noop import ( - "github.com/micro/go-micro/v2/debug/log" + "github.com/micro/go-micro/v3/debug/log" ) type noop struct{} diff --git a/debug/log/os.go b/debug/log/os.go index 022481c2..02b7243b 100644 --- a/debug/log/os.go +++ b/debug/log/os.go @@ -4,7 +4,7 @@ import ( "sync" "github.com/google/uuid" - "github.com/micro/go-micro/v2/util/ring" + "github.com/micro/go-micro/v3/util/ring" ) // Should stream from OS diff --git a/debug/profile/http/http.go b/debug/profile/http/http.go index a21bc2eb..609b045e 100644 --- a/debug/profile/http/http.go +++ b/debug/profile/http/http.go @@ -7,7 +7,7 @@ import ( "net/http/pprof" "sync" - "github.com/micro/go-micro/v2/debug/profile" + "github.com/micro/go-micro/v3/debug/profile" ) type httpProfile struct { diff --git a/debug/profile/pprof/pprof.go b/debug/profile/pprof/pprof.go index 42761efe..e4eb4519 100644 --- a/debug/profile/pprof/pprof.go +++ b/debug/profile/pprof/pprof.go @@ -9,7 +9,7 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/debug/profile" + "github.com/micro/go-micro/v3/debug/profile" ) type profiler struct { diff --git a/debug/service/client.go b/debug/service/client.go index 6b6affd1..29ce5569 100644 --- a/debug/service/client.go +++ b/debug/service/client.go @@ -5,9 +5,9 @@ import ( "context" "time" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/debug/log" - pb "github.com/micro/go-micro/v2/debug/service/proto" + "github.com/micro/go-micro/v3/client/grpc" + "github.com/micro/go-micro/v3/debug/log" + pb "github.com/micro/go-micro/v3/debug/service/proto" ) // Debug provides debug service client @@ -86,7 +86,7 @@ func (d *debugClient) streamLogs(lg *logStream, stream pb.Debug_LogService) { // NewClient provides a debug client func NewClient(name string) *debugClient { // create default client - cli := client.DefaultClient + cli := grpc.NewClient() return &debugClient{ Client: pb.NewDebugService(name, cli), diff --git a/debug/service/handler/debug.go b/debug/service/handler/debug.go index cf97cdc0..de92993f 100644 --- a/debug/service/handler/debug.go +++ b/debug/service/handler/debug.go @@ -5,12 +5,12 @@ import ( "context" "time" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/debug/log" - proto "github.com/micro/go-micro/v2/debug/service/proto" - "github.com/micro/go-micro/v2/debug/stats" - "github.com/micro/go-micro/v2/debug/trace" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/debug/log" + proto "github.com/micro/go-micro/v3/debug/service/proto" + "github.com/micro/go-micro/v3/debug/stats" + "github.com/micro/go-micro/v3/debug/trace" + "github.com/micro/go-micro/v3/server" ) // NewHandler returns an instance of the Debug Handler diff --git a/debug/service/proto/debug.pb.micro.go b/debug/service/proto/debug.pb.micro.go index 1e436e22..cfece62d 100644 --- a/debug/service/proto/debug.pb.micro.go +++ b/debug/service/proto/debug.pb.micro.go @@ -11,9 +11,9 @@ import ( import ( context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" + api "github.com/micro/go-micro/v3/api" + client "github.com/micro/go-micro/v3/client" + server "github.com/micro/go-micro/v3/server" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/debug/service/service.go b/debug/service/service.go index cadbe4b8..3aee13e5 100644 --- a/debug/service/service.go +++ b/debug/service/service.go @@ -3,8 +3,8 @@ package service import ( "time" - "github.com/micro/go-micro/v2/debug" - "github.com/micro/go-micro/v2/debug/log" + "github.com/micro/go-micro/v3/debug" + "github.com/micro/go-micro/v3/debug/log" ) type serviceLog struct { diff --git a/debug/service/stream.go b/debug/service/stream.go index f6662ad7..cb801329 100644 --- a/debug/service/stream.go +++ b/debug/service/stream.go @@ -1,7 +1,7 @@ package service import ( - "github.com/micro/go-micro/v2/debug/log" + "github.com/micro/go-micro/v3/debug/log" ) type logStream struct { diff --git a/debug/stats/default.go b/debug/stats/default.go index d36dfd0f..25d8957a 100644 --- a/debug/stats/default.go +++ b/debug/stats/default.go @@ -5,7 +5,7 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/util/ring" + "github.com/micro/go-micro/v3/util/ring" ) type stats struct { diff --git a/debug/trace/memory/memory.go b/debug/trace/memory/memory.go index 497cc1b6..c62d7cf4 100644 --- a/debug/trace/memory/memory.go +++ b/debug/trace/memory/memory.go @@ -5,8 +5,8 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/debug/trace" - "github.com/micro/go-micro/v2/util/ring" + "github.com/micro/go-micro/v3/debug/trace" + "github.com/micro/go-micro/v3/util/ring" ) type Tracer struct { diff --git a/debug/trace/trace.go b/debug/trace/trace.go index 12a6ccbf..343701f6 100644 --- a/debug/trace/trace.go +++ b/debug/trace/trace.go @@ -5,7 +5,7 @@ import ( "context" "time" - "github.com/micro/go-micro/v2/metadata" + "github.com/micro/go-micro/v3/metadata" ) // Tracer is an interface for distributed tracing diff --git a/defaults.go b/defaults.go deleted file mode 100644 index 815e591e..00000000 --- a/defaults.go +++ /dev/null @@ -1,134 +0,0 @@ -package micro - -import ( - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/cmd" - "github.com/micro/go-micro/v2/config" - "github.com/micro/go-micro/v2/debug/profile/http" - "github.com/micro/go-micro/v2/debug/profile/pprof" - "github.com/micro/go-micro/v2/debug/trace" - "github.com/micro/go-micro/v2/server" - "github.com/micro/go-micro/v2/store" - - // clients - gcli "github.com/micro/go-micro/v2/client/grpc" - cmucp "github.com/micro/go-micro/v2/client/mucp" - - gsrv "github.com/micro/go-micro/v2/server/grpc" - smucp "github.com/micro/go-micro/v2/server/mucp" - - // brokers - brokerHttp "github.com/micro/go-micro/v2/broker/http" - "github.com/micro/go-micro/v2/broker/memory" - "github.com/micro/go-micro/v2/broker/nats" - brokerSrv "github.com/micro/go-micro/v2/broker/service" - - // registries - "github.com/micro/go-micro/v2/registry/etcd" - "github.com/micro/go-micro/v2/registry/mdns" - rmem "github.com/micro/go-micro/v2/registry/memory" - regSrv "github.com/micro/go-micro/v2/registry/service" - - // routers - dnsRouter "github.com/micro/go-micro/v2/router/dns" - regRouter "github.com/micro/go-micro/v2/router/registry" - srvRouter "github.com/micro/go-micro/v2/router/service" - staticRouter "github.com/micro/go-micro/v2/router/static" - - // runtimes - kRuntime "github.com/micro/go-micro/v2/runtime/kubernetes" - lRuntime "github.com/micro/go-micro/v2/runtime/local" - srvRuntime "github.com/micro/go-micro/v2/runtime/service" - - // selectors - randSelector "github.com/micro/go-micro/v2/selector/random" - roundSelector "github.com/micro/go-micro/v2/selector/roundrobin" - - // transports - thttp "github.com/micro/go-micro/v2/transport/http" - tmem "github.com/micro/go-micro/v2/transport/memory" - - // stores - memStore "github.com/micro/go-micro/v2/store/memory" - svcStore "github.com/micro/go-micro/v2/store/service" - - // tracers - // jTracer "github.com/micro/go-micro/v2/debug/trace/jaeger" - memTracer "github.com/micro/go-micro/v2/debug/trace/memory" - - // auth - jwtAuth "github.com/micro/go-micro/v2/auth/jwt" - svcAuth "github.com/micro/go-micro/v2/auth/service" -) - -func init() { - // set defaults - - // default client - client.DefaultClient = gcli.NewClient() - // default server - server.DefaultServer = gsrv.NewServer() - // default store - store.DefaultStore = memStore.NewStore() - // set default trace - trace.DefaultTracer = memTracer.NewTracer() - - // import all the plugins - - // auth - cmd.DefaultAuths["service"] = svcAuth.NewAuth - cmd.DefaultAuths["jwt"] = jwtAuth.NewAuth - - // broker - cmd.DefaultBrokers["service"] = brokerSrv.NewBroker - cmd.DefaultBrokers["memory"] = memory.NewBroker - cmd.DefaultBrokers["nats"] = nats.NewBroker - cmd.DefaultBrokers["http"] = brokerHttp.NewBroker - - // config - cmd.DefaultConfigs["service"] = config.NewConfig - - // client - cmd.DefaultClients["mucp"] = cmucp.NewClient - cmd.DefaultClients["grpc"] = gcli.NewClient - - // profiler - cmd.DefaultProfiles["http"] = http.NewProfile - cmd.DefaultProfiles["pprof"] = pprof.NewProfile - - // registry - cmd.DefaultRegistries["service"] = regSrv.NewRegistry - cmd.DefaultRegistries["etcd"] = etcd.NewRegistry - cmd.DefaultRegistries["mdns"] = mdns.NewRegistry - cmd.DefaultRegistries["memory"] = rmem.NewRegistry - - // runtime - cmd.DefaultRuntimes["local"] = lRuntime.NewRuntime - cmd.DefaultRuntimes["service"] = srvRuntime.NewRuntime - cmd.DefaultRuntimes["kubernetes"] = kRuntime.NewRuntime - - // router - cmd.DefaultRouters["dns"] = dnsRouter.NewRouter - cmd.DefaultRouters["registry"] = regRouter.NewRouter - cmd.DefaultRouters["static"] = staticRouter.NewRouter - cmd.DefaultRouters["service"] = srvRouter.NewRouter - - // selector - cmd.DefaultSelectors["random"] = randSelector.NewSelector - cmd.DefaultSelectors["roundrobin"] = roundSelector.NewSelector - - // server - cmd.DefaultServers["mucp"] = smucp.NewServer - cmd.DefaultServers["grpc"] = gsrv.NewServer - - // store - cmd.DefaultStores["memory"] = memStore.NewStore - cmd.DefaultStores["service"] = svcStore.NewStore - - // trace - cmd.DefaultTracers["memory"] = memTracer.NewTracer - - // transport - cmd.DefaultTransports["memory"] = tmem.NewTransport - cmd.DefaultTransports["http"] = thttp.NewTransport -} diff --git a/event.go b/event.go deleted file mode 100644 index c55e37bb..00000000 --- a/event.go +++ /dev/null @@ -1,16 +0,0 @@ -package micro - -import ( - "context" - - "github.com/micro/go-micro/v2/client" -) - -type event struct { - c client.Client - topic string -} - -func (e *event) Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error { - return e.c.Publish(ctx, e.c.NewMessage(e.topic, msg), opts...) -} diff --git a/function.go b/function.go deleted file mode 100644 index 06037066..00000000 --- a/function.go +++ /dev/null @@ -1,81 +0,0 @@ -package micro - -import ( - "context" - "time" - - "github.com/micro/go-micro/v2/server" -) - -type function struct { - cancel context.CancelFunc - Service -} - -func fnHandlerWrapper(f Function) server.HandlerWrapper { - return func(h server.HandlerFunc) server.HandlerFunc { - return func(ctx context.Context, req server.Request, rsp interface{}) error { - defer f.Done() - return h(ctx, req, rsp) - } - } -} - -func fnSubWrapper(f Function) server.SubscriberWrapper { - return func(s server.SubscriberFunc) server.SubscriberFunc { - return func(ctx context.Context, msg server.Message) error { - defer f.Done() - return s(ctx, msg) - } - } -} - -func newFunction(opts ...Option) Function { - ctx, cancel := context.WithCancel(context.Background()) - - // force ttl/interval - fopts := []Option{ - RegisterTTL(time.Minute), - RegisterInterval(time.Second * 30), - } - - // prepend to opts - fopts = append(fopts, opts...) - - // make context the last thing - fopts = append(fopts, Context(ctx)) - - service := newService(fopts...) - - fn := &function{ - cancel: cancel, - Service: service, - } - - service.Server().Init( - // ensure the service waits for requests to finish - server.Wait(nil), - // wrap handlers and subscribers to finish execution - server.WrapHandler(fnHandlerWrapper(fn)), - server.WrapSubscriber(fnSubWrapper(fn)), - ) - - return fn -} - -func (f *function) Done() error { - f.cancel() - return nil -} - -func (f *function) Handle(v interface{}) error { - return f.Service.Server().Handle( - f.Service.Server().NewHandler(v), - ) -} - -func (f *function) Subscribe(topic string, v interface{}) error { - return f.Service.Server().Subscribe( - f.Service.Server().NewSubscriber(topic, v), - ) -} diff --git a/function_test.go b/function_test.go deleted file mode 100644 index 8b26516e..00000000 --- a/function_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package micro - -import ( - "context" - "sync" - "testing" - - proto "github.com/micro/go-micro/v2/debug/service/proto" - "github.com/micro/go-micro/v2/registry/memory" - "github.com/micro/go-micro/v2/util/test" -) - -func TestFunction(t *testing.T) { - var wg sync.WaitGroup - wg.Add(1) - - r := memory.NewRegistry(memory.Services(test.Data)) - - // create service - fn := NewFunction( - Registry(r), - Name("test.function"), - AfterStart(func() error { - wg.Done() - return nil - }), - ) - - // we can't test fn.Init as it parses the command line - // fn.Init() - - ch := make(chan error, 2) - - go func() { - // run service - ch <- fn.Run() - }() - - // wait for start - wg.Wait() - - // test call debug - req := fn.Client().NewRequest( - "test.function", - "Debug.Health", - new(proto.HealthRequest), - ) - - rsp := new(proto.HealthResponse) - - err := fn.Client().Call(context.TODO(), req, rsp) - if err != nil { - t.Fatal(err) - } - - if rsp.Status != "ok" { - t.Fatalf("function response: %s", rsp.Status) - } - - if err := <-ch; err != nil { - t.Fatal(err) - } -} diff --git a/go.mod b/go.mod index 1132d034..dae152fa 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/micro/go-micro/v2 +module github.com/micro/go-micro/v3 go 1.13 diff --git a/go.sum b/go.sum index 99d13a81..60cf6405 100644 --- a/go.sum +++ b/go.sum @@ -13,6 +13,7 @@ cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiy contrib.go.opencensus.io/exporter/ocagent v0.4.12/go.mod h1:450APlNTSR6FrvC3CTRqYosuDstRB9un7SOx2k/9ckA= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/Azure/azure-sdk-for-go v32.4.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 h1:w+iIsaOQNcT7OZ575w+acHgRric5iCyQh+xv+KJ4HB8= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/Azure/go-autorest/autorest v0.1.0/go.mod h1:AKyIcETwSUFxIcs/Wnq/C+kwCtlEYGUVd7FPNb2slmg= github.com/Azure/go-autorest/autorest v0.5.0/go.mod h1:9HLKlQjVBH6U3oDfsXOeVc56THsLPw1L03yban4xThw= @@ -29,29 +30,37 @@ github.com/Azure/go-autorest/tracing v0.1.0/go.mod h1:ROEEAFwXycQw7Sn3DXNtEedEvd github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5 h1:ygIc8M6trr62pF5DucadTWGdEB4mEyvzi0e2nbcmcyA= github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw= +github.com/Microsoft/hcsshim v0.8.7-0.20191101173118-65519b62243c h1:YMP6olTU903X3gxQJckdmiP8/zkSMq4kN3uipsU9XjU= github.com/Microsoft/hcsshim v0.8.7-0.20191101173118-65519b62243c/go.mod h1:7xhjOwRV2+0HXGmM0jxaEu+ZiXJFoVZOTfL/dmqbrD8= github.com/OpenDNS/vegadns2client v0.0.0-20180418235048-a3fa4a771d87/go.mod h1:iGLljf5n9GjT6kc0HBvyI1nOKnGQbNB66VzSNbK5iks= github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/akamai/AkamaiOPEN-edgegrid-golang v0.9.0/go.mod h1:zpDJeKyp9ScW4NNrbdr+Eyxvry3ilGPewKoXw3XGN1k= +github.com/alangpierce/go-forceexport v0.0.0-20160317203124-8f1d6941cd75 h1:3ILjVyslFbc4jl1w5TWuvvslFD/nDfR2H8tVaMVLrEY= github.com/alangpierce/go-forceexport v0.0.0-20160317203124-8f1d6941cd75/go.mod h1:uAXEEpARkRhCZfEvy/y0Jcc888f9tHCc1W7/UeEtreE= +github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 h1:uSoVVbwJiQipAclBbw+8quDsfcvFjOpI5iCf4p/cqCs= github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/aliyun/alibaba-cloud-sdk-go v0.0.0-20190808125512-07798873deee/go.mod h1:myCDvQSzCW+wB1WAlocEru4wMGJxy+vlxHdhegi1CDQ= github.com/aliyun/aliyun-oss-go-sdk v0.0.0-20190307165228-86c17b95fcd5/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= +github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/aws/aws-sdk-go v1.23.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod h1:AuiFmCCPBSrqvVMvuqFuk0qogytodnVFVSN5CeJB8Gc= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bitly/go-simplejson v0.5.0 h1:6IH+V8/tVMab511d5bn4M7EwGXZf9Hj6i2xSwkNEM+Y= github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngEKAMDJEczWVA= github.com/blang/semver v3.1.0+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= +github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY= github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0= github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA= @@ -78,9 +87,11 @@ github.com/containerd/fifo v0.0.0-20190226154929-a9fb20d87448/go.mod h1:ODA38xgv github.com/containerd/go-runc v0.0.0-20180907222934-5a6d9f37cfa3/go.mod h1:IV7qH3hrUgRmyYrtgEeGWJfWbgcHL9CSRruz2Vqcph0= github.com/containerd/ttrpc v0.0.0-20190828154514-0e0f228740de/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= github.com/containerd/typeurl v0.0.0-20180627222232-a93fcdb778cd/go.mod h1:Cm3kwCdlkCfMSHURc+r6fwoGH6/F1hH3S4sg0rLFWPc= +github.com/coreos/bbolt v1.3.3 h1:n6AiVyVRKQFNb6mJlwESEvvLoDyiTzXX7ORAUlkeBdY= github.com/coreos/bbolt v1.3.3/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.18+incompatible h1:Zz1aXgDrFFi1nadh58tA9ktt06cmPTwNNP3dXwIq1lE= github.com/coreos/etcd v3.3.18+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmfM= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f h1:JOrtw2xFKzlg+cbHpyrpLDmnN1HqhBfnX7WDiW7eG2c= @@ -121,6 +132,7 @@ github.com/evanphx/json-patch/v5 v5.0.0 h1:dKTrUeykyQwKb/kx7Z+4ukDs6l+4L41HqG1XH github.com/evanphx/json-patch/v5 v5.0.0/go.mod h1:G79N1coSVB93tBe7j6PhzjmR3/2VvlbKOFpnXhI9Bw4= github.com/exoscale/egoscale v0.18.1/go.mod h1:Z7OOdzzTOz1Q1PjQXumlz9Wn/CddH0zSYdCF3rnBKXE= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/forestgiant/sliceutil v0.0.0-20160425183142-94783f95db6c h1:pBgVXWDXju1m8W4lnEeIqTHPOzhTUO81a7yknM/xQR4= github.com/forestgiant/sliceutil v0.0.0-20160425183142-94783f95db6c/go.mod h1:pFdJbAhRf7rh6YYMUdIQGyzne6zYL1tCUW8QV2B3UfY= @@ -130,6 +142,7 @@ github.com/fsouza/go-dockerclient v1.6.0 h1:f7j+AX94143JL1H3TiqSMkM4EcLDI0De1qD4 github.com/fsouza/go-dockerclient v1.6.0/go.mod h1:YWwtNPuL4XTX1SKJQk86cWPmmqwx+4np9qfPbb+znGc= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0= github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= github.com/go-acme/lego/v3 v3.4.0 h1:deB9NkelA+TfjGHVw8J7iKl/rMtffcGMWSMmptvMv0A= github.com/go-acme/lego/v3 v3.4.0/go.mod h1:xYbLDuxq3Hy4bMUT1t9JIuz6GWIWb3m5X+TeTHYaT7M= @@ -139,6 +152,7 @@ github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= github.com/go-git/go-billy/v5 v5.0.0 h1:7NQHvd9FVid8VL4qVUMm8XifBK+2xCoZ2lSk0agRrHM= github.com/go-git/go-billy/v5 v5.0.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= +github.com/go-git/go-git-fixtures/v4 v4.0.1 h1:q+IFMfLx200Q3scvt2hN79JsEzy4AmBTp/pqnefH+Bc= github.com/go-git/go-git-fixtures/v4 v4.0.1/go.mod h1:m+ICp2rF3jDhFgEZ/8yziagdT1C+ZpZcrJjappBCDSw= github.com/go-git/go-git/v5 v5.1.0 h1:HxJn9g/E7eYvKW3Fm7Jt4ee8LXfPOm/H1cdDu8vEssk= github.com/go-git/go-git/v5 v5.1.0/go.mod h1:ZKfuPUoY1ZqIG4QG9BDBh3G4gLM5zvPuSJAozQrZuyM= @@ -148,6 +162,7 @@ github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2 github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU= github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= @@ -162,10 +177,13 @@ github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7a github.com/gogo/protobuf v1.2.1 h1:/s5zKNz0uPFCZ5hddgPdo2TK2TVrUNMn0OOX8/aZMTE= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1 h1:qGJ6qTW+x6xX/my+8YUVl4WNpX9B7+/l2tRsHGZ7f2s= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= @@ -180,10 +198,12 @@ github.com/golang/protobuf v1.4.0 h1:oOuy+ugB+P/kBdUnG5QaMXSIyJ1q38wWSojYCb3z5VQ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -206,9 +226,12 @@ github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoA github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grpc-ecosystem/go-grpc-middleware v1.1.0 h1:THDBEeQ9xZ8JEaCLyLQqXMMdRqNr0QAUJTIkQAUtFjg= github.com/grpc-ecosystem/go-grpc-middleware v1.1.0/go.mod h1:f5nM7jw/oeRSadq3xCzHAvxcr8HZnzsqU6ILg/0NiiE= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.8.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.9.5 h1:UImYN5qQ8tuGpGE16ZmjvcTtTw24zw1QAp/SlnNrZhI= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -227,10 +250,12 @@ github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOl github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= @@ -243,6 +268,7 @@ github.com/klauspost/cpuid v1.2.3 h1:CCtW0xUnWGVINKvE/WWOYKdsPV6mawAtvQuSl8guwQs github.com/klauspost/cpuid v1.2.3/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/kolo/xmlrpc v0.0.0-20190717152603-07c4ee3fd181/go.mod h1:o03bZfuBwAXHetKXuInt4S7omeXUu62/A845kiycsSQ= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= @@ -268,6 +294,7 @@ github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-tty v0.0.0-20180219170247-931426f7535a/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/micro/cli/v2 v2.1.2 h1:43J1lChg/rZCC1rvdqZNFSQDrGT7qfMrtp6/ztpIkEM= github.com/micro/cli/v2 v2.1.2/go.mod h1:EguNh6DAoWKm9nmk+k/Rg0H3lQnDxqzu5x5srOtGtYg= @@ -281,8 +308,10 @@ github.com/mitchellh/hashstructure v1.0.0 h1:ZkRJX1CyOoTkar7p/mLS5TZU4nJ1Rn/F8u9 github.com/mitchellh/hashstructure v1.0.0/go.mod h1:QjSHrPWS+BGUVBYkbTZWEnOh3G1DutKwClXU/ABz6AQ= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c h1:nXxl5PrvVm2L/wCy8dQu6DMTwH4oIuGN8GJDAlqDdVE= github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= @@ -290,6 +319,7 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW github.com/namedotcom/go v0.0.0-20180403034216-08470befbe04/go.mod h1:5sN+Lt1CaY4wsPvgQH/jsuJi4XO2ssZbdsIizr4CVC8= github.com/nats-io/jwt v0.3.2 h1:+RB5hMpXUUA2dfxuhBTEkMOrYmM+gKIZYS1KjSostMI= github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU= +github.com/nats-io/nats-server/v2 v2.1.6 h1:qAaHZaS8pRRNQLFaiBA1rq5WynyEGp9DFgmMfoaiXGY= github.com/nats-io/nats-server/v2 v2.1.6/go.mod h1:BL1NOtaBQ5/y97djERRVWNouMW7GT3gxnmbE/eC8u8A= github.com/nats-io/nats.go v1.9.2 h1:oDeERm3NcZVrPpdR/JpGdWHMv3oJ8yY30YwxKq+DU2s= github.com/nats-io/nats.go v1.9.2/go.mod h1:AjGArbfyR50+afOUotNX2Xs5SYHf+CoOa5HH1eEl2HE= @@ -299,6 +329,7 @@ github.com/nats-io/nkeys v0.1.4/go.mod h1:XdZpAbhgyyODYqjTawOnIOI7VlbKSarI9Gfy1t github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nlopes/slack v0.6.1-0.20191106133607-d06c2a2b3249 h1:Pr5gZa2VcmktVwq0lyC39MsN5tz356vC/pQHKvq+QBo= github.com/nlopes/slack v0.6.1-0.20191106133607-d06c2a2b3249/go.mod h1:JzQ9m3PMAqcpeCam7UaHSuBuupz7CmpjehYMayT6YOk= @@ -308,7 +339,9 @@ github.com/nrdcg/goinwx v0.6.1/go.mod h1:XPiut7enlbEdntAqalBIqcYcTEVhpv/dKWgDCX2 github.com/nrdcg/namesilo v0.2.1/go.mod h1:lwMvfQTyYq+BbjJd30ylEG4GPSS6PII0Tia4rRpRiyw= github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= github.com/opencontainers/go-digest v1.0.0-rc1 h1:WzifXhOVOEOuFYOJAW6aQqW0TooG2iki3E3Ii+WN7gQ= @@ -338,18 +371,22 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.1.0 h1:BQ53HtBmfOitExawJ6LokA4x8ov/z0SYYb0+HxJfRI8= github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.6.0 h1:kRhiuYSXR3+uv2IbVbZhUxK5zVD/2pp3Gd2PpvPkpEo= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= +github.com/prometheus/procfs v0.0.5 h1:3+auTFlqw+ZaQYJARz6ArODtkaIwtvBTx3N2NehQlL8= github.com/prometheus/procfs v0.0.5/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= github.com/rainycape/memcache v0.0.0-20150622160815-1031fa0ce2f2/go.mod h1:7tZKcyumwBO6qip7RNQ5r77yrssm9bfCowcLEBcU5IA= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= @@ -370,6 +407,7 @@ github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6Mwd github.com/skratchdot/open-golang v0.0.0-20160302144031-75fb7ed4208c/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/soheilhy/cmux v0.1.4 h1:0HKaf1o97UwFjHH9o5XsHUOF+tqmdA7KEzXLpiyaw0E= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -383,6 +421,7 @@ github.com/technoweenie/multipartstreamer v1.0.1/go.mod h1:jNVxdtShOxzAsukZwTSw6 github.com/teris-io/shortid v0.0.0-20171029131806-771a37caa5cf h1:Z2X3Os7oRzpdJ75iPqWZc0HeJWFYNCvKsfpQwFpRNTA= github.com/teris-io/shortid v0.0.0-20171029131806-771a37caa5cf/go.mod h1:M8agBzgqHIhgj7wEn9/0hJUZcrvt9VY+Ln+S1I5Mha0= github.com/timewasted/linode v0.0.0-20160829202747-37e84520dcf7/go.mod h1:imsgLplxEC/etjIhdr3dNzV3JeT27LbVu5pYWm0JCBY= +github.com/tmc/grpc-websocket-proxy v0.0.0-20200122045848-3419fae592fc h1:yUaosFVTJwnltaHbSNC3i82I92quFs+OFPRl8kNMVwo= github.com/tmc/grpc-websocket-proxy v0.0.0-20200122045848-3419fae592fc/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/transip/gotransip v0.0.0-20190812104329-6d8d9179b66f/go.mod h1:i0f4R4o2HM0m3DZYQWsj6/MEowD57VzoH0v3d7igeFY= github.com/uber-go/atomic v1.3.2/go.mod h1:/Ct5t2lcmbJ4OSe/waGBoaVvVqtO0bmtfVNex1PFV8g= @@ -395,6 +434,7 @@ github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2 github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v0.0.0-20180618132009-1d523034197f/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs= github.com/xeipuuv/gojsonschema v1.1.0/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 h1:eY9dn8+vbi4tKz5Qo6v2eYzo7kUS51QINcR5jNpbZS8= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= go.etcd.io/bbolt v1.3.4 h1:hi1bXHMVrlQh6WwxAy+qZCV/SYIlqo+Ushwdpa4tAKg= go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= @@ -410,6 +450,7 @@ go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/ go.uber.org/multierr v1.3.0 h1:sFPn2GLc3poCkfrpIXGhBD2X0CMIo4Q/zSULXrj/+uc= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/ratelimit v0.0.0-20180316092928-c15da0234277/go.mod h1:2X8KaoNd1J0lZV+PxJk/5+DGbO/tpwLR1m++a7FnB/Y= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee h1:0mgffUl7nfd+FpvXMVz4IDEaUSmT1ysygQC7qYo7sG4= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0 h1:nR6NoDBgAf67s68NhaXbsojM+2gxp3S1hWkHDl27pVU= @@ -445,6 +486,7 @@ golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f h1:J5lckAjkw6qYlOZNj90mLYNTEKDvWeuc1yieZ8qUzUE= golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= @@ -521,6 +563,7 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190921001708-c4c64cad1fd0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -544,9 +587,11 @@ golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361 h1:RIIXAeV6GvDBuADKumTODatUqANFZ+5BPMnzsy4hulY= golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= @@ -589,6 +634,7 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= @@ -612,13 +658,16 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= k8s.io/kubernetes v1.13.0/go.mod h1:ocZa8+6APFNC2tX1DZASIbocyYT5jHzqFVsY5aoB7Jk= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +sigs.k8s.io/yaml v1.1.0 h1:4A07+ZFc2wgJwo8YNlQpr1rVlgUDlxXHhPJciaPY5gs= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= diff --git a/logger/default.go b/logger/default.go index 56c6678c..8f1149f2 100644 --- a/logger/default.go +++ b/logger/default.go @@ -10,7 +10,7 @@ import ( "sync" "time" - dlog "github.com/micro/go-micro/v2/debug/log" + dlog "github.com/micro/go-micro/v3/debug/log" ) func init() { diff --git a/micro.go b/micro.go deleted file mode 100644 index 77be00d0..00000000 --- a/micro.go +++ /dev/null @@ -1,122 +0,0 @@ -// Package micro is a pluggable framework for microservices -package micro - -import ( - "context" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/server" -) - -type serviceKey struct{} - -// Service is an interface that wraps the lower level libraries -// within go-micro. Its a convenience method for building -// and initialising services. -type Service interface { - // The service name - Name() string - // Init initialises options - Init(...Option) - // Options returns the current options - Options() Options - // Client is used to call services - Client() client.Client - // Server is for handling requests and events - Server() server.Server - // Run the service - Run() error - // The service implementation - String() string -} - -// Function is a one time executing Service -type Function interface { - // Inherits Service interface - Service - // Done signals to complete execution - Done() error - // Handle registers an RPC handler - Handle(v interface{}) error - // Subscribe registers a subscriber - Subscribe(topic string, v interface{}) error -} - -/* -// Type Event is a future type for acting on asynchronous events -type Event interface { - // Publish publishes a message to the event topic - Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error - // Subscribe to the event - Subscribe(ctx context.Context, v in -} - -// Resource is a future type for defining dependencies -type Resource interface { - // Name of the resource - Name() string - // Type of resource - Type() string - // Method of creation - Create() error -} -*/ - -// Event is used to publish messages to a topic -type Event interface { - // Publish publishes a message to the event topic - Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error -} - -// Type alias to satisfy the deprecation -type Publisher = Event - -type Option func(*Options) - -var ( - HeaderPrefix = "Micro-" -) - -// NewService creates and returns a new Service based on the packages within. -func NewService(opts ...Option) Service { - return newService(opts...) -} - -// FromContext retrieves a Service from the Context. -func FromContext(ctx context.Context) (Service, bool) { - s, ok := ctx.Value(serviceKey{}).(Service) - return s, ok -} - -// NewContext returns a new Context with the Service embedded within it. -func NewContext(ctx context.Context, s Service) context.Context { - return context.WithValue(ctx, serviceKey{}, s) -} - -// NewFunction returns a new Function for a one time executing Service -func NewFunction(opts ...Option) Function { - return newFunction(opts...) -} - -// NewEvent creates a new event publisher -func NewEvent(topic string, c client.Client) Event { - if c == nil { - c = client.NewClient() - } - return &event{c, topic} -} - -// Deprecated: NewPublisher returns a new Publisher -func NewPublisher(topic string, c client.Client) Event { - return NewEvent(topic, c) -} - -// RegisterHandler is syntactic sugar for registering a handler -func RegisterHandler(s server.Server, h interface{}, opts ...server.HandlerOption) error { - return s.Handle(s.NewHandler(h, opts...)) -} - -// RegisterSubscriber is syntactic sugar for registering a subscriber -func RegisterSubscriber(topic string, s server.Server, h interface{}, opts ...server.SubscriberOption) error { - return s.Subscribe(s.NewSubscriber(topic, h, opts...)) -} diff --git a/model/model.go b/model/model.go index 9921b8df..57b17b1e 100644 --- a/model/model.go +++ b/model/model.go @@ -2,9 +2,9 @@ package model import ( - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/store" - "github.com/micro/go-micro/v2/sync" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/store" + "github.com/micro/go-micro/v3/sync" ) // Model provides an interface for data modelling diff --git a/model/mud/entity.go b/model/mud/entity.go index 03936598..8b286ecd 100644 --- a/model/mud/entity.go +++ b/model/mud/entity.go @@ -2,8 +2,8 @@ package mud import ( "github.com/google/uuid" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/model" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/model" ) type mudEntity struct { diff --git a/model/mud/mud.go b/model/mud/mud.go index a01bc882..46060df6 100644 --- a/model/mud/mud.go +++ b/model/mud/mud.go @@ -2,11 +2,11 @@ package mud import ( - "github.com/micro/go-micro/v2/codec/json" - "github.com/micro/go-micro/v2/model" - "github.com/micro/go-micro/v2/store" - "github.com/micro/go-micro/v2/store/memory" - memsync "github.com/micro/go-micro/v2/sync/memory" + "github.com/micro/go-micro/v3/codec/json" + "github.com/micro/go-micro/v3/model" + "github.com/micro/go-micro/v3/store" + "github.com/micro/go-micro/v3/store/memory" + memsync "github.com/micro/go-micro/v3/sync/memory" ) type mudModel struct { diff --git a/network/default.go b/network/mucp/mucp.go similarity index 87% rename from network/default.go rename to network/mucp/mucp.go index 70ecb88b..d46c3c6b 100644 --- a/network/default.go +++ b/network/mucp/mucp.go @@ -1,4 +1,4 @@ -package network +package mucp import ( "errors" @@ -12,25 +12,41 @@ import ( "time" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/client" - cmucp "github.com/micro/go-micro/v2/client/mucp" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/network/resolver/dns" - pbNet "github.com/micro/go-micro/v2/network/service/proto" - "github.com/micro/go-micro/v2/proxy" - "github.com/micro/go-micro/v2/router" - pbRtr "github.com/micro/go-micro/v2/router/service/proto" - "github.com/micro/go-micro/v2/server" - smucp "github.com/micro/go-micro/v2/server/mucp" - "github.com/micro/go-micro/v2/transport" - "github.com/micro/go-micro/v2/tunnel" - bun "github.com/micro/go-micro/v2/tunnel/broker" - tun "github.com/micro/go-micro/v2/tunnel/transport" - "github.com/micro/go-micro/v2/util/backoff" - pbUtil "github.com/micro/go-micro/v2/util/proto" + "github.com/micro/go-micro/v3/client" + cmucp "github.com/micro/go-micro/v3/client/mucp" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/network" + pb "github.com/micro/go-micro/v3/network/mucp/proto" + "github.com/micro/go-micro/v3/network/resolver/dns" + "github.com/micro/go-micro/v3/proxy" + "github.com/micro/go-micro/v3/router" + "github.com/micro/go-micro/v3/server" + smucp "github.com/micro/go-micro/v3/server/mucp" + "github.com/micro/go-micro/v3/transport" + "github.com/micro/go-micro/v3/tunnel" + bun "github.com/micro/go-micro/v3/tunnel/broker" + tun "github.com/micro/go-micro/v3/tunnel/transport" + "github.com/micro/go-micro/v3/util/backoff" ) var ( + // DefaultName is default network name + DefaultName = "go.micro" + // DefaultAddress is default network address + DefaultAddress = ":0" + // ResolveTime defines time interval to periodically resolve network nodes + ResolveTime = 1 * time.Minute + // AnnounceTime defines time interval to periodically announce node neighbours + AnnounceTime = 1 * time.Second + // KeepAliveTime is the time in which we want to have sent a message to a peer + KeepAliveTime = 30 * time.Second + // SyncTime is the time a network node requests full sync from the network + SyncTime = 1 * time.Minute + // PruneTime defines time interval to periodically check nodes that need to be pruned + // due to their not announcing their presence within this time interval + PruneTime = 90 * time.Second + // MaxDepth defines max depth of peer topology + MaxDepth uint = 3 // NetworkChannel is the name of the tunnel channel for passing network messages NetworkChannel = "network" // ControlChannel is the name of the tunnel channel for passing control message @@ -41,9 +57,10 @@ var ( MaxConnections = 3 // MaxPeerErrors is the max number of peer errors before we remove it from network graph MaxPeerErrors = 3 -) - -var ( + // ErrPeerExists is returned when adding a peer which already exists + ErrPeerExists = errors.New("peer already exists") + // ErrPeerNotFound is returned when a peer could not be found in node topology + ErrPeerNotFound = errors.New("peer not found") // ErrClientNotFound is returned when client for tunnel channel could not be found ErrClientNotFound = errors.New("client not found") // ErrPeerLinkNotFound is returned when peer link could not be found in tunnel Links @@ -53,11 +70,11 @@ var ( ) // network implements Network interface -type network struct { +type mucpNetwork struct { // node is network node *node // options configure the network - options Options + options network.Options // rtr is network router router router.Router // proxy is network proxy @@ -91,10 +108,10 @@ type message struct { session tunnel.Session } -// newNetwork returns a new network node -func newNetwork(opts ...Option) Network { +// NewNetwork returns a new network node +func NewNetwork(opts ...network.Option) network.Network { // create default options - options := DefaultOptions() + options := network.DefaultOptions() // initialize network options for _, o := range opts { o(&options) @@ -155,7 +172,7 @@ func newNetwork(opts ...Option) Network { client.Router(options.Router), ) - network := &network{ + network := &mucpNetwork{ node: &node{ id: options.Id, address: peerAddress, @@ -178,7 +195,7 @@ func newNetwork(opts ...Option) Network { return network } -func (n *network) Init(opts ...Option) error { +func (n *mucpNetwork) Init(opts ...network.Option) error { n.Lock() defer n.Unlock() @@ -191,7 +208,7 @@ func (n *network) Init(opts ...Option) error { } // Options returns network options -func (n *network) Options() Options { +func (n *mucpNetwork) Options() network.Options { n.RLock() defer n.RUnlock() @@ -201,7 +218,7 @@ func (n *network) Options() Options { } // Name returns network name -func (n *network) Name() string { +func (n *mucpNetwork) Name() string { n.RLock() defer n.RUnlock() @@ -211,7 +228,7 @@ func (n *network) Name() string { } // acceptNetConn accepts connections from NetworkChannel -func (n *network) acceptNetConn(l tunnel.Listener, recv chan *message) { +func (n *mucpNetwork) acceptNetConn(l tunnel.Listener, recv chan *message) { var i int for { // accept a connection @@ -238,7 +255,7 @@ func (n *network) acceptNetConn(l tunnel.Listener, recv chan *message) { } // acceptCtrlConn accepts connections from ControlChannel -func (n *network) acceptCtrlConn(l tunnel.Listener, recv chan *message) { +func (n *mucpNetwork) acceptCtrlConn(l tunnel.Listener, recv chan *message) { var i int for { // accept a connection @@ -269,7 +286,7 @@ func (n *network) acceptCtrlConn(l tunnel.Listener, recv chan *message) { } // maskRoute will mask the route so that we apply the right values -func (n *network) maskRoute(r *pbRtr.Route) { +func (n *mucpNetwork) maskRoute(r *pb.Route) { hasher := fnv.New64() // the routes service address address := r.Address @@ -297,18 +314,18 @@ func (n *network) maskRoute(r *pbRtr.Route) { } // advertise advertises routes to the network -func (n *network) advertise(advertChan <-chan *router.Advert) { +func (n *mucpNetwork) advertise(advertChan <-chan *router.Advert) { rnd := rand.New(rand.NewSource(time.Now().UnixNano())) for { select { // process local adverts and randomly fire them at other nodes case advert := <-advertChan: // create a proto advert - var events []*pbRtr.Event + var events []*pb.Event for _, event := range advert.Events { // make a copy of the route - route := &pbRtr.Route{ + route := &pb.Route{ Service: event.Route.Service, Address: event.Route.Address, Gateway: event.Route.Gateway, @@ -321,8 +338,8 @@ func (n *network) advertise(advertChan <-chan *router.Advert) { // override the various values n.maskRoute(route) - e := &pbRtr.Event{ - Type: pbRtr.EventType(event.Type), + e := &pb.Event{ + Type: pb.EventType(event.Type), Timestamp: event.Timestamp.UnixNano(), Route: route, } @@ -330,9 +347,9 @@ func (n *network) advertise(advertChan <-chan *router.Advert) { events = append(events, e) } - msg := &pbRtr.Advert{ + msg := &pb.Advert{ Id: advert.Id, - Type: pbRtr.AdvertType(advert.Type), + Type: pb.AdvertType(advert.Type), Timestamp: advert.Timestamp.UnixNano(), Events: events, } @@ -367,7 +384,7 @@ func (n *network) advertise(advertChan <-chan *router.Advert) { } // initNodes initializes tunnel with a list of resolved nodes -func (n *network) initNodes(startup bool) { +func (n *mucpNetwork) initNodes(startup bool) { nodes, err := n.resolveNodes() // NOTE: this condition never fires // as resolveNodes() never returns error @@ -404,7 +421,7 @@ func (n *network) initNodes(startup bool) { } // resolveNodes resolves network nodes to addresses -func (n *network) resolveNodes() ([]string, error) { +func (n *mucpNetwork) resolveNodes() ([]string, error) { // resolve the network address to network nodes records, err := n.options.Resolver.Resolve(n.options.Name) if err != nil { @@ -469,7 +486,7 @@ func (n *network) resolveNodes() ([]string, error) { } // handleNetConn handles network announcement messages -func (n *network) handleNetConn(s tunnel.Session, msg chan *message) { +func (n *mucpNetwork) handleNetConn(s tunnel.Session, msg chan *message) { for { m := new(transport.Message) if err := s.Recv(m); err != nil { @@ -504,7 +521,7 @@ func (n *network) handleNetConn(s tunnel.Session, msg chan *message) { } // handleCtrlConn handles ControlChannel connections -func (n *network) handleCtrlConn(s tunnel.Session, msg chan *message) { +func (n *mucpNetwork) handleCtrlConn(s tunnel.Session, msg chan *message) { for { m := new(transport.Message) if err := s.Recv(m); err != nil { @@ -544,7 +561,7 @@ func (n *network) handleCtrlConn(s tunnel.Session, msg chan *message) { // - Routes with ID of adjacent nodes have hop count 10 // - Routes by peers of the advertiser have hop count 100 // - Routes beyond node neighbourhood have hop count 1000 -func (n *network) getHopCount(rtr string) int { +func (n *mucpNetwork) getHopCount(rtr string) int { // make sure node.peers are not modified n.node.RLock() defer n.node.RUnlock() @@ -573,7 +590,7 @@ func (n *network) getHopCount(rtr string) int { // getRouteMetric calculates router metric and returns it // Route metric is calculated based on link status and route hopd count -func (n *network) getRouteMetric(router string, gateway string, link string) int64 { +func (n *mucpNetwork) getRouteMetric(router string, gateway string, link string) int64 { // set the route metric n.RLock() defer n.RUnlock() @@ -628,7 +645,7 @@ func (n *network) getRouteMetric(router string, gateway string, link string) int } // processCtrlChan processes messages received on ControlChannel -func (n *network) processCtrlChan(listener tunnel.Listener) { +func (n *mucpNetwork) processCtrlChan(listener tunnel.Listener) { defer listener.Close() // receive control message queue @@ -643,9 +660,9 @@ func (n *network) processCtrlChan(listener tunnel.Listener) { // switch on type of message and take action switch m.msg.Header["Micro-Method"] { case "advert": - pbRtrAdvert := &pbRtr.Advert{} + pbAdvert := &pb.Advert{} - if err := proto.Unmarshal(m.msg.Body, pbRtrAdvert); err != nil { + if err := proto.Unmarshal(m.msg.Body, pbAdvert); err != nil { if logger.V(logger.DebugLevel, logger.DefaultLogger) { logger.Debugf("Network fail to unmarshal advert message: %v", err) } @@ -653,38 +670,38 @@ func (n *network) processCtrlChan(listener tunnel.Listener) { } // don't process your own messages - if pbRtrAdvert.Id == n.options.Id { + if pbAdvert.Id == n.options.Id { continue } if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Network received advert message from: %s", pbRtrAdvert.Id) + logger.Debugf("Network received advert message from: %s", pbAdvert.Id) } // lookup advertising node in our peer topology - advertNode := n.node.GetPeerNode(pbRtrAdvert.Id) + advertNode := n.node.GetPeerNode(pbAdvert.Id) if advertNode == nil { // if we can't find the node in our topology (MaxDepth) we skipp prcessing adverts if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Network skipping advert message from unknown peer: %s", pbRtrAdvert.Id) + logger.Debugf("Network skipping advert message from unknown peer: %s", pbAdvert.Id) } continue } var events []*router.Event - for _, event := range pbRtrAdvert.Events { + for _, event := range pbAdvert.Events { // for backwards compatibility reasons if event == nil || event.Route == nil { continue } // we know the advertising node is not the origin of the route - if pbRtrAdvert.Id != event.Route.Router { + if pbAdvert.Id != event.Route.Router { // if the origin router is not the advertising node peer // we can't rule out potential routing loops so we bail here if peer := advertNode.GetPeerNode(event.Route.Router); peer == nil { if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Network skipping advert message from peer: %s", pbRtrAdvert.Id) + logger.Debugf("Network skipping advert message from peer: %s", pbAdvert.Id) } continue } @@ -719,7 +736,7 @@ func (n *network) processCtrlChan(listener tunnel.Listener) { // create router event e := &router.Event{ Type: router.EventType(event.Type), - Timestamp: time.Unix(0, pbRtrAdvert.Timestamp), + Timestamp: time.Unix(0, pbAdvert.Timestamp), Route: route, } events = append(events, e) @@ -735,10 +752,10 @@ func (n *network) processCtrlChan(listener tunnel.Listener) { // create an advert and process it advert := &router.Advert{ - Id: pbRtrAdvert.Id, - Type: router.AdvertType(pbRtrAdvert.Type), - Timestamp: time.Unix(0, pbRtrAdvert.Timestamp), - TTL: time.Duration(pbRtrAdvert.Ttl), + Id: pbAdvert.Id, + Type: router.AdvertType(pbAdvert.Type), + Timestamp: time.Unix(0, pbAdvert.Timestamp), + TTL: time.Duration(pbAdvert.Ttl), Events: events, } @@ -758,7 +775,7 @@ func (n *network) processCtrlChan(listener tunnel.Listener) { } // processNetChan processes messages received on NetworkChannel -func (n *network) processNetChan(listener tunnel.Listener) { +func (n *mucpNetwork) processNetChan(listener tunnel.Listener) { defer listener.Close() // receive network message queue @@ -776,22 +793,22 @@ func (n *network) processNetChan(listener tunnel.Listener) { // mark the time the message has been received now := time.Now() - pbNetConnect := &pbNet.Connect{} - if err := proto.Unmarshal(m.msg.Body, pbNetConnect); err != nil { + pbConnect := &pb.Connect{} + if err := proto.Unmarshal(m.msg.Body, pbConnect); err != nil { logger.Debugf("Network tunnel [%s] connect unmarshal error: %v", NetworkChannel, err) continue } // don't process your own messages - if pbNetConnect.Node.Id == n.options.Id { + if pbConnect.Node.Id == n.options.Id { continue } - logger.Debugf("Network received connect message from: %s", pbNetConnect.Node.Id) + logger.Debugf("Network received connect message from: %s", pbConnect.Node.Id) peer := &node{ - id: pbNetConnect.Node.Id, - address: pbNetConnect.Node.Address, + id: pbConnect.Node.Id, + address: pbConnect.Node.Address, link: m.msg.Header["Micro-Link"], peers: make(map[string]*node), status: newStatus(), @@ -824,7 +841,7 @@ func (n *network) processNetChan(listener tunnel.Listener) { // get node peer graph to send back to the connecting node node := PeersToProto(n.node, MaxDepth) - msg := &pbNet.Sync{ + msg := &pb.Sync{ Peer: node, } @@ -844,26 +861,26 @@ func (n *network) processNetChan(listener tunnel.Listener) { case "peer": // mark the time the message has been received now := time.Now() - pbNetPeer := &pbNet.Peer{} + pbPeer := &pb.Peer{} - if err := proto.Unmarshal(m.msg.Body, pbNetPeer); err != nil { + if err := proto.Unmarshal(m.msg.Body, pbPeer); err != nil { logger.Debugf("Network tunnel [%s] peer unmarshal error: %v", NetworkChannel, err) continue } // don't process your own messages - if pbNetPeer.Node.Id == n.options.Id { + if pbPeer.Node.Id == n.options.Id { continue } - logger.Debugf("Network received peer message from: %s %s", pbNetPeer.Node.Id, pbNetPeer.Node.Address) + logger.Debugf("Network received peer message from: %s %s", pbPeer.Node.Id, pbPeer.Node.Address) peer := &node{ - id: pbNetPeer.Node.Id, - address: pbNetPeer.Node.Address, + id: pbPeer.Node.Id, + address: pbPeer.Node.Address, link: m.msg.Header["Micro-Link"], peers: make(map[string]*node), - status: newPeerStatus(pbNetPeer), + status: newPeerStatus(pbPeer), lastSeen: now, } @@ -881,7 +898,7 @@ func (n *network) processNetChan(listener tunnel.Listener) { // marshal node graph into protobuf node := PeersToProto(n.node, MaxDepth) - msg := &pbNet.Sync{ + msg := &pb.Sync{ Peer: node, } @@ -906,15 +923,15 @@ func (n *network) processNetChan(listener tunnel.Listener) { continue } - logger.Tracef("Network peer exists, refreshing: %s", pbNetPeer.Node.Id) + logger.Tracef("Network peer exists, refreshing: %s", pbPeer.Node.Id) // update lastSeen time for the peer if err := n.RefreshPeer(peer.id, peer.link, now); err != nil { - logger.Debugf("Network failed refreshing peer %s: %v", pbNetPeer.Node.Id, err) + logger.Debugf("Network failed refreshing peer %s: %v", pbPeer.Node.Id, err) } // NOTE: we don't unpack MaxDepth topology - peer = UnpackPeerTopology(pbNetPeer, now, MaxDepth-1) + peer = UnpackPeerTopology(pbPeer, now, MaxDepth-1) // update the link peer.link = m.msg.Header["Micro-Link"] @@ -934,25 +951,25 @@ func (n *network) processNetChan(listener tunnel.Listener) { // record the timestamp of the message receipt now := time.Now() - pbNetSync := &pbNet.Sync{} - if err := proto.Unmarshal(m.msg.Body, pbNetSync); err != nil { + pbSync := &pb.Sync{} + if err := proto.Unmarshal(m.msg.Body, pbSync); err != nil { logger.Debugf("Network tunnel [%s] sync unmarshal error: %v", NetworkChannel, err) continue } // don't process your own messages - if pbNetSync.Peer.Node.Id == n.options.Id { + if pbSync.Peer.Node.Id == n.options.Id { continue } - logger.Debugf("Network received sync message from: %s", pbNetSync.Peer.Node.Id) + logger.Debugf("Network received sync message from: %s", pbSync.Peer.Node.Id) peer := &node{ - id: pbNetSync.Peer.Node.Id, - address: pbNetSync.Peer.Node.Address, + id: pbSync.Peer.Node.Id, + address: pbSync.Peer.Node.Address, link: m.msg.Header["Micro-Link"], peers: make(map[string]*node), - status: newPeerStatus(pbNetSync.Peer), + status: newPeerStatus(pbSync.Peer), lastSeen: now, } @@ -983,9 +1000,9 @@ func (n *network) processNetChan(listener tunnel.Listener) { // and send a peer message back to the network to announce our presence // add all the routes we have received in the sync message - for _, pbRoute := range pbNetSync.Routes { + for _, pbRoute := range pbSync.Routes { // unmarshal the routes received from remote peer - route := pbUtil.ProtoToRoute(pbRoute) + route := ProtoToRoute(pbRoute) // continue if we are the originator of the route if route.Router == n.router.Options().Id { if logger.V(logger.DebugLevel, logger.DefaultLogger) { @@ -1079,8 +1096,8 @@ func (n *network) processNetChan(listener tunnel.Listener) { } }() case "close": - pbNetClose := &pbNet.Close{} - if err := proto.Unmarshal(m.msg.Body, pbNetClose); err != nil { + pbClose := &pb.Close{} + if err := proto.Unmarshal(m.msg.Body, pbClose); err != nil { if logger.V(logger.DebugLevel, logger.DefaultLogger) { logger.Debugf("Network tunnel [%s] close unmarshal error: %v", NetworkChannel, err) } @@ -1088,17 +1105,17 @@ func (n *network) processNetChan(listener tunnel.Listener) { } // don't process your own messages - if pbNetClose.Node.Id == n.options.Id { + if pbClose.Node.Id == n.options.Id { continue } if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Network received close message from: %s", pbNetClose.Node.Id) + logger.Debugf("Network received close message from: %s", pbClose.Node.Id) } peer := &node{ - id: pbNetClose.Node.Id, - address: pbNetClose.Node.Address, + id: pbClose.Node.Id, + address: pbClose.Node.Address, } if err := n.DeletePeerNode(peer.id); err != nil { @@ -1118,7 +1135,7 @@ func (n *network) processNetChan(listener tunnel.Listener) { // delete peer from the peerLinks n.Lock() - delete(n.peerLinks, pbNetClose.Node.Address) + delete(n.peerLinks, pbClose.Node.Address) n.Unlock() } case <-n.closed: @@ -1128,7 +1145,7 @@ func (n *network) processNetChan(listener tunnel.Listener) { } // pruneRoutes prunes routes return by given query -func (n *network) pruneRoutes(q ...router.QueryOption) error { +func (n *mucpNetwork) pruneRoutes(q ...router.QueryOption) error { routes, err := n.router.Table().Query(q...) if err != nil && err != router.ErrRouteNotFound { return err @@ -1144,7 +1161,7 @@ func (n *network) pruneRoutes(q ...router.QueryOption) error { } // pruneNodeRoutes prunes routes that were either originated by or routable via given node -func (n *network) prunePeerRoutes(peer *node) error { +func (n *mucpNetwork) prunePeerRoutes(peer *node) error { // lookup all routes originated by router q := []router.QueryOption{ router.QueryRouter(peer.id), @@ -1167,7 +1184,7 @@ func (n *network) prunePeerRoutes(peer *node) error { // manage the process of announcing to peers and prune any peer nodes that have not been // seen for a period of time. Also removes all the routes either originated by or routable // by the stale nodes. it also resolves nodes periodically and adds them to the tunnel -func (n *network) manage() { +func (n *mucpNetwork) manage() { rnd := rand.New(rand.NewSource(time.Now().UnixNano())) announce := time.NewTicker(AnnounceTime) defer announce.Stop() @@ -1360,7 +1377,7 @@ func (n *network) manage() { // get node peer graph to send back to the connecting node node := PeersToProto(n.node, MaxDepth) - msg := &pbNet.Sync{ + msg := &pb.Sync{ Peer: node, } @@ -1390,7 +1407,7 @@ func (n *network) manage() { // getAdvertProtoRoutes returns a list of routes to advertise to remote peer // based on the advertisement strategy encoded in protobuf // It returns error if the routes failed to be retrieved from the routing table -func (n *network) getProtoRoutes() ([]*pbRtr.Route, error) { +func (n *mucpNetwork) getProtoRoutes() ([]*pb.Route, error) { // get a list of the best routes for each service in our routing table q := []router.QueryOption{ router.QueryStrategy(n.router.Options().Advertise), @@ -1402,10 +1419,10 @@ func (n *network) getProtoRoutes() ([]*pbRtr.Route, error) { } // encode the routes to protobuf - pbRoutes := make([]*pbRtr.Route, 0, len(routes)) + pbRoutes := make([]*pb.Route, 0, len(routes)) for _, route := range routes { // generate new route proto - pbRoute := pbUtil.RouteToProto(route) + pbRoute := RouteToProto(route) // mask the route before outbounding n.maskRoute(pbRoute) // add to list of routes @@ -1415,13 +1432,13 @@ func (n *network) getProtoRoutes() ([]*pbRtr.Route, error) { return pbRoutes, nil } -func (n *network) sendConnect() { +func (n *mucpNetwork) sendConnect() { // send connect message to NetworkChannel // NOTE: in theory we could do this as soon as // Dial to NetworkChannel succeeds, but instead // we initialize all other node resources first - msg := &pbNet.Connect{ - Node: &pbNet.Node{ + msg := &pb.Connect{ + Node: &pb.Node{ Id: n.node.id, Address: n.node.address, }, @@ -1437,7 +1454,7 @@ func (n *network) sendConnect() { // sendTo sends a message to a specific node as a one off. // we need this because when links die, we have no discovery info, // and sending to an existing multicast link doesn't immediately work -func (n *network) sendTo(method, channel string, peer *node, msg proto.Message) error { +func (n *mucpNetwork) sendTo(method, channel string, peer *node, msg proto.Message) error { body, err := proto.Marshal(msg) if err != nil { return err @@ -1509,7 +1526,7 @@ func (n *network) sendTo(method, channel string, peer *node, msg proto.Message) } // sendMsg sends a message to the tunnel channel -func (n *network) sendMsg(method, channel string, msg proto.Message) error { +func (n *mucpNetwork) sendMsg(method, channel string, msg proto.Message) error { body, err := proto.Marshal(msg) if err != nil { return err @@ -1537,7 +1554,7 @@ func (n *network) sendMsg(method, channel string, msg proto.Message) error { } // updatePeerLinks updates link for a given peer -func (n *network) updatePeerLinks(peer *node) error { +func (n *mucpNetwork) updatePeerLinks(peer *node) error { n.Lock() defer n.Unlock() @@ -1582,7 +1599,7 @@ func (n *network) updatePeerLinks(peer *node) error { } // isLoopback checks if a link is a loopback to ourselves -func (n *network) isLoopback(link tunnel.Link) bool { +func (n *mucpNetwork) isLoopback(link tunnel.Link) bool { // skip loopback if link.Loopback() { return true @@ -1606,7 +1623,7 @@ func (n *network) isLoopback(link tunnel.Link) bool { // message. We're trying to ensure convergence pretty quickly. So we want // to hear back. In the case we become completely disconnected we'll // connect again once a new link is established -func (n *network) connect() { +func (n *mucpNetwork) connect() { // discovered lets us know what we received a peer message back var discovered bool var attempts int @@ -1671,7 +1688,7 @@ func (n *network) connect() { } // Connect connects the network -func (n *network) Connect() error { +func (n *mucpNetwork) Connect() error { n.Lock() defer n.Unlock() @@ -1769,7 +1786,7 @@ func (n *network) Connect() error { return nil } -func (n *network) close() error { +func (n *mucpNetwork) close() error { // stop the server if err := n.server.Stop(); err != nil { return err @@ -1789,7 +1806,7 @@ func (n *network) close() error { } // createClients is used to create new clients in the event we lose all the tunnels -func (n *network) createClients() error { +func (n *mucpNetwork) createClients() error { // dial into ControlChannel to send route adverts ctrlClient, err := n.tunnel.Dial(ControlChannel, tunnel.DialMode(tunnel.Multicast)) if err != nil { @@ -1823,7 +1840,7 @@ func (n *network) createClients() error { } // Close closes network connection -func (n *network) Close() error { +func (n *mucpNetwork) Close() error { n.Lock() if !n.connected { @@ -1844,8 +1861,8 @@ func (n *network) Close() error { // unlock the lock otherwise we'll deadlock sending the close n.Unlock() - msg := &pbNet.Close{ - Node: &pbNet.Node{ + msg := &pb.Close{ + Node: &pb.Node{ Id: n.node.id, Address: n.node.address, }, @@ -1863,11 +1880,37 @@ func (n *network) Close() error { } // Client returns network client -func (n *network) Client() client.Client { +func (n *mucpNetwork) Client() client.Client { return n.client } // Server returns network server -func (n *network) Server() server.Server { +func (n *mucpNetwork) Server() server.Server { return n.server } + +// RouteToProto encodes route into protobuf and returns it +func RouteToProto(route router.Route) *pb.Route { + return &pb.Route{ + Service: route.Service, + Address: route.Address, + Gateway: route.Gateway, + Network: route.Network, + Router: route.Router, + Link: route.Link, + Metric: int64(route.Metric), + } +} + +// ProtoToRoute decodes protobuf route into router route and returns it +func ProtoToRoute(route *pb.Route) router.Route { + return router.Route{ + Service: route.Service, + Address: route.Address, + Gateway: route.Gateway, + Network: route.Network, + Router: route.Router, + Link: route.Link, + Metric: route.Metric, + } +} diff --git a/network/node.go b/network/mucp/node.go similarity index 93% rename from network/node.go rename to network/mucp/node.go index a6101994..0231dfc7 100644 --- a/network/node.go +++ b/network/mucp/node.go @@ -1,4 +1,4 @@ -package network +package mucp import ( "container/list" @@ -6,19 +6,8 @@ import ( "sync" "time" - pb "github.com/micro/go-micro/v2/network/service/proto" -) - -var ( - // MaxDepth defines max depth of peer topology - MaxDepth uint = 3 -) - -var ( - // ErrPeerExists is returned when adding a peer which already exists - ErrPeerExists = errors.New("peer already exists") - // ErrPeerNotFound is returned when a peer could not be found in node topology - ErrPeerNotFound = errors.New("peer not found") + "github.com/micro/go-micro/v3/network" + pb "github.com/micro/go-micro/v3/network/mucp/proto" ) // nodeError tracks node errors @@ -88,7 +77,7 @@ func newPeerStatus(peer *pb.Peer) *status { return status } -func (s *status) Error() Error { +func (s *status) Error() network.Error { s.RLock() defer s.RUnlock() @@ -110,7 +99,7 @@ type node struct { // peers are nodes with direct link to this node peers map[string]*node // network returns the node network - network Network + network network.Network // lastSeen keeps track of node lifetime and updates lastSeen time.Time // lastSync keeps track of node last sync request @@ -130,12 +119,12 @@ func (n *node) Address() string { } // Network returns node network -func (n *node) Network() Network { +func (n *node) Network() network.Network { return n.network } // Status returns node status -func (n *node) Status() Status { +func (n *node) Status() network.Status { n.RLock() defer n.RUnlock() @@ -272,7 +261,7 @@ func (n *node) RefreshSync(now time.Time) error { } // Nodes returns a slice of all nodes in the whole node topology -func (n *node) Nodes() []Node { +func (n *node) Nodes() []network.Node { // we need to freeze the network graph here // otherwise we might get inconsistent results n.RLock() @@ -286,7 +275,7 @@ func (n *node) Nodes() []Node { visited := n.walk(untilNoMorePeers, justWalk) - nodes := make([]Node, 0, len(visited)) + nodes := make([]network.Node, 0, len(visited)) // collect all the nodes and return them for _, node := range visited { nodes = append(nodes, node) @@ -425,11 +414,11 @@ func (n *node) Topology(depth uint) *node { } // Peers returns node peers up to MaxDepth -func (n *node) Peers() []Node { +func (n *node) Peers() []network.Node { n.RLock() defer n.RUnlock() - peers := make([]Node, 0, len(n.peers)) + peers := make([]network.Node, 0, len(n.peers)) for _, nodePeer := range n.peers { peer := nodePeer.getTopology(MaxDepth) peers = append(peers, peer) @@ -467,7 +456,7 @@ func UnpackPeerTopology(pbPeer *pb.Peer, lastSeen time.Time, depth uint) *node { return peerNode } -func peerProtoTopology(peer Node, depth uint) *pb.Peer { +func peerProtoTopology(peer network.Node, depth uint) *pb.Peer { node := &pb.Node{ Id: peer.Id(), Address: peer.Address(), @@ -507,7 +496,7 @@ func peerProtoTopology(peer Node, depth uint) *pb.Peer { } // PeersToProto returns node peers graph encoded into protobuf -func PeersToProto(node Node, depth uint) *pb.Peer { +func PeersToProto(node network.Node, depth uint) *pb.Peer { // network node aka root node pbNode := &pb.Node{ Id: node.Id(), diff --git a/network/node_test.go b/network/mucp/node_test.go similarity index 95% rename from network/node_test.go rename to network/mucp/node_test.go index d256e3f8..3b805e34 100644 --- a/network/node_test.go +++ b/network/mucp/node_test.go @@ -1,10 +1,11 @@ -package network +package mucp import ( "testing" "time" - pb "github.com/micro/go-micro/v2/network/service/proto" + "github.com/micro/go-micro/v3/network" + pb "github.com/micro/go-micro/v3/network/mucp/proto" ) var ( @@ -20,7 +21,7 @@ func testSetup() *node { id: testNodeId, address: testNodeAddress, peers: make(map[string]*node), - network: newNetwork(Name(testNodeNetName)), + network: NewNetwork(network.Name(testNodeNetName)), status: newStatus(), } @@ -81,7 +82,7 @@ func TestNodes(t *testing.T) { id: testNodeId, address: testNodeAddress, peers: make(map[string]*node), - network: newNetwork(Name(testNodeNetName)), + network: NewNetwork(network.Name(testNodeNetName)), } // get all the nodes including yourself nodes := single.Nodes() @@ -128,7 +129,7 @@ func TestNodes(t *testing.T) { } } -func collectPeerIds(peer Node, ids map[string]bool) map[string]bool { +func collectPeerIds(peer network.Node, ids map[string]bool) map[string]bool { if len(peer.Peers()) == 0 { return ids } @@ -150,7 +151,7 @@ func TestPeers(t *testing.T) { id: testNodeId, address: testNodeAddress, peers: make(map[string]*node), - network: newNetwork(Name(testNodeNetName)), + network: NewNetwork(network.Name(testNodeNetName)), } // get node peers peers := single.Peers() @@ -338,7 +339,7 @@ func TestPeersToProto(t *testing.T) { id: testNodeId, address: testNodeAddress, peers: make(map[string]*node), - network: newNetwork(Name(testNodeNetName)), + network: NewNetwork(network.Name(testNodeNetName)), status: newStatus(), } topCount := 0 diff --git a/network/mucp/proto/network.pb.go b/network/mucp/proto/network.pb.go new file mode 100644 index 00000000..2d3cba5c --- /dev/null +++ b/network/mucp/proto/network.pb.go @@ -0,0 +1,1102 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.11.4 +// source: github.com/micro/go-micro/network/mucp/proto/network.proto + +package go_micro_network_mucp + +import ( + proto "github.com/golang/protobuf/proto" + 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) +) + +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + +// AdvertType defines the type of advert +type AdvertType int32 + +const ( + AdvertType_AdvertAnnounce AdvertType = 0 + AdvertType_AdvertUpdate AdvertType = 1 +) + +// Enum value maps for AdvertType. +var ( + AdvertType_name = map[int32]string{ + 0: "AdvertAnnounce", + 1: "AdvertUpdate", + } + AdvertType_value = map[string]int32{ + "AdvertAnnounce": 0, + "AdvertUpdate": 1, + } +) + +func (x AdvertType) Enum() *AdvertType { + p := new(AdvertType) + *p = x + return p +} + +func (x AdvertType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (AdvertType) Descriptor() protoreflect.EnumDescriptor { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_enumTypes[0].Descriptor() +} + +func (AdvertType) Type() protoreflect.EnumType { + return &file_github_com_micro_go_micro_network_mucp_proto_network_proto_enumTypes[0] +} + +func (x AdvertType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use AdvertType.Descriptor instead. +func (AdvertType) EnumDescriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{0} +} + +// EventType defines the type of event +type EventType int32 + +const ( + EventType_Create EventType = 0 + EventType_Delete EventType = 1 + EventType_Update EventType = 2 +) + +// Enum value maps for EventType. +var ( + EventType_name = map[int32]string{ + 0: "Create", + 1: "Delete", + 2: "Update", + } + EventType_value = map[string]int32{ + "Create": 0, + "Delete": 1, + "Update": 2, + } +) + +func (x EventType) Enum() *EventType { + p := new(EventType) + *p = x + return p +} + +func (x EventType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (EventType) Descriptor() protoreflect.EnumDescriptor { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_enumTypes[1].Descriptor() +} + +func (EventType) Type() protoreflect.EnumType { + return &file_github_com_micro_go_micro_network_mucp_proto_network_proto_enumTypes[1] +} + +func (x EventType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use EventType.Descriptor instead. +func (EventType) EnumDescriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{1} +} + +// Advert is router advertsement streamed by Watch +type Advert struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // id of the advertising router + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + // type of advertisement + Type AdvertType `protobuf:"varint,2,opt,name=type,proto3,enum=go.micro.network.mucp.AdvertType" json:"type,omitempty"` + // unix timestamp of the advertisement + Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + // TTL of the Advert + Ttl int64 `protobuf:"varint,4,opt,name=ttl,proto3" json:"ttl,omitempty"` + // events is a list of advertised events + Events []*Event `protobuf:"bytes,5,rep,name=events,proto3" json:"events,omitempty"` +} + +func (x *Advert) Reset() { + *x = Advert{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Advert) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Advert) ProtoMessage() {} + +func (x *Advert) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Advert.ProtoReflect.Descriptor instead. +func (*Advert) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{0} +} + +func (x *Advert) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *Advert) GetType() AdvertType { + if x != nil { + return x.Type + } + return AdvertType_AdvertAnnounce +} + +func (x *Advert) GetTimestamp() int64 { + if x != nil { + return x.Timestamp + } + return 0 +} + +func (x *Advert) GetTtl() int64 { + if x != nil { + return x.Ttl + } + return 0 +} + +func (x *Advert) GetEvents() []*Event { + if x != nil { + return x.Events + } + return nil +} + +// Event is routing table event +type Event struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // the unique event id + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + // type of event + Type EventType `protobuf:"varint,2,opt,name=type,proto3,enum=go.micro.network.mucp.EventType" json:"type,omitempty"` + // unix timestamp of event + Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + // service route + Route *Route `protobuf:"bytes,4,opt,name=route,proto3" json:"route,omitempty"` +} + +func (x *Event) Reset() { + *x = Event{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Event) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Event) ProtoMessage() {} + +func (x *Event) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Event.ProtoReflect.Descriptor instead. +func (*Event) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{1} +} + +func (x *Event) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *Event) GetType() EventType { + if x != nil { + return x.Type + } + return EventType_Create +} + +func (x *Event) GetTimestamp() int64 { + if x != nil { + return x.Timestamp + } + return 0 +} + +func (x *Event) GetRoute() *Route { + if x != nil { + return x.Route + } + return nil +} + +// Route is a service route +type Route struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // service for the route + Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` + // the address that advertise this route + Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` + // gateway as the next hop + Gateway string `protobuf:"bytes,3,opt,name=gateway,proto3" json:"gateway,omitempty"` + // the network for this destination + Network string `protobuf:"bytes,4,opt,name=network,proto3" json:"network,omitempty"` + // router if the router id + Router string `protobuf:"bytes,5,opt,name=router,proto3" json:"router,omitempty"` + // the network link + Link string `protobuf:"bytes,6,opt,name=link,proto3" json:"link,omitempty"` + // the metric / score of this route + Metric int64 `protobuf:"varint,7,opt,name=metric,proto3" json:"metric,omitempty"` + // metadata for the route + Metadata map[string]string `protobuf:"bytes,8,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` +} + +func (x *Route) Reset() { + *x = Route{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Route) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Route) ProtoMessage() {} + +func (x *Route) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Route.ProtoReflect.Descriptor instead. +func (*Route) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{2} +} + +func (x *Route) GetService() string { + if x != nil { + return x.Service + } + return "" +} + +func (x *Route) GetAddress() string { + if x != nil { + return x.Address + } + return "" +} + +func (x *Route) GetGateway() string { + if x != nil { + return x.Gateway + } + return "" +} + +func (x *Route) GetNetwork() string { + if x != nil { + return x.Network + } + return "" +} + +func (x *Route) GetRouter() string { + if x != nil { + return x.Router + } + return "" +} + +func (x *Route) GetLink() string { + if x != nil { + return x.Link + } + return "" +} + +func (x *Route) GetMetric() int64 { + if x != nil { + return x.Metric + } + return 0 +} + +func (x *Route) GetMetadata() map[string]string { + if x != nil { + return x.Metadata + } + return nil +} + +// Error tracks network errors +type Error struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Count uint32 `protobuf:"varint,1,opt,name=count,proto3" json:"count,omitempty"` + Msg string `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"` +} + +func (x *Error) Reset() { + *x = Error{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Error) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Error) ProtoMessage() {} + +func (x *Error) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Error.ProtoReflect.Descriptor instead. +func (*Error) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{3} +} + +func (x *Error) GetCount() uint32 { + if x != nil { + return x.Count + } + return 0 +} + +func (x *Error) GetMsg() string { + if x != nil { + return x.Msg + } + return "" +} + +// Status is node status +type Status struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Error *Error `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` +} + +func (x *Status) Reset() { + *x = Status{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Status) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Status) ProtoMessage() {} + +func (x *Status) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Status.ProtoReflect.Descriptor instead. +func (*Status) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{4} +} + +func (x *Status) GetError() *Error { + if x != nil { + return x.Error + } + return nil +} + +// Node is network node +type Node struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // node id + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + // node address + Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` + // the network + Network string `protobuf:"bytes,3,opt,name=network,proto3" json:"network,omitempty"` + // associated metadata + Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + // node status + Status *Status `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` +} + +func (x *Node) Reset() { + *x = Node{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Node) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Node) ProtoMessage() {} + +func (x *Node) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Node.ProtoReflect.Descriptor instead. +func (*Node) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{5} +} + +func (x *Node) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *Node) GetAddress() string { + if x != nil { + return x.Address + } + return "" +} + +func (x *Node) GetNetwork() string { + if x != nil { + return x.Network + } + return "" +} + +func (x *Node) GetMetadata() map[string]string { + if x != nil { + return x.Metadata + } + return nil +} + +func (x *Node) GetStatus() *Status { + if x != nil { + return x.Status + } + return nil +} + +// Connect is sent when the node connects to the network +type Connect struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // network mode + Node *Node `protobuf:"bytes,1,opt,name=node,proto3" json:"node,omitempty"` +} + +func (x *Connect) Reset() { + *x = Connect{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Connect) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Connect) ProtoMessage() {} + +func (x *Connect) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Connect.ProtoReflect.Descriptor instead. +func (*Connect) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{6} +} + +func (x *Connect) GetNode() *Node { + if x != nil { + return x.Node + } + return nil +} + +// Close is sent when the node disconnects from the network +type Close struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // network node + Node *Node `protobuf:"bytes,1,opt,name=node,proto3" json:"node,omitempty"` +} + +func (x *Close) Reset() { + *x = Close{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Close) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Close) ProtoMessage() {} + +func (x *Close) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Close.ProtoReflect.Descriptor instead. +func (*Close) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{7} +} + +func (x *Close) GetNode() *Node { + if x != nil { + return x.Node + } + return nil +} + +// Peer is used to advertise node peers +type Peer struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // network node + Node *Node `protobuf:"bytes,1,opt,name=node,proto3" json:"node,omitempty"` + // node peers + Peers []*Peer `protobuf:"bytes,2,rep,name=peers,proto3" json:"peers,omitempty"` +} + +func (x *Peer) Reset() { + *x = Peer{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Peer) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Peer) ProtoMessage() {} + +func (x *Peer) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Peer.ProtoReflect.Descriptor instead. +func (*Peer) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{8} +} + +func (x *Peer) GetNode() *Node { + if x != nil { + return x.Node + } + return nil +} + +func (x *Peer) GetPeers() []*Peer { + if x != nil { + return x.Peers + } + return nil +} + +// Sync is network sync message +type Sync struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // peer origin + Peer *Peer `protobuf:"bytes,1,opt,name=peer,proto3" json:"peer,omitempty"` + // node routes + Routes []*Route `protobuf:"bytes,2,rep,name=routes,proto3" json:"routes,omitempty"` +} + +func (x *Sync) Reset() { + *x = Sync{} + if protoimpl.UnsafeEnabled { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Sync) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Sync) ProtoMessage() {} + +func (x *Sync) ProtoReflect() protoreflect.Message { + mi := &file_github_com_micro_go_micro_network_mucp_proto_network_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 Sync.ProtoReflect.Descriptor instead. +func (*Sync) Descriptor() ([]byte, []int) { + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP(), []int{9} +} + +func (x *Sync) GetPeer() *Peer { + if x != nil { + return x.Peer + } + return nil +} + +func (x *Sync) GetRoutes() []*Route { + if x != nil { + return x.Routes + } + return nil +} + +var File_github_com_micro_go_micro_network_mucp_proto_network_proto protoreflect.FileDescriptor + +var file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDesc = []byte{ + 0x0a, 0x3a, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6d, 0x69, 0x63, + 0x72, 0x6f, 0x2f, 0x67, 0x6f, 0x2d, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2f, 0x6e, 0x65, 0x74, 0x77, + 0x6f, 0x72, 0x6b, 0x2f, 0x6d, 0x75, 0x63, 0x70, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6e, + 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x67, 0x6f, + 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, + 0x75, 0x63, 0x70, 0x22, 0xb5, 0x01, 0x0a, 0x06, 0x41, 0x64, 0x76, 0x65, 0x72, 0x74, 0x12, 0x0e, + 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x35, + 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x21, 0x2e, 0x67, + 0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, + 0x6d, 0x75, 0x63, 0x70, 0x2e, 0x41, 0x64, 0x76, 0x65, 0x72, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, + 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, + 0x6d, 0x70, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, + 0x61, 0x6d, 0x70, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x74, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, + 0x52, 0x03, 0x74, 0x74, 0x6c, 0x12, 0x34, 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, + 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, + 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, 0x63, 0x70, 0x2e, 0x45, 0x76, + 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x22, 0x9f, 0x01, 0x0a, 0x05, + 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x34, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0e, 0x32, 0x20, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x6e, + 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, 0x63, 0x70, 0x2e, 0x45, 0x76, 0x65, 0x6e, + 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x74, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, + 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x32, 0x0a, 0x05, 0x72, 0x6f, 0x75, + 0x74, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69, + 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, 0x63, 0x70, + 0x2e, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x52, 0x05, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x22, 0xb8, 0x02, + 0x0a, 0x05, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x67, + 0x61, 0x74, 0x65, 0x77, 0x61, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x67, 0x61, + 0x74, 0x65, 0x77, 0x61, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, + 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x12, + 0x16, 0x0a, 0x06, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x06, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x6c, 0x69, 0x6e, 0x6b, 0x18, + 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6c, 0x69, 0x6e, 0x6b, 0x12, 0x16, 0x0a, 0x06, 0x6d, + 0x65, 0x74, 0x72, 0x69, 0x63, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x6d, 0x65, 0x74, + 0x72, 0x69, 0x63, 0x12, 0x46, 0x0a, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, + 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, + 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, 0x63, 0x70, 0x2e, 0x52, 0x6f, + 0x75, 0x74, 0x65, 0x2e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, + 0x79, 0x52, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x1a, 0x3b, 0x0a, 0x0d, 0x4d, + 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, + 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, + 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, + 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x2f, 0x0a, 0x05, 0x45, 0x72, 0x72, 0x6f, + 0x72, 0x12, 0x14, 0x0a, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, + 0x52, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x22, 0x3c, 0x0a, 0x06, 0x53, 0x74, 0x61, + 0x74, 0x75, 0x73, 0x12, 0x32, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, + 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, 0x63, 0x70, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, + 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x85, 0x02, 0x0a, 0x04, 0x4e, 0x6f, 0x64, 0x65, + 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, + 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x6e, 0x65, + 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6e, 0x65, 0x74, + 0x77, 0x6f, 0x72, 0x6b, 0x12, 0x45, 0x0a, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, + 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72, + 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, 0x63, 0x70, 0x2e, 0x4e, + 0x6f, 0x64, 0x65, 0x2e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, + 0x79, 0x52, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x35, 0x0a, 0x06, 0x73, + 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, + 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, + 0x75, 0x63, 0x70, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, + 0x75, 0x73, 0x1a, 0x3b, 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, + 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, + 0x3a, 0x0a, 0x07, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x12, 0x2f, 0x0a, 0x04, 0x6e, 0x6f, + 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69, + 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, 0x63, 0x70, + 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x52, 0x04, 0x6e, 0x6f, 0x64, 0x65, 0x22, 0x38, 0x0a, 0x05, 0x43, + 0x6c, 0x6f, 0x73, 0x65, 0x12, 0x2f, 0x0a, 0x04, 0x6e, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, + 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, 0x63, 0x70, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x52, + 0x04, 0x6e, 0x6f, 0x64, 0x65, 0x22, 0x6a, 0x0a, 0x04, 0x50, 0x65, 0x65, 0x72, 0x12, 0x2f, 0x0a, + 0x04, 0x6e, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, + 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, + 0x75, 0x63, 0x70, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x52, 0x04, 0x6e, 0x6f, 0x64, 0x65, 0x12, 0x31, + 0x0a, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, + 0x67, 0x6f, 0x2e, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, + 0x2e, 0x6d, 0x75, 0x63, 0x70, 0x2e, 0x50, 0x65, 0x65, 0x72, 0x52, 0x05, 0x70, 0x65, 0x65, 0x72, + 0x73, 0x22, 0x6d, 0x0a, 0x04, 0x53, 0x79, 0x6e, 0x63, 0x12, 0x2f, 0x0a, 0x04, 0x70, 0x65, 0x65, + 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x2e, 0x6d, 0x69, 0x63, + 0x72, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, 0x63, 0x70, 0x2e, + 0x50, 0x65, 0x65, 0x72, 0x52, 0x04, 0x70, 0x65, 0x65, 0x72, 0x12, 0x34, 0x0a, 0x06, 0x72, 0x6f, + 0x75, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x2e, + 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x6d, 0x75, + 0x63, 0x70, 0x2e, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x52, 0x06, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x73, + 0x2a, 0x32, 0x0a, 0x0a, 0x41, 0x64, 0x76, 0x65, 0x72, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x12, + 0x0a, 0x0e, 0x41, 0x64, 0x76, 0x65, 0x72, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x75, 0x6e, 0x63, 0x65, + 0x10, 0x00, 0x12, 0x10, 0x0a, 0x0c, 0x41, 0x64, 0x76, 0x65, 0x72, 0x74, 0x55, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x10, 0x01, 0x2a, 0x2f, 0x0a, 0x09, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, + 0x65, 0x12, 0x0a, 0x0a, 0x06, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x10, 0x00, 0x12, 0x0a, 0x0a, + 0x06, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x55, 0x70, 0x64, + 0x61, 0x74, 0x65, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescOnce sync.Once + file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescData = file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDesc +) + +func file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescGZIP() []byte { + file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescOnce.Do(func() { + file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescData = protoimpl.X.CompressGZIP(file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescData) + }) + return file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDescData +} + +var file_github_com_micro_go_micro_network_mucp_proto_network_proto_enumTypes = make([]protoimpl.EnumInfo, 2) +var file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes = make([]protoimpl.MessageInfo, 12) +var file_github_com_micro_go_micro_network_mucp_proto_network_proto_goTypes = []interface{}{ + (AdvertType)(0), // 0: go.micro.network.mucp.AdvertType + (EventType)(0), // 1: go.micro.network.mucp.EventType + (*Advert)(nil), // 2: go.micro.network.mucp.Advert + (*Event)(nil), // 3: go.micro.network.mucp.Event + (*Route)(nil), // 4: go.micro.network.mucp.Route + (*Error)(nil), // 5: go.micro.network.mucp.Error + (*Status)(nil), // 6: go.micro.network.mucp.Status + (*Node)(nil), // 7: go.micro.network.mucp.Node + (*Connect)(nil), // 8: go.micro.network.mucp.Connect + (*Close)(nil), // 9: go.micro.network.mucp.Close + (*Peer)(nil), // 10: go.micro.network.mucp.Peer + (*Sync)(nil), // 11: go.micro.network.mucp.Sync + nil, // 12: go.micro.network.mucp.Route.MetadataEntry + nil, // 13: go.micro.network.mucp.Node.MetadataEntry +} +var file_github_com_micro_go_micro_network_mucp_proto_network_proto_depIdxs = []int32{ + 0, // 0: go.micro.network.mucp.Advert.type:type_name -> go.micro.network.mucp.AdvertType + 3, // 1: go.micro.network.mucp.Advert.events:type_name -> go.micro.network.mucp.Event + 1, // 2: go.micro.network.mucp.Event.type:type_name -> go.micro.network.mucp.EventType + 4, // 3: go.micro.network.mucp.Event.route:type_name -> go.micro.network.mucp.Route + 12, // 4: go.micro.network.mucp.Route.metadata:type_name -> go.micro.network.mucp.Route.MetadataEntry + 5, // 5: go.micro.network.mucp.Status.error:type_name -> go.micro.network.mucp.Error + 13, // 6: go.micro.network.mucp.Node.metadata:type_name -> go.micro.network.mucp.Node.MetadataEntry + 6, // 7: go.micro.network.mucp.Node.status:type_name -> go.micro.network.mucp.Status + 7, // 8: go.micro.network.mucp.Connect.node:type_name -> go.micro.network.mucp.Node + 7, // 9: go.micro.network.mucp.Close.node:type_name -> go.micro.network.mucp.Node + 7, // 10: go.micro.network.mucp.Peer.node:type_name -> go.micro.network.mucp.Node + 10, // 11: go.micro.network.mucp.Peer.peers:type_name -> go.micro.network.mucp.Peer + 10, // 12: go.micro.network.mucp.Sync.peer:type_name -> go.micro.network.mucp.Peer + 4, // 13: go.micro.network.mucp.Sync.routes:type_name -> go.micro.network.mucp.Route + 14, // [14:14] is the sub-list for method output_type + 14, // [14:14] is the sub-list for method input_type + 14, // [14:14] is the sub-list for extension type_name + 14, // [14:14] is the sub-list for extension extendee + 0, // [0:14] is the sub-list for field type_name +} + +func init() { file_github_com_micro_go_micro_network_mucp_proto_network_proto_init() } +func file_github_com_micro_go_micro_network_mucp_proto_network_proto_init() { + if File_github_com_micro_go_micro_network_mucp_proto_network_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Advert); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Event); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Route); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Error); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Status); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Node); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Connect); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Close); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Peer); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Sync); 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_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDesc, + NumEnums: 2, + NumMessages: 12, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_github_com_micro_go_micro_network_mucp_proto_network_proto_goTypes, + DependencyIndexes: file_github_com_micro_go_micro_network_mucp_proto_network_proto_depIdxs, + EnumInfos: file_github_com_micro_go_micro_network_mucp_proto_network_proto_enumTypes, + MessageInfos: file_github_com_micro_go_micro_network_mucp_proto_network_proto_msgTypes, + }.Build() + File_github_com_micro_go_micro_network_mucp_proto_network_proto = out.File + file_github_com_micro_go_micro_network_mucp_proto_network_proto_rawDesc = nil + file_github_com_micro_go_micro_network_mucp_proto_network_proto_goTypes = nil + file_github_com_micro_go_micro_network_mucp_proto_network_proto_depIdxs = nil +} diff --git a/network/mucp/proto/network.pb.micro.go b/network/mucp/proto/network.pb.micro.go new file mode 100644 index 00000000..efe35670 --- /dev/null +++ b/network/mucp/proto/network.pb.micro.go @@ -0,0 +1,21 @@ +// Code generated by protoc-gen-micro. DO NOT EDIT. +// source: github.com/micro/go-micro/network/mucp/proto/network.proto + +package go_micro_network_mucp + +import ( + fmt "fmt" + proto "github.com/golang/protobuf/proto" + math "math" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package diff --git a/network/mucp/proto/network.proto b/network/mucp/proto/network.proto new file mode 100644 index 00000000..627e0e66 --- /dev/null +++ b/network/mucp/proto/network.proto @@ -0,0 +1,115 @@ +syntax = "proto3"; + +package go.micro.network.mucp; + +// AdvertType defines the type of advert +enum AdvertType { + AdvertAnnounce = 0; + AdvertUpdate = 1; +} + +// Advert is router advertsement streamed by Watch +message Advert { + // id of the advertising router + string id = 1; + // type of advertisement + AdvertType type = 2; + // unix timestamp of the advertisement + int64 timestamp = 3; + // TTL of the Advert + int64 ttl = 4; + // events is a list of advertised events + repeated Event events = 5; +} + +// EventType defines the type of event +enum EventType { + Create = 0; + Delete = 1; + Update = 2; +} + +// Event is routing table event +message Event { + // the unique event id + string id = 1; + // type of event + EventType type = 2; + // unix timestamp of event + int64 timestamp = 3; + // service route + Route route = 4; +} + +// Route is a service route +message Route { + // service for the route + string service = 1; + // the address that advertise this route + string address = 2; + // gateway as the next hop + string gateway = 3; + // the network for this destination + string network = 4; + // router if the router id + string router = 5; + // the network link + string link = 6; + // the metric / score of this route + int64 metric = 7; + // metadata for the route + map metadata = 8; +} + +// Error tracks network errors +message Error { + uint32 count = 1; + string msg = 2; +} + +// Status is node status +message Status { + Error error = 1; +} + +// Node is network node +message Node { + // node id + string id = 1; + // node address + string address = 2; + // the network + string network = 3; + // associated metadata + map metadata = 4; + // node status + Status status = 5; +} + +// Connect is sent when the node connects to the network +message Connect { + // network mode + Node node = 1; +} + +// Close is sent when the node disconnects from the network +message Close { + // network node + Node node = 1; +} + +// Peer is used to advertise node peers +message Peer { + // network node + Node node = 1; + // node peers + repeated Peer peers = 2; +} + +// Sync is network sync message +message Sync { + // peer origin + Peer peer = 1; + // node routes + repeated Route routes = 2; +} diff --git a/network/network.go b/network/network.go index e71c6ab2..054d3745 100644 --- a/network/network.go +++ b/network/network.go @@ -2,28 +2,8 @@ package network import ( - "time" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/server" -) - -var ( - // DefaultName is default network name - DefaultName = "go.micro" - // DefaultAddress is default network address - DefaultAddress = ":0" - // ResolveTime defines time interval to periodically resolve network nodes - ResolveTime = 1 * time.Minute - // AnnounceTime defines time interval to periodically announce node neighbours - AnnounceTime = 1 * time.Second - // KeepAliveTime is the time in which we want to have sent a message to a peer - KeepAliveTime = 30 * time.Second - // SyncTime is the time a network node requests full sync from the network - SyncTime = 1 * time.Minute - // PruneTime defines time interval to periodically check nodes that need to be pruned - // due to their not announcing their presence within this time interval - PruneTime = 90 * time.Second + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/server" ) // Error is network node errors @@ -73,8 +53,3 @@ type Network interface { // Server is micro server Server() server.Server } - -// NewNetwork returns a new network interface -func NewNetwork(opts ...Option) Network { - return newNetwork(opts...) -} diff --git a/network/options.go b/network/options.go index 084dce63..a0ea31be 100644 --- a/network/options.go +++ b/network/options.go @@ -2,12 +2,13 @@ package network import ( "github.com/google/uuid" - "github.com/micro/go-micro/v2/network/resolver" - "github.com/micro/go-micro/v2/network/resolver/registry" - "github.com/micro/go-micro/v2/proxy" - "github.com/micro/go-micro/v2/proxy/mucp" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/tunnel" + "github.com/micro/go-micro/v3/network/resolver" + "github.com/micro/go-micro/v3/network/resolver/registry" + "github.com/micro/go-micro/v3/proxy" + "github.com/micro/go-micro/v3/proxy/mucp" + "github.com/micro/go-micro/v3/router" + regRouter "github.com/micro/go-micro/v3/router/registry" + "github.com/micro/go-micro/v3/tunnel" ) type Option func(*Options) @@ -101,10 +102,10 @@ func Resolver(r resolver.Resolver) Option { func DefaultOptions() Options { return Options{ Id: uuid.New().String(), - Name: DefaultName, - Address: DefaultAddress, + Name: "go.micro", + Address: ":0", Tunnel: tunnel.NewTunnel(), - Router: router.DefaultRouter, + Router: regRouter.NewRouter(), Proxy: mucp.NewProxy(), Resolver: ®istry.Resolver{}, } diff --git a/network/resolver/dns/dns.go b/network/resolver/dns/dns.go index 2b1670f1..f70766a2 100644 --- a/network/resolver/dns/dns.go +++ b/network/resolver/dns/dns.go @@ -5,7 +5,7 @@ import ( "context" "net" - "github.com/micro/go-micro/v2/network/resolver" + "github.com/micro/go-micro/v3/network/resolver" "github.com/miekg/dns" ) diff --git a/network/resolver/dnssrv/dnssrv.go b/network/resolver/dnssrv/dnssrv.go index 80259eec..667f690a 100644 --- a/network/resolver/dnssrv/dnssrv.go +++ b/network/resolver/dnssrv/dnssrv.go @@ -5,7 +5,7 @@ import ( "fmt" "net" - "github.com/micro/go-micro/v2/network/resolver" + "github.com/micro/go-micro/v3/network/resolver" ) // Resolver is a DNS network resolve diff --git a/network/resolver/http/http.go b/network/resolver/http/http.go index c94911f0..1ccad794 100644 --- a/network/resolver/http/http.go +++ b/network/resolver/http/http.go @@ -8,7 +8,7 @@ import ( "net/http" "net/url" - "github.com/micro/go-micro/v2/network/resolver" + "github.com/micro/go-micro/v3/network/resolver" ) // Resolver is a HTTP network resolver diff --git a/network/resolver/registry/registry.go b/network/resolver/registry/registry.go index 0852d9c8..caacf431 100644 --- a/network/resolver/registry/registry.go +++ b/network/resolver/registry/registry.go @@ -2,8 +2,9 @@ package registry import ( - "github.com/micro/go-micro/v2/network/resolver" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/network/resolver" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/mdns" ) // Resolver is a registry network resolver @@ -16,7 +17,7 @@ type Resolver struct { func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) { reg := r.Registry if reg == nil { - reg = registry.DefaultRegistry + reg = mdns.NewRegistry() } services, err := reg.GetService(name) diff --git a/network/resolver/static/static.go b/network/resolver/static/static.go index 49f64003..207e04d8 100644 --- a/network/resolver/static/static.go +++ b/network/resolver/static/static.go @@ -2,7 +2,7 @@ package registry import ( - "github.com/micro/go-micro/v2/network/resolver" + "github.com/micro/go-micro/v3/network/resolver" ) // Resolver returns a static list of nodes. In the event the node list diff --git a/network/service/proto/network.pb.go b/network/service/proto/network.pb.go deleted file mode 100644 index 553d74e6..00000000 --- a/network/service/proto/network.pb.go +++ /dev/null @@ -1,1241 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: network/service/proto/network.proto - -package go_micro_network - -import ( - context "context" - fmt "fmt" - proto "github.com/golang/protobuf/proto" - proto1 "github.com/micro/go-micro/v2/router/service/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// Query is passed in a LookupRequest -type Query struct { - Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - Gateway string `protobuf:"bytes,3,opt,name=gateway,proto3" json:"gateway,omitempty"` - Router string `protobuf:"bytes,4,opt,name=router,proto3" json:"router,omitempty"` - Network string `protobuf:"bytes,5,opt,name=network,proto3" json:"network,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Query) Reset() { *m = Query{} } -func (m *Query) String() string { return proto.CompactTextString(m) } -func (*Query) ProtoMessage() {} -func (*Query) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{0} -} - -func (m *Query) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Query.Unmarshal(m, b) -} -func (m *Query) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Query.Marshal(b, m, deterministic) -} -func (m *Query) XXX_Merge(src proto.Message) { - xxx_messageInfo_Query.Merge(m, src) -} -func (m *Query) XXX_Size() int { - return xxx_messageInfo_Query.Size(m) -} -func (m *Query) XXX_DiscardUnknown() { - xxx_messageInfo_Query.DiscardUnknown(m) -} - -var xxx_messageInfo_Query proto.InternalMessageInfo - -func (m *Query) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -func (m *Query) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *Query) GetGateway() string { - if m != nil { - return m.Gateway - } - return "" -} - -func (m *Query) GetRouter() string { - if m != nil { - return m.Router - } - return "" -} - -func (m *Query) GetNetwork() string { - if m != nil { - return m.Network - } - return "" -} - -type ConnectRequest struct { - Nodes []*Node `protobuf:"bytes,1,rep,name=nodes,proto3" json:"nodes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ConnectRequest) Reset() { *m = ConnectRequest{} } -func (m *ConnectRequest) String() string { return proto.CompactTextString(m) } -func (*ConnectRequest) ProtoMessage() {} -func (*ConnectRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{1} -} - -func (m *ConnectRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ConnectRequest.Unmarshal(m, b) -} -func (m *ConnectRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ConnectRequest.Marshal(b, m, deterministic) -} -func (m *ConnectRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ConnectRequest.Merge(m, src) -} -func (m *ConnectRequest) XXX_Size() int { - return xxx_messageInfo_ConnectRequest.Size(m) -} -func (m *ConnectRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ConnectRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ConnectRequest proto.InternalMessageInfo - -func (m *ConnectRequest) GetNodes() []*Node { - if m != nil { - return m.Nodes - } - return nil -} - -type ConnectResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ConnectResponse) Reset() { *m = ConnectResponse{} } -func (m *ConnectResponse) String() string { return proto.CompactTextString(m) } -func (*ConnectResponse) ProtoMessage() {} -func (*ConnectResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{2} -} - -func (m *ConnectResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ConnectResponse.Unmarshal(m, b) -} -func (m *ConnectResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ConnectResponse.Marshal(b, m, deterministic) -} -func (m *ConnectResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ConnectResponse.Merge(m, src) -} -func (m *ConnectResponse) XXX_Size() int { - return xxx_messageInfo_ConnectResponse.Size(m) -} -func (m *ConnectResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ConnectResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ConnectResponse proto.InternalMessageInfo - -// PeerRequest requests list of peers -type NodesRequest struct { - // node topology depth - Depth uint32 `protobuf:"varint,1,opt,name=depth,proto3" json:"depth,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NodesRequest) Reset() { *m = NodesRequest{} } -func (m *NodesRequest) String() string { return proto.CompactTextString(m) } -func (*NodesRequest) ProtoMessage() {} -func (*NodesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{3} -} - -func (m *NodesRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_NodesRequest.Unmarshal(m, b) -} -func (m *NodesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_NodesRequest.Marshal(b, m, deterministic) -} -func (m *NodesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_NodesRequest.Merge(m, src) -} -func (m *NodesRequest) XXX_Size() int { - return xxx_messageInfo_NodesRequest.Size(m) -} -func (m *NodesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_NodesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_NodesRequest proto.InternalMessageInfo - -func (m *NodesRequest) GetDepth() uint32 { - if m != nil { - return m.Depth - } - return 0 -} - -// PeerResponse is returned by ListPeers -type NodesResponse struct { - // return peer topology - Nodes []*Node `protobuf:"bytes,1,rep,name=nodes,proto3" json:"nodes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NodesResponse) Reset() { *m = NodesResponse{} } -func (m *NodesResponse) String() string { return proto.CompactTextString(m) } -func (*NodesResponse) ProtoMessage() {} -func (*NodesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{4} -} - -func (m *NodesResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_NodesResponse.Unmarshal(m, b) -} -func (m *NodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_NodesResponse.Marshal(b, m, deterministic) -} -func (m *NodesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_NodesResponse.Merge(m, src) -} -func (m *NodesResponse) XXX_Size() int { - return xxx_messageInfo_NodesResponse.Size(m) -} -func (m *NodesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_NodesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_NodesResponse proto.InternalMessageInfo - -func (m *NodesResponse) GetNodes() []*Node { - if m != nil { - return m.Nodes - } - return nil -} - -type GraphRequest struct { - // node topology depth - Depth uint32 `protobuf:"varint,1,opt,name=depth,proto3" json:"depth,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GraphRequest) Reset() { *m = GraphRequest{} } -func (m *GraphRequest) String() string { return proto.CompactTextString(m) } -func (*GraphRequest) ProtoMessage() {} -func (*GraphRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{5} -} - -func (m *GraphRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GraphRequest.Unmarshal(m, b) -} -func (m *GraphRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GraphRequest.Marshal(b, m, deterministic) -} -func (m *GraphRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GraphRequest.Merge(m, src) -} -func (m *GraphRequest) XXX_Size() int { - return xxx_messageInfo_GraphRequest.Size(m) -} -func (m *GraphRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GraphRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GraphRequest proto.InternalMessageInfo - -func (m *GraphRequest) GetDepth() uint32 { - if m != nil { - return m.Depth - } - return 0 -} - -type GraphResponse struct { - Root *Peer `protobuf:"bytes,1,opt,name=root,proto3" json:"root,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GraphResponse) Reset() { *m = GraphResponse{} } -func (m *GraphResponse) String() string { return proto.CompactTextString(m) } -func (*GraphResponse) ProtoMessage() {} -func (*GraphResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{6} -} - -func (m *GraphResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GraphResponse.Unmarshal(m, b) -} -func (m *GraphResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GraphResponse.Marshal(b, m, deterministic) -} -func (m *GraphResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GraphResponse.Merge(m, src) -} -func (m *GraphResponse) XXX_Size() int { - return xxx_messageInfo_GraphResponse.Size(m) -} -func (m *GraphResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GraphResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GraphResponse proto.InternalMessageInfo - -func (m *GraphResponse) GetRoot() *Peer { - if m != nil { - return m.Root - } - return nil -} - -type RoutesRequest struct { - // filter based on - Query *Query `protobuf:"bytes,1,opt,name=query,proto3" json:"query,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RoutesRequest) Reset() { *m = RoutesRequest{} } -func (m *RoutesRequest) String() string { return proto.CompactTextString(m) } -func (*RoutesRequest) ProtoMessage() {} -func (*RoutesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{7} -} - -func (m *RoutesRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RoutesRequest.Unmarshal(m, b) -} -func (m *RoutesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RoutesRequest.Marshal(b, m, deterministic) -} -func (m *RoutesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_RoutesRequest.Merge(m, src) -} -func (m *RoutesRequest) XXX_Size() int { - return xxx_messageInfo_RoutesRequest.Size(m) -} -func (m *RoutesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_RoutesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_RoutesRequest proto.InternalMessageInfo - -func (m *RoutesRequest) GetQuery() *Query { - if m != nil { - return m.Query - } - return nil -} - -type RoutesResponse struct { - Routes []*proto1.Route `protobuf:"bytes,1,rep,name=routes,proto3" json:"routes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RoutesResponse) Reset() { *m = RoutesResponse{} } -func (m *RoutesResponse) String() string { return proto.CompactTextString(m) } -func (*RoutesResponse) ProtoMessage() {} -func (*RoutesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{8} -} - -func (m *RoutesResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RoutesResponse.Unmarshal(m, b) -} -func (m *RoutesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RoutesResponse.Marshal(b, m, deterministic) -} -func (m *RoutesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_RoutesResponse.Merge(m, src) -} -func (m *RoutesResponse) XXX_Size() int { - return xxx_messageInfo_RoutesResponse.Size(m) -} -func (m *RoutesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_RoutesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_RoutesResponse proto.InternalMessageInfo - -func (m *RoutesResponse) GetRoutes() []*proto1.Route { - if m != nil { - return m.Routes - } - return nil -} - -type ServicesRequest struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServicesRequest) Reset() { *m = ServicesRequest{} } -func (m *ServicesRequest) String() string { return proto.CompactTextString(m) } -func (*ServicesRequest) ProtoMessage() {} -func (*ServicesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{9} -} - -func (m *ServicesRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServicesRequest.Unmarshal(m, b) -} -func (m *ServicesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServicesRequest.Marshal(b, m, deterministic) -} -func (m *ServicesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServicesRequest.Merge(m, src) -} -func (m *ServicesRequest) XXX_Size() int { - return xxx_messageInfo_ServicesRequest.Size(m) -} -func (m *ServicesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ServicesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ServicesRequest proto.InternalMessageInfo - -type ServicesResponse struct { - Services []string `protobuf:"bytes,1,rep,name=services,proto3" json:"services,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServicesResponse) Reset() { *m = ServicesResponse{} } -func (m *ServicesResponse) String() string { return proto.CompactTextString(m) } -func (*ServicesResponse) ProtoMessage() {} -func (*ServicesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{10} -} - -func (m *ServicesResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServicesResponse.Unmarshal(m, b) -} -func (m *ServicesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServicesResponse.Marshal(b, m, deterministic) -} -func (m *ServicesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServicesResponse.Merge(m, src) -} -func (m *ServicesResponse) XXX_Size() int { - return xxx_messageInfo_ServicesResponse.Size(m) -} -func (m *ServicesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ServicesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ServicesResponse proto.InternalMessageInfo - -func (m *ServicesResponse) GetServices() []string { - if m != nil { - return m.Services - } - return nil -} - -type StatusRequest struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StatusRequest) Reset() { *m = StatusRequest{} } -func (m *StatusRequest) String() string { return proto.CompactTextString(m) } -func (*StatusRequest) ProtoMessage() {} -func (*StatusRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{11} -} - -func (m *StatusRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StatusRequest.Unmarshal(m, b) -} -func (m *StatusRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StatusRequest.Marshal(b, m, deterministic) -} -func (m *StatusRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_StatusRequest.Merge(m, src) -} -func (m *StatusRequest) XXX_Size() int { - return xxx_messageInfo_StatusRequest.Size(m) -} -func (m *StatusRequest) XXX_DiscardUnknown() { - xxx_messageInfo_StatusRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_StatusRequest proto.InternalMessageInfo - -type StatusResponse struct { - Status *Status `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StatusResponse) Reset() { *m = StatusResponse{} } -func (m *StatusResponse) String() string { return proto.CompactTextString(m) } -func (*StatusResponse) ProtoMessage() {} -func (*StatusResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{12} -} - -func (m *StatusResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StatusResponse.Unmarshal(m, b) -} -func (m *StatusResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StatusResponse.Marshal(b, m, deterministic) -} -func (m *StatusResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_StatusResponse.Merge(m, src) -} -func (m *StatusResponse) XXX_Size() int { - return xxx_messageInfo_StatusResponse.Size(m) -} -func (m *StatusResponse) XXX_DiscardUnknown() { - xxx_messageInfo_StatusResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_StatusResponse proto.InternalMessageInfo - -func (m *StatusResponse) GetStatus() *Status { - if m != nil { - return m.Status - } - return nil -} - -// Error tracks network errors -type Error struct { - Count uint32 `protobuf:"varint,1,opt,name=count,proto3" json:"count,omitempty"` - Msg string `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Error) Reset() { *m = Error{} } -func (m *Error) String() string { return proto.CompactTextString(m) } -func (*Error) ProtoMessage() {} -func (*Error) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{13} -} - -func (m *Error) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Error.Unmarshal(m, b) -} -func (m *Error) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Error.Marshal(b, m, deterministic) -} -func (m *Error) XXX_Merge(src proto.Message) { - xxx_messageInfo_Error.Merge(m, src) -} -func (m *Error) XXX_Size() int { - return xxx_messageInfo_Error.Size(m) -} -func (m *Error) XXX_DiscardUnknown() { - xxx_messageInfo_Error.DiscardUnknown(m) -} - -var xxx_messageInfo_Error proto.InternalMessageInfo - -func (m *Error) GetCount() uint32 { - if m != nil { - return m.Count - } - return 0 -} - -func (m *Error) GetMsg() string { - if m != nil { - return m.Msg - } - return "" -} - -// Status is node status -type Status struct { - Error *Error `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Status) Reset() { *m = Status{} } -func (m *Status) String() string { return proto.CompactTextString(m) } -func (*Status) ProtoMessage() {} -func (*Status) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{14} -} - -func (m *Status) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Status.Unmarshal(m, b) -} -func (m *Status) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Status.Marshal(b, m, deterministic) -} -func (m *Status) XXX_Merge(src proto.Message) { - xxx_messageInfo_Status.Merge(m, src) -} -func (m *Status) XXX_Size() int { - return xxx_messageInfo_Status.Size(m) -} -func (m *Status) XXX_DiscardUnknown() { - xxx_messageInfo_Status.DiscardUnknown(m) -} - -var xxx_messageInfo_Status proto.InternalMessageInfo - -func (m *Status) GetError() *Error { - if m != nil { - return m.Error - } - return nil -} - -// Node is network node -type Node struct { - // node id - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // node address - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - // the network - Network string `protobuf:"bytes,3,opt,name=network,proto3" json:"network,omitempty"` - // associated metadata - Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // node status - Status *Status `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Node) Reset() { *m = Node{} } -func (m *Node) String() string { return proto.CompactTextString(m) } -func (*Node) ProtoMessage() {} -func (*Node) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{15} -} - -func (m *Node) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Node.Unmarshal(m, b) -} -func (m *Node) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Node.Marshal(b, m, deterministic) -} -func (m *Node) XXX_Merge(src proto.Message) { - xxx_messageInfo_Node.Merge(m, src) -} -func (m *Node) XXX_Size() int { - return xxx_messageInfo_Node.Size(m) -} -func (m *Node) XXX_DiscardUnknown() { - xxx_messageInfo_Node.DiscardUnknown(m) -} - -var xxx_messageInfo_Node proto.InternalMessageInfo - -func (m *Node) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *Node) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *Node) GetNetwork() string { - if m != nil { - return m.Network - } - return "" -} - -func (m *Node) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Node) GetStatus() *Status { - if m != nil { - return m.Status - } - return nil -} - -// Connect is sent when the node connects to the network -type Connect struct { - // network mode - Node *Node `protobuf:"bytes,1,opt,name=node,proto3" json:"node,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Connect) Reset() { *m = Connect{} } -func (m *Connect) String() string { return proto.CompactTextString(m) } -func (*Connect) ProtoMessage() {} -func (*Connect) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{16} -} - -func (m *Connect) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Connect.Unmarshal(m, b) -} -func (m *Connect) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Connect.Marshal(b, m, deterministic) -} -func (m *Connect) XXX_Merge(src proto.Message) { - xxx_messageInfo_Connect.Merge(m, src) -} -func (m *Connect) XXX_Size() int { - return xxx_messageInfo_Connect.Size(m) -} -func (m *Connect) XXX_DiscardUnknown() { - xxx_messageInfo_Connect.DiscardUnknown(m) -} - -var xxx_messageInfo_Connect proto.InternalMessageInfo - -func (m *Connect) GetNode() *Node { - if m != nil { - return m.Node - } - return nil -} - -// Close is sent when the node disconnects from the network -type Close struct { - // network node - Node *Node `protobuf:"bytes,1,opt,name=node,proto3" json:"node,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Close) Reset() { *m = Close{} } -func (m *Close) String() string { return proto.CompactTextString(m) } -func (*Close) ProtoMessage() {} -func (*Close) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{17} -} - -func (m *Close) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Close.Unmarshal(m, b) -} -func (m *Close) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Close.Marshal(b, m, deterministic) -} -func (m *Close) XXX_Merge(src proto.Message) { - xxx_messageInfo_Close.Merge(m, src) -} -func (m *Close) XXX_Size() int { - return xxx_messageInfo_Close.Size(m) -} -func (m *Close) XXX_DiscardUnknown() { - xxx_messageInfo_Close.DiscardUnknown(m) -} - -var xxx_messageInfo_Close proto.InternalMessageInfo - -func (m *Close) GetNode() *Node { - if m != nil { - return m.Node - } - return nil -} - -// Peer is used to advertise node peers -type Peer struct { - // network node - Node *Node `protobuf:"bytes,1,opt,name=node,proto3" json:"node,omitempty"` - // node peers - Peers []*Peer `protobuf:"bytes,2,rep,name=peers,proto3" json:"peers,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Peer) Reset() { *m = Peer{} } -func (m *Peer) String() string { return proto.CompactTextString(m) } -func (*Peer) ProtoMessage() {} -func (*Peer) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{18} -} - -func (m *Peer) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Peer.Unmarshal(m, b) -} -func (m *Peer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Peer.Marshal(b, m, deterministic) -} -func (m *Peer) XXX_Merge(src proto.Message) { - xxx_messageInfo_Peer.Merge(m, src) -} -func (m *Peer) XXX_Size() int { - return xxx_messageInfo_Peer.Size(m) -} -func (m *Peer) XXX_DiscardUnknown() { - xxx_messageInfo_Peer.DiscardUnknown(m) -} - -var xxx_messageInfo_Peer proto.InternalMessageInfo - -func (m *Peer) GetNode() *Node { - if m != nil { - return m.Node - } - return nil -} - -func (m *Peer) GetPeers() []*Peer { - if m != nil { - return m.Peers - } - return nil -} - -// Sync is network sync message -type Sync struct { - // peer origin - Peer *Peer `protobuf:"bytes,1,opt,name=peer,proto3" json:"peer,omitempty"` - // node routes - Routes []*proto1.Route `protobuf:"bytes,2,rep,name=routes,proto3" json:"routes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Sync) Reset() { *m = Sync{} } -func (m *Sync) String() string { return proto.CompactTextString(m) } -func (*Sync) ProtoMessage() {} -func (*Sync) Descriptor() ([]byte, []int) { - return fileDescriptor_1aab434177f140e0, []int{19} -} - -func (m *Sync) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Sync.Unmarshal(m, b) -} -func (m *Sync) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Sync.Marshal(b, m, deterministic) -} -func (m *Sync) XXX_Merge(src proto.Message) { - xxx_messageInfo_Sync.Merge(m, src) -} -func (m *Sync) XXX_Size() int { - return xxx_messageInfo_Sync.Size(m) -} -func (m *Sync) XXX_DiscardUnknown() { - xxx_messageInfo_Sync.DiscardUnknown(m) -} - -var xxx_messageInfo_Sync proto.InternalMessageInfo - -func (m *Sync) GetPeer() *Peer { - if m != nil { - return m.Peer - } - return nil -} - -func (m *Sync) GetRoutes() []*proto1.Route { - if m != nil { - return m.Routes - } - return nil -} - -func init() { - proto.RegisterType((*Query)(nil), "go.micro.network.Query") - proto.RegisterType((*ConnectRequest)(nil), "go.micro.network.ConnectRequest") - proto.RegisterType((*ConnectResponse)(nil), "go.micro.network.ConnectResponse") - proto.RegisterType((*NodesRequest)(nil), "go.micro.network.NodesRequest") - proto.RegisterType((*NodesResponse)(nil), "go.micro.network.NodesResponse") - proto.RegisterType((*GraphRequest)(nil), "go.micro.network.GraphRequest") - proto.RegisterType((*GraphResponse)(nil), "go.micro.network.GraphResponse") - proto.RegisterType((*RoutesRequest)(nil), "go.micro.network.RoutesRequest") - proto.RegisterType((*RoutesResponse)(nil), "go.micro.network.RoutesResponse") - proto.RegisterType((*ServicesRequest)(nil), "go.micro.network.ServicesRequest") - proto.RegisterType((*ServicesResponse)(nil), "go.micro.network.ServicesResponse") - proto.RegisterType((*StatusRequest)(nil), "go.micro.network.StatusRequest") - proto.RegisterType((*StatusResponse)(nil), "go.micro.network.StatusResponse") - proto.RegisterType((*Error)(nil), "go.micro.network.Error") - proto.RegisterType((*Status)(nil), "go.micro.network.Status") - proto.RegisterType((*Node)(nil), "go.micro.network.Node") - proto.RegisterMapType((map[string]string)(nil), "go.micro.network.Node.MetadataEntry") - proto.RegisterType((*Connect)(nil), "go.micro.network.Connect") - proto.RegisterType((*Close)(nil), "go.micro.network.Close") - proto.RegisterType((*Peer)(nil), "go.micro.network.Peer") - proto.RegisterType((*Sync)(nil), "go.micro.network.Sync") -} - -func init() { - proto.RegisterFile("network/service/proto/network.proto", fileDescriptor_1aab434177f140e0) -} - -var fileDescriptor_1aab434177f140e0 = []byte{ - // 667 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0xdd, 0x4e, 0xdb, 0x4c, - 0x10, 0xc5, 0xb1, 0x1d, 0x60, 0x3e, 0x1c, 0xf8, 0x56, 0x15, 0xb5, 0x7c, 0x51, 0xc2, 0x96, 0x0b, - 0x54, 0xb5, 0x4e, 0x05, 0xaa, 0x5a, 0x15, 0x15, 0xa1, 0x22, 0x54, 0xa9, 0x12, 0x88, 0x3a, 0x2f, - 0x50, 0x13, 0xaf, 0x20, 0x02, 0xbc, 0x61, 0xbd, 0x06, 0xe5, 0x09, 0xfa, 0xa6, 0x7d, 0x89, 0xde, - 0x54, 0xbb, 0x3b, 0x36, 0x36, 0xb1, 0xd3, 0x70, 0x97, 0x99, 0x3d, 0x67, 0xc6, 0xf3, 0x77, 0x02, - 0xaf, 0x53, 0x26, 0x1f, 0xb8, 0xb8, 0x1e, 0x64, 0x4c, 0xdc, 0x8f, 0x47, 0x6c, 0x30, 0x11, 0x5c, - 0xf2, 0x01, 0x7a, 0x43, 0x6d, 0x91, 0x8d, 0x4b, 0x1e, 0xde, 0x8e, 0x47, 0x82, 0x87, 0xe8, 0x0f, - 0xb6, 0x05, 0xcf, 0x25, 0x13, 0x4f, 0x58, 0xc6, 0x69, 0x48, 0xf4, 0x97, 0x05, 0xee, 0x8f, 0x9c, - 0x89, 0x29, 0xf1, 0x61, 0x19, 0x71, 0xbe, 0xd5, 0xb7, 0x76, 0x57, 0xa3, 0xc2, 0x54, 0x2f, 0x71, - 0x92, 0x08, 0x96, 0x65, 0x7e, 0xc7, 0xbc, 0xa0, 0xa9, 0x5e, 0x2e, 0x63, 0xc9, 0x1e, 0xe2, 0xa9, - 0x6f, 0x9b, 0x17, 0x34, 0xc9, 0x26, 0x74, 0x4d, 0x1e, 0xdf, 0xd1, 0x0f, 0x68, 0x29, 0x06, 0x7e, - 0x9d, 0xef, 0x1a, 0x06, 0x9a, 0xf4, 0x10, 0x7a, 0xc7, 0x3c, 0x4d, 0xd9, 0x48, 0x46, 0xec, 0x2e, - 0x67, 0x99, 0x24, 0x6f, 0xc1, 0x4d, 0x79, 0xc2, 0x32, 0xdf, 0xea, 0xdb, 0xbb, 0xff, 0xed, 0x6d, - 0x86, 0x4f, 0x0b, 0x0c, 0xcf, 0x78, 0xc2, 0x22, 0x03, 0xa2, 0xff, 0xc3, 0x7a, 0xc9, 0xcf, 0x26, - 0x3c, 0xcd, 0x18, 0xdd, 0x81, 0x35, 0x85, 0xc8, 0x8a, 0x80, 0x2f, 0xc0, 0x4d, 0xd8, 0x44, 0x5e, - 0xe9, 0x02, 0xbd, 0xc8, 0x18, 0xf4, 0x0b, 0x78, 0x88, 0x32, 0xb4, 0x67, 0xe6, 0xdd, 0x81, 0xb5, - 0x6f, 0x22, 0x9e, 0x5c, 0xcd, 0x4f, 0x72, 0x00, 0x1e, 0xa2, 0x30, 0xc9, 0x1b, 0x70, 0x04, 0xe7, - 0x52, 0xa3, 0x1a, 0x73, 0x9c, 0x33, 0x26, 0x22, 0x8d, 0xa1, 0x87, 0xe0, 0x45, 0xaa, 0x7d, 0x65, - 0x21, 0xef, 0xc0, 0xbd, 0x53, 0x43, 0x43, 0xf6, 0xcb, 0x59, 0xb6, 0x9e, 0x69, 0x64, 0x50, 0xf4, - 0x08, 0x7a, 0x05, 0x1f, 0xb3, 0x87, 0x38, 0x9e, 0x86, 0x1a, 0x71, 0x3d, 0x34, 0x01, 0xc7, 0xa6, - 0x9b, 0x3b, 0x34, 0xdb, 0x50, 0x7c, 0x03, 0x0d, 0x61, 0xe3, 0xd1, 0x85, 0x61, 0x03, 0x58, 0xc1, - 0xa5, 0x31, 0x81, 0x57, 0xa3, 0xd2, 0xa6, 0xeb, 0xe0, 0x0d, 0x65, 0x2c, 0xf3, 0x32, 0xc0, 0x57, - 0xe8, 0x15, 0x0e, 0xa4, 0xbf, 0x87, 0x6e, 0xa6, 0x3d, 0x58, 0x97, 0x3f, 0x5b, 0x17, 0x32, 0x10, - 0x47, 0x07, 0xe0, 0x9e, 0x08, 0xc1, 0x85, 0xea, 0xfa, 0x88, 0xe7, 0xa9, 0x2c, 0xba, 0xae, 0x0d, - 0xb2, 0x01, 0xf6, 0x6d, 0x76, 0x89, 0x5b, 0xab, 0x7e, 0xd2, 0x8f, 0xd0, 0x35, 0x21, 0x54, 0x0f, - 0x99, 0xa2, 0xb6, 0xf7, 0x50, 0x47, 0x8e, 0x0c, 0x8a, 0xfe, 0xb1, 0xc0, 0x51, 0x63, 0x27, 0x3d, - 0xe8, 0x8c, 0x13, 0x3c, 0x91, 0xce, 0x38, 0x99, 0x7f, 0x1d, 0xc5, 0xae, 0xdb, 0xb5, 0x5d, 0x27, - 0x47, 0xb0, 0x72, 0xcb, 0x64, 0x9c, 0xc4, 0x32, 0xf6, 0x1d, 0x3d, 0x80, 0x9d, 0xe6, 0x25, 0x0b, - 0x4f, 0x11, 0x76, 0x92, 0x4a, 0x31, 0x8d, 0x4a, 0x56, 0xa5, 0x55, 0xee, 0x62, 0xad, 0x0a, 0x0e, - 0xc0, 0xab, 0x05, 0x53, 0xcd, 0xb9, 0x66, 0x53, 0xac, 0x44, 0xfd, 0x54, 0x4d, 0xbc, 0x8f, 0x6f, - 0x72, 0x86, 0x85, 0x18, 0xe3, 0x73, 0xe7, 0x93, 0x45, 0x3f, 0xc0, 0x32, 0x1e, 0x97, 0x5a, 0x5c, - 0xb5, 0xf8, 0xed, 0x8b, 0xab, 0x8f, 0x43, 0x63, 0xe8, 0x3e, 0xb8, 0xc7, 0x37, 0xdc, 0x6c, 0xfb, - 0xc2, 0xa4, 0x9f, 0xe0, 0xa8, 0xdd, 0x7f, 0x0e, 0x47, 0x9d, 0xec, 0x84, 0x31, 0xa1, 0x46, 0x60, - 0xcf, 0x39, 0x27, 0x03, 0xa2, 0x17, 0xe0, 0x0c, 0xa7, 0xe9, 0x48, 0x65, 0x50, 0x8e, 0x7f, 0xdd, - 0xa0, 0xc2, 0x54, 0x2e, 0xa6, 0xb3, 0xc8, 0xc5, 0xec, 0xfd, 0xb6, 0x61, 0xf9, 0x0c, 0xc7, 0x7d, - 0xfe, 0xd8, 0xbd, 0xfe, 0x6c, 0x92, 0xba, 0xea, 0x05, 0xdb, 0x73, 0x10, 0xa8, 0x6b, 0x4b, 0xe4, - 0x3b, 0xb8, 0x5a, 0x4e, 0xc8, 0xab, 0x59, 0x74, 0x55, 0x8d, 0x82, 0xad, 0xd6, 0xf7, 0x6a, 0x2c, - 0xad, 0x7f, 0x4d, 0xb1, 0xaa, 0xf2, 0xd9, 0x14, 0xab, 0x26, 0x9c, 0x74, 0x89, 0x9c, 0x42, 0xd7, - 0x28, 0x0d, 0x69, 0x00, 0xd7, 0x34, 0x2c, 0xe8, 0xb7, 0x03, 0xca, 0x70, 0x43, 0x58, 0x29, 0x34, - 0x86, 0x34, 0xf4, 0xe5, 0x89, 0x24, 0x05, 0x74, 0x1e, 0xa4, 0xfa, 0x8d, 0x28, 0x01, 0x5b, 0xad, - 0x47, 0xd3, 0xfe, 0x8d, 0x75, 0xc9, 0xa2, 0x4b, 0x17, 0x5d, 0xfd, 0x47, 0xba, 0xff, 0x37, 0x00, - 0x00, 0xff, 0xff, 0x13, 0x9f, 0x0c, 0xc2, 0xa4, 0x07, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// NetworkClient is the client API for Network service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type NetworkClient interface { - // Connect to the network - Connect(ctx context.Context, in *ConnectRequest, opts ...grpc.CallOption) (*ConnectResponse, error) - // Returns the entire network graph - Graph(ctx context.Context, in *GraphRequest, opts ...grpc.CallOption) (*GraphResponse, error) - // Returns a list of known nodes in the network - Nodes(ctx context.Context, in *NodesRequest, opts ...grpc.CallOption) (*NodesResponse, error) - // Returns a list of known routes in the network - Routes(ctx context.Context, in *RoutesRequest, opts ...grpc.CallOption) (*RoutesResponse, error) - // Returns a list of known services based on routes - Services(ctx context.Context, in *ServicesRequest, opts ...grpc.CallOption) (*ServicesResponse, error) - // Status returns network status - Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (*StatusResponse, error) -} - -type networkClient struct { - cc *grpc.ClientConn -} - -func NewNetworkClient(cc *grpc.ClientConn) NetworkClient { - return &networkClient{cc} -} - -func (c *networkClient) Connect(ctx context.Context, in *ConnectRequest, opts ...grpc.CallOption) (*ConnectResponse, error) { - out := new(ConnectResponse) - err := c.cc.Invoke(ctx, "/go.micro.network.Network/Connect", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkClient) Graph(ctx context.Context, in *GraphRequest, opts ...grpc.CallOption) (*GraphResponse, error) { - out := new(GraphResponse) - err := c.cc.Invoke(ctx, "/go.micro.network.Network/Graph", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkClient) Nodes(ctx context.Context, in *NodesRequest, opts ...grpc.CallOption) (*NodesResponse, error) { - out := new(NodesResponse) - err := c.cc.Invoke(ctx, "/go.micro.network.Network/Nodes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkClient) Routes(ctx context.Context, in *RoutesRequest, opts ...grpc.CallOption) (*RoutesResponse, error) { - out := new(RoutesResponse) - err := c.cc.Invoke(ctx, "/go.micro.network.Network/Routes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkClient) Services(ctx context.Context, in *ServicesRequest, opts ...grpc.CallOption) (*ServicesResponse, error) { - out := new(ServicesResponse) - err := c.cc.Invoke(ctx, "/go.micro.network.Network/Services", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkClient) Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (*StatusResponse, error) { - out := new(StatusResponse) - err := c.cc.Invoke(ctx, "/go.micro.network.Network/Status", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// NetworkServer is the server API for Network service. -type NetworkServer interface { - // Connect to the network - Connect(context.Context, *ConnectRequest) (*ConnectResponse, error) - // Returns the entire network graph - Graph(context.Context, *GraphRequest) (*GraphResponse, error) - // Returns a list of known nodes in the network - Nodes(context.Context, *NodesRequest) (*NodesResponse, error) - // Returns a list of known routes in the network - Routes(context.Context, *RoutesRequest) (*RoutesResponse, error) - // Returns a list of known services based on routes - Services(context.Context, *ServicesRequest) (*ServicesResponse, error) - // Status returns network status - Status(context.Context, *StatusRequest) (*StatusResponse, error) -} - -// UnimplementedNetworkServer can be embedded to have forward compatible implementations. -type UnimplementedNetworkServer struct { -} - -func (*UnimplementedNetworkServer) Connect(ctx context.Context, req *ConnectRequest) (*ConnectResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Connect not implemented") -} -func (*UnimplementedNetworkServer) Graph(ctx context.Context, req *GraphRequest) (*GraphResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Graph not implemented") -} -func (*UnimplementedNetworkServer) Nodes(ctx context.Context, req *NodesRequest) (*NodesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Nodes not implemented") -} -func (*UnimplementedNetworkServer) Routes(ctx context.Context, req *RoutesRequest) (*RoutesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Routes not implemented") -} -func (*UnimplementedNetworkServer) Services(ctx context.Context, req *ServicesRequest) (*ServicesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Services not implemented") -} -func (*UnimplementedNetworkServer) Status(ctx context.Context, req *StatusRequest) (*StatusResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Status not implemented") -} - -func RegisterNetworkServer(s *grpc.Server, srv NetworkServer) { - s.RegisterService(&_Network_serviceDesc, srv) -} - -func _Network_Connect_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ConnectRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(NetworkServer).Connect(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.network.Network/Connect", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(NetworkServer).Connect(ctx, req.(*ConnectRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Network_Graph_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GraphRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(NetworkServer).Graph(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.network.Network/Graph", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(NetworkServer).Graph(ctx, req.(*GraphRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Network_Nodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(NodesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(NetworkServer).Nodes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.network.Network/Nodes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(NetworkServer).Nodes(ctx, req.(*NodesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Network_Routes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RoutesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(NetworkServer).Routes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.network.Network/Routes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(NetworkServer).Routes(ctx, req.(*RoutesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Network_Services_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ServicesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(NetworkServer).Services(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.network.Network/Services", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(NetworkServer).Services(ctx, req.(*ServicesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Network_Status_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(StatusRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(NetworkServer).Status(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.network.Network/Status", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(NetworkServer).Status(ctx, req.(*StatusRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Network_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.network.Network", - HandlerType: (*NetworkServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Connect", - Handler: _Network_Connect_Handler, - }, - { - MethodName: "Graph", - Handler: _Network_Graph_Handler, - }, - { - MethodName: "Nodes", - Handler: _Network_Nodes_Handler, - }, - { - MethodName: "Routes", - Handler: _Network_Routes_Handler, - }, - { - MethodName: "Services", - Handler: _Network_Services_Handler, - }, - { - MethodName: "Status", - Handler: _Network_Status_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "network/service/proto/network.proto", -} diff --git a/network/service/proto/network.pb.micro.go b/network/service/proto/network.pb.micro.go deleted file mode 100644 index 2446ff23..00000000 --- a/network/service/proto/network.pb.micro.go +++ /dev/null @@ -1,191 +0,0 @@ -// Code generated by protoc-gen-micro. DO NOT EDIT. -// source: network/service/proto/network.proto - -package go_micro_network - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - _ "github.com/micro/go-micro/v2/router/service/proto" - math "math" -) - -import ( - context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ api.Endpoint -var _ context.Context -var _ client.Option -var _ server.Option - -// Api Endpoints for Network service - -func NewNetworkEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Network service - -type NetworkService interface { - // Connect to the network - Connect(ctx context.Context, in *ConnectRequest, opts ...client.CallOption) (*ConnectResponse, error) - // Returns the entire network graph - Graph(ctx context.Context, in *GraphRequest, opts ...client.CallOption) (*GraphResponse, error) - // Returns a list of known nodes in the network - Nodes(ctx context.Context, in *NodesRequest, opts ...client.CallOption) (*NodesResponse, error) - // Returns a list of known routes in the network - Routes(ctx context.Context, in *RoutesRequest, opts ...client.CallOption) (*RoutesResponse, error) - // Returns a list of known services based on routes - Services(ctx context.Context, in *ServicesRequest, opts ...client.CallOption) (*ServicesResponse, error) - // Status returns network status - Status(ctx context.Context, in *StatusRequest, opts ...client.CallOption) (*StatusResponse, error) -} - -type networkService struct { - c client.Client - name string -} - -func NewNetworkService(name string, c client.Client) NetworkService { - return &networkService{ - c: c, - name: name, - } -} - -func (c *networkService) Connect(ctx context.Context, in *ConnectRequest, opts ...client.CallOption) (*ConnectResponse, error) { - req := c.c.NewRequest(c.name, "Network.Connect", in) - out := new(ConnectResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkService) Graph(ctx context.Context, in *GraphRequest, opts ...client.CallOption) (*GraphResponse, error) { - req := c.c.NewRequest(c.name, "Network.Graph", in) - out := new(GraphResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkService) Nodes(ctx context.Context, in *NodesRequest, opts ...client.CallOption) (*NodesResponse, error) { - req := c.c.NewRequest(c.name, "Network.Nodes", in) - out := new(NodesResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkService) Routes(ctx context.Context, in *RoutesRequest, opts ...client.CallOption) (*RoutesResponse, error) { - req := c.c.NewRequest(c.name, "Network.Routes", in) - out := new(RoutesResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkService) Services(ctx context.Context, in *ServicesRequest, opts ...client.CallOption) (*ServicesResponse, error) { - req := c.c.NewRequest(c.name, "Network.Services", in) - out := new(ServicesResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *networkService) Status(ctx context.Context, in *StatusRequest, opts ...client.CallOption) (*StatusResponse, error) { - req := c.c.NewRequest(c.name, "Network.Status", in) - out := new(StatusResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Network service - -type NetworkHandler interface { - // Connect to the network - Connect(context.Context, *ConnectRequest, *ConnectResponse) error - // Returns the entire network graph - Graph(context.Context, *GraphRequest, *GraphResponse) error - // Returns a list of known nodes in the network - Nodes(context.Context, *NodesRequest, *NodesResponse) error - // Returns a list of known routes in the network - Routes(context.Context, *RoutesRequest, *RoutesResponse) error - // Returns a list of known services based on routes - Services(context.Context, *ServicesRequest, *ServicesResponse) error - // Status returns network status - Status(context.Context, *StatusRequest, *StatusResponse) error -} - -func RegisterNetworkHandler(s server.Server, hdlr NetworkHandler, opts ...server.HandlerOption) error { - type network interface { - Connect(ctx context.Context, in *ConnectRequest, out *ConnectResponse) error - Graph(ctx context.Context, in *GraphRequest, out *GraphResponse) error - Nodes(ctx context.Context, in *NodesRequest, out *NodesResponse) error - Routes(ctx context.Context, in *RoutesRequest, out *RoutesResponse) error - Services(ctx context.Context, in *ServicesRequest, out *ServicesResponse) error - Status(ctx context.Context, in *StatusRequest, out *StatusResponse) error - } - type Network struct { - network - } - h := &networkHandler{hdlr} - return s.Handle(s.NewHandler(&Network{h}, opts...)) -} - -type networkHandler struct { - NetworkHandler -} - -func (h *networkHandler) Connect(ctx context.Context, in *ConnectRequest, out *ConnectResponse) error { - return h.NetworkHandler.Connect(ctx, in, out) -} - -func (h *networkHandler) Graph(ctx context.Context, in *GraphRequest, out *GraphResponse) error { - return h.NetworkHandler.Graph(ctx, in, out) -} - -func (h *networkHandler) Nodes(ctx context.Context, in *NodesRequest, out *NodesResponse) error { - return h.NetworkHandler.Nodes(ctx, in, out) -} - -func (h *networkHandler) Routes(ctx context.Context, in *RoutesRequest, out *RoutesResponse) error { - return h.NetworkHandler.Routes(ctx, in, out) -} - -func (h *networkHandler) Services(ctx context.Context, in *ServicesRequest, out *ServicesResponse) error { - return h.NetworkHandler.Services(ctx, in, out) -} - -func (h *networkHandler) Status(ctx context.Context, in *StatusRequest, out *StatusResponse) error { - return h.NetworkHandler.Status(ctx, in, out) -} diff --git a/network/service/proto/network.proto b/network/service/proto/network.proto deleted file mode 100644 index 5822d48d..00000000 --- a/network/service/proto/network.proto +++ /dev/null @@ -1,131 +0,0 @@ -syntax = "proto3"; - -package go.micro.network; - -import "router/service/proto/router.proto"; - -// Network service is usesd to gain visibility into networks -service Network { - // Connect to the network - rpc Connect(ConnectRequest) returns (ConnectResponse) {}; - // Returns the entire network graph - rpc Graph(GraphRequest) returns (GraphResponse) {}; - // Returns a list of known nodes in the network - rpc Nodes(NodesRequest) returns (NodesResponse) {}; - // Returns a list of known routes in the network - rpc Routes(RoutesRequest) returns (RoutesResponse) {}; - // Returns a list of known services based on routes - rpc Services(ServicesRequest) returns (ServicesResponse) {}; - // Status returns network status - rpc Status(StatusRequest) returns (StatusResponse) {}; -} - -// Query is passed in a LookupRequest -message Query { - string service = 1; - string address = 2; - string gateway = 3; - string router = 4; - string network = 5; -} - -message ConnectRequest { - repeated Node nodes = 1; -} - -message ConnectResponse {} - -// PeerRequest requests list of peers -message NodesRequest { - // node topology depth - uint32 depth = 1; -} - -// PeerResponse is returned by ListPeers -message NodesResponse { - // return peer topology - repeated Node nodes = 1; -} - -message GraphRequest { - // node topology depth - uint32 depth = 1; -} - -message GraphResponse { - Peer root = 1; -} - -message RoutesRequest { - // filter based on - Query query = 1; -} - -message RoutesResponse { - repeated go.micro.router.Route routes = 1; -} - -message ServicesRequest {} - -message ServicesResponse { - repeated string services = 1; -} - -message StatusRequest {} - -message StatusResponse { - Status status = 1; -} - -// Error tracks network errors -message Error { - uint32 count = 1; - string msg = 2; -} - -// Status is node status -message Status { - Error error = 1; -} - -// Node is network node -message Node { - // node id - string id = 1; - // node address - string address = 2; - // the network - string network = 3; - // associated metadata - map metadata = 4; - // node status - Status status = 5; -} - -// Connect is sent when the node connects to the network -message Connect { - // network mode - Node node = 1; -} - -// Close is sent when the node disconnects from the network -message Close { - // network node - Node node = 1; -} - -// Peer is used to advertise node peers -message Peer { - // network node - Node node = 1; - // node peers - repeated Peer peers = 2; -} - -// Sync is network sync message -message Sync { - // peer origin - Peer peer = 1; - // node routes - repeated go.micro.router.Route routes = 2; -} diff --git a/options.go b/options.go deleted file mode 100644 index d3c24615..00000000 --- a/options.go +++ /dev/null @@ -1,340 +0,0 @@ -package micro - -import ( - "context" - "time" - - "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/cmd" - "github.com/micro/go-micro/v2/config" - "github.com/micro/go-micro/v2/debug/profile" - "github.com/micro/go-micro/v2/debug/trace" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/runtime" - "github.com/micro/go-micro/v2/selector" - "github.com/micro/go-micro/v2/server" - "github.com/micro/go-micro/v2/store" - "github.com/micro/go-micro/v2/transport" -) - -// Options for micro service -type Options struct { - Auth auth.Auth - Broker broker.Broker - Cmd cmd.Cmd - Config config.Config - Client client.Client - Server server.Server - Store store.Store - Registry registry.Registry - Router router.Router - Runtime runtime.Runtime - Transport transport.Transport - Profile profile.Profile - - // Before and After funcs - BeforeStart []func() error - BeforeStop []func() error - AfterStart []func() error - AfterStop []func() error - - // Other options for implementations of the interface - // can be stored in a context - Context context.Context - - Signal bool -} - -func newOptions(opts ...Option) Options { - opt := Options{ - Auth: auth.DefaultAuth, - Broker: broker.DefaultBroker, - Cmd: cmd.DefaultCmd, - Config: config.DefaultConfig, - Client: client.DefaultClient, - Server: server.DefaultServer, - Store: store.DefaultStore, - Registry: registry.DefaultRegistry, - Router: router.DefaultRouter, - Runtime: runtime.DefaultRuntime, - Transport: transport.DefaultTransport, - Context: context.Background(), - Signal: true, - } - - for _, o := range opts { - o(&opt) - } - - return opt -} - -// Broker to be used for service -func Broker(b broker.Broker) Option { - return func(o *Options) { - o.Broker = b - // Update Client and Server - o.Client.Init(client.Broker(b)) - o.Server.Init(server.Broker(b)) - } -} - -func Cmd(c cmd.Cmd) Option { - return func(o *Options) { - o.Cmd = c - } -} - -// Client to be used for service -func Client(c client.Client) Option { - return func(o *Options) { - o.Client = c - } -} - -// Context specifies a context for the service. -// Can be used to signal shutdown of the service and for extra option values. -func Context(ctx context.Context) Option { - return func(o *Options) { - o.Context = ctx - } -} - -// HandleSignal toggles automatic installation of the signal handler that -// traps TERM, INT, and QUIT. Users of this feature to disable the signal -// handler, should control liveness of the service through the context. -func HandleSignal(b bool) Option { - return func(o *Options) { - o.Signal = b - } -} - -// Profile to be used for debug profile -func Profile(p profile.Profile) Option { - return func(o *Options) { - o.Profile = p - } -} - -// Server to be used for service -func Server(s server.Server) Option { - return func(o *Options) { - o.Server = s - } -} - -// Store sets the store to use -func Store(s store.Store) Option { - return func(o *Options) { - o.Store = s - } -} - -// Registry sets the registry for the service -// and the underlying components -func Registry(r registry.Registry) Option { - return func(o *Options) { - o.Registry = r - // Update router - o.Router.Init(router.Registry(r)) - // Update server - o.Server.Init(server.Registry(r)) - // Update Broker - o.Broker.Init(broker.Registry(r)) - } -} - -// Tracer sets the tracer for the service -func Tracer(t trace.Tracer) Option { - return func(o *Options) { - o.Server.Init(server.Tracer(t)) - } -} - -// Auth sets the auth for the service -func Auth(a auth.Auth) Option { - return func(o *Options) { - o.Auth = a - o.Server.Init(server.Auth(a)) - } -} - -// Config sets the config for the service -func Config(c config.Config) Option { - return func(o *Options) { - o.Config = c - } -} - -// Selector sets the selector for the service client -func Selector(s selector.Selector) Option { - return func(o *Options) { - o.Client.Init(client.Selector(s)) - } -} - -// Transport sets the transport for the service -// and the underlying components -func Transport(t transport.Transport) Option { - return func(o *Options) { - o.Transport = t - // Update Client and Server - o.Client.Init(client.Transport(t)) - o.Server.Init(server.Transport(t)) - } -} - -// Runtime sets the runtime -func Runtime(r runtime.Runtime) Option { - return func(o *Options) { - o.Runtime = r - } -} - -// Router sets the router -func Router(r router.Router) Option { - return func(o *Options) { - o.Router = r - // Update client - o.Client.Init(client.Router(r)) - } -} - -// Convenience options - -// Address sets the address of the server -func Address(addr string) Option { - return func(o *Options) { - o.Server.Init(server.Address(addr)) - } -} - -// Name of the service -func Name(n string) Option { - return func(o *Options) { - o.Server.Init(server.Name(n)) - } -} - -// Version of the service -func Version(v string) Option { - return func(o *Options) { - o.Server.Init(server.Version(v)) - } -} - -// Metadata associated with the service -func Metadata(md map[string]string) Option { - return func(o *Options) { - o.Server.Init(server.Metadata(md)) - } -} - -// Flags that can be passed to service -func Flags(flags ...cli.Flag) Option { - return func(o *Options) { - o.Cmd.App().Flags = append(o.Cmd.App().Flags, flags...) - } -} - -// Action can be used to parse user provided cli options -func Action(a func(*cli.Context) error) Option { - return func(o *Options) { - o.Cmd.App().Action = a - } -} - -// RegisterTTL specifies the TTL to use when registering the service -func RegisterTTL(t time.Duration) Option { - return func(o *Options) { - o.Server.Init(server.RegisterTTL(t)) - } -} - -// RegisterInterval specifies the interval on which to re-register -func RegisterInterval(t time.Duration) Option { - return func(o *Options) { - o.Server.Init(server.RegisterInterval(t)) - } -} - -// WrapClient is a convenience method for wrapping a Client with -// some middleware component. A list of wrappers can be provided. -// Wrappers are applied in reverse order so the last is executed first. -func WrapClient(w ...client.Wrapper) Option { - return func(o *Options) { - // apply in reverse - for i := len(w); i > 0; i-- { - o.Client = w[i-1](o.Client) - } - } -} - -// WrapCall is a convenience method for wrapping a Client CallFunc -func WrapCall(w ...client.CallWrapper) Option { - return func(o *Options) { - o.Client.Init(client.WrapCall(w...)) - } -} - -// WrapHandler adds a handler Wrapper to a list of options passed into the server -func WrapHandler(w ...server.HandlerWrapper) Option { - return func(o *Options) { - var wrappers []server.Option - - for _, wrap := range w { - wrappers = append(wrappers, server.WrapHandler(wrap)) - } - - // Init once - o.Server.Init(wrappers...) - } -} - -// WrapSubscriber adds a subscriber Wrapper to a list of options passed into the server -func WrapSubscriber(w ...server.SubscriberWrapper) Option { - return func(o *Options) { - var wrappers []server.Option - - for _, wrap := range w { - wrappers = append(wrappers, server.WrapSubscriber(wrap)) - } - - // Init once - o.Server.Init(wrappers...) - } -} - -// Before and Afters - -// BeforeStart run funcs before service starts -func BeforeStart(fn func() error) Option { - return func(o *Options) { - o.BeforeStart = append(o.BeforeStart, fn) - } -} - -// BeforeStop run funcs before service stops -func BeforeStop(fn func() error) Option { - return func(o *Options) { - o.BeforeStop = append(o.BeforeStop, fn) - } -} - -// AfterStart run funcs after service starts -func AfterStart(fn func() error) Option { - return func(o *Options) { - o.AfterStart = append(o.AfterStart, fn) - } -} - -// AfterStop run funcs after service stops -func AfterStop(fn func() error) Option { - return func(o *Options) { - o.AfterStop = append(o.AfterStop, fn) - } -} diff --git a/plugin/default.go b/plugin/default.go index 62842cf2..181dace2 100644 --- a/plugin/default.go +++ b/plugin/default.go @@ -10,65 +10,10 @@ import ( pg "plugin" "strings" "text/template" - - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/cmd" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/selector" - "github.com/micro/go-micro/v2/server" - "github.com/micro/go-micro/v2/transport" ) type plugin struct{} -// Init sets up the plugin -func (p *plugin) Init(c *Config) error { - switch c.Type { - case "broker": - pg, ok := c.NewFunc.(func(...broker.Option) broker.Broker) - if !ok { - return fmt.Errorf("Invalid plugin %s", c.Name) - } - cmd.DefaultBrokers[c.Name] = pg - case "client": - pg, ok := c.NewFunc.(func(...client.Option) client.Client) - if !ok { - return fmt.Errorf("Invalid plugin %s", c.Name) - } - cmd.DefaultClients[c.Name] = pg - case "registry": - pg, ok := c.NewFunc.(func(...registry.Option) registry.Registry) - if !ok { - return fmt.Errorf("Invalid plugin %s", c.Name) - } - cmd.DefaultRegistries[c.Name] = pg - - case "selector": - pg, ok := c.NewFunc.(func(...selector.Option) selector.Selector) - if !ok { - return fmt.Errorf("Invalid plugin %s", c.Name) - } - cmd.DefaultSelectors[c.Name] = pg - case "server": - pg, ok := c.NewFunc.(func(...server.Option) server.Server) - if !ok { - return fmt.Errorf("Invalid plugin %s", c.Name) - } - cmd.DefaultServers[c.Name] = pg - case "transport": - pg, ok := c.NewFunc.(func(...transport.Option) transport.Transport) - if !ok { - return fmt.Errorf("Invalid plugin %s", c.Name) - } - cmd.DefaultTransports[c.Name] = pg - default: - return fmt.Errorf("Unknown plugin type: %s for %s", c.Type, c.Name) - } - - return nil -} - // Load loads a plugin created with `go build -buildmode=plugin` func (p *plugin) Load(path string) (*Config, error) { plugin, err := pg.Open(path) diff --git a/plugin/plugin.go b/plugin/plugin.go index c1aecc6e..b982085a 100644 --- a/plugin/plugin.go +++ b/plugin/plugin.go @@ -3,8 +3,6 @@ package plugin // Plugin is a plugin loaded from a file type Plugin interface { - // Initialise a plugin with the config - Init(c *Config) error // Load loads a .so plugin at the given path Load(path string) (*Config, error) // Build a .so plugin with config at the path specified @@ -40,7 +38,3 @@ func Build(path string, c *Config) error { func Load(path string) (*Config, error) { return DefaultPlugin.Load(path) } - -func Init(c *Config) error { - return DefaultPlugin.Init(c) -} diff --git a/plugin/template.go b/plugin/template.go index 38e6f7e4..5f8035e2 100644 --- a/plugin/template.go +++ b/plugin/template.go @@ -5,7 +5,7 @@ var ( package main import ( - "github.com/micro/go-micro/v2/plugin" + "github.com/micro/go-micro/v3/plugin" "{{.Path}}" ) diff --git a/proxy/grpc/grpc.go b/proxy/grpc/grpc.go index 0df9bbe0..a0590368 100644 --- a/proxy/grpc/grpc.go +++ b/proxy/grpc/grpc.go @@ -6,11 +6,11 @@ import ( "io" "strings" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/client/grpc" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/proxy" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/client/grpc" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/proxy" + "github.com/micro/go-micro/v3/server" ) // Proxy will transparently proxy requests to the backend. diff --git a/proxy/http/http.go b/proxy/http/http.go index 06332da5..122134fd 100644 --- a/proxy/http/http.go +++ b/proxy/http/http.go @@ -10,9 +10,9 @@ import ( "net/url" "path" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/proxy" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/proxy" + "github.com/micro/go-micro/v3/server" ) // Proxy will proxy rpc requests as http POST requests. It is a server.Proxy diff --git a/proxy/http/http_test.go b/proxy/http/http_test.go index fd3a1c11..ace10acf 100644 --- a/proxy/http/http_test.go +++ b/proxy/http/http_test.go @@ -8,10 +8,11 @@ import ( "sync" "testing" - "github.com/micro/go-micro/v2" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/registry/memory" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/registry/memory" + "github.com/micro/go-micro/v3/server" + "github.com/micro/go-micro/v3/service" + "github.com/micro/go-micro/v3/service/mucp" ) type testHandler struct{} @@ -56,11 +57,11 @@ func TestHTTPProxy(t *testing.T) { wg.Add(1) // new micro service - service := micro.NewService( - micro.Context(ctx), - micro.Name("foobar"), - micro.Registry(memory.NewRegistry()), - micro.AfterStart(func() error { + service := mucp.NewService( + service.Context(ctx), + service.Name("foobar"), + service.Registry(memory.NewRegistry()), + service.AfterStart(func() error { wg.Done() return nil }), diff --git a/proxy/mucp/mucp.go b/proxy/mucp/mucp.go index 4c774de4..3a2733bf 100644 --- a/proxy/mucp/mucp.go +++ b/proxy/mucp/mucp.go @@ -10,16 +10,18 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/codec/bytes" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/proxy" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/selector/roundrobin" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/client/grpc" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/codec/bytes" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/proxy" + "github.com/micro/go-micro/v3/router" + "github.com/micro/go-micro/v3/router/registry" + "github.com/micro/go-micro/v3/selector/roundrobin" + "github.com/micro/go-micro/v3/server" ) // Proxy will transparently proxy requests to an endpoint. @@ -593,12 +595,12 @@ func NewProxy(opts ...proxy.Option) proxy.Proxy { // set the default client if p.Client == nil { - p.Client = client.DefaultClient + p.Client = grpc.NewClient() } // create default router and start it if p.Router == nil { - p.Router = router.DefaultRouter + p.Router = registry.NewRouter() } // set the links if options.Links != nil { diff --git a/proxy/options.go b/proxy/options.go index 877d66d5..ad1a3ef4 100644 --- a/proxy/options.go +++ b/proxy/options.go @@ -2,8 +2,8 @@ package proxy import ( - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/router" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/router" ) type Options struct { diff --git a/proxy/proxy.go b/proxy/proxy.go index 6b7b3a8d..167b1a81 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -4,7 +4,7 @@ package proxy import ( "context" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/server" ) // Proxy can be used as a proxy server for go-micro services diff --git a/registry/cache/cache.go b/registry/cache/cache.go index 70c359ca..5cc432f6 100644 --- a/registry/cache/cache.go +++ b/registry/cache/cache.go @@ -7,9 +7,9 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/registry" - util "github.com/micro/go-micro/v2/util/registry" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/registry" + util "github.com/micro/go-micro/v3/util/registry" ) // Cache is the registry cache interface diff --git a/registry/etcd/etcd.go b/registry/etcd/etcd.go index f768bd48..c9e8f08d 100644 --- a/registry/etcd/etcd.go +++ b/registry/etcd/etcd.go @@ -17,8 +17,8 @@ import ( "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes" "github.com/coreos/etcd/mvcc/mvccpb" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/registry" hash "github.com/mitchellh/hashstructure" "go.uber.org/zap" ) diff --git a/registry/etcd/options.go b/registry/etcd/options.go index b3ea19f1..f444c884 100644 --- a/registry/etcd/options.go +++ b/registry/etcd/options.go @@ -3,7 +3,7 @@ package etcd import ( "context" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" "go.uber.org/zap" ) diff --git a/registry/etcd/watcher.go b/registry/etcd/watcher.go index e1fab511..8a812a93 100644 --- a/registry/etcd/watcher.go +++ b/registry/etcd/watcher.go @@ -6,7 +6,7 @@ import ( "time" "github.com/coreos/etcd/clientv3" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) type etcdWatcher struct { diff --git a/registry/mdns/mdns.go b/registry/mdns/mdns.go index 498b2429..33e91be7 100644 --- a/registry/mdns/mdns.go +++ b/registry/mdns/mdns.go @@ -1,23 +1,769 @@ -// Package mdns provides a multicast dns registry package mdns import ( + "bytes" + "compress/zlib" "context" + "encoding/hex" + "encoding/json" + "fmt" + "io/ioutil" + "net" + "strconv" + "strings" + "sync" + "time" - "github.com/micro/go-micro/v2/registry" + "github.com/google/uuid" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/util/mdns" ) -// NewRegistry returns a new mdns registry -func NewRegistry(opts ...registry.Option) registry.Registry { - return registry.NewRegistry(opts...) +const ( + // every service is written to the global domain so * domain queries work, e.g. + // calling mdns.List(registry.ListDomain("*")) will list the services across all + // domains + globalDomain = "global" +) + +type mdnsTxt struct { + Service string + Version string + Endpoints []*registry.Endpoint + Metadata map[string]string } -// Domain sets the mdnsDomain -func Domain(d string) registry.Option { - return func(o *registry.Options) { - if o.Context == nil { - o.Context = context.Background() +type mdnsEntry struct { + id string + node *mdns.Server +} + +// services are a key/value map, with the service name as a key and the value being a +// slice of mdns entries, representing the nodes with a single _services entry to be +// used for listing +type services map[string][]*mdnsEntry + +// mdsRegistry is a multicast dns registry +type mdnsRegistry struct { + opts registry.Options + + // the top level domains, these can be overriden using options + defaultDomain string + globalDomain string + + sync.Mutex + domains map[string]services + + mtx sync.RWMutex + + // watchers + watchers map[string]*mdnsWatcher + + // listener + listener chan *mdns.ServiceEntry +} + +type mdnsWatcher struct { + id string + wo registry.WatchOptions + ch chan *mdns.ServiceEntry + exit chan struct{} + // the mdns domain + domain string + // the registry + registry *mdnsRegistry +} + +func encode(txt *mdnsTxt) ([]string, error) { + b, err := json.Marshal(txt) + if err != nil { + return nil, err + } + + var buf bytes.Buffer + defer buf.Reset() + + w := zlib.NewWriter(&buf) + defer func() { + if closeErr := w.Close(); closeErr != nil { + if logger.V(logger.ErrorLevel, logger.DefaultLogger) { + logger.Errorf("[mdns] registry close encoding writer err: %v", closeErr) + } } - o.Context = context.WithValue(o.Context, "mdns.domain", d) + }() + if _, err := w.Write(b); err != nil { + return nil, err + } + + if err = w.Close(); err != nil { + return nil, err + } + + encoded := hex.EncodeToString(buf.Bytes()) + // individual txt limit + if len(encoded) <= 255 { + return []string{encoded}, nil + } + + // split encoded string + var record []string + + for len(encoded) > 255 { + record = append(record, encoded[:255]) + encoded = encoded[255:] + } + + record = append(record, encoded) + + return record, nil +} + +func decode(record []string) (*mdnsTxt, error) { + encoded := strings.Join(record, "") + + hr, err := hex.DecodeString(encoded) + if err != nil { + return nil, err + } + + br := bytes.NewReader(hr) + zr, err := zlib.NewReader(br) + if err != nil { + return nil, err + } + defer zr.Close() + + rbuf, err := ioutil.ReadAll(zr) + if err != nil { + return nil, err + } + + var txt *mdnsTxt + + if err := json.Unmarshal(rbuf, &txt); err != nil { + return nil, err + } + + return txt, nil +} + +func newRegistry(opts ...registry.Option) registry.Registry { + options := registry.Options{ + Context: context.Background(), + Timeout: time.Millisecond * 100, + } + + for _, o := range opts { + o(&options) + } + + // set the domain + defaultDomain := registry.DefaultDomain + if d, ok := options.Context.Value("mdns.domain").(string); ok { + defaultDomain = d + } + + return &mdnsRegistry{ + defaultDomain: defaultDomain, + globalDomain: globalDomain, + opts: options, + domains: make(map[string]services), + watchers: make(map[string]*mdnsWatcher), } } + +func (m *mdnsRegistry) Init(opts ...registry.Option) error { + for _, o := range opts { + o(&m.opts) + } + return nil +} + +func (m *mdnsRegistry) Options() registry.Options { + return m.opts +} + +// createServiceMDNSEntry will create a new wildcard mdns entry for the service in the +// given domain. This wildcard mdns entry is used when listing services. +func createServiceMDNSEntry(name, domain string) (*mdnsEntry, error) { + ip := net.ParseIP("0.0.0.0") + + s, err := mdns.NewMDNSService(name, "_services", domain+".", "", 9999, []net.IP{ip}, nil) + if err != nil { + return nil, err + } + + srv, err := mdns.NewServer(&mdns.Config{Zone: &mdns.DNSSDService{MDNSService: s}, LocalhostChecking: true}) + if err != nil { + return nil, err + } + + return &mdnsEntry{id: "*", node: srv}, nil +} + +func (m *mdnsRegistry) getMdnsEntries(domain, serviceName string) ([]*mdnsEntry, error) { + entries, ok := m.domains[domain][serviceName] + if ok { + return entries, nil + } + + // create the wildcard entry used for list queries in this domain + entry, err := createServiceMDNSEntry(serviceName, domain) + if err != nil { + return nil, err + } + + return []*mdnsEntry{entry}, nil +} + +func registerService(service *registry.Service, entries []*mdnsEntry, options registry.RegisterOptions) ([]*mdnsEntry, error) { + var lastError error + for _, node := range service.Nodes { + var seen bool + + for _, entry := range entries { + if node.Id == entry.id { + seen = true + break + } + } + + // this node has already been registered, continue + if seen { + continue + } + + txt, err := encode(&mdnsTxt{ + Service: service.Name, + Version: service.Version, + Endpoints: service.Endpoints, + Metadata: node.Metadata, + }) + + if err != nil { + lastError = err + continue + } + + host, pt, err := net.SplitHostPort(node.Address) + if err != nil { + lastError = err + continue + } + port, _ := strconv.Atoi(pt) + + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("[mdns] registry create new service with ip: %s for: %s", net.ParseIP(host).String(), host) + } + // we got here, new node + s, err := mdns.NewMDNSService( + node.Id, + service.Name, + options.Domain+".", + "", + port, + []net.IP{net.ParseIP(host)}, + txt, + ) + if err != nil { + lastError = err + continue + } + + srv, err := mdns.NewServer(&mdns.Config{Zone: s, LocalhostChecking: true}) + if err != nil { + lastError = err + continue + } + + entries = append(entries, &mdnsEntry{id: node.Id, node: srv}) + } + + return entries, lastError +} + +func createGlobalDomainService(service *registry.Service, options registry.RegisterOptions) *registry.Service { + srv := *service + srv.Nodes = nil + + for _, n := range service.Nodes { + node := n + + // set the original domain in node metadata + if node.Metadata == nil { + node.Metadata = map[string]string{"domain": options.Domain} + } else { + node.Metadata["domain"] = options.Domain + } + + srv.Nodes = append(srv.Nodes, node) + } + + return &srv +} + +func (m *mdnsRegistry) Register(service *registry.Service, opts ...registry.RegisterOption) error { + m.Lock() + + // parse the options + var options registry.RegisterOptions + for _, o := range opts { + o(&options) + } + if len(options.Domain) == 0 { + options.Domain = m.defaultDomain + } + + // create the domain in the memory store if it doesn't yet exist + if _, ok := m.domains[options.Domain]; !ok { + m.domains[options.Domain] = make(services) + } + + entries, err := m.getMdnsEntries(options.Domain, service.Name) + if err != nil { + m.Unlock() + return err + } + + entries, gerr := registerService(service, entries, options) + + // save the mdns entry + m.domains[options.Domain][service.Name] = entries + m.Unlock() + + // register in the global Domain so it can be queried as one + if options.Domain != m.globalDomain { + srv := createGlobalDomainService(service, options) + if err := m.Register(srv, append(opts, registry.RegisterDomain(m.globalDomain))...); err != nil { + gerr = err + } + } + + return gerr +} + +func (m *mdnsRegistry) Deregister(service *registry.Service, opts ...registry.DeregisterOption) error { + // parse the options + var options registry.DeregisterOptions + for _, o := range opts { + o(&options) + } + if len(options.Domain) == 0 { + options.Domain = m.defaultDomain + } + + // register in the global Domain + var err error + if options.Domain != m.globalDomain { + defer func() { + err = m.Deregister(service, append(opts, registry.DeregisterDomain(m.globalDomain))...) + }() + } + + // we want to unlock before we call deregister on the global domain, so it's important this unlock + // is applied after the defer m.Deregister is called above + m.Lock() + defer m.Unlock() + + // the service wasn't registered, we can safely exist + if _, ok := m.domains[options.Domain]; !ok { + return err + } + + // loop existing entries, check if any match, shutdown those that do + var newEntries []*mdnsEntry + for _, entry := range m.domains[options.Domain][service.Name] { + var remove bool + + for _, node := range service.Nodes { + if node.Id == entry.id { + entry.node.Shutdown() + remove = true + break + } + } + + // keep it? + if !remove { + newEntries = append(newEntries, entry) + } + } + + // we have no new entries, we can exit + if len(newEntries) == 0 { + return nil + } + + // we have more than one entry remaining, we can exit + if len(newEntries) > 1 { + m.domains[options.Domain][service.Name] = newEntries + return err + } + + // our remaining entry is not a wildcard, we can exit + if len(newEntries) == 1 && newEntries[0].id != "*" { + m.domains[options.Domain][service.Name] = newEntries + return err + } + + // last entry is the wildcard for list queries. Remove it. + newEntries[0].node.Shutdown() + delete(m.domains[options.Domain], service.Name) + + // check to see if we can delete the domain entry + if len(m.domains[options.Domain]) == 0 { + delete(m.domains, options.Domain) + } + + return err +} + +func (m *mdnsRegistry) GetService(service string, opts ...registry.GetOption) ([]*registry.Service, error) { + // parse the options + var options registry.GetOptions + for _, o := range opts { + o(&options) + } + if len(options.Domain) == 0 { + options.Domain = m.defaultDomain + } + if options.Domain == registry.WildcardDomain { + options.Domain = m.globalDomain + } + + serviceMap := make(map[string]*registry.Service) + entries := make(chan *mdns.ServiceEntry, 10) + done := make(chan bool) + + p := mdns.DefaultParams(service) + // set context with timeout + var cancel context.CancelFunc + p.Context, cancel = context.WithTimeout(context.Background(), m.opts.Timeout) + defer cancel() + // set entries channel + p.Entries = entries + // set the domain + p.Domain = options.Domain + + go func() { + for { + select { + case e := <-entries: + // list record so skip + if e.Name == "_services" { + continue + } + if e.TTL == 0 { + continue + } + + txt, err := decode(e.InfoFields) + if err != nil { + continue + } + + if txt.Service != service { + continue + } + + s, ok := serviceMap[txt.Version] + if !ok { + s = ®istry.Service{ + Name: txt.Service, + Version: txt.Version, + Endpoints: txt.Endpoints, + } + } + addr := "" + // prefer ipv4 addrs + if len(e.AddrV4) > 0 { + addr = e.AddrV4.String() + // else use ipv6 + } else if len(e.AddrV6) > 0 { + addr = "[" + e.AddrV6.String() + "]" + } else { + if logger.V(logger.InfoLevel, logger.DefaultLogger) { + logger.Infof("[mdns]: invalid endpoint received: %v", e) + } + continue + } + s.Nodes = append(s.Nodes, ®istry.Node{ + Id: strings.TrimSuffix(e.Name, "."+p.Service+"."+p.Domain+"."), + Address: fmt.Sprintf("%s:%d", addr, e.Port), + Metadata: txt.Metadata, + }) + + serviceMap[txt.Version] = s + case <-p.Context.Done(): + close(done) + return + } + } + }() + + // execute the query + if err := mdns.Query(p); err != nil { + return nil, err + } + + // wait for completion + <-done + + // create list and return + services := make([]*registry.Service, 0, len(serviceMap)) + + for _, service := range serviceMap { + services = append(services, service) + } + + return services, nil +} + +func (m *mdnsRegistry) ListServices(opts ...registry.ListOption) ([]*registry.Service, error) { + // parse the options + var options registry.ListOptions + for _, o := range opts { + o(&options) + } + if len(options.Domain) == 0 { + options.Domain = m.defaultDomain + } + if options.Domain == registry.WildcardDomain { + options.Domain = m.globalDomain + } + + serviceMap := make(map[string]bool) + entries := make(chan *mdns.ServiceEntry, 10) + done := make(chan bool) + + p := mdns.DefaultParams("_services") + // set context with timeout + var cancel context.CancelFunc + p.Context, cancel = context.WithTimeout(context.Background(), m.opts.Timeout) + defer cancel() + // set entries channel + p.Entries = entries + // set domain + p.Domain = options.Domain + + var services []*registry.Service + + go func() { + for { + select { + case e := <-entries: + if e.TTL == 0 { + continue + } + if !strings.HasSuffix(e.Name, p.Domain+".") { + continue + } + name := strings.TrimSuffix(e.Name, "."+p.Service+"."+p.Domain+".") + if !serviceMap[name] { + serviceMap[name] = true + services = append(services, ®istry.Service{Name: name}) + } + case <-p.Context.Done(): + close(done) + return + } + } + }() + + // execute query + if err := mdns.Query(p); err != nil { + return nil, err + } + + // wait till done + <-done + + return services, nil +} + +func (m *mdnsRegistry) Watch(opts ...registry.WatchOption) (registry.Watcher, error) { + var wo registry.WatchOptions + for _, o := range opts { + o(&wo) + } + if len(wo.Domain) == 0 { + wo.Domain = m.defaultDomain + } + if wo.Domain == registry.WildcardDomain { + wo.Domain = m.globalDomain + } + + md := &mdnsWatcher{ + id: uuid.New().String(), + wo: wo, + ch: make(chan *mdns.ServiceEntry, 32), + exit: make(chan struct{}), + domain: wo.Domain, + registry: m, + } + + m.mtx.Lock() + defer m.mtx.Unlock() + + // save the watcher + m.watchers[md.id] = md + + // check of the listener exists + if m.listener != nil { + return md, nil + } + + // start the listener + go func() { + // go to infinity + for { + m.mtx.Lock() + + // just return if there are no watchers + if len(m.watchers) == 0 { + m.listener = nil + m.mtx.Unlock() + return + } + + // check existing listener + if m.listener != nil { + m.mtx.Unlock() + return + } + + // reset the listener + exit := make(chan struct{}) + ch := make(chan *mdns.ServiceEntry, 32) + m.listener = ch + + m.mtx.Unlock() + + // send messages to the watchers + go func() { + send := func(w *mdnsWatcher, e *mdns.ServiceEntry) { + select { + case w.ch <- e: + default: + } + } + + for { + select { + case <-exit: + return + case e, ok := <-ch: + if !ok { + return + } + m.mtx.RLock() + // send service entry to all watchers + for _, w := range m.watchers { + send(w, e) + } + m.mtx.RUnlock() + } + } + + }() + + // start listening, blocking call + mdns.Listen(ch, exit) + + // mdns.Listen has unblocked + // kill the saved listener + m.mtx.Lock() + m.listener = nil + close(ch) + m.mtx.Unlock() + } + }() + + return md, nil +} + +func (m *mdnsRegistry) String() string { + return "mdns" +} + +func (m *mdnsWatcher) Next() (*registry.Result, error) { + for { + select { + case e := <-m.ch: + txt, err := decode(e.InfoFields) + if err != nil { + continue + } + + if len(txt.Service) == 0 || len(txt.Version) == 0 { + continue + } + + // Filter watch options + // wo.Service: Only keep services we care about + if len(m.wo.Service) > 0 && txt.Service != m.wo.Service { + continue + } + var action string + if e.TTL == 0 { + action = "delete" + } else { + action = "create" + } + + service := ®istry.Service{ + Name: txt.Service, + Version: txt.Version, + Endpoints: txt.Endpoints, + Metadata: txt.Metadata, + } + + // skip anything without the domain we care about + suffix := fmt.Sprintf(".%s.%s.", service.Name, m.domain) + if !strings.HasSuffix(e.Name, suffix) { + continue + } + + var addr string + if len(e.AddrV4) > 0 { + addr = e.AddrV4.String() + } else if len(e.AddrV6) > 0 { + addr = "[" + e.AddrV6.String() + "]" + } else { + addr = e.Addr.String() + } + + service.Nodes = append(service.Nodes, ®istry.Node{ + Id: strings.TrimSuffix(e.Name, suffix), + Address: fmt.Sprintf("%s:%d", addr, e.Port), + Metadata: txt.Metadata, + }) + + return ®istry.Result{ + Action: action, + Service: service, + }, nil + case <-m.exit: + return nil, registry.ErrWatcherStopped + } + } +} + +func (m *mdnsWatcher) Stop() { + select { + case <-m.exit: + return + default: + close(m.exit) + // remove self from the registry + m.registry.mtx.Lock() + delete(m.registry.watchers, m.id) + m.registry.mtx.Unlock() + } +} + +// NewRegistry returns a new default registry which is mdns +func NewRegistry(opts ...registry.Option) registry.Registry { + return newRegistry(opts...) +} diff --git a/registry/mdns_test.go b/registry/mdns/mdns_test.go similarity index 90% rename from registry/mdns_test.go rename to registry/mdns/mdns_test.go index e1cb12da..7e3d4c1a 100644 --- a/registry/mdns_test.go +++ b/registry/mdns/mdns_test.go @@ -1,9 +1,11 @@ -package registry +package mdns import ( "os" "testing" "time" + + "github.com/micro/go-micro/v3/registry" ) func TestMDNS(t *testing.T) { @@ -12,11 +14,11 @@ func TestMDNS(t *testing.T) { t.Skip() } - testData := []*Service{ + testData := []*registry.Service{ { Name: "test1", Version: "1.0.1", - Nodes: []*Node{ + Nodes: []*registry.Node{ { Id: "test1-1", Address: "10.0.0.1:10001", @@ -29,7 +31,7 @@ func TestMDNS(t *testing.T) { { Name: "test2", Version: "1.0.2", - Nodes: []*Node{ + Nodes: []*registry.Node{ { Id: "test2-1", Address: "10.0.0.2:10002", @@ -42,7 +44,7 @@ func TestMDNS(t *testing.T) { { Name: "test3", Version: "1.0.3", - Nodes: []*Node{ + Nodes: []*registry.Node{ { Id: "test3-1", Address: "10.0.0.3:10003", @@ -56,10 +58,10 @@ func TestMDNS(t *testing.T) { travis := os.Getenv("TRAVIS") - var opts []Option + var opts []registry.Option if travis == "true" { - opts = append(opts, Timeout(time.Millisecond*100)) + opts = append(opts, registry.Timeout(time.Millisecond*100)) } // new registry @@ -144,14 +146,14 @@ func TestEncoding(t *testing.T) { Metadata: map[string]string{ "foo": "bar", }, - Endpoints: []*Endpoint{ + Endpoints: []*registry.Endpoint{ { Name: "endpoint1", - Request: &Value{ + Request: ®istry.Value{ Name: "request", Type: "request", }, - Response: &Value{ + Response: ®istry.Value{ Name: "response", Type: "response", }, @@ -202,11 +204,11 @@ func TestWatcher(t *testing.T) { t.Skip() } - testData := []*Service{ + testData := []*registry.Service{ { Name: "test1", Version: "1.0.1", - Nodes: []*Node{ + Nodes: []*registry.Node{ { Id: "test1-1", Address: "10.0.0.1:10001", @@ -219,7 +221,7 @@ func TestWatcher(t *testing.T) { { Name: "test2", Version: "1.0.2", - Nodes: []*Node{ + Nodes: []*registry.Node{ { Id: "test2-1", Address: "10.0.0.2:10002", @@ -232,7 +234,7 @@ func TestWatcher(t *testing.T) { { Name: "test3", Version: "1.0.3", - Nodes: []*Node{ + Nodes: []*registry.Node{ { Id: "test3-1", Address: "10.0.0.3:10003", @@ -244,7 +246,7 @@ func TestWatcher(t *testing.T) { }, } - testFn := func(service, s *Service) { + testFn := func(service, s *registry.Service) { if s == nil { t.Fatalf("Expected one result for %s got nil", service.Name) @@ -275,10 +277,10 @@ func TestWatcher(t *testing.T) { travis := os.Getenv("TRAVIS") - var opts []Option + var opts []registry.Option if travis == "true" { - opts = append(opts, Timeout(time.Millisecond*100)) + opts = append(opts, registry.Timeout(time.Millisecond*100)) } // new registry diff --git a/registry/mdns/options.go b/registry/mdns/options.go new file mode 100644 index 00000000..0de2d3bb --- /dev/null +++ b/registry/mdns/options.go @@ -0,0 +1,18 @@ +// Package mdns provides a multicast dns registry +package mdns + +import ( + "context" + + "github.com/micro/go-micro/v3/registry" +) + +// Domain sets the mdnsDomain +func Domain(d string) registry.Option { + return func(o *registry.Options) { + if o.Context == nil { + o.Context = context.Background() + } + o.Context = context.WithValue(o.Context, "mdns.domain", d) + } +} diff --git a/registry/mdns_registry.go b/registry/mdns_registry.go deleted file mode 100644 index fabc4978..00000000 --- a/registry/mdns_registry.go +++ /dev/null @@ -1,768 +0,0 @@ -package registry - -import ( - "bytes" - "compress/zlib" - "context" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net" - "strconv" - "strings" - "sync" - "time" - - "github.com/google/uuid" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/util/mdns" -) - -const ( - // every service is written to the global domain so * domain queries work, e.g. - // calling mdns.List(registry.ListDomain("*")) will list the services across all - // domains - globalDomain = "global" -) - -type mdnsTxt struct { - Service string - Version string - Endpoints []*Endpoint - Metadata map[string]string -} - -type mdnsEntry struct { - id string - node *mdns.Server -} - -// services are a key/value map, with the service name as a key and the value being a -// slice of mdns entries, representing the nodes with a single _services entry to be -// used for listing -type services map[string][]*mdnsEntry - -// mdsRegistry is a multicast dns registry -type mdnsRegistry struct { - opts Options - - // the top level domains, these can be overriden using options - defaultDomain string - globalDomain string - - sync.Mutex - domains map[string]services - - mtx sync.RWMutex - - // watchers - watchers map[string]*mdnsWatcher - - // listener - listener chan *mdns.ServiceEntry -} - -type mdnsWatcher struct { - id string - wo WatchOptions - ch chan *mdns.ServiceEntry - exit chan struct{} - // the mdns domain - domain string - // the registry - registry *mdnsRegistry -} - -func encode(txt *mdnsTxt) ([]string, error) { - b, err := json.Marshal(txt) - if err != nil { - return nil, err - } - - var buf bytes.Buffer - defer buf.Reset() - - w := zlib.NewWriter(&buf) - defer func() { - if closeErr := w.Close(); closeErr != nil { - if logger.V(logger.ErrorLevel, logger.DefaultLogger) { - logger.Errorf("[mdns] registry close encoding writer err: %v", closeErr) - } - } - }() - if _, err := w.Write(b); err != nil { - return nil, err - } - - if err = w.Close(); err != nil { - return nil, err - } - - encoded := hex.EncodeToString(buf.Bytes()) - // individual txt limit - if len(encoded) <= 255 { - return []string{encoded}, nil - } - - // split encoded string - var record []string - - for len(encoded) > 255 { - record = append(record, encoded[:255]) - encoded = encoded[255:] - } - - record = append(record, encoded) - - return record, nil -} - -func decode(record []string) (*mdnsTxt, error) { - encoded := strings.Join(record, "") - - hr, err := hex.DecodeString(encoded) - if err != nil { - return nil, err - } - - br := bytes.NewReader(hr) - zr, err := zlib.NewReader(br) - if err != nil { - return nil, err - } - defer zr.Close() - - rbuf, err := ioutil.ReadAll(zr) - if err != nil { - return nil, err - } - - var txt *mdnsTxt - - if err := json.Unmarshal(rbuf, &txt); err != nil { - return nil, err - } - - return txt, nil -} - -func newRegistry(opts ...Option) Registry { - options := Options{ - Context: context.Background(), - Timeout: time.Millisecond * 100, - } - - for _, o := range opts { - o(&options) - } - - // set the domain - defaultDomain := DefaultDomain - if d, ok := options.Context.Value("mdns.domain").(string); ok { - defaultDomain = d - } - - return &mdnsRegistry{ - defaultDomain: defaultDomain, - globalDomain: globalDomain, - opts: options, - domains: make(map[string]services), - watchers: make(map[string]*mdnsWatcher), - } -} - -func (m *mdnsRegistry) Init(opts ...Option) error { - for _, o := range opts { - o(&m.opts) - } - return nil -} - -func (m *mdnsRegistry) Options() Options { - return m.opts -} - -// createServiceMDNSEntry will create a new wildcard mdns entry for the service in the -// given domain. This wildcard mdns entry is used when listing services. -func createServiceMDNSEntry(name, domain string) (*mdnsEntry, error) { - ip := net.ParseIP("0.0.0.0") - - s, err := mdns.NewMDNSService(name, "_services", domain+".", "", 9999, []net.IP{ip}, nil) - if err != nil { - return nil, err - } - - srv, err := mdns.NewServer(&mdns.Config{Zone: &mdns.DNSSDService{MDNSService: s}, LocalhostChecking: true}) - if err != nil { - return nil, err - } - - return &mdnsEntry{id: "*", node: srv}, nil -} - -func (m *mdnsRegistry) getMdnsEntries(domain, serviceName string) ([]*mdnsEntry, error) { - entries, ok := m.domains[domain][serviceName] - if ok { - return entries, nil - } - - // create the wildcard entry used for list queries in this domain - entry, err := createServiceMDNSEntry(serviceName, domain) - if err != nil { - return nil, err - } - - return []*mdnsEntry{entry}, nil -} - -func registerService(service *Service, entries []*mdnsEntry, options RegisterOptions) ([]*mdnsEntry, error) { - var lastError error - for _, node := range service.Nodes { - var seen bool - - for _, entry := range entries { - if node.Id == entry.id { - seen = true - break - } - } - - // this node has already been registered, continue - if seen { - continue - } - - txt, err := encode(&mdnsTxt{ - Service: service.Name, - Version: service.Version, - Endpoints: service.Endpoints, - Metadata: node.Metadata, - }) - - if err != nil { - lastError = err - continue - } - - host, pt, err := net.SplitHostPort(node.Address) - if err != nil { - lastError = err - continue - } - port, _ := strconv.Atoi(pt) - - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("[mdns] registry create new service with ip: %s for: %s", net.ParseIP(host).String(), host) - } - // we got here, new node - s, err := mdns.NewMDNSService( - node.Id, - service.Name, - options.Domain+".", - "", - port, - []net.IP{net.ParseIP(host)}, - txt, - ) - if err != nil { - lastError = err - continue - } - - srv, err := mdns.NewServer(&mdns.Config{Zone: s, LocalhostChecking: true}) - if err != nil { - lastError = err - continue - } - - entries = append(entries, &mdnsEntry{id: node.Id, node: srv}) - } - - return entries, lastError -} - -func createGlobalDomainService(service *Service, options RegisterOptions) *Service { - srv := *service - srv.Nodes = nil - - for _, n := range service.Nodes { - node := n - - // set the original domain in node metadata - if node.Metadata == nil { - node.Metadata = map[string]string{"domain": options.Domain} - } else { - node.Metadata["domain"] = options.Domain - } - - srv.Nodes = append(srv.Nodes, node) - } - - return &srv -} - -func (m *mdnsRegistry) Register(service *Service, opts ...RegisterOption) error { - m.Lock() - - // parse the options - var options RegisterOptions - for _, o := range opts { - o(&options) - } - if len(options.Domain) == 0 { - options.Domain = m.defaultDomain - } - - // create the domain in the memory store if it doesn't yet exist - if _, ok := m.domains[options.Domain]; !ok { - m.domains[options.Domain] = make(services) - } - - entries, err := m.getMdnsEntries(options.Domain, service.Name) - if err != nil { - m.Unlock() - return err - } - - entries, gerr := registerService(service, entries, options) - - // save the mdns entry - m.domains[options.Domain][service.Name] = entries - m.Unlock() - - // register in the global Domain so it can be queried as one - if options.Domain != m.globalDomain { - srv := createGlobalDomainService(service, options) - if err := m.Register(srv, append(opts, RegisterDomain(m.globalDomain))...); err != nil { - gerr = err - } - } - - return gerr -} - -func (m *mdnsRegistry) Deregister(service *Service, opts ...DeregisterOption) error { - // parse the options - var options DeregisterOptions - for _, o := range opts { - o(&options) - } - if len(options.Domain) == 0 { - options.Domain = m.defaultDomain - } - - // register in the global Domain - var err error - if options.Domain != m.globalDomain { - defer func() { - err = m.Deregister(service, append(opts, DeregisterDomain(m.globalDomain))...) - }() - } - - // we want to unlock before we call deregister on the global domain, so it's important this unlock - // is applied after the defer m.Deregister is called above - m.Lock() - defer m.Unlock() - - // the service wasn't registered, we can safely exist - if _, ok := m.domains[options.Domain]; !ok { - return err - } - - // loop existing entries, check if any match, shutdown those that do - var newEntries []*mdnsEntry - for _, entry := range m.domains[options.Domain][service.Name] { - var remove bool - - for _, node := range service.Nodes { - if node.Id == entry.id { - entry.node.Shutdown() - remove = true - break - } - } - - // keep it? - if !remove { - newEntries = append(newEntries, entry) - } - } - - // we have no new entries, we can exit - if len(newEntries) == 0 { - return nil - } - - // we have more than one entry remaining, we can exit - if len(newEntries) > 1 { - m.domains[options.Domain][service.Name] = newEntries - return err - } - - // our remaining entry is not a wildcard, we can exit - if len(newEntries) == 1 && newEntries[0].id != "*" { - m.domains[options.Domain][service.Name] = newEntries - return err - } - - // last entry is the wildcard for list queries. Remove it. - newEntries[0].node.Shutdown() - delete(m.domains[options.Domain], service.Name) - - // check to see if we can delete the domain entry - if len(m.domains[options.Domain]) == 0 { - delete(m.domains, options.Domain) - } - - return err -} - -func (m *mdnsRegistry) GetService(service string, opts ...GetOption) ([]*Service, error) { - // parse the options - var options GetOptions - for _, o := range opts { - o(&options) - } - if len(options.Domain) == 0 { - options.Domain = m.defaultDomain - } - if options.Domain == WildcardDomain { - options.Domain = m.globalDomain - } - - serviceMap := make(map[string]*Service) - entries := make(chan *mdns.ServiceEntry, 10) - done := make(chan bool) - - p := mdns.DefaultParams(service) - // set context with timeout - var cancel context.CancelFunc - p.Context, cancel = context.WithTimeout(context.Background(), m.opts.Timeout) - defer cancel() - // set entries channel - p.Entries = entries - // set the domain - p.Domain = options.Domain - - go func() { - for { - select { - case e := <-entries: - // list record so skip - if e.Name == "_services" { - continue - } - if e.TTL == 0 { - continue - } - - txt, err := decode(e.InfoFields) - if err != nil { - continue - } - - if txt.Service != service { - continue - } - - s, ok := serviceMap[txt.Version] - if !ok { - s = &Service{ - Name: txt.Service, - Version: txt.Version, - Endpoints: txt.Endpoints, - } - } - addr := "" - // prefer ipv4 addrs - if len(e.AddrV4) > 0 { - addr = e.AddrV4.String() - // else use ipv6 - } else if len(e.AddrV6) > 0 { - addr = "[" + e.AddrV6.String() + "]" - } else { - if logger.V(logger.InfoLevel, logger.DefaultLogger) { - logger.Infof("[mdns]: invalid endpoint received: %v", e) - } - continue - } - s.Nodes = append(s.Nodes, &Node{ - Id: strings.TrimSuffix(e.Name, "."+p.Service+"."+p.Domain+"."), - Address: fmt.Sprintf("%s:%d", addr, e.Port), - Metadata: txt.Metadata, - }) - - serviceMap[txt.Version] = s - case <-p.Context.Done(): - close(done) - return - } - } - }() - - // execute the query - if err := mdns.Query(p); err != nil { - return nil, err - } - - // wait for completion - <-done - - // create list and return - services := make([]*Service, 0, len(serviceMap)) - - for _, service := range serviceMap { - services = append(services, service) - } - - return services, nil -} - -func (m *mdnsRegistry) ListServices(opts ...ListOption) ([]*Service, error) { - // parse the options - var options ListOptions - for _, o := range opts { - o(&options) - } - if len(options.Domain) == 0 { - options.Domain = m.defaultDomain - } - if options.Domain == WildcardDomain { - options.Domain = m.globalDomain - } - - serviceMap := make(map[string]bool) - entries := make(chan *mdns.ServiceEntry, 10) - done := make(chan bool) - - p := mdns.DefaultParams("_services") - // set context with timeout - var cancel context.CancelFunc - p.Context, cancel = context.WithTimeout(context.Background(), m.opts.Timeout) - defer cancel() - // set entries channel - p.Entries = entries - // set domain - p.Domain = options.Domain - - var services []*Service - - go func() { - for { - select { - case e := <-entries: - if e.TTL == 0 { - continue - } - if !strings.HasSuffix(e.Name, p.Domain+".") { - continue - } - name := strings.TrimSuffix(e.Name, "."+p.Service+"."+p.Domain+".") - if !serviceMap[name] { - serviceMap[name] = true - services = append(services, &Service{Name: name}) - } - case <-p.Context.Done(): - close(done) - return - } - } - }() - - // execute query - if err := mdns.Query(p); err != nil { - return nil, err - } - - // wait till done - <-done - - return services, nil -} - -func (m *mdnsRegistry) Watch(opts ...WatchOption) (Watcher, error) { - var wo WatchOptions - for _, o := range opts { - o(&wo) - } - if len(wo.Domain) == 0 { - wo.Domain = m.defaultDomain - } - if wo.Domain == WildcardDomain { - wo.Domain = m.globalDomain - } - - md := &mdnsWatcher{ - id: uuid.New().String(), - wo: wo, - ch: make(chan *mdns.ServiceEntry, 32), - exit: make(chan struct{}), - domain: wo.Domain, - registry: m, - } - - m.mtx.Lock() - defer m.mtx.Unlock() - - // save the watcher - m.watchers[md.id] = md - - // check of the listener exists - if m.listener != nil { - return md, nil - } - - // start the listener - go func() { - // go to infinity - for { - m.mtx.Lock() - - // just return if there are no watchers - if len(m.watchers) == 0 { - m.listener = nil - m.mtx.Unlock() - return - } - - // check existing listener - if m.listener != nil { - m.mtx.Unlock() - return - } - - // reset the listener - exit := make(chan struct{}) - ch := make(chan *mdns.ServiceEntry, 32) - m.listener = ch - - m.mtx.Unlock() - - // send messages to the watchers - go func() { - send := func(w *mdnsWatcher, e *mdns.ServiceEntry) { - select { - case w.ch <- e: - default: - } - } - - for { - select { - case <-exit: - return - case e, ok := <-ch: - if !ok { - return - } - m.mtx.RLock() - // send service entry to all watchers - for _, w := range m.watchers { - send(w, e) - } - m.mtx.RUnlock() - } - } - - }() - - // start listening, blocking call - mdns.Listen(ch, exit) - - // mdns.Listen has unblocked - // kill the saved listener - m.mtx.Lock() - m.listener = nil - close(ch) - m.mtx.Unlock() - } - }() - - return md, nil -} - -func (m *mdnsRegistry) String() string { - return "mdns" -} - -func (m *mdnsWatcher) Next() (*Result, error) { - for { - select { - case e := <-m.ch: - txt, err := decode(e.InfoFields) - if err != nil { - continue - } - - if len(txt.Service) == 0 || len(txt.Version) == 0 { - continue - } - - // Filter watch options - // wo.Service: Only keep services we care about - if len(m.wo.Service) > 0 && txt.Service != m.wo.Service { - continue - } - var action string - if e.TTL == 0 { - action = "delete" - } else { - action = "create" - } - - service := &Service{ - Name: txt.Service, - Version: txt.Version, - Endpoints: txt.Endpoints, - Metadata: txt.Metadata, - } - - // skip anything without the domain we care about - suffix := fmt.Sprintf(".%s.%s.", service.Name, m.domain) - if !strings.HasSuffix(e.Name, suffix) { - continue - } - - var addr string - if len(e.AddrV4) > 0 { - addr = e.AddrV4.String() - } else if len(e.AddrV6) > 0 { - addr = "[" + e.AddrV6.String() + "]" - } else { - addr = e.Addr.String() - } - - service.Nodes = append(service.Nodes, &Node{ - Id: strings.TrimSuffix(e.Name, suffix), - Address: fmt.Sprintf("%s:%d", addr, e.Port), - Metadata: txt.Metadata, - }) - - return &Result{ - Action: action, - Service: service, - }, nil - case <-m.exit: - return nil, ErrWatcherStopped - } - } -} - -func (m *mdnsWatcher) Stop() { - select { - case <-m.exit: - return - default: - close(m.exit) - // remove self from the registry - m.registry.mtx.Lock() - delete(m.registry.watchers, m.id) - m.registry.mtx.Unlock() - } -} - -// NewRegistry returns a new default registry which is mdns -func NewRegistry(opts ...Option) Registry { - return newRegistry(opts...) -} diff --git a/registry/memory/memory.go b/registry/memory/memory.go index dc3c5ad7..0c54fa81 100644 --- a/registry/memory/memory.go +++ b/registry/memory/memory.go @@ -7,8 +7,8 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/registry" ) var ( diff --git a/registry/memory/memory_test.go b/registry/memory/memory_test.go index faf1a1d8..ee17634f 100644 --- a/registry/memory/memory_test.go +++ b/registry/memory/memory_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) var ( diff --git a/registry/memory/options.go b/registry/memory/options.go index 57e430ef..f9027632 100644 --- a/registry/memory/options.go +++ b/registry/memory/options.go @@ -3,7 +3,7 @@ package memory import ( "context" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) type servicesKey struct{} diff --git a/registry/memory/util.go b/registry/memory/util.go index b1f3830b..82c02762 100644 --- a/registry/memory/util.go +++ b/registry/memory/util.go @@ -3,7 +3,7 @@ package memory import ( "time" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) func serviceToRecord(s *registry.Service, ttl time.Duration) *record { diff --git a/registry/memory/watcher.go b/registry/memory/watcher.go index 123d4810..328a4bed 100644 --- a/registry/memory/watcher.go +++ b/registry/memory/watcher.go @@ -3,7 +3,7 @@ package memory import ( "errors" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) type Watcher struct { diff --git a/registry/memory/watcher_test.go b/registry/memory/watcher_test.go index 4890647d..0180a94c 100644 --- a/registry/memory/watcher_test.go +++ b/registry/memory/watcher_test.go @@ -3,7 +3,7 @@ package memory import ( "testing" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) func TestWatcher(t *testing.T) { diff --git a/registry/registry.go b/registry/registry.go index 45dd0b3d..0dfc2c61 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -13,8 +13,6 @@ const ( ) var ( - DefaultRegistry = NewRegistry() - // Not found error when GetService is called ErrNotFound = errors.New("service not found") // Watcher stopped error when watcher is stopped @@ -73,32 +71,3 @@ type DeregisterOption func(*DeregisterOptions) type GetOption func(*GetOptions) type ListOption func(*ListOptions) - -// Register a service node. Additionally supply options such as TTL. -func Register(s *Service, opts ...RegisterOption) error { - return DefaultRegistry.Register(s, opts...) -} - -// Deregister a service node -func Deregister(s *Service) error { - return DefaultRegistry.Deregister(s) -} - -// Retrieve a service. A slice is returned since we separate Name/Version. -func GetService(name string) ([]*Service, error) { - return DefaultRegistry.GetService(name) -} - -// List the services. Only returns service names -func ListServices() ([]*Service, error) { - return DefaultRegistry.ListServices() -} - -// Watch returns a watcher which allows you to track updates to the registry. -func Watch(opts ...WatchOption) (Watcher, error) { - return DefaultRegistry.Watch(opts...) -} - -func String() string { - return DefaultRegistry.String() -} diff --git a/registry/service/options.go b/registry/service/options.go deleted file mode 100644 index fd251d77..00000000 --- a/registry/service/options.go +++ /dev/null @@ -1,21 +0,0 @@ -package service - -import ( - "context" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/registry" -) - -type clientKey struct{} - -// WithClient sets the RPC client -func WithClient(c client.Client) registry.Option { - return func(o *registry.Options) { - if o.Context == nil { - o.Context = context.Background() - } - - o.Context = context.WithValue(o.Context, clientKey{}, c) - } -} diff --git a/registry/service/proto/registry.pb.go b/registry/service/proto/registry.pb.go deleted file mode 100644 index 8041d03e..00000000 --- a/registry/service/proto/registry.pb.go +++ /dev/null @@ -1,1057 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: registry/service/proto/registry.proto - -package go_micro_registry - -import ( - context "context" - fmt "fmt" - proto "github.com/golang/protobuf/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// EventType defines the type of event -type EventType int32 - -const ( - EventType_Create EventType = 0 - EventType_Delete EventType = 1 - EventType_Update EventType = 2 -) - -var EventType_name = map[int32]string{ - 0: "Create", - 1: "Delete", - 2: "Update", -} - -var EventType_value = map[string]int32{ - "Create": 0, - "Delete": 1, - "Update": 2, -} - -func (x EventType) String() string { - return proto.EnumName(EventType_name, int32(x)) -} - -func (EventType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{0} -} - -// Service represents a go-micro service -type Service struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` - Metadata map[string]string `protobuf:"bytes,3,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Endpoints []*Endpoint `protobuf:"bytes,4,rep,name=endpoints,proto3" json:"endpoints,omitempty"` - Nodes []*Node `protobuf:"bytes,5,rep,name=nodes,proto3" json:"nodes,omitempty"` - Options *Options `protobuf:"bytes,6,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Service) Reset() { *m = Service{} } -func (m *Service) String() string { return proto.CompactTextString(m) } -func (*Service) ProtoMessage() {} -func (*Service) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{0} -} - -func (m *Service) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Service.Unmarshal(m, b) -} -func (m *Service) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Service.Marshal(b, m, deterministic) -} -func (m *Service) XXX_Merge(src proto.Message) { - xxx_messageInfo_Service.Merge(m, src) -} -func (m *Service) XXX_Size() int { - return xxx_messageInfo_Service.Size(m) -} -func (m *Service) XXX_DiscardUnknown() { - xxx_messageInfo_Service.DiscardUnknown(m) -} - -var xxx_messageInfo_Service proto.InternalMessageInfo - -func (m *Service) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Service) GetVersion() string { - if m != nil { - return m.Version - } - return "" -} - -func (m *Service) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Service) GetEndpoints() []*Endpoint { - if m != nil { - return m.Endpoints - } - return nil -} - -func (m *Service) GetNodes() []*Node { - if m != nil { - return m.Nodes - } - return nil -} - -func (m *Service) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -// Node represents the node the service is on -type Node struct { - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - Port int64 `protobuf:"varint,3,opt,name=port,proto3" json:"port,omitempty"` - Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Node) Reset() { *m = Node{} } -func (m *Node) String() string { return proto.CompactTextString(m) } -func (*Node) ProtoMessage() {} -func (*Node) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{1} -} - -func (m *Node) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Node.Unmarshal(m, b) -} -func (m *Node) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Node.Marshal(b, m, deterministic) -} -func (m *Node) XXX_Merge(src proto.Message) { - xxx_messageInfo_Node.Merge(m, src) -} -func (m *Node) XXX_Size() int { - return xxx_messageInfo_Node.Size(m) -} -func (m *Node) XXX_DiscardUnknown() { - xxx_messageInfo_Node.DiscardUnknown(m) -} - -var xxx_messageInfo_Node proto.InternalMessageInfo - -func (m *Node) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *Node) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *Node) GetPort() int64 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *Node) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -// Endpoint is a endpoint provided by a service -type Endpoint struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Request *Value `protobuf:"bytes,2,opt,name=request,proto3" json:"request,omitempty"` - Response *Value `protobuf:"bytes,3,opt,name=response,proto3" json:"response,omitempty"` - Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Endpoint) Reset() { *m = Endpoint{} } -func (m *Endpoint) String() string { return proto.CompactTextString(m) } -func (*Endpoint) ProtoMessage() {} -func (*Endpoint) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{2} -} - -func (m *Endpoint) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Endpoint.Unmarshal(m, b) -} -func (m *Endpoint) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Endpoint.Marshal(b, m, deterministic) -} -func (m *Endpoint) XXX_Merge(src proto.Message) { - xxx_messageInfo_Endpoint.Merge(m, src) -} -func (m *Endpoint) XXX_Size() int { - return xxx_messageInfo_Endpoint.Size(m) -} -func (m *Endpoint) XXX_DiscardUnknown() { - xxx_messageInfo_Endpoint.DiscardUnknown(m) -} - -var xxx_messageInfo_Endpoint proto.InternalMessageInfo - -func (m *Endpoint) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Endpoint) GetRequest() *Value { - if m != nil { - return m.Request - } - return nil -} - -func (m *Endpoint) GetResponse() *Value { - if m != nil { - return m.Response - } - return nil -} - -func (m *Endpoint) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -// Value is an opaque value for a request or response -type Value struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` - Values []*Value `protobuf:"bytes,3,rep,name=values,proto3" json:"values,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Value) Reset() { *m = Value{} } -func (m *Value) String() string { return proto.CompactTextString(m) } -func (*Value) ProtoMessage() {} -func (*Value) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{3} -} - -func (m *Value) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Value.Unmarshal(m, b) -} -func (m *Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Value.Marshal(b, m, deterministic) -} -func (m *Value) XXX_Merge(src proto.Message) { - xxx_messageInfo_Value.Merge(m, src) -} -func (m *Value) XXX_Size() int { - return xxx_messageInfo_Value.Size(m) -} -func (m *Value) XXX_DiscardUnknown() { - xxx_messageInfo_Value.DiscardUnknown(m) -} - -var xxx_messageInfo_Value proto.InternalMessageInfo - -func (m *Value) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Value) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *Value) GetValues() []*Value { - if m != nil { - return m.Values - } - return nil -} - -// Options are registry options -type Options struct { - Ttl int64 `protobuf:"varint,1,opt,name=ttl,proto3" json:"ttl,omitempty"` - Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Options) Reset() { *m = Options{} } -func (m *Options) String() string { return proto.CompactTextString(m) } -func (*Options) ProtoMessage() {} -func (*Options) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{4} -} - -func (m *Options) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Options.Unmarshal(m, b) -} -func (m *Options) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Options.Marshal(b, m, deterministic) -} -func (m *Options) XXX_Merge(src proto.Message) { - xxx_messageInfo_Options.Merge(m, src) -} -func (m *Options) XXX_Size() int { - return xxx_messageInfo_Options.Size(m) -} -func (m *Options) XXX_DiscardUnknown() { - xxx_messageInfo_Options.DiscardUnknown(m) -} - -var xxx_messageInfo_Options proto.InternalMessageInfo - -func (m *Options) GetTtl() int64 { - if m != nil { - return m.Ttl - } - return 0 -} - -func (m *Options) GetDomain() string { - if m != nil { - return m.Domain - } - return "" -} - -// Result is returns by the watcher -type Result struct { - Action string `protobuf:"bytes,1,opt,name=action,proto3" json:"action,omitempty"` - Service *Service `protobuf:"bytes,2,opt,name=service,proto3" json:"service,omitempty"` - Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Result) Reset() { *m = Result{} } -func (m *Result) String() string { return proto.CompactTextString(m) } -func (*Result) ProtoMessage() {} -func (*Result) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{5} -} - -func (m *Result) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Result.Unmarshal(m, b) -} -func (m *Result) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Result.Marshal(b, m, deterministic) -} -func (m *Result) XXX_Merge(src proto.Message) { - xxx_messageInfo_Result.Merge(m, src) -} -func (m *Result) XXX_Size() int { - return xxx_messageInfo_Result.Size(m) -} -func (m *Result) XXX_DiscardUnknown() { - xxx_messageInfo_Result.DiscardUnknown(m) -} - -var xxx_messageInfo_Result proto.InternalMessageInfo - -func (m *Result) GetAction() string { - if m != nil { - return m.Action - } - return "" -} - -func (m *Result) GetService() *Service { - if m != nil { - return m.Service - } - return nil -} - -func (m *Result) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -type EmptyResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EmptyResponse) Reset() { *m = EmptyResponse{} } -func (m *EmptyResponse) String() string { return proto.CompactTextString(m) } -func (*EmptyResponse) ProtoMessage() {} -func (*EmptyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{6} -} - -func (m *EmptyResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EmptyResponse.Unmarshal(m, b) -} -func (m *EmptyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EmptyResponse.Marshal(b, m, deterministic) -} -func (m *EmptyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_EmptyResponse.Merge(m, src) -} -func (m *EmptyResponse) XXX_Size() int { - return xxx_messageInfo_EmptyResponse.Size(m) -} -func (m *EmptyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_EmptyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_EmptyResponse proto.InternalMessageInfo - -type GetRequest struct { - Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - Options *Options `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetRequest) Reset() { *m = GetRequest{} } -func (m *GetRequest) String() string { return proto.CompactTextString(m) } -func (*GetRequest) ProtoMessage() {} -func (*GetRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{7} -} - -func (m *GetRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetRequest.Unmarshal(m, b) -} -func (m *GetRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetRequest.Marshal(b, m, deterministic) -} -func (m *GetRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetRequest.Merge(m, src) -} -func (m *GetRequest) XXX_Size() int { - return xxx_messageInfo_GetRequest.Size(m) -} -func (m *GetRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetRequest proto.InternalMessageInfo - -func (m *GetRequest) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -func (m *GetRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type GetResponse struct { - Services []*Service `protobuf:"bytes,1,rep,name=services,proto3" json:"services,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetResponse) Reset() { *m = GetResponse{} } -func (m *GetResponse) String() string { return proto.CompactTextString(m) } -func (*GetResponse) ProtoMessage() {} -func (*GetResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{8} -} - -func (m *GetResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetResponse.Unmarshal(m, b) -} -func (m *GetResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetResponse.Marshal(b, m, deterministic) -} -func (m *GetResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetResponse.Merge(m, src) -} -func (m *GetResponse) XXX_Size() int { - return xxx_messageInfo_GetResponse.Size(m) -} -func (m *GetResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GetResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GetResponse proto.InternalMessageInfo - -func (m *GetResponse) GetServices() []*Service { - if m != nil { - return m.Services - } - return nil -} - -type ListRequest struct { - Options *Options `protobuf:"bytes,1,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListRequest) Reset() { *m = ListRequest{} } -func (m *ListRequest) String() string { return proto.CompactTextString(m) } -func (*ListRequest) ProtoMessage() {} -func (*ListRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{9} -} - -func (m *ListRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListRequest.Unmarshal(m, b) -} -func (m *ListRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListRequest.Marshal(b, m, deterministic) -} -func (m *ListRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListRequest.Merge(m, src) -} -func (m *ListRequest) XXX_Size() int { - return xxx_messageInfo_ListRequest.Size(m) -} -func (m *ListRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListRequest proto.InternalMessageInfo - -func (m *ListRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -type ListResponse struct { - Services []*Service `protobuf:"bytes,1,rep,name=services,proto3" json:"services,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListResponse) Reset() { *m = ListResponse{} } -func (m *ListResponse) String() string { return proto.CompactTextString(m) } -func (*ListResponse) ProtoMessage() {} -func (*ListResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{10} -} - -func (m *ListResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListResponse.Unmarshal(m, b) -} -func (m *ListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListResponse.Marshal(b, m, deterministic) -} -func (m *ListResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListResponse.Merge(m, src) -} -func (m *ListResponse) XXX_Size() int { - return xxx_messageInfo_ListResponse.Size(m) -} -func (m *ListResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListResponse proto.InternalMessageInfo - -func (m *ListResponse) GetServices() []*Service { - if m != nil { - return m.Services - } - return nil -} - -type WatchRequest struct { - // service is optional - Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - Options *Options `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *WatchRequest) Reset() { *m = WatchRequest{} } -func (m *WatchRequest) String() string { return proto.CompactTextString(m) } -func (*WatchRequest) ProtoMessage() {} -func (*WatchRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{11} -} - -func (m *WatchRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_WatchRequest.Unmarshal(m, b) -} -func (m *WatchRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_WatchRequest.Marshal(b, m, deterministic) -} -func (m *WatchRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_WatchRequest.Merge(m, src) -} -func (m *WatchRequest) XXX_Size() int { - return xxx_messageInfo_WatchRequest.Size(m) -} -func (m *WatchRequest) XXX_DiscardUnknown() { - xxx_messageInfo_WatchRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_WatchRequest proto.InternalMessageInfo - -func (m *WatchRequest) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -func (m *WatchRequest) GetOptions() *Options { - if m != nil { - return m.Options - } - return nil -} - -// Event is registry event -type Event struct { - // Event Id - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // type of event - Type EventType `protobuf:"varint,2,opt,name=type,proto3,enum=go.micro.registry.EventType" json:"type,omitempty"` - // unix timestamp of event - Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - // service entry - Service *Service `protobuf:"bytes,4,opt,name=service,proto3" json:"service,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Event) Reset() { *m = Event{} } -func (m *Event) String() string { return proto.CompactTextString(m) } -func (*Event) ProtoMessage() {} -func (*Event) Descriptor() ([]byte, []int) { - return fileDescriptor_3f5817c11f323eb6, []int{12} -} - -func (m *Event) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Event.Unmarshal(m, b) -} -func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Event.Marshal(b, m, deterministic) -} -func (m *Event) XXX_Merge(src proto.Message) { - xxx_messageInfo_Event.Merge(m, src) -} -func (m *Event) XXX_Size() int { - return xxx_messageInfo_Event.Size(m) -} -func (m *Event) XXX_DiscardUnknown() { - xxx_messageInfo_Event.DiscardUnknown(m) -} - -var xxx_messageInfo_Event proto.InternalMessageInfo - -func (m *Event) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *Event) GetType() EventType { - if m != nil { - return m.Type - } - return EventType_Create -} - -func (m *Event) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -func (m *Event) GetService() *Service { - if m != nil { - return m.Service - } - return nil -} - -func init() { - proto.RegisterEnum("go.micro.registry.EventType", EventType_name, EventType_value) - proto.RegisterType((*Service)(nil), "go.micro.registry.Service") - proto.RegisterMapType((map[string]string)(nil), "go.micro.registry.Service.MetadataEntry") - proto.RegisterType((*Node)(nil), "go.micro.registry.Node") - proto.RegisterMapType((map[string]string)(nil), "go.micro.registry.Node.MetadataEntry") - proto.RegisterType((*Endpoint)(nil), "go.micro.registry.Endpoint") - proto.RegisterMapType((map[string]string)(nil), "go.micro.registry.Endpoint.MetadataEntry") - proto.RegisterType((*Value)(nil), "go.micro.registry.Value") - proto.RegisterType((*Options)(nil), "go.micro.registry.Options") - proto.RegisterType((*Result)(nil), "go.micro.registry.Result") - proto.RegisterType((*EmptyResponse)(nil), "go.micro.registry.EmptyResponse") - proto.RegisterType((*GetRequest)(nil), "go.micro.registry.GetRequest") - proto.RegisterType((*GetResponse)(nil), "go.micro.registry.GetResponse") - proto.RegisterType((*ListRequest)(nil), "go.micro.registry.ListRequest") - proto.RegisterType((*ListResponse)(nil), "go.micro.registry.ListResponse") - proto.RegisterType((*WatchRequest)(nil), "go.micro.registry.WatchRequest") - proto.RegisterType((*Event)(nil), "go.micro.registry.Event") -} - -func init() { - proto.RegisterFile("registry/service/proto/registry.proto", fileDescriptor_3f5817c11f323eb6) -} - -var fileDescriptor_3f5817c11f323eb6 = []byte{ - // 700 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0xed, 0x6a, 0xd4, 0x40, - 0x14, 0xdd, 0x24, 0xfb, 0x79, 0xb7, 0xad, 0x75, 0x10, 0x8d, 0xb1, 0xea, 0x12, 0x28, 0xac, 0x82, - 0xbb, 0x65, 0x5b, 0xc4, 0x8f, 0x5f, 0xd2, 0xae, 0x05, 0x69, 0x15, 0xc7, 0xaf, 0x3f, 0x22, 0xc4, - 0xcd, 0xa5, 0x06, 0x37, 0x99, 0x38, 0x33, 0x5d, 0xd8, 0x77, 0x10, 0x7c, 0x02, 0xdf, 0xc6, 0xa7, - 0xf0, 0x69, 0x64, 0x26, 0x93, 0x6c, 0x4a, 0xb3, 0x4b, 0xa1, 0xf6, 0xdf, 0x9d, 0xe4, 0x9c, 0x33, - 0x77, 0xce, 0x9c, 0x9b, 0x5d, 0xd8, 0xe6, 0x78, 0x12, 0x09, 0xc9, 0xe7, 0x43, 0x81, 0x7c, 0x16, - 0x4d, 0x70, 0x98, 0x72, 0x26, 0xd9, 0x30, 0x7f, 0x3c, 0xd0, 0x4b, 0x72, 0xfd, 0x84, 0x0d, 0xe2, - 0x68, 0xc2, 0xd9, 0x20, 0x7f, 0xe1, 0xff, 0xb5, 0xa1, 0xf5, 0x2e, 0xe3, 0x10, 0x02, 0xf5, 0x24, - 0x88, 0xd1, 0xb5, 0x7a, 0x56, 0xbf, 0x43, 0x75, 0x4d, 0x5c, 0x68, 0xcd, 0x90, 0x8b, 0x88, 0x25, - 0xae, 0xad, 0x1f, 0xe7, 0x4b, 0x72, 0x00, 0xed, 0x18, 0x65, 0x10, 0x06, 0x32, 0x70, 0x9d, 0x9e, - 0xd3, 0xef, 0x8e, 0xfa, 0x83, 0x73, 0xfa, 0x03, 0xa3, 0x3d, 0x38, 0x36, 0xd0, 0x71, 0x22, 0xf9, - 0x9c, 0x16, 0x4c, 0xf2, 0x14, 0x3a, 0x98, 0x84, 0x29, 0x8b, 0x12, 0x29, 0xdc, 0xba, 0x96, 0xb9, - 0x53, 0x21, 0x33, 0x36, 0x18, 0xba, 0x40, 0x93, 0x47, 0xd0, 0x48, 0x58, 0x88, 0xc2, 0x6d, 0x68, - 0xda, 0xad, 0x0a, 0xda, 0x6b, 0x16, 0x22, 0xcd, 0x50, 0x64, 0x0f, 0x5a, 0x2c, 0x95, 0x11, 0x4b, - 0x84, 0xdb, 0xec, 0x59, 0xfd, 0xee, 0xc8, 0xab, 0x20, 0xbc, 0xc9, 0x10, 0x34, 0x87, 0x7a, 0xcf, - 0x61, 0xfd, 0x4c, 0xeb, 0x64, 0x13, 0x9c, 0xef, 0x38, 0x37, 0x1e, 0xa9, 0x92, 0xdc, 0x80, 0xc6, - 0x2c, 0x98, 0x9e, 0xa2, 0x31, 0x28, 0x5b, 0x3c, 0xb3, 0x9f, 0x58, 0xfe, 0x1f, 0x0b, 0xea, 0xaa, - 0x05, 0xb2, 0x01, 0x76, 0x14, 0x1a, 0x8e, 0x1d, 0x85, 0xca, 0xd5, 0x20, 0x0c, 0x39, 0x0a, 0x91, - 0xbb, 0x6a, 0x96, 0xea, 0x0e, 0x52, 0xc6, 0xa5, 0xeb, 0xf4, 0xac, 0xbe, 0x43, 0x75, 0x4d, 0x5e, - 0x94, 0x9c, 0xce, 0x2c, 0xda, 0x5e, 0x72, 0xd6, 0x65, 0x36, 0x5f, 0xee, 0x18, 0x3f, 0x6d, 0x68, - 0xe7, 0x17, 0x50, 0x19, 0x92, 0x11, 0xb4, 0x38, 0xfe, 0x38, 0x45, 0x21, 0x35, 0xb9, 0x3b, 0x72, - 0x2b, 0xfa, 0xfb, 0xa8, 0xf4, 0x68, 0x0e, 0x24, 0x7b, 0xd0, 0xe6, 0x28, 0x52, 0x96, 0x08, 0xd4, - 0x87, 0x5d, 0x45, 0x2a, 0x90, 0x64, 0x7c, 0xce, 0x8a, 0x07, 0x2b, 0xd2, 0x72, 0x35, 0x76, 0x04, - 0xd0, 0xd0, 0x6d, 0x55, 0x5a, 0x41, 0xa0, 0x2e, 0xe7, 0x69, 0xce, 0xd2, 0x35, 0xd9, 0x81, 0xa6, - 0x66, 0x0b, 0x33, 0x27, 0xcb, 0x0f, 0x6a, 0x70, 0xfe, 0x2e, 0xb4, 0x4c, 0x12, 0x55, 0x67, 0x52, - 0x4e, 0xf5, 0x1e, 0x0e, 0x55, 0x25, 0xb9, 0x09, 0xcd, 0x90, 0xc5, 0x41, 0x94, 0x4f, 0xa4, 0x59, - 0xf9, 0x12, 0x9a, 0x14, 0xc5, 0xe9, 0x54, 0x2a, 0x44, 0x30, 0x51, 0x74, 0xd3, 0x9a, 0x59, 0xa9, - 0x11, 0x30, 0xdf, 0x07, 0x73, 0x4f, 0xde, 0xf2, 0x89, 0xa5, 0x39, 0x94, 0x6c, 0x41, 0x47, 0x46, - 0x31, 0x0a, 0x19, 0xc4, 0xa9, 0xc9, 0xe5, 0xe2, 0x81, 0x7f, 0x0d, 0xd6, 0xc7, 0x71, 0x2a, 0xe7, - 0xd4, 0x5c, 0x91, 0xff, 0x19, 0xe0, 0x10, 0x25, 0x35, 0xd7, 0xec, 0x2e, 0xb6, 0xcc, 0x7a, 0x29, - 0x64, 0x4b, 0xf3, 0x68, 0x5f, 0x78, 0x1e, 0xfd, 0x31, 0x74, 0xb5, 0xba, 0xc9, 0xc3, 0x63, 0x68, - 0x1b, 0x3d, 0xe1, 0x5a, 0xda, 0xdc, 0x55, 0x47, 0x2a, 0xb0, 0xfe, 0x3e, 0x74, 0x8f, 0x22, 0x51, - 0x74, 0x59, 0xea, 0xc5, 0xba, 0x78, 0x2f, 0x2f, 0x61, 0x2d, 0x13, 0xb9, 0x64, 0x33, 0x5f, 0x60, - 0xed, 0x53, 0x20, 0x27, 0xdf, 0xae, 0xca, 0xb3, 0xdf, 0x16, 0x34, 0xc6, 0x33, 0x4c, 0xe4, 0xb9, - 0xef, 0xd0, 0x4e, 0x29, 0xad, 0x1b, 0xa3, 0xad, 0xaa, 0x51, 0x52, 0xbc, 0xf7, 0xf3, 0x14, 0x4d, - 0x96, 0x57, 0x86, 0xa1, 0x1c, 0xb0, 0xfa, 0x85, 0x03, 0xf6, 0x70, 0x08, 0x9d, 0x62, 0x1b, 0x02, - 0xd0, 0xdc, 0xe7, 0x18, 0x48, 0xdc, 0xac, 0xa9, 0xfa, 0x00, 0xa7, 0x28, 0x71, 0xd3, 0x52, 0xf5, - 0x87, 0x34, 0x54, 0xcf, 0xed, 0xd1, 0x2f, 0x07, 0xda, 0xd4, 0xc8, 0x91, 0x63, 0x9d, 0xb7, 0xfc, - 0x37, 0xec, 0x6e, 0xc5, 0x86, 0x8b, 0x38, 0x7a, 0xf7, 0x96, 0xbd, 0x36, 0xe1, 0xad, 0x91, 0x57, - 0xb9, 0x34, 0x72, 0xb2, 0xa2, 0x7b, 0xaf, 0x57, 0x65, 0xd6, 0x99, 0x41, 0xa8, 0x91, 0x23, 0x80, - 0x03, 0xe4, 0xff, 0x4b, 0xed, 0x6d, 0x16, 0x37, 0x43, 0x11, 0xa4, 0xea, 0x2c, 0xa5, 0x50, 0x7b, - 0xf7, 0x97, 0xbe, 0x2f, 0x24, 0x0f, 0xa1, 0xa1, 0x93, 0x47, 0xaa, 0xb0, 0xe5, 0x4c, 0x7a, 0xb7, - 0x2b, 0x00, 0xd9, 0xd7, 0xc6, 0xaf, 0xed, 0x58, 0x5f, 0x9b, 0xfa, 0x0f, 0xc6, 0xee, 0xbf, 0x00, - 0x00, 0x00, 0xff, 0xff, 0xef, 0xac, 0x43, 0xb5, 0x89, 0x08, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// RegistryClient is the client API for Registry service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type RegistryClient interface { - GetService(ctx context.Context, in *GetRequest, opts ...grpc.CallOption) (*GetResponse, error) - Register(ctx context.Context, in *Service, opts ...grpc.CallOption) (*EmptyResponse, error) - Deregister(ctx context.Context, in *Service, opts ...grpc.CallOption) (*EmptyResponse, error) - ListServices(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) - Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (Registry_WatchClient, error) -} - -type registryClient struct { - cc *grpc.ClientConn -} - -func NewRegistryClient(cc *grpc.ClientConn) RegistryClient { - return ®istryClient{cc} -} - -func (c *registryClient) GetService(ctx context.Context, in *GetRequest, opts ...grpc.CallOption) (*GetResponse, error) { - out := new(GetResponse) - err := c.cc.Invoke(ctx, "/go.micro.registry.Registry/GetService", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *registryClient) Register(ctx context.Context, in *Service, opts ...grpc.CallOption) (*EmptyResponse, error) { - out := new(EmptyResponse) - err := c.cc.Invoke(ctx, "/go.micro.registry.Registry/Register", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *registryClient) Deregister(ctx context.Context, in *Service, opts ...grpc.CallOption) (*EmptyResponse, error) { - out := new(EmptyResponse) - err := c.cc.Invoke(ctx, "/go.micro.registry.Registry/Deregister", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *registryClient) ListServices(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) { - out := new(ListResponse) - err := c.cc.Invoke(ctx, "/go.micro.registry.Registry/ListServices", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *registryClient) Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (Registry_WatchClient, error) { - stream, err := c.cc.NewStream(ctx, &_Registry_serviceDesc.Streams[0], "/go.micro.registry.Registry/Watch", opts...) - if err != nil { - return nil, err - } - x := ®istryWatchClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Registry_WatchClient interface { - Recv() (*Result, error) - grpc.ClientStream -} - -type registryWatchClient struct { - grpc.ClientStream -} - -func (x *registryWatchClient) Recv() (*Result, error) { - m := new(Result) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// RegistryServer is the server API for Registry service. -type RegistryServer interface { - GetService(context.Context, *GetRequest) (*GetResponse, error) - Register(context.Context, *Service) (*EmptyResponse, error) - Deregister(context.Context, *Service) (*EmptyResponse, error) - ListServices(context.Context, *ListRequest) (*ListResponse, error) - Watch(*WatchRequest, Registry_WatchServer) error -} - -// UnimplementedRegistryServer can be embedded to have forward compatible implementations. -type UnimplementedRegistryServer struct { -} - -func (*UnimplementedRegistryServer) GetService(ctx context.Context, req *GetRequest) (*GetResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetService not implemented") -} -func (*UnimplementedRegistryServer) Register(ctx context.Context, req *Service) (*EmptyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Register not implemented") -} -func (*UnimplementedRegistryServer) Deregister(ctx context.Context, req *Service) (*EmptyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deregister not implemented") -} -func (*UnimplementedRegistryServer) ListServices(ctx context.Context, req *ListRequest) (*ListResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ListServices not implemented") -} -func (*UnimplementedRegistryServer) Watch(req *WatchRequest, srv Registry_WatchServer) error { - return status.Errorf(codes.Unimplemented, "method Watch not implemented") -} - -func RegisterRegistryServer(s *grpc.Server, srv RegistryServer) { - s.RegisterService(&_Registry_serviceDesc, srv) -} - -func _Registry_GetService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RegistryServer).GetService(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.registry.Registry/GetService", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RegistryServer).GetService(ctx, req.(*GetRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Registry_Register_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Service) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RegistryServer).Register(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.registry.Registry/Register", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RegistryServer).Register(ctx, req.(*Service)) - } - return interceptor(ctx, in, info, handler) -} - -func _Registry_Deregister_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Service) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RegistryServer).Deregister(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.registry.Registry/Deregister", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RegistryServer).Deregister(ctx, req.(*Service)) - } - return interceptor(ctx, in, info, handler) -} - -func _Registry_ListServices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RegistryServer).ListServices(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.registry.Registry/ListServices", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RegistryServer).ListServices(ctx, req.(*ListRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Registry_Watch_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(WatchRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(RegistryServer).Watch(m, ®istryWatchServer{stream}) -} - -type Registry_WatchServer interface { - Send(*Result) error - grpc.ServerStream -} - -type registryWatchServer struct { - grpc.ServerStream -} - -func (x *registryWatchServer) Send(m *Result) error { - return x.ServerStream.SendMsg(m) -} - -var _Registry_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.registry.Registry", - HandlerType: (*RegistryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetService", - Handler: _Registry_GetService_Handler, - }, - { - MethodName: "Register", - Handler: _Registry_Register_Handler, - }, - { - MethodName: "Deregister", - Handler: _Registry_Deregister_Handler, - }, - { - MethodName: "ListServices", - Handler: _Registry_ListServices_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Watch", - Handler: _Registry_Watch_Handler, - ServerStreams: true, - }, - }, - Metadata: "registry/service/proto/registry.proto", -} diff --git a/registry/service/proto/registry.pb.micro.go b/registry/service/proto/registry.pb.micro.go deleted file mode 100644 index 482b2146..00000000 --- a/registry/service/proto/registry.pb.micro.go +++ /dev/null @@ -1,236 +0,0 @@ -// Code generated by protoc-gen-micro. DO NOT EDIT. -// source: registry/service/proto/registry.proto - -package go_micro_registry - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -import ( - context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ api.Endpoint -var _ context.Context -var _ client.Option -var _ server.Option - -// Api Endpoints for Registry service - -func NewRegistryEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Registry service - -type RegistryService interface { - GetService(ctx context.Context, in *GetRequest, opts ...client.CallOption) (*GetResponse, error) - Register(ctx context.Context, in *Service, opts ...client.CallOption) (*EmptyResponse, error) - Deregister(ctx context.Context, in *Service, opts ...client.CallOption) (*EmptyResponse, error) - ListServices(ctx context.Context, in *ListRequest, opts ...client.CallOption) (*ListResponse, error) - Watch(ctx context.Context, in *WatchRequest, opts ...client.CallOption) (Registry_WatchService, error) -} - -type registryService struct { - c client.Client - name string -} - -func NewRegistryService(name string, c client.Client) RegistryService { - return ®istryService{ - c: c, - name: name, - } -} - -func (c *registryService) GetService(ctx context.Context, in *GetRequest, opts ...client.CallOption) (*GetResponse, error) { - req := c.c.NewRequest(c.name, "Registry.GetService", in) - out := new(GetResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *registryService) Register(ctx context.Context, in *Service, opts ...client.CallOption) (*EmptyResponse, error) { - req := c.c.NewRequest(c.name, "Registry.Register", in) - out := new(EmptyResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *registryService) Deregister(ctx context.Context, in *Service, opts ...client.CallOption) (*EmptyResponse, error) { - req := c.c.NewRequest(c.name, "Registry.Deregister", in) - out := new(EmptyResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *registryService) ListServices(ctx context.Context, in *ListRequest, opts ...client.CallOption) (*ListResponse, error) { - req := c.c.NewRequest(c.name, "Registry.ListServices", in) - out := new(ListResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *registryService) Watch(ctx context.Context, in *WatchRequest, opts ...client.CallOption) (Registry_WatchService, error) { - req := c.c.NewRequest(c.name, "Registry.Watch", &WatchRequest{}) - stream, err := c.c.Stream(ctx, req, opts...) - if err != nil { - return nil, err - } - if err := stream.Send(in); err != nil { - return nil, err - } - return ®istryServiceWatch{stream}, nil -} - -type Registry_WatchService interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Recv() (*Result, error) -} - -type registryServiceWatch struct { - stream client.Stream -} - -func (x *registryServiceWatch) Close() error { - return x.stream.Close() -} - -func (x *registryServiceWatch) Context() context.Context { - return x.stream.Context() -} - -func (x *registryServiceWatch) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *registryServiceWatch) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *registryServiceWatch) Recv() (*Result, error) { - m := new(Result) - err := x.stream.Recv(m) - if err != nil { - return nil, err - } - return m, nil -} - -// Server API for Registry service - -type RegistryHandler interface { - GetService(context.Context, *GetRequest, *GetResponse) error - Register(context.Context, *Service, *EmptyResponse) error - Deregister(context.Context, *Service, *EmptyResponse) error - ListServices(context.Context, *ListRequest, *ListResponse) error - Watch(context.Context, *WatchRequest, Registry_WatchStream) error -} - -func RegisterRegistryHandler(s server.Server, hdlr RegistryHandler, opts ...server.HandlerOption) error { - type registry interface { - GetService(ctx context.Context, in *GetRequest, out *GetResponse) error - Register(ctx context.Context, in *Service, out *EmptyResponse) error - Deregister(ctx context.Context, in *Service, out *EmptyResponse) error - ListServices(ctx context.Context, in *ListRequest, out *ListResponse) error - Watch(ctx context.Context, stream server.Stream) error - } - type Registry struct { - registry - } - h := ®istryHandler{hdlr} - return s.Handle(s.NewHandler(&Registry{h}, opts...)) -} - -type registryHandler struct { - RegistryHandler -} - -func (h *registryHandler) GetService(ctx context.Context, in *GetRequest, out *GetResponse) error { - return h.RegistryHandler.GetService(ctx, in, out) -} - -func (h *registryHandler) Register(ctx context.Context, in *Service, out *EmptyResponse) error { - return h.RegistryHandler.Register(ctx, in, out) -} - -func (h *registryHandler) Deregister(ctx context.Context, in *Service, out *EmptyResponse) error { - return h.RegistryHandler.Deregister(ctx, in, out) -} - -func (h *registryHandler) ListServices(ctx context.Context, in *ListRequest, out *ListResponse) error { - return h.RegistryHandler.ListServices(ctx, in, out) -} - -func (h *registryHandler) Watch(ctx context.Context, stream server.Stream) error { - m := new(WatchRequest) - if err := stream.Recv(m); err != nil { - return err - } - return h.RegistryHandler.Watch(ctx, m, ®istryWatchStream{stream}) -} - -type Registry_WatchStream interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Send(*Result) error -} - -type registryWatchStream struct { - stream server.Stream -} - -func (x *registryWatchStream) Close() error { - return x.stream.Close() -} - -func (x *registryWatchStream) Context() context.Context { - return x.stream.Context() -} - -func (x *registryWatchStream) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *registryWatchStream) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *registryWatchStream) Send(m *Result) error { - return x.stream.Send(m) -} diff --git a/registry/service/proto/registry.proto b/registry/service/proto/registry.proto deleted file mode 100644 index 877720a8..00000000 --- a/registry/service/proto/registry.proto +++ /dev/null @@ -1,101 +0,0 @@ -syntax = "proto3"; - -package go.micro.registry; - -service Registry { - rpc GetService(GetRequest) returns (GetResponse) {}; - rpc Register(Service) returns (EmptyResponse) {}; - rpc Deregister(Service) returns (EmptyResponse) {}; - rpc ListServices(ListRequest) returns (ListResponse) {}; - rpc Watch(WatchRequest) returns (stream Result) {}; -} - -// Service represents a go-micro service -message Service { - string name = 1; - string version = 2; - map metadata = 3; - repeated Endpoint endpoints = 4; - repeated Node nodes = 5; - Options options = 6; -} - -// Node represents the node the service is on -message Node { - string id = 1; - string address = 2; - int64 port = 3; - map metadata = 4; -} - -// Endpoint is a endpoint provided by a service -message Endpoint { - string name = 1; - Value request = 2; - Value response = 3; - map metadata = 4; -} - -// Value is an opaque value for a request or response -message Value { - string name = 1; - string type = 2; - repeated Value values = 3; -} - -// Options are registry options -message Options { - int64 ttl = 1; - string domain = 2; -} - -// Result is returns by the watcher -message Result { - string action = 1; // create, update, delete - Service service = 2; - int64 timestamp = 3; // unix timestamp -} - -message EmptyResponse {} - -message GetRequest { - string service = 1; - Options options = 2; -} - -message GetResponse { - repeated Service services = 1; -} - -message ListRequest { - Options options = 1; -} - -message ListResponse { - repeated Service services = 1; -} - -message WatchRequest { - // service is optional - string service = 1; - Options options = 2; -} - -// EventType defines the type of event -enum EventType { - Create = 0; - Delete = 1; - Update = 2; -} - -// Event is registry event -message Event { - // Event Id - string id = 1; - // type of event - EventType type = 2; - // unix timestamp of event - int64 timestamp = 3; - // service entry - Service service = 4; -} diff --git a/registry/service/service.go b/registry/service/service.go deleted file mode 100644 index fc03ce54..00000000 --- a/registry/service/service.go +++ /dev/null @@ -1,216 +0,0 @@ -// Package service uses the registry service -package service - -import ( - "context" - "time" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/client/grpc" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/registry" - pb "github.com/micro/go-micro/v2/registry/service/proto" -) - -var ( - // The default service name - DefaultService = "go.micro.registry" -) - -type serviceRegistry struct { - opts registry.Options - // name of the registry - name string - // address - address []string - // client to call registry - client pb.RegistryService -} - -func (s *serviceRegistry) callOpts() []client.CallOption { - var opts []client.CallOption - - // set registry address - if len(s.address) > 0 { - opts = append(opts, client.WithAddress(s.address...)) - } - - // set timeout - if s.opts.Timeout > time.Duration(0) { - opts = append(opts, client.WithRequestTimeout(s.opts.Timeout)) - } - - return opts -} - -func (s *serviceRegistry) Init(opts ...registry.Option) error { - for _, o := range opts { - o(&s.opts) - } - - if len(s.opts.Addrs) > 0 { - s.address = s.opts.Addrs - } - - // extract the client from the context, fallback to grpc - var cli client.Client - if c, ok := s.opts.Context.Value(clientKey{}).(client.Client); ok { - cli = c - } else { - cli = grpc.NewClient() - } - - s.client = pb.NewRegistryService(DefaultService, cli) - - return nil -} - -func (s *serviceRegistry) Options() registry.Options { - return s.opts -} - -func (s *serviceRegistry) Register(srv *registry.Service, opts ...registry.RegisterOption) error { - var options registry.RegisterOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.TODO() - } - - // encode srv into protobuf and pack TTL and domain into it - pbSrv := ToProto(srv) - pbSrv.Options.Ttl = int64(options.TTL.Seconds()) - pbSrv.Options.Domain = options.Domain - - // register the service - _, err := s.client.Register(options.Context, pbSrv, s.callOpts()...) - return err -} - -func (s *serviceRegistry) Deregister(srv *registry.Service, opts ...registry.DeregisterOption) error { - var options registry.DeregisterOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.TODO() - } - - // encode srv into protobuf and pack domain into it - pbSrv := ToProto(srv) - pbSrv.Options.Domain = options.Domain - - // deregister the service - _, err := s.client.Deregister(options.Context, pbSrv, s.callOpts()...) - return err -} - -func (s *serviceRegistry) GetService(name string, opts ...registry.GetOption) ([]*registry.Service, error) { - var options registry.GetOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.TODO() - } - - rsp, err := s.client.GetService(options.Context, &pb.GetRequest{ - Service: name, Options: &pb.Options{Domain: options.Domain}, - }, s.callOpts()...) - - if verr, ok := err.(*errors.Error); ok && verr.Code == 404 { - return nil, registry.ErrNotFound - } else if err != nil { - return nil, err - } - - services := make([]*registry.Service, 0, len(rsp.Services)) - for _, service := range rsp.Services { - services = append(services, ToService(service)) - } - return services, nil -} - -func (s *serviceRegistry) ListServices(opts ...registry.ListOption) ([]*registry.Service, error) { - var options registry.ListOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.TODO() - } - - req := &pb.ListRequest{Options: &pb.Options{Domain: options.Domain}} - rsp, err := s.client.ListServices(options.Context, req, s.callOpts()...) - if err != nil { - return nil, err - } - - services := make([]*registry.Service, 0, len(rsp.Services)) - for _, service := range rsp.Services { - services = append(services, ToService(service)) - } - - return services, nil -} - -func (s *serviceRegistry) Watch(opts ...registry.WatchOption) (registry.Watcher, error) { - var options registry.WatchOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.TODO() - } - - stream, err := s.client.Watch(options.Context, &pb.WatchRequest{ - Service: options.Service, Options: &pb.Options{Domain: options.Domain}, - }, s.callOpts()...) - - if err != nil { - return nil, err - } - - return newWatcher(stream), nil -} - -func (s *serviceRegistry) String() string { - return "service" -} - -// NewRegistry returns a new registry service client -func NewRegistry(opts ...registry.Option) registry.Registry { - var options registry.Options - for _, o := range opts { - o(&options) - } - - // the registry address - addrs := options.Addrs - if len(addrs) == 0 { - addrs = []string{"127.0.0.1:8000"} - } - - if options.Context == nil { - options.Context = context.TODO() - } - - // extract the client from the context, fallback to grpc - var cli client.Client - if c, ok := options.Context.Value(clientKey{}).(client.Client); ok { - cli = c - } else { - cli = grpc.NewClient() - } - - // service name. TODO: accept option - name := DefaultService - - return &serviceRegistry{ - opts: options, - name: name, - address: addrs, - client: pb.NewRegistryService(name, cli), - } -} diff --git a/registry/service/util.go b/registry/service/util.go deleted file mode 100644 index 4ba5f4da..00000000 --- a/registry/service/util.go +++ /dev/null @@ -1,134 +0,0 @@ -package service - -import ( - "github.com/micro/go-micro/v2/registry" - pb "github.com/micro/go-micro/v2/registry/service/proto" -) - -func values(v []*registry.Value) []*pb.Value { - if len(v) == 0 { - return []*pb.Value{} - } - - vs := make([]*pb.Value, 0, len(v)) - for _, vi := range v { - vs = append(vs, &pb.Value{ - Name: vi.Name, - Type: vi.Type, - Values: values(vi.Values), - }) - } - return vs -} - -func toValues(v []*pb.Value) []*registry.Value { - if len(v) == 0 { - return []*registry.Value{} - } - - vs := make([]*registry.Value, 0, len(v)) - for _, vi := range v { - vs = append(vs, ®istry.Value{ - Name: vi.Name, - Type: vi.Type, - Values: toValues(vi.Values), - }) - } - return vs -} - -func ToProto(s *registry.Service) *pb.Service { - endpoints := make([]*pb.Endpoint, 0, len(s.Endpoints)) - for _, ep := range s.Endpoints { - var request, response *pb.Value - - if ep.Request != nil { - request = &pb.Value{ - Name: ep.Request.Name, - Type: ep.Request.Type, - Values: values(ep.Request.Values), - } - } - - if ep.Response != nil { - response = &pb.Value{ - Name: ep.Response.Name, - Type: ep.Response.Type, - Values: values(ep.Response.Values), - } - } - - endpoints = append(endpoints, &pb.Endpoint{ - Name: ep.Name, - Request: request, - Response: response, - Metadata: ep.Metadata, - }) - } - - nodes := make([]*pb.Node, 0, len(s.Nodes)) - - for _, node := range s.Nodes { - nodes = append(nodes, &pb.Node{ - Id: node.Id, - Address: node.Address, - Metadata: node.Metadata, - }) - } - - return &pb.Service{ - Name: s.Name, - Version: s.Version, - Metadata: s.Metadata, - Endpoints: endpoints, - Nodes: nodes, - Options: new(pb.Options), - } -} - -func ToService(s *pb.Service) *registry.Service { - endpoints := make([]*registry.Endpoint, 0, len(s.Endpoints)) - for _, ep := range s.Endpoints { - var request, response *registry.Value - - if ep.Request != nil { - request = ®istry.Value{ - Name: ep.Request.Name, - Type: ep.Request.Type, - Values: toValues(ep.Request.Values), - } - } - - if ep.Response != nil { - response = ®istry.Value{ - Name: ep.Response.Name, - Type: ep.Response.Type, - Values: toValues(ep.Response.Values), - } - } - - endpoints = append(endpoints, ®istry.Endpoint{ - Name: ep.Name, - Request: request, - Response: response, - Metadata: ep.Metadata, - }) - } - - nodes := make([]*registry.Node, 0, len(s.Nodes)) - for _, node := range s.Nodes { - nodes = append(nodes, ®istry.Node{ - Id: node.Id, - Address: node.Address, - Metadata: node.Metadata, - }) - } - - return ®istry.Service{ - Name: s.Name, - Version: s.Version, - Metadata: s.Metadata, - Endpoints: endpoints, - Nodes: nodes, - } -} diff --git a/registry/service/watcher.go b/registry/service/watcher.go deleted file mode 100644 index bf998a2f..00000000 --- a/registry/service/watcher.go +++ /dev/null @@ -1,47 +0,0 @@ -package service - -import ( - "github.com/micro/go-micro/v2/registry" - pb "github.com/micro/go-micro/v2/registry/service/proto" -) - -type serviceWatcher struct { - stream pb.Registry_WatchService - closed chan bool -} - -func (s *serviceWatcher) Next() (*registry.Result, error) { - // check if closed - select { - case <-s.closed: - return nil, registry.ErrWatcherStopped - default: - } - - r, err := s.stream.Recv() - if err != nil { - return nil, err - } - - return ®istry.Result{ - Action: r.Action, - Service: ToService(r.Service), - }, nil -} - -func (s *serviceWatcher) Stop() { - select { - case <-s.closed: - return - default: - close(s.closed) - s.stream.Close() - } -} - -func newWatcher(stream pb.Registry_WatchService) registry.Watcher { - return &serviceWatcher{ - stream: stream, - closed: make(chan bool), - } -} diff --git a/router/default.go b/router/default.go deleted file mode 100644 index 7ef99831..00000000 --- a/router/default.go +++ /dev/null @@ -1,722 +0,0 @@ -package router - -import ( - "errors" - "fmt" - "sort" - "strings" - "sync" - "time" - - "github.com/google/uuid" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/registry" -) - -var ( - // AdvertiseEventsTick is time interval in which the router advertises route updates - AdvertiseEventsTick = 10 * time.Second - // DefaultAdvertTTL is default advertisement TTL - DefaultAdvertTTL = 2 * time.Minute -) - -// router implements default router -type router struct { - sync.RWMutex - - running bool - table *table - options Options - exit chan bool - eventChan chan *Event - - // advert subscribers - sub sync.RWMutex - subscribers map[string]chan *Advert -} - -// newRouter creates new router and returns it -func newRouter(opts ...Option) Router { - // get default options - options := DefaultOptions() - - // apply requested options - for _, o := range opts { - o(&options) - } - - // construct the router - r := &router{ - options: options, - subscribers: make(map[string]chan *Advert), - } - - // create the new table, passing the fetchRoute method in as a fallback if - // the table doesn't contain the result for a query. - r.table = newTable(r.fetchRoutes) - - // start the router and return - r.start() - return r -} - -// Init initializes router with given options -func (r *router) Init(opts ...Option) error { - // stop the router before we initialize - if err := r.Close(); err != nil { - return err - } - - r.Lock() - defer r.Unlock() - - for _, o := range opts { - o(&r.options) - } - - // restart the router - if err := r.start(); err != nil { - return err - } - - return nil -} - -// Options returns router options -func (r *router) Options() Options { - r.RLock() - defer r.RUnlock() - - options := r.options - - return options -} - -// Table returns routing table -func (r *router) Table() Table { - return r.table -} - -// manageRoute applies action on a given route -func (r *router) manageRoute(route Route, action string) error { - switch action { - case "create": - if err := r.table.Create(route); err != nil && err != ErrDuplicateRoute { - return fmt.Errorf("failed adding route for service %s: %s", route.Service, err) - } - case "delete": - if err := r.table.Delete(route); err != nil && err != ErrRouteNotFound { - return fmt.Errorf("failed deleting route for service %s: %s", route.Service, err) - } - case "update": - if err := r.table.Update(route); err != nil { - return fmt.Errorf("failed updating route for service %s: %s", route.Service, err) - } - default: - return fmt.Errorf("failed to manage route for service %s: unknown action %s", route.Service, action) - } - - return nil -} - -// manageServiceRoutes applies action to all routes of the service. -// It returns error of the action fails with error. -func (r *router) manageRoutes(service *registry.Service, action, network string) error { - // action is the routing table action - action = strings.ToLower(action) - - // take route action on each service node - for _, node := range service.Nodes { - route := Route{ - Service: service.Name, - Address: node.Address, - Gateway: "", - Network: network, - Router: r.options.Id, - Link: DefaultLink, - Metric: DefaultLocalMetric, - Metadata: node.Metadata, - } - - if err := r.manageRoute(route, action); err != nil { - return err - } - } - - return nil -} - -// manageRegistryRoutes applies action to all routes of each service found in the registry. -// It returns error if either the services failed to be listed or the routing table action fails. -func (r *router) manageRegistryRoutes(reg registry.Registry, action string) error { - services, err := reg.ListServices(registry.ListDomain(registry.WildcardDomain)) - if err != nil { - return fmt.Errorf("failed listing services: %v", err) - } - - // add each service node as a separate route - for _, service := range services { - // get the services domain from metadata. Fallback to wildcard. - var domain string - if service.Metadata != nil && len(service.Metadata["domain"]) > 0 { - domain = service.Metadata["domain"] - } else { - domain = registry.WildcardDomain - } - - // get the service to retrieve all its info - srvs, err := reg.GetService(service.Name, registry.GetDomain(domain)) - if err != nil { - continue - } - // manage the routes for all returned services - for _, srv := range srvs { - if err := r.manageRoutes(srv, action, domain); err != nil { - return err - } - } - } - - return nil -} - -// fetchRoutes retrieves all the routes for a given service and creates them in the routing table -func (r *router) fetchRoutes(service string) error { - services, err := r.options.Registry.GetService(service, registry.GetDomain(registry.WildcardDomain)) - if err == registry.ErrNotFound { - return nil - } else if err != nil { - return fmt.Errorf("failed getting services: %v", err) - } - - for _, srv := range services { - var domain string - if srv.Metadata != nil && len(srv.Metadata["domain"]) > 0 { - domain = srv.Metadata["domain"] - } else { - domain = registry.WildcardDomain - } - - if err := r.manageRoutes(srv, "create", domain); err != nil { - return err - } - } - - return nil -} - -// watchRegistry watches registry and updates routing table based on the received events. -// It returns error if either the registry watcher fails with error or if the routing table update fails. -func (r *router) watchRegistry(w registry.Watcher) error { - exit := make(chan bool) - - defer func() { - close(exit) - }() - - go func() { - defer w.Stop() - - select { - case <-exit: - return - case <-r.exit: - return - } - }() - - for { - res, err := w.Next() - if err != nil { - if err != registry.ErrWatcherStopped { - return err - } - break - } - - if res.Service == nil { - continue - } - - // get the services domain from metadata. Fallback to wildcard. - var domain string - if res.Service.Metadata != nil && len(res.Service.Metadata["domain"]) > 0 { - domain = res.Service.Metadata["domain"] - } else { - domain = registry.WildcardDomain - } - - if err := r.manageRoutes(res.Service, res.Action, domain); err != nil { - return err - } - } - - return nil -} - -// watchTable watches routing table entries and either adds or deletes locally registered service to/from network registry -// It returns error if the locally registered services either fails to be added/deleted to/from network registry. -func (r *router) watchTable(w Watcher) error { - exit := make(chan bool) - - defer func() { - close(exit) - }() - - // wait in the background for the router to stop - // when the router stops, stop the watcher and exit - go func() { - defer w.Stop() - - select { - case <-r.exit: - return - case <-exit: - return - } - }() - - for { - event, err := w.Next() - if err != nil { - if err != ErrWatcherStopped { - return err - } - break - } - - select { - case <-r.exit: - return nil - case r.eventChan <- event: - // process event - } - } - - return nil -} - -// publishAdvert publishes router advert to advert channel -func (r *router) publishAdvert(advType AdvertType, events []*Event) { - a := &Advert{ - Id: r.options.Id, - Type: advType, - TTL: DefaultAdvertTTL, - Timestamp: time.Now(), - Events: events, - } - - r.sub.RLock() - for _, sub := range r.subscribers { - // now send the message - select { - case sub <- a: - case <-r.exit: - r.sub.RUnlock() - return - } - } - r.sub.RUnlock() -} - -// adverts maintains a map of router adverts -type adverts map[uint64]*Event - -// advertiseEvents advertises routing table events -// It suppresses unhealthy flapping events and advertises healthy events upstream. -func (r *router) advertiseEvents() error { - // ticker to periodically scan event for advertising - ticker := time.NewTicker(AdvertiseEventsTick) - defer ticker.Stop() - - // adverts is a map of advert events - adverts := make(adverts) - - // routing table watcher - w, err := r.Watch() - if err != nil { - return err - } - defer w.Stop() - - go func() { - var err error - - for { - select { - case <-r.exit: - return - default: - if w == nil { - // routing table watcher - w, err = r.Watch() - if err != nil { - if logger.V(logger.ErrorLevel, logger.DefaultLogger) { - logger.Errorf("Error creating watcher: %v", err) - } - time.Sleep(time.Second) - continue - } - } - - if err := r.watchTable(w); err != nil { - if logger.V(logger.ErrorLevel, logger.DefaultLogger) { - logger.Errorf("Error watching table: %v", err) - } - time.Sleep(time.Second) - } - - if w != nil { - // reset - w.Stop() - w = nil - } - } - } - }() - - for { - select { - case <-ticker.C: - // If we're not advertising any events then sip processing them entirely - if r.options.Advertise == AdvertiseNone { - continue - } - - var events []*Event - - // collect all events which are not flapping - for key, event := range adverts { - // if we only advertise local routes skip processing anything not link local - if r.options.Advertise == AdvertiseLocal && event.Route.Link != "local" { - continue - } - - // copy the event and append - e := new(Event) - // this is ok, because router.Event only contains builtin types - // and no references so this creates a deep copy of struct Event - *e = *event - events = append(events, e) - // delete the advert from adverts - delete(adverts, key) - } - - // advertise events to subscribers - if len(events) > 0 { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Router publishing %d events", len(events)) - } - go r.publishAdvert(RouteUpdate, events) - } - case e := <-r.eventChan: - // if event is nil, continue - if e == nil { - continue - } - - // If we're not advertising any events then skip processing them entirely - if r.options.Advertise == AdvertiseNone { - continue - } - - // if we only advertise local routes skip processing anything not link local - if r.options.Advertise == AdvertiseLocal && e.Route.Link != "local" { - continue - } - - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Router processing table event %s for service %s %s", e.Type, e.Route.Service, e.Route.Address) - } - - // check if we have already registered the route - hash := e.Route.Hash() - ev, ok := adverts[hash] - if !ok { - ev = e - adverts[hash] = e - continue - } - - // override the route event only if the previous event was different - if ev.Type != e.Type { - ev = e - } - case <-r.exit: - if w != nil { - w.Stop() - } - return nil - } - } -} - -// drain all the events, only called on Stop -func (r *router) drain() { - for { - select { - case <-r.eventChan: - default: - return - } - } -} - -// start the router. Should be called under lock. -func (r *router) start() error { - if r.running { - return nil - } - - if r.options.Prewarm { - // add all local service routes into the routing table - if err := r.manageRegistryRoutes(r.options.Registry, "create"); err != nil { - return fmt.Errorf("failed adding registry routes: %s", err) - } - } - - // add default gateway into routing table - if r.options.Gateway != "" { - // note, the only non-default value is the gateway - route := Route{ - Service: "*", - Address: "*", - Gateway: r.options.Gateway, - Network: "*", - Router: r.options.Id, - Link: DefaultLink, - Metric: DefaultLocalMetric, - } - if err := r.table.Create(route); err != nil { - return fmt.Errorf("failed adding default gateway route: %s", err) - } - } - - // create error and exit channels - r.exit = make(chan bool) - - // registry watcher - w, err := r.options.Registry.Watch(registry.WatchDomain(registry.WildcardDomain)) - if err != nil { - return fmt.Errorf("failed creating registry watcher: %v", err) - } - - go func() { - var err error - - for { - select { - case <-r.exit: - if w != nil { - w.Stop() - } - return - default: - if w == nil { - w, err = r.options.Registry.Watch() - if err != nil { - if logger.V(logger.WarnLevel, logger.DefaultLogger) { - logger.Warnf("failed creating registry watcher: %v", err) - } - time.Sleep(time.Second) - continue - } - } - - if err := r.watchRegistry(w); err != nil { - if logger.V(logger.WarnLevel, logger.DefaultLogger) { - logger.Warnf("Error watching the registry: %v", err) - } - time.Sleep(time.Second) - } - - if w != nil { - w.Stop() - w = nil - } - } - } - }() - - r.running = true - - return nil -} - -// Advertise stars advertising the routes to the network and returns the advertisements channel to consume from. -// If the router is already advertising it returns the channel to consume from. -// It returns error if either the router is not running or if the routing table fails to list the routes to advertise. -func (r *router) Advertise() (<-chan *Advert, error) { - r.Lock() - defer r.Unlock() - - if !r.running { - return nil, errors.New("not running") - } - - // we're mutating the subscribers so they need to be locked also - r.sub.Lock() - defer r.sub.Unlock() - - // already advertising - if r.eventChan != nil { - advertChan := make(chan *Advert, 128) - r.subscribers[uuid.New().String()] = advertChan - return advertChan, nil - } - - // list all the routes and pack them into even slice to advertise - events, err := r.flushRouteEvents(Create) - if err != nil { - return nil, fmt.Errorf("failed to flush routes: %s", err) - } - - // create event channels - r.eventChan = make(chan *Event) - - // create advert channel - advertChan := make(chan *Advert, 128) - r.subscribers[uuid.New().String()] = advertChan - - // advertise your presence - go r.publishAdvert(Announce, events) - - go func() { - select { - case <-r.exit: - return - default: - if err := r.advertiseEvents(); err != nil { - if logger.V(logger.ErrorLevel, logger.DefaultLogger) { - logger.Errorf("Error adveritising events: %v", err) - } - } - } - }() - - return advertChan, nil - -} - -// Process updates the routing table using the advertised values -func (r *router) Process(a *Advert) error { - // NOTE: event sorting might not be necessary - // copy update events intp new slices - events := make([]*Event, len(a.Events)) - copy(events, a.Events) - // sort events by timestamp - sort.Slice(events, func(i, j int) bool { - return events[i].Timestamp.Before(events[j].Timestamp) - }) - - if logger.V(logger.TraceLevel, logger.DefaultLogger) { - logger.Tracef("Router %s processing advert from: %s", r.options.Id, a.Id) - } - - for _, event := range events { - // skip if the router is the origin of this route - if event.Route.Router == r.options.Id { - if logger.V(logger.TraceLevel, logger.DefaultLogger) { - logger.Tracef("Router skipping processing its own route: %s", r.options.Id) - } - continue - } - // create a copy of the route - route := event.Route - action := event.Type - - if logger.V(logger.TraceLevel, logger.DefaultLogger) { - logger.Tracef("Router %s applying %s from router %s for service %s %s", r.options.Id, action, route.Router, route.Service, route.Address) - } - - if err := r.manageRoute(route, action.String()); err != nil { - return fmt.Errorf("failed applying action %s to routing table: %s", action, err) - } - } - - return nil -} - -// flushRouteEvents returns a slice of events, one per each route in the routing table -func (r *router) flushRouteEvents(evType EventType) ([]*Event, error) { - // get a list of routes for each service in our routing table - // for the configured advertising strategy - q := []QueryOption{ - QueryStrategy(r.options.Advertise), - } - - routes, err := r.Table().Query(q...) - if err != nil && err != ErrRouteNotFound { - return nil, err - } - - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Router advertising %d routes with strategy %s", len(routes), r.options.Advertise) - } - - // build a list of events to advertise - events := make([]*Event, len(routes)) - var i int - - for _, route := range routes { - event := &Event{ - Type: evType, - Timestamp: time.Now(), - Route: route, - } - events[i] = event - i++ - } - - return events, nil -} - -// Lookup routes in the routing table -func (r *router) Lookup(q ...QueryOption) ([]Route, error) { - return r.table.Query(q...) -} - -// Watch routes -func (r *router) Watch(opts ...WatchOption) (Watcher, error) { - return r.table.Watch(opts...) -} - -// Close the router -func (r *router) Close() error { - r.Lock() - defer r.Unlock() - - select { - case <-r.exit: - return nil - default: - close(r.exit) - - // extract the events - r.drain() - - r.sub.Lock() - // close advert subscribers - for id, sub := range r.subscribers { - // close the channel - close(sub) - // delete the subscriber - delete(r.subscribers, id) - } - r.sub.Unlock() - } - - // close and remove event chan - if r.eventChan != nil { - close(r.eventChan) - r.eventChan = nil - } - - r.running = false - return nil -} - -// String prints debugging information about router -func (r *router) String() string { - return "registry" -} diff --git a/router/dns/dns.go b/router/dns/dns.go index 4241b3d4..151c9c23 100644 --- a/router/dns/dns.go +++ b/router/dns/dns.go @@ -5,7 +5,7 @@ import ( "net" "strconv" - "github.com/micro/go-micro/v2/router" + "github.com/micro/go-micro/v3/router" ) // NewRouter returns an initialized dns router diff --git a/router/options.go b/router/options.go index cba10356..f162fefd 100644 --- a/router/options.go +++ b/router/options.go @@ -4,7 +4,8 @@ import ( "context" "github.com/google/uuid" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/mdns" ) // Options are router options @@ -23,8 +24,8 @@ type Options struct { Advertise Strategy // Context for additional options Context context.Context - // Prewarm the route table on router startup - Prewarm bool + // Precache the route table on router startup + Precache bool } // Id sets Router Id @@ -69,10 +70,10 @@ func Advertise(a Strategy) Option { } } -// Prewarm sets whether to prewarm the route table -func Prewarm(b bool) Option { +// Precache sets whether to precache the route table +func Precache(b bool) Option { return func(o *Options) { - o.Prewarm = b + o.Precache = b } } @@ -82,7 +83,7 @@ func DefaultOptions() Options { Id: uuid.New().String(), Address: DefaultAddress, Network: DefaultNetwork, - Registry: registry.DefaultRegistry, + Registry: mdns.NewRegistry(), Advertise: AdvertiseLocal, Context: context.Background(), } diff --git a/router/registry/registry.go b/router/registry/registry.go index 01172b46..b585965b 100644 --- a/router/registry/registry.go +++ b/router/registry/registry.go @@ -1,8 +1,723 @@ package registry -import "github.com/micro/go-micro/v2/router" +import ( + "errors" + "fmt" + "sort" + "strings" + "sync" + "time" -// NewRouter returns an initialised registry router -func NewRouter(opts ...router.Option) router.Router { - return router.NewRouter(opts...) + "github.com/google/uuid" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/router" +) + +var ( + // AdvertiseEventsTick is time interval in which the router advertises route updates + AdvertiseEventsTick = 10 * time.Second + // DefaultAdvertTTL is default advertisement TTL + DefaultAdvertTTL = 2 * time.Minute +) + +// rtr implements router interface +type rtr struct { + sync.RWMutex + + running bool + table *table + options router.Options + exit chan bool + eventChan chan *router.Event + + // advert subscribers + sub sync.RWMutex + subscribers map[string]chan *router.Advert +} + +// NewRouter creates new router and returns it +func NewRouter(opts ...router.Option) router.Router { + // get default options + options := router.DefaultOptions() + + // apply requested options + for _, o := range opts { + o(&options) + } + + // construct the router + r := &rtr{ + options: options, + subscribers: make(map[string]chan *router.Advert), + } + + // create the new table, passing the fetchRoute method in as a fallback if + // the table doesn't contain the result for a query. + r.table = newTable(r.fetchRoutes) + return r +} + +// Init initializes router with given options +func (r *rtr) Init(opts ...router.Option) error { + // stop the router before we initialize + if err := r.Close(); err != nil { + return err + } + + r.Lock() + defer r.Unlock() + + for _, o := range opts { + o(&r.options) + } + + return nil +} + +// Options returns router options +func (r *rtr) Options() router.Options { + r.RLock() + defer r.RUnlock() + + options := r.options + + return options +} + +// Table returns routing table +func (r *rtr) Table() router.Table { + r.Lock() + defer r.Unlock() + return r.table +} + +// manageRoute applies action on a given route +func (r *rtr) manageRoute(route router.Route, action string) error { + switch action { + case "create": + if err := r.table.Create(route); err != nil && err != router.ErrDuplicateRoute { + return fmt.Errorf("failed adding route for service %s: %s", route.Service, err) + } + case "delete": + if err := r.table.Delete(route); err != nil && err != router.ErrRouteNotFound { + return fmt.Errorf("failed deleting route for service %s: %s", route.Service, err) + } + case "update": + if err := r.table.Update(route); err != nil { + return fmt.Errorf("failed updating route for service %s: %s", route.Service, err) + } + default: + return fmt.Errorf("failed to manage route for service %s: unknown action %s", route.Service, action) + } + + return nil +} + +// manageServiceRoutes applies action to all routes of the service. +// It returns error of the action fails with error. +func (r *rtr) manageRoutes(service *registry.Service, action, network string) error { + // action is the routing table action + action = strings.ToLower(action) + + // take route action on each service node + for _, node := range service.Nodes { + route := router.Route{ + Service: service.Name, + Address: node.Address, + Gateway: "", + Network: network, + Router: r.options.Id, + Link: router.DefaultLink, + Metric: router.DefaultLocalMetric, + Metadata: node.Metadata, + } + + if err := r.manageRoute(route, action); err != nil { + return err + } + } + + return nil +} + +// manageRegistryRoutes applies action to all routes of each service found in the registry. +// It returns error if either the services failed to be listed or the routing table action fails. +func (r *rtr) manageRegistryRoutes(reg registry.Registry, action string) error { + services, err := reg.ListServices(registry.ListDomain(registry.WildcardDomain)) + if err != nil { + return fmt.Errorf("failed listing services: %v", err) + } + + // add each service node as a separate route + for _, service := range services { + // get the services domain from metadata. Fallback to wildcard. + var domain string + if service.Metadata != nil && len(service.Metadata["domain"]) > 0 { + domain = service.Metadata["domain"] + } else { + domain = registry.WildcardDomain + } + + // get the service to retrieve all its info + srvs, err := reg.GetService(service.Name, registry.GetDomain(domain)) + if err != nil { + continue + } + // manage the routes for all returned services + for _, srv := range srvs { + if err := r.manageRoutes(srv, action, domain); err != nil { + return err + } + } + } + + return nil +} + +// fetchRoutes retrieves all the routes for a given service and creates them in the routing table +func (r *rtr) fetchRoutes(service string) error { + services, err := r.options.Registry.GetService(service, registry.GetDomain(registry.WildcardDomain)) + if err == registry.ErrNotFound { + return nil + } else if err != nil { + return fmt.Errorf("failed getting services: %v", err) + } + + for _, srv := range services { + var domain string + if srv.Metadata != nil && len(srv.Metadata["domain"]) > 0 { + domain = srv.Metadata["domain"] + } else { + domain = registry.WildcardDomain + } + + if err := r.manageRoutes(srv, "create", domain); err != nil { + return err + } + } + + return nil +} + +// watchRegistry watches registry and updates routing table based on the received events. +// It returns error if either the registry watcher fails with error or if the routing table update fails. +func (r *rtr) watchRegistry(w registry.Watcher) error { + exit := make(chan bool) + + defer func() { + close(exit) + }() + + go func() { + defer w.Stop() + + select { + case <-exit: + return + case <-r.exit: + return + } + }() + + for { + res, err := w.Next() + if err != nil { + if err != registry.ErrWatcherStopped { + return err + } + break + } + + if res.Service == nil { + continue + } + + // get the services domain from metadata. Fallback to wildcard. + var domain string + if res.Service.Metadata != nil && len(res.Service.Metadata["domain"]) > 0 { + domain = res.Service.Metadata["domain"] + } else { + domain = registry.WildcardDomain + } + + if err := r.manageRoutes(res.Service, res.Action, domain); err != nil { + return err + } + } + + return nil +} + +// watchTable watches routing table entries and either adds or deletes locally registered service to/from network registry +// It returns error if the locally registered services either fails to be added/deleted to/from network registry. +func (r *rtr) watchTable(w router.Watcher) error { + exit := make(chan bool) + + defer func() { + close(exit) + }() + + // wait in the background for the router to stop + // when the router stops, stop the watcher and exit + go func() { + defer w.Stop() + + select { + case <-r.exit: + return + case <-exit: + return + } + }() + + for { + event, err := w.Next() + if err != nil { + if err != router.ErrWatcherStopped { + return err + } + break + } + + select { + case <-r.exit: + return nil + case r.eventChan <- event: + // process event + } + } + + return nil +} + +// publishAdvert publishes router advert to advert channel +func (r *rtr) publishAdvert(advType router.AdvertType, events []*router.Event) { + a := &router.Advert{ + Id: r.options.Id, + Type: advType, + TTL: DefaultAdvertTTL, + Timestamp: time.Now(), + Events: events, + } + + r.sub.RLock() + for _, sub := range r.subscribers { + // now send the message + select { + case sub <- a: + case <-r.exit: + r.sub.RUnlock() + return + } + } + r.sub.RUnlock() +} + +// adverts maintains a map of router adverts +type adverts map[uint64]*router.Event + +// advertiseEvents advertises routing table events +// It suppresses unhealthy flapping events and advertises healthy events upstream. +func (r *rtr) advertiseEvents() error { + // ticker to periodically scan event for advertising + ticker := time.NewTicker(AdvertiseEventsTick) + defer ticker.Stop() + + // adverts is a map of advert events + adverts := make(adverts) + + // routing table watcher + w, err := r.Watch() + if err != nil { + return err + } + defer w.Stop() + + go func() { + var err error + + for { + select { + case <-r.exit: + return + default: + if w == nil { + // routing table watcher + w, err = r.Watch() + if err != nil { + if logger.V(logger.ErrorLevel, logger.DefaultLogger) { + logger.Errorf("Error creating watcher: %v", err) + } + time.Sleep(time.Second) + continue + } + } + + if err := r.watchTable(w); err != nil { + if logger.V(logger.ErrorLevel, logger.DefaultLogger) { + logger.Errorf("Error watching table: %v", err) + } + time.Sleep(time.Second) + } + + if w != nil { + // reset + w.Stop() + w = nil + } + } + } + }() + + for { + select { + case <-ticker.C: + // If we're not advertising any events then sip processing them entirely + if r.options.Advertise == router.AdvertiseNone { + continue + } + + var events []*router.Event + + // collect all events which are not flapping + for key, event := range adverts { + // if we only advertise local routes skip processing anything not link local + if r.options.Advertise == router.AdvertiseLocal && event.Route.Link != "local" { + continue + } + + // copy the event and append + e := new(router.Event) + // this is ok, because router.Event only contains builtin types + // and no references so this creates a deep copy of struct Event + *e = *event + events = append(events, e) + // delete the advert from adverts + delete(adverts, key) + } + + // advertise events to subscribers + if len(events) > 0 { + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Router publishing %d events", len(events)) + } + go r.publishAdvert(router.RouteUpdate, events) + } + case e := <-r.eventChan: + // if event is nil, continue + if e == nil { + continue + } + + // If we're not advertising any events then skip processing them entirely + if r.options.Advertise == router.AdvertiseNone { + continue + } + + // if we only advertise local routes skip processing anything not link local + if r.options.Advertise == router.AdvertiseLocal && e.Route.Link != "local" { + continue + } + + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Router processing table event %s for service %s %s", e.Type, e.Route.Service, e.Route.Address) + } + + // check if we have already registered the route + hash := e.Route.Hash() + ev, ok := adverts[hash] + if !ok { + ev = e + adverts[hash] = e + continue + } + + // override the route event only if the previous event was different + if ev.Type != e.Type { + ev = e + } + case <-r.exit: + if w != nil { + w.Stop() + } + return nil + } + } +} + +// drain all the events, only called on Stop +func (r *rtr) drain() { + for { + select { + case <-r.eventChan: + default: + return + } + } +} + +// start the router. Should be called under lock. +func (r *rtr) start() error { + if r.running { + return nil + } + + if r.options.Precache { + // add all local service routes into the routing table + if err := r.manageRegistryRoutes(r.options.Registry, "create"); err != nil { + return fmt.Errorf("failed adding registry routes: %s", err) + } + } + + // add default gateway into routing table + if r.options.Gateway != "" { + // note, the only non-default value is the gateway + route := router.Route{ + Service: "*", + Address: "*", + Gateway: r.options.Gateway, + Network: "*", + Router: r.options.Id, + Link: router.DefaultLink, + Metric: router.DefaultLocalMetric, + } + if err := r.table.Create(route); err != nil { + return fmt.Errorf("failed adding default gateway route: %s", err) + } + } + + // create error and exit channels + r.exit = make(chan bool) + + // registry watcher + w, err := r.options.Registry.Watch(registry.WatchDomain(registry.WildcardDomain)) + if err != nil { + return fmt.Errorf("failed creating registry watcher: %v", err) + } + + go func() { + var err error + + for { + select { + case <-r.exit: + if w != nil { + w.Stop() + } + return + default: + if w == nil { + w, err = r.options.Registry.Watch() + if err != nil { + if logger.V(logger.WarnLevel, logger.DefaultLogger) { + logger.Warnf("failed creating registry watcher: %v", err) + } + time.Sleep(time.Second) + continue + } + } + + if err := r.watchRegistry(w); err != nil { + if logger.V(logger.WarnLevel, logger.DefaultLogger) { + logger.Warnf("Error watching the registry: %v", err) + } + time.Sleep(time.Second) + } + + if w != nil { + w.Stop() + w = nil + } + } + } + }() + + r.running = true + + return nil +} + +// Advertise stars advertising the routes to the network and returns the advertisements channel to consume from. +// If the router is already advertising it returns the channel to consume from. +// It returns error if either the router is not running or if the routing table fails to list the routes to advertise. +func (r *rtr) Advertise() (<-chan *router.Advert, error) { + r.Lock() + defer r.Unlock() + + if r.running { + return nil, errors.New("cannot re-advertise, already running") + } + + // start the router + r.start() + + // we're mutating the subscribers so they need to be locked also + r.sub.Lock() + defer r.sub.Unlock() + + // already advertising + if r.eventChan != nil { + advertChan := make(chan *router.Advert, 128) + r.subscribers[uuid.New().String()] = advertChan + return advertChan, nil + } + + // list all the routes and pack them into even slice to advertise + events, err := r.flushRouteEvents(router.Create) + if err != nil { + return nil, fmt.Errorf("failed to flush routes: %s", err) + } + + // create event channels + r.eventChan = make(chan *router.Event) + + // create advert channel + advertChan := make(chan *router.Advert, 128) + r.subscribers[uuid.New().String()] = advertChan + + // advertise your presence + go r.publishAdvert(router.Announce, events) + + go func() { + select { + case <-r.exit: + return + default: + if err := r.advertiseEvents(); err != nil { + if logger.V(logger.ErrorLevel, logger.DefaultLogger) { + logger.Errorf("Error adveritising events: %v", err) + } + } + } + }() + + return advertChan, nil + +} + +// Process updates the routing table using the advertised values +func (r *rtr) Process(a *router.Advert) error { + // NOTE: event sorting might not be necessary + // copy update events intp new slices + events := make([]*router.Event, len(a.Events)) + copy(events, a.Events) + // sort events by timestamp + sort.Slice(events, func(i, j int) bool { + return events[i].Timestamp.Before(events[j].Timestamp) + }) + + if logger.V(logger.TraceLevel, logger.DefaultLogger) { + logger.Tracef("Router %s processing advert from: %s", r.options.Id, a.Id) + } + + for _, event := range events { + // skip if the router is the origin of this route + if event.Route.Router == r.options.Id { + if logger.V(logger.TraceLevel, logger.DefaultLogger) { + logger.Tracef("Router skipping processing its own route: %s", r.options.Id) + } + continue + } + // create a copy of the route + route := event.Route + action := event.Type + + if logger.V(logger.TraceLevel, logger.DefaultLogger) { + logger.Tracef("Router %s applying %s from router %s for service %s %s", r.options.Id, action, route.Router, route.Service, route.Address) + } + + if err := r.manageRoute(route, action.String()); err != nil { + return fmt.Errorf("failed applying action %s to routing table: %s", action, err) + } + } + + return nil +} + +// flushRouteEvents returns a slice of events, one per each route in the routing table +func (r *rtr) flushRouteEvents(evType router.EventType) ([]*router.Event, error) { + // get a list of routes for each service in our routing table + // for the configured advertising strategy + q := []router.QueryOption{ + router.QueryStrategy(r.options.Advertise), + } + + routes, err := r.table.Query(q...) + if err != nil && err != router.ErrRouteNotFound { + return nil, err + } + + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Router advertising %d routes with strategy %s", len(routes), r.options.Advertise) + } + + // build a list of events to advertise + events := make([]*router.Event, len(routes)) + var i int + + for _, route := range routes { + event := &router.Event{ + Type: evType, + Timestamp: time.Now(), + Route: route, + } + events[i] = event + i++ + } + + return events, nil +} + +// Lookup routes in the routing table +func (r *rtr) Lookup(q ...router.QueryOption) ([]router.Route, error) { + return r.Table().Query(q...) +} + +// Watch routes +func (r *rtr) Watch(opts ...router.WatchOption) (router.Watcher, error) { + return r.table.Watch(opts...) +} + +// Close the router +func (r *rtr) Close() error { + r.Lock() + defer r.Unlock() + + select { + case <-r.exit: + return nil + default: + if !r.running { + return nil + } + close(r.exit) + + // extract the events + r.drain() + + r.sub.Lock() + // close advert subscribers + for id, sub := range r.subscribers { + // close the channel + close(sub) + // delete the subscriber + delete(r.subscribers, id) + } + r.sub.Unlock() + } + + // close and remove event chan + if r.eventChan != nil { + close(r.eventChan) + r.eventChan = nil + } + + r.running = false + return nil +} + +// String prints debugging information about router +func (r *rtr) String() string { + return "registry" } diff --git a/router/default_test.go b/router/registry/registry_test.go similarity index 90% rename from router/default_test.go rename to router/registry/registry_test.go index 5c2d7845..0c1af956 100644 --- a/router/default_test.go +++ b/router/registry/registry_test.go @@ -1,4 +1,4 @@ -package router +package registry import ( "fmt" @@ -7,12 +7,13 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/registry/memory" + "github.com/micro/go-micro/v3/registry/memory" + "github.com/micro/go-micro/v3/router" ) -func routerTestSetup() Router { +func routerTestSetup() router.Router { r := memory.NewRegistry() - return newRouter(Registry(r)) + return NewRouter(router.Registry(r)) } func TestRouterClose(t *testing.T) { @@ -50,8 +51,8 @@ func TestRouterAdvertise(t *testing.T) { // Generate random unique routes nrRoutes := 5 - routes := make([]Route, nrRoutes) - route := Route{ + routes := make([]router.Route, nrRoutes) + route := router.Route{ Service: "dest.svc", Address: "dest.addr", Gateway: "dest.gw", diff --git a/router/table.go b/router/registry/table.go similarity index 71% rename from router/table.go rename to router/registry/table.go index 3402508a..2f1d748b 100644 --- a/router/table.go +++ b/router/registry/table.go @@ -1,19 +1,12 @@ -package router +package registry import ( - "errors" "sync" "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/logger" -) - -var ( - // ErrRouteNotFound is returned when no route was found in the routing table - ErrRouteNotFound = errors.New("route not found") - // ErrDuplicateRoute is returned when the route already exists - ErrDuplicateRoute = errors.New("duplicate route") + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/router" ) // table is an in-memory routing table @@ -22,22 +15,22 @@ type table struct { // fetchRoutes for a service fetchRoutes func(string) error // routes stores service routes - routes map[string]map[uint64]Route + routes map[string]map[uint64]router.Route // watchers stores table watchers watchers map[string]*tableWatcher } // newtable creates a new routing table and returns it -func newTable(fetchRoutes func(string) error, opts ...Option) *table { +func newTable(fetchRoutes func(string) error, opts ...router.Option) *table { return &table{ fetchRoutes: fetchRoutes, - routes: make(map[string]map[uint64]Route), + routes: make(map[string]map[uint64]router.Route), watchers: make(map[string]*tableWatcher), } } // sendEvent sends events to all subscribed watchers -func (t *table) sendEvent(e *Event) { +func (t *table) sendEvent(e *router.Event) { t.RLock() defer t.RUnlock() @@ -56,7 +49,7 @@ func (t *table) sendEvent(e *Event) { } // Create creates new route in the routing table -func (t *table) Create(r Route) error { +func (t *table) Create(r router.Route) error { service := r.Service sum := r.Hash() @@ -65,24 +58,24 @@ func (t *table) Create(r Route) error { // check if there are any routes in the table for the route destination if _, ok := t.routes[service]; !ok { - t.routes[service] = make(map[uint64]Route) + t.routes[service] = make(map[uint64]router.Route) } // add new route to the table for the route destination if _, ok := t.routes[service][sum]; !ok { t.routes[service][sum] = r if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Router emitting %s for route: %s", Create, r.Address) + logger.Debugf("Router emitting %s for route: %s", router.Create, r.Address) } - go t.sendEvent(&Event{Type: Create, Timestamp: time.Now(), Route: r}) + go t.sendEvent(&router.Event{Type: router.Create, Timestamp: time.Now(), Route: r}) return nil } - return ErrDuplicateRoute + return router.ErrDuplicateRoute } // Delete deletes the route from the routing table -func (t *table) Delete(r Route) error { +func (t *table) Delete(r router.Route) error { service := r.Service sum := r.Hash() @@ -90,11 +83,11 @@ func (t *table) Delete(r Route) error { defer t.Unlock() if _, ok := t.routes[service]; !ok { - return ErrRouteNotFound + return router.ErrRouteNotFound } if _, ok := t.routes[service][sum]; !ok { - return ErrRouteNotFound + return router.ErrRouteNotFound } delete(t.routes[service], sum) @@ -102,15 +95,15 @@ func (t *table) Delete(r Route) error { delete(t.routes, service) } if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Router emitting %s for route: %s", Delete, r.Address) + logger.Debugf("Router emitting %s for route: %s", router.Delete, r.Address) } - go t.sendEvent(&Event{Type: Delete, Timestamp: time.Now(), Route: r}) + go t.sendEvent(&router.Event{Type: router.Delete, Timestamp: time.Now(), Route: r}) return nil } // Update updates routing table with the new route -func (t *table) Update(r Route) error { +func (t *table) Update(r router.Route) error { service := r.Service sum := r.Hash() @@ -119,15 +112,15 @@ func (t *table) Update(r Route) error { // check if the route destination has any routes in the table if _, ok := t.routes[service]; !ok { - t.routes[service] = make(map[uint64]Route) + t.routes[service] = make(map[uint64]router.Route) } if _, ok := t.routes[service][sum]; !ok { t.routes[service][sum] = r if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Router emitting %s for route: %s", Update, r.Address) + logger.Debugf("Router emitting %s for route: %s", router.Update, r.Address) } - go t.sendEvent(&Event{Type: Update, Timestamp: time.Now(), Route: r}) + go t.sendEvent(&router.Event{Type: router.Update, Timestamp: time.Now(), Route: r}) return nil } @@ -138,11 +131,11 @@ func (t *table) Update(r Route) error { } // List returns a list of all routes in the table -func (t *table) List() ([]Route, error) { +func (t *table) List() ([]router.Route, error) { t.RLock() defer t.RUnlock() - var routes []Route + var routes []router.Route for _, rmap := range t.routes { for _, route := range rmap { routes = append(routes, route) @@ -153,7 +146,7 @@ func (t *table) List() ([]Route, error) { } // isMatch checks if the route matches given query options -func isMatch(route Route, address, gateway, network, router string, strategy Strategy) bool { +func isMatch(route router.Route, address, gateway, network, rtr string, strategy router.Strategy) bool { // matches the values provided match := func(a, b string) bool { if a == "*" || b == "*" || a == b { @@ -171,7 +164,7 @@ func isMatch(route Route, address, gateway, network, router string, strategy Str // by default assume we are querying all routes link := "*" // if AdvertiseLocal change the link query accordingly - if strategy == AdvertiseLocal { + if strategy == router.AdvertiseLocal { link = "local" } @@ -179,7 +172,7 @@ func isMatch(route Route, address, gateway, network, router string, strategy Str values := []compare{ {gateway, route.Gateway}, {network, route.Network}, - {router, route.Router}, + {rtr, route.Router}, {address, route.Address}, {link, route.Link}, } @@ -195,12 +188,12 @@ func isMatch(route Route, address, gateway, network, router string, strategy Str } // findRoutes finds all the routes for given network and router and returns them -func findRoutes(routes map[uint64]Route, address, gateway, network, router string, strategy Strategy) []Route { +func findRoutes(routes map[uint64]router.Route, address, gateway, network, rtr string, strategy router.Strategy) []router.Route { // routeMap stores the routes we're going to advertise - routeMap := make(map[string][]Route) + routeMap := make(map[string][]router.Route) for _, route := range routes { - if isMatch(route, address, gateway, network, router, strategy) { + if isMatch(route, address, gateway, network, rtr, strategy) { // add matchihg route to the routeMap routeKey := route.Service + "@" + route.Network // append the first found route to routeMap @@ -211,13 +204,13 @@ func findRoutes(routes map[uint64]Route, address, gateway, network, router strin } // if AdvertiseAll, keep appending - if strategy == AdvertiseAll || strategy == AdvertiseLocal { + if strategy == router.AdvertiseAll || strategy == router.AdvertiseLocal { routeMap[routeKey] = append(routeMap[routeKey], route) continue } // now we're going to find the best routes - if strategy == AdvertiseBest { + if strategy == router.AdvertiseBest { // if the current optimal route metric is higher than routing table route, replace it if len(routeMap[routeKey]) > 0 { // NOTE: we know that when AdvertiseBest is set, we only ever have one item in current @@ -230,7 +223,7 @@ func findRoutes(routes map[uint64]Route, address, gateway, network, router strin } } - var results []Route + var results []router.Route for _, route := range routeMap { results = append(results, route...) } @@ -239,20 +232,20 @@ func findRoutes(routes map[uint64]Route, address, gateway, network, router strin } // Lookup queries routing table and returns all routes that match the lookup query -func (t *table) Query(q ...QueryOption) ([]Route, error) { +func (t *table) Query(q ...router.QueryOption) ([]router.Route, error) { // create new query options - opts := NewQuery(q...) + opts := router.NewQuery(q...) // create a cwslicelist of query results - results := make([]Route, 0, len(t.routes)) + results := make([]router.Route, 0, len(t.routes)) // if No routes are queried, return early - if opts.Strategy == AdvertiseNone { + if opts.Strategy == router.AdvertiseNone { return results, nil } // readAndFilter routes for this service under read lock. - readAndFilter := func() ([]Route, bool) { + readAndFilter := func() ([]router.Route, bool) { t.RLock() defer t.RUnlock() @@ -280,7 +273,7 @@ func (t *table) Query(q ...QueryOption) ([]Route, error) { return routes, nil } - return nil, ErrRouteNotFound + return nil, router.ErrRouteNotFound } // search through all destinations @@ -294,9 +287,9 @@ func (t *table) Query(q ...QueryOption) ([]Route, error) { } // Watch returns routing table entry watcher -func (t *table) Watch(opts ...WatchOption) (Watcher, error) { +func (t *table) Watch(opts ...router.WatchOption) (router.Watcher, error) { // by default watch everything - wopts := WatchOptions{ + wopts := router.WatchOptions{ Service: "*", } @@ -307,7 +300,7 @@ func (t *table) Watch(opts ...WatchOption) (Watcher, error) { w := &tableWatcher{ id: uuid.New().String(), opts: wopts, - resChan: make(chan *Event, 10), + resChan: make(chan *router.Event, 10), done: make(chan struct{}), } diff --git a/router/table_test.go b/router/registry/table_test.go similarity index 77% rename from router/table_test.go rename to router/registry/table_test.go index cfbc1e3a..5e2590ff 100644 --- a/router/table_test.go +++ b/router/registry/table_test.go @@ -1,15 +1,17 @@ -package router +package registry import ( "fmt" "testing" + + "github.com/micro/go-micro/v3/router" ) -func testSetup() (*table, Route) { - router := newRouter().(*router) - table := router.table +func testSetup() (*table, router.Route) { + routr := NewRouter().(*rtr) + table := newTable(routr.fetchRoutes) - route := Route{ + route := router.Route{ Service: "dest.svc", Address: "dest.addr", Gateway: "dest.gw", @@ -37,8 +39,8 @@ func TestCreate(t *testing.T) { } // adding the same route under Insert policy must error - if err := table.Create(route); err != ErrDuplicateRoute { - t.Errorf("error adding route. Expected error: %s, found: %s", ErrDuplicateRoute, err) + if err := table.Create(route); err != router.ErrDuplicateRoute { + t.Errorf("error adding route. Expected error: %s, found: %s", router.ErrDuplicateRoute, err) } } @@ -53,8 +55,8 @@ func TestDelete(t *testing.T) { prevSvc := route.Service route.Service = "randDest" - if err := table.Delete(route); err != ErrRouteNotFound { - t.Errorf("error deleting route. Expected: %s, found: %s", ErrRouteNotFound, err) + if err := table.Delete(route); err != router.ErrRouteNotFound { + t.Errorf("error deleting route. Expected: %s, found: %s", router.ErrRouteNotFound, err) } // we should be able to delete the existing route @@ -138,7 +140,7 @@ func TestQuery(t *testing.T) { // query routes particular network network := "net1" - routes, err = table.Query(QueryNetwork(network)) + routes, err = table.Query(router.QueryNetwork(network)) if err != nil { t.Errorf("error looking up routes: %s", err) } @@ -156,7 +158,7 @@ func TestQuery(t *testing.T) { // query routes for particular gateway gateway := "gw1" - routes, err = table.Query(QueryGateway(gateway)) + routes, err = table.Query(router.QueryGateway(gateway)) if err != nil { t.Errorf("error looking up routes: %s", err) } @@ -170,9 +172,9 @@ func TestQuery(t *testing.T) { } // query routes for particular router - router := "rtr1" + rt := "rtr1" - routes, err = table.Query(QueryRouter(router)) + routes, err = table.Query(router.QueryRouter(rt)) if err != nil { t.Errorf("error looking up routes: %s", err) } @@ -181,15 +183,15 @@ func TestQuery(t *testing.T) { t.Errorf("incorrect number of routes returned. Expected: %d, found: %d", 1, len(routes)) } - if routes[0].Router != router { - t.Errorf("incorrect route returned. Expected router: %s, found: %s", router, routes[0].Router) + if routes[0].Router != rt { + t.Errorf("incorrect route returned. Expected router: %s, found: %s", rt, routes[0].Router) } // query particular gateway and network - query := []QueryOption{ - QueryGateway(gateway), - QueryNetwork(network), - QueryRouter(router), + query := []router.QueryOption{ + router.QueryGateway(gateway), + router.QueryNetwork(network), + router.QueryRouter(rt), } routes, err = table.Query(query...) @@ -209,14 +211,14 @@ func TestQuery(t *testing.T) { t.Errorf("incorrect network returned. Expected network: %s, found: %s", network, routes[0].Network) } - if routes[0].Router != router { - t.Errorf("incorrect route returned. Expected router: %s, found: %s", router, routes[0].Router) + if routes[0].Router != rt { + t.Errorf("incorrect route returned. Expected router: %s, found: %s", rt, routes[0].Router) } // non-existen route query - routes, err = table.Query(QueryService("foobar")) - if err != ErrRouteNotFound { - t.Errorf("error looking up routes. Expected: %s, found: %s", ErrRouteNotFound, err) + routes, err = table.Query(router.QueryService("foobar")) + if err != router.ErrRouteNotFound { + t.Errorf("error looking up routes. Expected: %s, found: %s", router.ErrRouteNotFound, err) } if len(routes) != 0 { @@ -224,10 +226,10 @@ func TestQuery(t *testing.T) { } // query NO routes - query = []QueryOption{ - QueryGateway(gateway), - QueryNetwork(network), - QueryStrategy(AdvertiseNone), + query = []router.QueryOption{ + router.QueryGateway(gateway), + router.QueryNetwork(network), + router.QueryStrategy(router.AdvertiseNone), } routes, err = table.Query(query...) @@ -249,10 +251,10 @@ func TestQuery(t *testing.T) { } // query local routes - query = []QueryOption{ - QueryGateway("*"), - QueryNetwork("*"), - QueryStrategy(AdvertiseLocal), + query = []router.QueryOption{ + router.QueryGateway("*"), + router.QueryNetwork("*"), + router.QueryStrategy(router.AdvertiseLocal), } routes, err = table.Query(query...) @@ -275,9 +277,9 @@ func TestQuery(t *testing.T) { } // query best routes for svcX - query = []QueryOption{ - QueryService("svcX"), - QueryStrategy(AdvertiseBest), + query = []router.QueryOption{ + router.QueryService("svcX"), + router.QueryStrategy(router.AdvertiseBest), } routes, err = table.Query(query...) @@ -292,15 +294,15 @@ func TestQuery(t *testing.T) { func TestFallback(t *testing.T) { - r := &router{ - subscribers: make(map[string]chan *Advert), - options: DefaultOptions(), + r := &rtr{ + subscribers: make(map[string]chan *router.Advert), + options: router.DefaultOptions(), } - route := Route{ + route := router.Route{ Service: "go.micro.service.foo", Router: r.options.Id, - Link: DefaultLink, - Metric: DefaultLocalMetric, + Link: router.DefaultLink, + Metric: router.DefaultLocalMetric, } r.table = newTable(func(s string) error { r.table.Create(route) @@ -308,7 +310,7 @@ func TestFallback(t *testing.T) { }) r.start() - rts, err := r.Lookup(QueryService("go.micro.service.foo")) + rts, err := r.Lookup(router.QueryService("go.micro.service.foo")) if err != nil { t.Errorf("error looking up service %s", err) } @@ -321,7 +323,7 @@ func TestFallback(t *testing.T) { t.Errorf("error deleting route %s", err) } - rts, err = r.Lookup(QueryService("go.micro.service.foo")) + rts, err = r.Lookup(router.QueryService("go.micro.service.foo")) if err != nil { t.Errorf("error looking up service %s", err) } @@ -332,15 +334,15 @@ func TestFallback(t *testing.T) { } func TestFallbackError(t *testing.T) { - r := &router{ - subscribers: make(map[string]chan *Advert), - options: DefaultOptions(), + r := &rtr{ + subscribers: make(map[string]chan *router.Advert), + options: router.DefaultOptions(), } r.table = newTable(func(s string) error { return fmt.Errorf("ERROR") }) r.start() - _, err := r.Lookup(QueryService("go.micro.service.foo")) + _, err := r.Lookup(router.QueryService("go.micro.service.foo")) if err == nil { t.Errorf("expected error looking up service but none returned") } diff --git a/router/registry/watcher.go b/router/registry/watcher.go new file mode 100644 index 00000000..edc94ea1 --- /dev/null +++ b/router/registry/watcher.go @@ -0,0 +1,52 @@ +package registry + +import ( + "sync" + + "github.com/micro/go-micro/v3/router" +) + +// tableWatcher implements routing table Watcher +type tableWatcher struct { + sync.RWMutex + id string + opts router.WatchOptions + resChan chan *router.Event + done chan struct{} +} + +// Next returns the next noticed action taken on table +// TODO: right now we only allow to watch particular service +func (w *tableWatcher) Next() (*router.Event, error) { + for { + select { + case res := <-w.resChan: + switch w.opts.Service { + case res.Route.Service, "*": + return res, nil + default: + continue + } + case <-w.done: + return nil, router.ErrWatcherStopped + } + } +} + +// Chan returns watcher events channel +func (w *tableWatcher) Chan() (<-chan *router.Event, error) { + return w.resChan, nil +} + +// Stop stops routing table watcher +func (w *tableWatcher) Stop() { + w.Lock() + defer w.Unlock() + + select { + case <-w.done: + return + default: + close(w.done) + } +} diff --git a/router/router.go b/router/router.go index 72ecd3b9..66bf9089 100644 --- a/router/router.go +++ b/router/router.go @@ -2,6 +2,7 @@ package router import ( + "errors" "time" ) @@ -12,8 +13,10 @@ var ( DefaultName = "go.micro.router" // DefaultNetwork is default micro network DefaultNetwork = "micro" - // DefaultRouter is default network router - DefaultRouter = NewRouter() + // ErrRouteNotFound is returned when no route was found in the routing table + ErrRouteNotFound = errors.New("route not found") + // ErrDuplicateRoute is returned when the route already exists + ErrDuplicateRoute = errors.New("duplicate route") ) // Router is an interface for a routing control plane @@ -135,8 +138,3 @@ func (s Strategy) String() string { return "unknown" } } - -// NewRouter creates new Router and returns it -func NewRouter(opts ...Option) Router { - return newRouter(opts...) -} diff --git a/router/service/options.go b/router/service/options.go deleted file mode 100644 index 9f067a4a..00000000 --- a/router/service/options.go +++ /dev/null @@ -1,22 +0,0 @@ -package service - -import ( - "context" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/router" -) - -type clientKey struct{} - -// Client to call router service -func Client(c client.Client) router.Option { - return func(o *router.Options) { - if o.Context == nil { - o.Context = context.WithValue(context.Background(), clientKey{}, c) - return - } - - o.Context = context.WithValue(o.Context, clientKey{}, c) - } -} diff --git a/router/service/proto/router.pb.go b/router/service/proto/router.pb.go deleted file mode 100644 index 44660ecc..00000000 --- a/router/service/proto/router.pb.go +++ /dev/null @@ -1,1345 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: router/service/proto/router.proto - -package router - -import ( - context "context" - fmt "fmt" - proto "github.com/golang/protobuf/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// AdvertType defines the type of advert -type AdvertType int32 - -const ( - AdvertType_AdvertAnnounce AdvertType = 0 - AdvertType_AdvertUpdate AdvertType = 1 -) - -var AdvertType_name = map[int32]string{ - 0: "AdvertAnnounce", - 1: "AdvertUpdate", -} - -var AdvertType_value = map[string]int32{ - "AdvertAnnounce": 0, - "AdvertUpdate": 1, -} - -func (x AdvertType) String() string { - return proto.EnumName(AdvertType_name, int32(x)) -} - -func (AdvertType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{0} -} - -// EventType defines the type of event -type EventType int32 - -const ( - EventType_Create EventType = 0 - EventType_Delete EventType = 1 - EventType_Update EventType = 2 -) - -var EventType_name = map[int32]string{ - 0: "Create", - 1: "Delete", - 2: "Update", -} - -var EventType_value = map[string]int32{ - "Create": 0, - "Delete": 1, - "Update": 2, -} - -func (x EventType) String() string { - return proto.EnumName(EventType_name, int32(x)) -} - -func (EventType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{1} -} - -// Empty request -type Request struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Request) Reset() { *m = Request{} } -func (m *Request) String() string { return proto.CompactTextString(m) } -func (*Request) ProtoMessage() {} -func (*Request) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{0} -} - -func (m *Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Request.Unmarshal(m, b) -} -func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Request.Marshal(b, m, deterministic) -} -func (m *Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_Request.Merge(m, src) -} -func (m *Request) XXX_Size() int { - return xxx_messageInfo_Request.Size(m) -} -func (m *Request) XXX_DiscardUnknown() { - xxx_messageInfo_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_Request proto.InternalMessageInfo - -// Empty response -type Response struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Response) Reset() { *m = Response{} } -func (m *Response) String() string { return proto.CompactTextString(m) } -func (*Response) ProtoMessage() {} -func (*Response) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{1} -} - -func (m *Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Response.Unmarshal(m, b) -} -func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Response.Marshal(b, m, deterministic) -} -func (m *Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_Response.Merge(m, src) -} -func (m *Response) XXX_Size() int { - return xxx_messageInfo_Response.Size(m) -} -func (m *Response) XXX_DiscardUnknown() { - xxx_messageInfo_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_Response proto.InternalMessageInfo - -// ListResponse is returned by List -type ListResponse struct { - Routes []*Route `protobuf:"bytes,1,rep,name=routes,proto3" json:"routes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListResponse) Reset() { *m = ListResponse{} } -func (m *ListResponse) String() string { return proto.CompactTextString(m) } -func (*ListResponse) ProtoMessage() {} -func (*ListResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{2} -} - -func (m *ListResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListResponse.Unmarshal(m, b) -} -func (m *ListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListResponse.Marshal(b, m, deterministic) -} -func (m *ListResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListResponse.Merge(m, src) -} -func (m *ListResponse) XXX_Size() int { - return xxx_messageInfo_ListResponse.Size(m) -} -func (m *ListResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListResponse proto.InternalMessageInfo - -func (m *ListResponse) GetRoutes() []*Route { - if m != nil { - return m.Routes - } - return nil -} - -// LookupRequest is made to Lookup -type LookupRequest struct { - Query *Query `protobuf:"bytes,1,opt,name=query,proto3" json:"query,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LookupRequest) Reset() { *m = LookupRequest{} } -func (m *LookupRequest) String() string { return proto.CompactTextString(m) } -func (*LookupRequest) ProtoMessage() {} -func (*LookupRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{3} -} - -func (m *LookupRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LookupRequest.Unmarshal(m, b) -} -func (m *LookupRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LookupRequest.Marshal(b, m, deterministic) -} -func (m *LookupRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_LookupRequest.Merge(m, src) -} -func (m *LookupRequest) XXX_Size() int { - return xxx_messageInfo_LookupRequest.Size(m) -} -func (m *LookupRequest) XXX_DiscardUnknown() { - xxx_messageInfo_LookupRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_LookupRequest proto.InternalMessageInfo - -func (m *LookupRequest) GetQuery() *Query { - if m != nil { - return m.Query - } - return nil -} - -// LookupResponse is returned by Lookup -type LookupResponse struct { - Routes []*Route `protobuf:"bytes,1,rep,name=routes,proto3" json:"routes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LookupResponse) Reset() { *m = LookupResponse{} } -func (m *LookupResponse) String() string { return proto.CompactTextString(m) } -func (*LookupResponse) ProtoMessage() {} -func (*LookupResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{4} -} - -func (m *LookupResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LookupResponse.Unmarshal(m, b) -} -func (m *LookupResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LookupResponse.Marshal(b, m, deterministic) -} -func (m *LookupResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_LookupResponse.Merge(m, src) -} -func (m *LookupResponse) XXX_Size() int { - return xxx_messageInfo_LookupResponse.Size(m) -} -func (m *LookupResponse) XXX_DiscardUnknown() { - xxx_messageInfo_LookupResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_LookupResponse proto.InternalMessageInfo - -func (m *LookupResponse) GetRoutes() []*Route { - if m != nil { - return m.Routes - } - return nil -} - -// QueryRequest queries Table for Routes -type QueryRequest struct { - Query *Query `protobuf:"bytes,1,opt,name=query,proto3" json:"query,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{5} -} - -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_QueryRequest.Unmarshal(m, b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return xxx_messageInfo_QueryRequest.Size(m) -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -func (m *QueryRequest) GetQuery() *Query { - if m != nil { - return m.Query - } - return nil -} - -// QueryResponse is returned by Query -type QueryResponse struct { - Routes []*Route `protobuf:"bytes,1,rep,name=routes,proto3" json:"routes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{6} -} - -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_QueryResponse.Unmarshal(m, b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return xxx_messageInfo_QueryResponse.Size(m) -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func (m *QueryResponse) GetRoutes() []*Route { - if m != nil { - return m.Routes - } - return nil -} - -// WatchRequest is made to Watch Router -type WatchRequest struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *WatchRequest) Reset() { *m = WatchRequest{} } -func (m *WatchRequest) String() string { return proto.CompactTextString(m) } -func (*WatchRequest) ProtoMessage() {} -func (*WatchRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{7} -} - -func (m *WatchRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_WatchRequest.Unmarshal(m, b) -} -func (m *WatchRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_WatchRequest.Marshal(b, m, deterministic) -} -func (m *WatchRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_WatchRequest.Merge(m, src) -} -func (m *WatchRequest) XXX_Size() int { - return xxx_messageInfo_WatchRequest.Size(m) -} -func (m *WatchRequest) XXX_DiscardUnknown() { - xxx_messageInfo_WatchRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_WatchRequest proto.InternalMessageInfo - -// Advert is router advertsement streamed by Watch -type Advert struct { - // id of the advertising router - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // type of advertisement - Type AdvertType `protobuf:"varint,2,opt,name=type,proto3,enum=go.micro.router.AdvertType" json:"type,omitempty"` - // unix timestamp of the advertisement - Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - // TTL of the Advert - Ttl int64 `protobuf:"varint,4,opt,name=ttl,proto3" json:"ttl,omitempty"` - // events is a list of advertised events - Events []*Event `protobuf:"bytes,5,rep,name=events,proto3" json:"events,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Advert) Reset() { *m = Advert{} } -func (m *Advert) String() string { return proto.CompactTextString(m) } -func (*Advert) ProtoMessage() {} -func (*Advert) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{8} -} - -func (m *Advert) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Advert.Unmarshal(m, b) -} -func (m *Advert) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Advert.Marshal(b, m, deterministic) -} -func (m *Advert) XXX_Merge(src proto.Message) { - xxx_messageInfo_Advert.Merge(m, src) -} -func (m *Advert) XXX_Size() int { - return xxx_messageInfo_Advert.Size(m) -} -func (m *Advert) XXX_DiscardUnknown() { - xxx_messageInfo_Advert.DiscardUnknown(m) -} - -var xxx_messageInfo_Advert proto.InternalMessageInfo - -func (m *Advert) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *Advert) GetType() AdvertType { - if m != nil { - return m.Type - } - return AdvertType_AdvertAnnounce -} - -func (m *Advert) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -func (m *Advert) GetTtl() int64 { - if m != nil { - return m.Ttl - } - return 0 -} - -func (m *Advert) GetEvents() []*Event { - if m != nil { - return m.Events - } - return nil -} - -// ProcessResponse is returned by Process -type ProcessResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProcessResponse) Reset() { *m = ProcessResponse{} } -func (m *ProcessResponse) String() string { return proto.CompactTextString(m) } -func (*ProcessResponse) ProtoMessage() {} -func (*ProcessResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{9} -} - -func (m *ProcessResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProcessResponse.Unmarshal(m, b) -} -func (m *ProcessResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProcessResponse.Marshal(b, m, deterministic) -} -func (m *ProcessResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProcessResponse.Merge(m, src) -} -func (m *ProcessResponse) XXX_Size() int { - return xxx_messageInfo_ProcessResponse.Size(m) -} -func (m *ProcessResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ProcessResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ProcessResponse proto.InternalMessageInfo - -// CreateResponse is returned by Create -type CreateResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateResponse) Reset() { *m = CreateResponse{} } -func (m *CreateResponse) String() string { return proto.CompactTextString(m) } -func (*CreateResponse) ProtoMessage() {} -func (*CreateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{10} -} - -func (m *CreateResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateResponse.Unmarshal(m, b) -} -func (m *CreateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateResponse.Marshal(b, m, deterministic) -} -func (m *CreateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateResponse.Merge(m, src) -} -func (m *CreateResponse) XXX_Size() int { - return xxx_messageInfo_CreateResponse.Size(m) -} -func (m *CreateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CreateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateResponse proto.InternalMessageInfo - -// DeleteResponse is returned by Delete -type DeleteResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteResponse) Reset() { *m = DeleteResponse{} } -func (m *DeleteResponse) String() string { return proto.CompactTextString(m) } -func (*DeleteResponse) ProtoMessage() {} -func (*DeleteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{11} -} - -func (m *DeleteResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteResponse.Unmarshal(m, b) -} -func (m *DeleteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteResponse.Marshal(b, m, deterministic) -} -func (m *DeleteResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteResponse.Merge(m, src) -} -func (m *DeleteResponse) XXX_Size() int { - return xxx_messageInfo_DeleteResponse.Size(m) -} -func (m *DeleteResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteResponse proto.InternalMessageInfo - -// UpdateResponse is returned by Update -type UpdateResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpdateResponse) Reset() { *m = UpdateResponse{} } -func (m *UpdateResponse) String() string { return proto.CompactTextString(m) } -func (*UpdateResponse) ProtoMessage() {} -func (*UpdateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{12} -} - -func (m *UpdateResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpdateResponse.Unmarshal(m, b) -} -func (m *UpdateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpdateResponse.Marshal(b, m, deterministic) -} -func (m *UpdateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateResponse.Merge(m, src) -} -func (m *UpdateResponse) XXX_Size() int { - return xxx_messageInfo_UpdateResponse.Size(m) -} -func (m *UpdateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateResponse proto.InternalMessageInfo - -// Event is routing table event -type Event struct { - // the unique event id - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // type of event - Type EventType `protobuf:"varint,2,opt,name=type,proto3,enum=go.micro.router.EventType" json:"type,omitempty"` - // unix timestamp of event - Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - // service route - Route *Route `protobuf:"bytes,4,opt,name=route,proto3" json:"route,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Event) Reset() { *m = Event{} } -func (m *Event) String() string { return proto.CompactTextString(m) } -func (*Event) ProtoMessage() {} -func (*Event) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{13} -} - -func (m *Event) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Event.Unmarshal(m, b) -} -func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Event.Marshal(b, m, deterministic) -} -func (m *Event) XXX_Merge(src proto.Message) { - xxx_messageInfo_Event.Merge(m, src) -} -func (m *Event) XXX_Size() int { - return xxx_messageInfo_Event.Size(m) -} -func (m *Event) XXX_DiscardUnknown() { - xxx_messageInfo_Event.DiscardUnknown(m) -} - -var xxx_messageInfo_Event proto.InternalMessageInfo - -func (m *Event) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *Event) GetType() EventType { - if m != nil { - return m.Type - } - return EventType_Create -} - -func (m *Event) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -func (m *Event) GetRoute() *Route { - if m != nil { - return m.Route - } - return nil -} - -// Query is passed in a LookupRequest -type Query struct { - // service to lookup - Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - // gateway to lookup - Gateway string `protobuf:"bytes,2,opt,name=gateway,proto3" json:"gateway,omitempty"` - // network to lookup - Network string `protobuf:"bytes,3,opt,name=network,proto3" json:"network,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Query) Reset() { *m = Query{} } -func (m *Query) String() string { return proto.CompactTextString(m) } -func (*Query) ProtoMessage() {} -func (*Query) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{14} -} - -func (m *Query) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Query.Unmarshal(m, b) -} -func (m *Query) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Query.Marshal(b, m, deterministic) -} -func (m *Query) XXX_Merge(src proto.Message) { - xxx_messageInfo_Query.Merge(m, src) -} -func (m *Query) XXX_Size() int { - return xxx_messageInfo_Query.Size(m) -} -func (m *Query) XXX_DiscardUnknown() { - xxx_messageInfo_Query.DiscardUnknown(m) -} - -var xxx_messageInfo_Query proto.InternalMessageInfo - -func (m *Query) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -func (m *Query) GetGateway() string { - if m != nil { - return m.Gateway - } - return "" -} - -func (m *Query) GetNetwork() string { - if m != nil { - return m.Network - } - return "" -} - -// Route is a service route -type Route struct { - // service for the route - Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - // the address that advertise this route - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - // gateway as the next hop - Gateway string `protobuf:"bytes,3,opt,name=gateway,proto3" json:"gateway,omitempty"` - // the network for this destination - Network string `protobuf:"bytes,4,opt,name=network,proto3" json:"network,omitempty"` - // router if the router id - Router string `protobuf:"bytes,5,opt,name=router,proto3" json:"router,omitempty"` - // the network link - Link string `protobuf:"bytes,6,opt,name=link,proto3" json:"link,omitempty"` - // the metric / score of this route - Metric int64 `protobuf:"varint,7,opt,name=metric,proto3" json:"metric,omitempty"` - // metadata for the route - Metadata map[string]string `protobuf:"bytes,8,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Route) Reset() { *m = Route{} } -func (m *Route) String() string { return proto.CompactTextString(m) } -func (*Route) ProtoMessage() {} -func (*Route) Descriptor() ([]byte, []int) { - return fileDescriptor_3123ad01af3cc940, []int{15} -} - -func (m *Route) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Route.Unmarshal(m, b) -} -func (m *Route) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Route.Marshal(b, m, deterministic) -} -func (m *Route) XXX_Merge(src proto.Message) { - xxx_messageInfo_Route.Merge(m, src) -} -func (m *Route) XXX_Size() int { - return xxx_messageInfo_Route.Size(m) -} -func (m *Route) XXX_DiscardUnknown() { - xxx_messageInfo_Route.DiscardUnknown(m) -} - -var xxx_messageInfo_Route proto.InternalMessageInfo - -func (m *Route) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -func (m *Route) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *Route) GetGateway() string { - if m != nil { - return m.Gateway - } - return "" -} - -func (m *Route) GetNetwork() string { - if m != nil { - return m.Network - } - return "" -} - -func (m *Route) GetRouter() string { - if m != nil { - return m.Router - } - return "" -} - -func (m *Route) GetLink() string { - if m != nil { - return m.Link - } - return "" -} - -func (m *Route) GetMetric() int64 { - if m != nil { - return m.Metric - } - return 0 -} - -func (m *Route) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func init() { - proto.RegisterEnum("go.micro.router.AdvertType", AdvertType_name, AdvertType_value) - proto.RegisterEnum("go.micro.router.EventType", EventType_name, EventType_value) - proto.RegisterType((*Request)(nil), "go.micro.router.Request") - proto.RegisterType((*Response)(nil), "go.micro.router.Response") - proto.RegisterType((*ListResponse)(nil), "go.micro.router.ListResponse") - proto.RegisterType((*LookupRequest)(nil), "go.micro.router.LookupRequest") - proto.RegisterType((*LookupResponse)(nil), "go.micro.router.LookupResponse") - proto.RegisterType((*QueryRequest)(nil), "go.micro.router.QueryRequest") - proto.RegisterType((*QueryResponse)(nil), "go.micro.router.QueryResponse") - proto.RegisterType((*WatchRequest)(nil), "go.micro.router.WatchRequest") - proto.RegisterType((*Advert)(nil), "go.micro.router.Advert") - proto.RegisterType((*ProcessResponse)(nil), "go.micro.router.ProcessResponse") - proto.RegisterType((*CreateResponse)(nil), "go.micro.router.CreateResponse") - proto.RegisterType((*DeleteResponse)(nil), "go.micro.router.DeleteResponse") - proto.RegisterType((*UpdateResponse)(nil), "go.micro.router.UpdateResponse") - proto.RegisterType((*Event)(nil), "go.micro.router.Event") - proto.RegisterType((*Query)(nil), "go.micro.router.Query") - proto.RegisterType((*Route)(nil), "go.micro.router.Route") - proto.RegisterMapType((map[string]string)(nil), "go.micro.router.Route.MetadataEntry") -} - -func init() { proto.RegisterFile("router/service/proto/router.proto", fileDescriptor_3123ad01af3cc940) } - -var fileDescriptor_3123ad01af3cc940 = []byte{ - // 728 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0xcb, 0x4e, 0xdb, 0x5c, - 0x10, 0xb6, 0x9d, 0x38, 0x21, 0xf3, 0x87, 0x90, 0xff, 0xe8, 0x17, 0xbf, 0x95, 0x16, 0x9a, 0x5a, - 0x5d, 0x20, 0x44, 0xed, 0x2a, 0xdd, 0x20, 0xe8, 0x85, 0x4b, 0xa9, 0x2a, 0x95, 0x4a, 0xad, 0x05, - 0xaa, 0xd4, 0x9d, 0x89, 0x47, 0xc1, 0x4a, 0x62, 0x9b, 0xe3, 0xe3, 0xa0, 0x3c, 0x47, 0x9f, 0xa1, - 0x8b, 0x6e, 0xfb, 0x4a, 0x7d, 0x91, 0xea, 0x5c, 0x0c, 0x49, 0x1c, 0xa3, 0xc2, 0xca, 0x73, 0xfd, - 0xe6, 0x72, 0x66, 0xc6, 0xf0, 0x94, 0xc6, 0x19, 0x43, 0xea, 0xa6, 0x48, 0x27, 0x61, 0x1f, 0xdd, - 0x84, 0xc6, 0x2c, 0x76, 0xa5, 0xd0, 0x11, 0x0c, 0x59, 0x1b, 0xc4, 0xce, 0x38, 0xec, 0xd3, 0xd8, - 0x91, 0x62, 0xbb, 0x01, 0x75, 0x0f, 0xaf, 0x32, 0x4c, 0x99, 0x0d, 0xb0, 0xe2, 0x61, 0x9a, 0xc4, - 0x51, 0x8a, 0xf6, 0x1b, 0x68, 0x9e, 0x86, 0x29, 0xcb, 0x79, 0xe2, 0x40, 0x4d, 0x38, 0xa4, 0x96, - 0xde, 0xad, 0x6c, 0xfd, 0xd3, 0x5b, 0x77, 0x16, 0x80, 0x1c, 0x8f, 0x7f, 0x3c, 0x65, 0x65, 0xbf, - 0x86, 0xd5, 0xd3, 0x38, 0x1e, 0x66, 0x89, 0x02, 0x27, 0x3b, 0x60, 0x5e, 0x65, 0x48, 0xa7, 0x96, - 0xde, 0xd5, 0x97, 0xfa, 0x7f, 0xe1, 0x5a, 0x4f, 0x1a, 0xd9, 0x07, 0xd0, 0xca, 0xdd, 0x1f, 0x98, - 0xc0, 0x2b, 0x68, 0x4a, 0xc4, 0x07, 0xc5, 0x7f, 0x0b, 0xab, 0xca, 0xfb, 0x81, 0xe1, 0x5b, 0xd0, - 0xfc, 0xea, 0xb3, 0xfe, 0x65, 0xde, 0xdb, 0x9f, 0x3a, 0xd4, 0x0e, 0x83, 0x09, 0x52, 0x46, 0x5a, - 0x60, 0x84, 0x81, 0x48, 0xa3, 0xe1, 0x19, 0x61, 0x40, 0x5c, 0xa8, 0xb2, 0x69, 0x82, 0x96, 0xd1, - 0xd5, 0xb7, 0x5a, 0xbd, 0x47, 0x05, 0x60, 0xe9, 0x76, 0x36, 0x4d, 0xd0, 0x13, 0x86, 0xe4, 0x31, - 0x34, 0x58, 0x38, 0xc6, 0x94, 0xf9, 0xe3, 0xc4, 0xaa, 0x74, 0xf5, 0xad, 0x8a, 0x77, 0x2b, 0x20, - 0x6d, 0xa8, 0x30, 0x36, 0xb2, 0xaa, 0x42, 0xce, 0x49, 0x9e, 0x3b, 0x4e, 0x30, 0x62, 0xa9, 0x65, - 0x96, 0xe4, 0x7e, 0xc2, 0xd5, 0x9e, 0xb2, 0xb2, 0xff, 0x85, 0xb5, 0xcf, 0x34, 0xee, 0x63, 0x9a, - 0xde, 0x8c, 0x43, 0x1b, 0x5a, 0xc7, 0x14, 0x7d, 0x86, 0xb3, 0x92, 0x77, 0x38, 0xc2, 0x79, 0xc9, - 0x79, 0x12, 0xcc, 0xda, 0x7c, 0xd7, 0xc1, 0x14, 0xd0, 0x85, 0x9a, 0x9d, 0xb9, 0x9a, 0x3b, 0xcb, - 0x13, 0xfa, 0xeb, 0x92, 0x77, 0xc0, 0x14, 0x7e, 0xa2, 0xe8, 0xf2, 0xb7, 0x91, 0x46, 0xf6, 0x39, - 0x98, 0xe2, 0x6d, 0x89, 0x05, 0x75, 0xb5, 0x29, 0x2a, 0xb3, 0x9c, 0xe5, 0x9a, 0x81, 0xcf, 0xf0, - 0xda, 0x9f, 0x8a, 0x0c, 0x1b, 0x5e, 0xce, 0x72, 0x4d, 0x84, 0xec, 0x3a, 0xa6, 0x43, 0x91, 0x46, - 0xc3, 0xcb, 0x59, 0xfb, 0x97, 0x01, 0xa6, 0x88, 0x73, 0x37, 0xae, 0x1f, 0x04, 0x14, 0xd3, 0x34, - 0xc7, 0x55, 0xec, 0x6c, 0xc4, 0x4a, 0x69, 0xc4, 0xea, 0x5c, 0x44, 0xb2, 0xae, 0x66, 0x92, 0x5a, - 0xa6, 0x50, 0x28, 0x8e, 0x10, 0xa8, 0x8e, 0xc2, 0x68, 0x68, 0xd5, 0x84, 0x54, 0xd0, 0xdc, 0x76, - 0x8c, 0x8c, 0x86, 0x7d, 0xab, 0x2e, 0xba, 0xa7, 0x38, 0x72, 0x00, 0x2b, 0x63, 0x64, 0x7e, 0xe0, - 0x33, 0xdf, 0x5a, 0x11, 0xd3, 0xf1, 0x6c, 0x79, 0xf7, 0x9c, 0x4f, 0xca, 0xec, 0x24, 0x62, 0x74, - 0xea, 0xdd, 0x78, 0x75, 0xf6, 0x61, 0x75, 0x4e, 0xc5, 0x07, 0x70, 0x88, 0x53, 0x55, 0x3a, 0x27, - 0xc9, 0x7f, 0x60, 0x4e, 0xfc, 0x51, 0x86, 0xaa, 0x68, 0xc9, 0xec, 0x19, 0xbb, 0xfa, 0x76, 0x0f, - 0xe0, 0x76, 0xbc, 0x09, 0x81, 0x96, 0xe4, 0x0e, 0xa3, 0x28, 0xce, 0xa2, 0x3e, 0xb6, 0x35, 0xd2, - 0x86, 0xa6, 0x94, 0xc9, 0xd9, 0x6a, 0xeb, 0xdb, 0x2e, 0x34, 0x6e, 0xc6, 0x83, 0x00, 0xd4, 0xe4, - 0x60, 0xb6, 0x35, 0x4e, 0xcb, 0x91, 0x6c, 0xeb, 0x9c, 0x56, 0x0e, 0x46, 0xef, 0x87, 0x01, 0x35, - 0x4f, 0xb6, 0xe6, 0x23, 0xd4, 0xe4, 0x5d, 0x21, 0x9b, 0x85, 0x32, 0xe7, 0xee, 0x55, 0xe7, 0x49, - 0xa9, 0x5e, 0x0d, 0xb7, 0x46, 0x8e, 0xc0, 0x14, 0x3b, 0x4e, 0x36, 0x0a, 0xb6, 0xb3, 0xbb, 0xdf, - 0x29, 0xd9, 0x37, 0x5b, 0x7b, 0xa1, 0x93, 0x23, 0x68, 0xc8, 0xf2, 0xc2, 0x14, 0x89, 0x55, 0x6c, - 0xbd, 0x82, 0xf8, 0xbf, 0xe4, 0x2a, 0x08, 0x8c, 0xf7, 0x50, 0x57, 0xfb, 0x4a, 0xca, 0xec, 0x3a, - 0xdd, 0x82, 0x62, 0x71, 0xc5, 0xb5, 0xde, 0x6f, 0x03, 0xcc, 0x33, 0xff, 0x62, 0x84, 0xe4, 0x38, - 0xef, 0x2a, 0x29, 0xd9, 0xa5, 0x25, 0xed, 0x59, 0xb8, 0x0f, 0x1a, 0x07, 0x91, 0xcf, 0x71, 0x0f, - 0x90, 0x85, 0x93, 0x22, 0x40, 0xe4, 0x3b, 0xde, 0x03, 0x64, 0xe1, 0x0a, 0x69, 0xe4, 0x10, 0xaa, - 0xfc, 0x67, 0x76, 0x47, 0x7f, 0x8b, 0x2f, 0x38, 0xfb, 0xf7, 0xb3, 0x35, 0xf2, 0x21, 0x3f, 0x1a, - 0x1b, 0x25, 0x3f, 0x0e, 0x05, 0xb4, 0x59, 0xa6, 0xce, 0x91, 0x8e, 0xf6, 0xbe, 0xed, 0x0e, 0x42, - 0x76, 0x99, 0x5d, 0x38, 0xfd, 0x78, 0xec, 0x0a, 0x53, 0x77, 0x10, 0x3f, 0x97, 0xc4, 0xa4, 0xe7, - 0x2e, 0xfb, 0x87, 0xef, 0x4b, 0xe1, 0x45, 0x4d, 0x70, 0x2f, 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, - 0xce, 0x3b, 0xf2, 0x50, 0xe9, 0x07, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// RouterClient is the client API for Router service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type RouterClient interface { - Lookup(ctx context.Context, in *LookupRequest, opts ...grpc.CallOption) (*LookupResponse, error) - Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (Router_WatchClient, error) - Advertise(ctx context.Context, in *Request, opts ...grpc.CallOption) (Router_AdvertiseClient, error) - Process(ctx context.Context, in *Advert, opts ...grpc.CallOption) (*ProcessResponse, error) -} - -type routerClient struct { - cc *grpc.ClientConn -} - -func NewRouterClient(cc *grpc.ClientConn) RouterClient { - return &routerClient{cc} -} - -func (c *routerClient) Lookup(ctx context.Context, in *LookupRequest, opts ...grpc.CallOption) (*LookupResponse, error) { - out := new(LookupResponse) - err := c.cc.Invoke(ctx, "/go.micro.router.Router/Lookup", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *routerClient) Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (Router_WatchClient, error) { - stream, err := c.cc.NewStream(ctx, &_Router_serviceDesc.Streams[0], "/go.micro.router.Router/Watch", opts...) - if err != nil { - return nil, err - } - x := &routerWatchClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Router_WatchClient interface { - Recv() (*Event, error) - grpc.ClientStream -} - -type routerWatchClient struct { - grpc.ClientStream -} - -func (x *routerWatchClient) Recv() (*Event, error) { - m := new(Event) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *routerClient) Advertise(ctx context.Context, in *Request, opts ...grpc.CallOption) (Router_AdvertiseClient, error) { - stream, err := c.cc.NewStream(ctx, &_Router_serviceDesc.Streams[1], "/go.micro.router.Router/Advertise", opts...) - if err != nil { - return nil, err - } - x := &routerAdvertiseClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Router_AdvertiseClient interface { - Recv() (*Advert, error) - grpc.ClientStream -} - -type routerAdvertiseClient struct { - grpc.ClientStream -} - -func (x *routerAdvertiseClient) Recv() (*Advert, error) { - m := new(Advert) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *routerClient) Process(ctx context.Context, in *Advert, opts ...grpc.CallOption) (*ProcessResponse, error) { - out := new(ProcessResponse) - err := c.cc.Invoke(ctx, "/go.micro.router.Router/Process", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// RouterServer is the server API for Router service. -type RouterServer interface { - Lookup(context.Context, *LookupRequest) (*LookupResponse, error) - Watch(*WatchRequest, Router_WatchServer) error - Advertise(*Request, Router_AdvertiseServer) error - Process(context.Context, *Advert) (*ProcessResponse, error) -} - -// UnimplementedRouterServer can be embedded to have forward compatible implementations. -type UnimplementedRouterServer struct { -} - -func (*UnimplementedRouterServer) Lookup(ctx context.Context, req *LookupRequest) (*LookupResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Lookup not implemented") -} -func (*UnimplementedRouterServer) Watch(req *WatchRequest, srv Router_WatchServer) error { - return status.Errorf(codes.Unimplemented, "method Watch not implemented") -} -func (*UnimplementedRouterServer) Advertise(req *Request, srv Router_AdvertiseServer) error { - return status.Errorf(codes.Unimplemented, "method Advertise not implemented") -} -func (*UnimplementedRouterServer) Process(ctx context.Context, req *Advert) (*ProcessResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Process not implemented") -} - -func RegisterRouterServer(s *grpc.Server, srv RouterServer) { - s.RegisterService(&_Router_serviceDesc, srv) -} - -func _Router_Lookup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(LookupRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RouterServer).Lookup(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.router.Router/Lookup", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RouterServer).Lookup(ctx, req.(*LookupRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Router_Watch_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(WatchRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(RouterServer).Watch(m, &routerWatchServer{stream}) -} - -type Router_WatchServer interface { - Send(*Event) error - grpc.ServerStream -} - -type routerWatchServer struct { - grpc.ServerStream -} - -func (x *routerWatchServer) Send(m *Event) error { - return x.ServerStream.SendMsg(m) -} - -func _Router_Advertise_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(Request) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(RouterServer).Advertise(m, &routerAdvertiseServer{stream}) -} - -type Router_AdvertiseServer interface { - Send(*Advert) error - grpc.ServerStream -} - -type routerAdvertiseServer struct { - grpc.ServerStream -} - -func (x *routerAdvertiseServer) Send(m *Advert) error { - return x.ServerStream.SendMsg(m) -} - -func _Router_Process_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Advert) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RouterServer).Process(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.router.Router/Process", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RouterServer).Process(ctx, req.(*Advert)) - } - return interceptor(ctx, in, info, handler) -} - -var _Router_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.router.Router", - HandlerType: (*RouterServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Lookup", - Handler: _Router_Lookup_Handler, - }, - { - MethodName: "Process", - Handler: _Router_Process_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Watch", - Handler: _Router_Watch_Handler, - ServerStreams: true, - }, - { - StreamName: "Advertise", - Handler: _Router_Advertise_Handler, - ServerStreams: true, - }, - }, - Metadata: "router/service/proto/router.proto", -} - -// TableClient is the client API for Table service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type TableClient interface { - Create(ctx context.Context, in *Route, opts ...grpc.CallOption) (*CreateResponse, error) - Delete(ctx context.Context, in *Route, opts ...grpc.CallOption) (*DeleteResponse, error) - Update(ctx context.Context, in *Route, opts ...grpc.CallOption) (*UpdateResponse, error) - List(ctx context.Context, in *Request, opts ...grpc.CallOption) (*ListResponse, error) - Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type tableClient struct { - cc *grpc.ClientConn -} - -func NewTableClient(cc *grpc.ClientConn) TableClient { - return &tableClient{cc} -} - -func (c *tableClient) Create(ctx context.Context, in *Route, opts ...grpc.CallOption) (*CreateResponse, error) { - out := new(CreateResponse) - err := c.cc.Invoke(ctx, "/go.micro.router.Table/Create", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *tableClient) Delete(ctx context.Context, in *Route, opts ...grpc.CallOption) (*DeleteResponse, error) { - out := new(DeleteResponse) - err := c.cc.Invoke(ctx, "/go.micro.router.Table/Delete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *tableClient) Update(ctx context.Context, in *Route, opts ...grpc.CallOption) (*UpdateResponse, error) { - out := new(UpdateResponse) - err := c.cc.Invoke(ctx, "/go.micro.router.Table/Update", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *tableClient) List(ctx context.Context, in *Request, opts ...grpc.CallOption) (*ListResponse, error) { - out := new(ListResponse) - err := c.cc.Invoke(ctx, "/go.micro.router.Table/List", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *tableClient) Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/go.micro.router.Table/Query", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// TableServer is the server API for Table service. -type TableServer interface { - Create(context.Context, *Route) (*CreateResponse, error) - Delete(context.Context, *Route) (*DeleteResponse, error) - Update(context.Context, *Route) (*UpdateResponse, error) - List(context.Context, *Request) (*ListResponse, error) - Query(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedTableServer can be embedded to have forward compatible implementations. -type UnimplementedTableServer struct { -} - -func (*UnimplementedTableServer) Create(ctx context.Context, req *Route) (*CreateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Create not implemented") -} -func (*UnimplementedTableServer) Delete(ctx context.Context, req *Route) (*DeleteResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") -} -func (*UnimplementedTableServer) Update(ctx context.Context, req *Route) (*UpdateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Update not implemented") -} -func (*UnimplementedTableServer) List(ctx context.Context, req *Request) (*ListResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method List not implemented") -} -func (*UnimplementedTableServer) Query(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Query not implemented") -} - -func RegisterTableServer(s *grpc.Server, srv TableServer) { - s.RegisterService(&_Table_serviceDesc, srv) -} - -func _Table_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Route) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TableServer).Create(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.router.Table/Create", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TableServer).Create(ctx, req.(*Route)) - } - return interceptor(ctx, in, info, handler) -} - -func _Table_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Route) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TableServer).Delete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.router.Table/Delete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TableServer).Delete(ctx, req.(*Route)) - } - return interceptor(ctx, in, info, handler) -} - -func _Table_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Route) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TableServer).Update(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.router.Table/Update", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TableServer).Update(ctx, req.(*Route)) - } - return interceptor(ctx, in, info, handler) -} - -func _Table_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TableServer).List(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.router.Table/List", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TableServer).List(ctx, req.(*Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Table_Query_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TableServer).Query(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.router.Table/Query", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TableServer).Query(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Table_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.router.Table", - HandlerType: (*TableServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Create", - Handler: _Table_Create_Handler, - }, - { - MethodName: "Delete", - Handler: _Table_Delete_Handler, - }, - { - MethodName: "Update", - Handler: _Table_Update_Handler, - }, - { - MethodName: "List", - Handler: _Table_List_Handler, - }, - { - MethodName: "Query", - Handler: _Table_Query_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "router/service/proto/router.proto", -} diff --git a/router/service/proto/router.pb.micro.go b/router/service/proto/router.pb.micro.go deleted file mode 100644 index b39fff3a..00000000 --- a/router/service/proto/router.pb.micro.go +++ /dev/null @@ -1,421 +0,0 @@ -// Code generated by protoc-gen-micro. DO NOT EDIT. -// source: router/service/proto/router.proto - -package router - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -import ( - context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ api.Endpoint -var _ context.Context -var _ client.Option -var _ server.Option - -// Api Endpoints for Router service - -func NewRouterEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Router service - -type RouterService interface { - Lookup(ctx context.Context, in *LookupRequest, opts ...client.CallOption) (*LookupResponse, error) - Watch(ctx context.Context, in *WatchRequest, opts ...client.CallOption) (Router_WatchService, error) - Advertise(ctx context.Context, in *Request, opts ...client.CallOption) (Router_AdvertiseService, error) - Process(ctx context.Context, in *Advert, opts ...client.CallOption) (*ProcessResponse, error) -} - -type routerService struct { - c client.Client - name string -} - -func NewRouterService(name string, c client.Client) RouterService { - return &routerService{ - c: c, - name: name, - } -} - -func (c *routerService) Lookup(ctx context.Context, in *LookupRequest, opts ...client.CallOption) (*LookupResponse, error) { - req := c.c.NewRequest(c.name, "Router.Lookup", in) - out := new(LookupResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *routerService) Watch(ctx context.Context, in *WatchRequest, opts ...client.CallOption) (Router_WatchService, error) { - req := c.c.NewRequest(c.name, "Router.Watch", &WatchRequest{}) - stream, err := c.c.Stream(ctx, req, opts...) - if err != nil { - return nil, err - } - if err := stream.Send(in); err != nil { - return nil, err - } - return &routerServiceWatch{stream}, nil -} - -type Router_WatchService interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Recv() (*Event, error) -} - -type routerServiceWatch struct { - stream client.Stream -} - -func (x *routerServiceWatch) Close() error { - return x.stream.Close() -} - -func (x *routerServiceWatch) Context() context.Context { - return x.stream.Context() -} - -func (x *routerServiceWatch) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *routerServiceWatch) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *routerServiceWatch) Recv() (*Event, error) { - m := new(Event) - err := x.stream.Recv(m) - if err != nil { - return nil, err - } - return m, nil -} - -func (c *routerService) Advertise(ctx context.Context, in *Request, opts ...client.CallOption) (Router_AdvertiseService, error) { - req := c.c.NewRequest(c.name, "Router.Advertise", &Request{}) - stream, err := c.c.Stream(ctx, req, opts...) - if err != nil { - return nil, err - } - if err := stream.Send(in); err != nil { - return nil, err - } - return &routerServiceAdvertise{stream}, nil -} - -type Router_AdvertiseService interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Recv() (*Advert, error) -} - -type routerServiceAdvertise struct { - stream client.Stream -} - -func (x *routerServiceAdvertise) Close() error { - return x.stream.Close() -} - -func (x *routerServiceAdvertise) Context() context.Context { - return x.stream.Context() -} - -func (x *routerServiceAdvertise) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *routerServiceAdvertise) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *routerServiceAdvertise) Recv() (*Advert, error) { - m := new(Advert) - err := x.stream.Recv(m) - if err != nil { - return nil, err - } - return m, nil -} - -func (c *routerService) Process(ctx context.Context, in *Advert, opts ...client.CallOption) (*ProcessResponse, error) { - req := c.c.NewRequest(c.name, "Router.Process", in) - out := new(ProcessResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Router service - -type RouterHandler interface { - Lookup(context.Context, *LookupRequest, *LookupResponse) error - Watch(context.Context, *WatchRequest, Router_WatchStream) error - Advertise(context.Context, *Request, Router_AdvertiseStream) error - Process(context.Context, *Advert, *ProcessResponse) error -} - -func RegisterRouterHandler(s server.Server, hdlr RouterHandler, opts ...server.HandlerOption) error { - type router interface { - Lookup(ctx context.Context, in *LookupRequest, out *LookupResponse) error - Watch(ctx context.Context, stream server.Stream) error - Advertise(ctx context.Context, stream server.Stream) error - Process(ctx context.Context, in *Advert, out *ProcessResponse) error - } - type Router struct { - router - } - h := &routerHandler{hdlr} - return s.Handle(s.NewHandler(&Router{h}, opts...)) -} - -type routerHandler struct { - RouterHandler -} - -func (h *routerHandler) Lookup(ctx context.Context, in *LookupRequest, out *LookupResponse) error { - return h.RouterHandler.Lookup(ctx, in, out) -} - -func (h *routerHandler) Watch(ctx context.Context, stream server.Stream) error { - m := new(WatchRequest) - if err := stream.Recv(m); err != nil { - return err - } - return h.RouterHandler.Watch(ctx, m, &routerWatchStream{stream}) -} - -type Router_WatchStream interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Send(*Event) error -} - -type routerWatchStream struct { - stream server.Stream -} - -func (x *routerWatchStream) Close() error { - return x.stream.Close() -} - -func (x *routerWatchStream) Context() context.Context { - return x.stream.Context() -} - -func (x *routerWatchStream) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *routerWatchStream) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *routerWatchStream) Send(m *Event) error { - return x.stream.Send(m) -} - -func (h *routerHandler) Advertise(ctx context.Context, stream server.Stream) error { - m := new(Request) - if err := stream.Recv(m); err != nil { - return err - } - return h.RouterHandler.Advertise(ctx, m, &routerAdvertiseStream{stream}) -} - -type Router_AdvertiseStream interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Send(*Advert) error -} - -type routerAdvertiseStream struct { - stream server.Stream -} - -func (x *routerAdvertiseStream) Close() error { - return x.stream.Close() -} - -func (x *routerAdvertiseStream) Context() context.Context { - return x.stream.Context() -} - -func (x *routerAdvertiseStream) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *routerAdvertiseStream) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *routerAdvertiseStream) Send(m *Advert) error { - return x.stream.Send(m) -} - -func (h *routerHandler) Process(ctx context.Context, in *Advert, out *ProcessResponse) error { - return h.RouterHandler.Process(ctx, in, out) -} - -// Api Endpoints for Table service - -func NewTableEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Table service - -type TableService interface { - Create(ctx context.Context, in *Route, opts ...client.CallOption) (*CreateResponse, error) - Delete(ctx context.Context, in *Route, opts ...client.CallOption) (*DeleteResponse, error) - Update(ctx context.Context, in *Route, opts ...client.CallOption) (*UpdateResponse, error) - List(ctx context.Context, in *Request, opts ...client.CallOption) (*ListResponse, error) - Query(ctx context.Context, in *QueryRequest, opts ...client.CallOption) (*QueryResponse, error) -} - -type tableService struct { - c client.Client - name string -} - -func NewTableService(name string, c client.Client) TableService { - return &tableService{ - c: c, - name: name, - } -} - -func (c *tableService) Create(ctx context.Context, in *Route, opts ...client.CallOption) (*CreateResponse, error) { - req := c.c.NewRequest(c.name, "Table.Create", in) - out := new(CreateResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *tableService) Delete(ctx context.Context, in *Route, opts ...client.CallOption) (*DeleteResponse, error) { - req := c.c.NewRequest(c.name, "Table.Delete", in) - out := new(DeleteResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *tableService) Update(ctx context.Context, in *Route, opts ...client.CallOption) (*UpdateResponse, error) { - req := c.c.NewRequest(c.name, "Table.Update", in) - out := new(UpdateResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *tableService) List(ctx context.Context, in *Request, opts ...client.CallOption) (*ListResponse, error) { - req := c.c.NewRequest(c.name, "Table.List", in) - out := new(ListResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *tableService) Query(ctx context.Context, in *QueryRequest, opts ...client.CallOption) (*QueryResponse, error) { - req := c.c.NewRequest(c.name, "Table.Query", in) - out := new(QueryResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Table service - -type TableHandler interface { - Create(context.Context, *Route, *CreateResponse) error - Delete(context.Context, *Route, *DeleteResponse) error - Update(context.Context, *Route, *UpdateResponse) error - List(context.Context, *Request, *ListResponse) error - Query(context.Context, *QueryRequest, *QueryResponse) error -} - -func RegisterTableHandler(s server.Server, hdlr TableHandler, opts ...server.HandlerOption) error { - type table interface { - Create(ctx context.Context, in *Route, out *CreateResponse) error - Delete(ctx context.Context, in *Route, out *DeleteResponse) error - Update(ctx context.Context, in *Route, out *UpdateResponse) error - List(ctx context.Context, in *Request, out *ListResponse) error - Query(ctx context.Context, in *QueryRequest, out *QueryResponse) error - } - type Table struct { - table - } - h := &tableHandler{hdlr} - return s.Handle(s.NewHandler(&Table{h}, opts...)) -} - -type tableHandler struct { - TableHandler -} - -func (h *tableHandler) Create(ctx context.Context, in *Route, out *CreateResponse) error { - return h.TableHandler.Create(ctx, in, out) -} - -func (h *tableHandler) Delete(ctx context.Context, in *Route, out *DeleteResponse) error { - return h.TableHandler.Delete(ctx, in, out) -} - -func (h *tableHandler) Update(ctx context.Context, in *Route, out *UpdateResponse) error { - return h.TableHandler.Update(ctx, in, out) -} - -func (h *tableHandler) List(ctx context.Context, in *Request, out *ListResponse) error { - return h.TableHandler.List(ctx, in, out) -} - -func (h *tableHandler) Query(ctx context.Context, in *QueryRequest, out *QueryResponse) error { - return h.TableHandler.Query(ctx, in, out) -} diff --git a/router/service/proto/router.proto b/router/service/proto/router.proto deleted file mode 100644 index fe13ee21..00000000 --- a/router/service/proto/router.proto +++ /dev/null @@ -1,135 +0,0 @@ -syntax = "proto3"; - -package go.micro.router; - -option go_package = "github.com/micro/go-micro/v2/router/service/proto;router"; -// Router service is used by the proxy to lookup routes -service Router { - rpc Lookup(LookupRequest) returns (LookupResponse) {}; - rpc Watch(WatchRequest) returns (stream Event) {}; - rpc Advertise(Request) returns (stream Advert) {}; - rpc Process(Advert) returns (ProcessResponse) {}; -} - -service Table { - rpc Create(Route) returns (CreateResponse) {}; - rpc Delete(Route) returns (DeleteResponse) {}; - rpc Update(Route) returns (UpdateResponse) {}; - rpc List(Request) returns (ListResponse) {}; - rpc Query(QueryRequest) returns (QueryResponse) {}; -} - -// Empty request -message Request {} - -// Empty response -message Response {} - -// ListResponse is returned by List -message ListResponse { - repeated Route routes = 1; -} - -// LookupRequest is made to Lookup -message LookupRequest { - Query query = 1; -} - -// LookupResponse is returned by Lookup -message LookupResponse { - repeated Route routes = 1; -} - -// QueryRequest queries Table for Routes -message QueryRequest{ - Query query = 1; -} - -// QueryResponse is returned by Query -message QueryResponse { - repeated Route routes = 1; -} - -// WatchRequest is made to Watch Router -message WatchRequest {} - -// AdvertType defines the type of advert -enum AdvertType { - AdvertAnnounce = 0; - AdvertUpdate = 1; -} - -// Advert is router advertsement streamed by Watch -message Advert { - // id of the advertising router - string id = 1; - // type of advertisement - AdvertType type = 2; - // unix timestamp of the advertisement - int64 timestamp = 3; - // TTL of the Advert - int64 ttl = 4; - // events is a list of advertised events - repeated Event events = 5; -} - -// ProcessResponse is returned by Process -message ProcessResponse {} - -// CreateResponse is returned by Create -message CreateResponse {} - -// DeleteResponse is returned by Delete -message DeleteResponse {} - -// UpdateResponse is returned by Update -message UpdateResponse {} - -// EventType defines the type of event -enum EventType { - Create = 0; - Delete = 1; - Update = 2; -} - -// Event is routing table event -message Event { - // the unique event id - string id = 1; - // type of event - EventType type = 2; - // unix timestamp of event - int64 timestamp = 3; - // service route - Route route = 4; -} - -// Query is passed in a LookupRequest -message Query { - // service to lookup - string service = 1; - // gateway to lookup - string gateway = 2; - // network to lookup - string network = 3; -} - -// Route is a service route -message Route { - // service for the route - string service = 1; - // the address that advertise this route - string address = 2; - // gateway as the next hop - string gateway = 3; - // the network for this destination - string network = 4; - // router if the router id - string router = 5; - // the network link - string link = 6; - // the metric / score of this route - int64 metric = 7; - // metadata for the route - map metadata = 8; -} diff --git a/router/service/service.go b/router/service/service.go deleted file mode 100644 index 625946f3..00000000 --- a/router/service/service.go +++ /dev/null @@ -1,271 +0,0 @@ -package service - -import ( - "context" - "fmt" - "io" - "net/http" - "sync" - "time" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/router" - pb "github.com/micro/go-micro/v2/router/service/proto" -) - -type svc struct { - sync.RWMutex - opts router.Options - callOpts []client.CallOption - router pb.RouterService - table *table - exit chan bool - errChan chan error - advertChan chan *router.Advert -} - -// NewRouter creates new service router and returns it -func NewRouter(opts ...router.Option) router.Router { - // get default options - options := router.DefaultOptions() - - // apply requested options - for _, o := range opts { - o(&options) - } - - // NOTE: might need some client opts here - cli := client.DefaultClient - - // get options client from the context. We set this in the context to prevent an import loop, as - // the client depends on the router - if c, ok := options.Context.Value(clientKey{}).(client.Client); ok { - cli = c - } - - // NOTE: should we have Client/Service option in router.Options? - s := &svc{ - opts: options, - router: pb.NewRouterService(router.DefaultName, cli), - } - - // set the router address to call - if len(options.Address) > 0 { - s.callOpts = []client.CallOption{ - client.WithAddress(options.Address), - } - } - // set the table - s.table = &table{pb.NewTableService(router.DefaultName, cli), s.callOpts} - - return s -} - -// Init initializes router with given options -func (s *svc) Init(opts ...router.Option) error { - s.Lock() - defer s.Unlock() - - for _, o := range opts { - o(&s.opts) - } - - return nil -} - -// Options returns router options -func (s *svc) Options() router.Options { - s.Lock() - opts := s.opts - s.Unlock() - - return opts -} - -// Table returns routing table -func (s *svc) Table() router.Table { - return s.table -} - -func (s *svc) advertiseEvents(advertChan chan *router.Advert, stream pb.Router_AdvertiseService) error { - go func() { - <-s.exit - stream.Close() - }() - - var advErr error - - for { - resp, err := stream.Recv() - if err != nil { - if err != io.EOF { - advErr = err - } - break - } - - events := make([]*router.Event, len(resp.Events)) - for i, event := range resp.Events { - route := router.Route{ - Service: event.Route.Service, - Address: event.Route.Address, - Gateway: event.Route.Gateway, - Network: event.Route.Network, - Link: event.Route.Link, - Metric: event.Route.Metric, - Metadata: event.Route.Metadata, - } - - events[i] = &router.Event{ - Id: event.Id, - Type: router.EventType(event.Type), - Timestamp: time.Unix(0, event.Timestamp), - Route: route, - } - } - - advert := &router.Advert{ - Id: resp.Id, - Type: router.AdvertType(resp.Type), - Timestamp: time.Unix(0, resp.Timestamp), - TTL: time.Duration(resp.Ttl), - Events: events, - } - - select { - case advertChan <- advert: - case <-s.exit: - close(advertChan) - return nil - } - } - - // close the channel on exit - close(advertChan) - - return advErr -} - -// Advertise advertises routes to the network -func (s *svc) Advertise() (<-chan *router.Advert, error) { - s.Lock() - defer s.Unlock() - - stream, err := s.router.Advertise(context.Background(), &pb.Request{}, s.callOpts...) - if err != nil { - return nil, fmt.Errorf("failed getting advert stream: %s", err) - } - - // create advertise and event channels - advertChan := make(chan *router.Advert) - go s.advertiseEvents(advertChan, stream) - - return advertChan, nil -} - -// Process processes incoming adverts -func (s *svc) Process(advert *router.Advert) error { - events := make([]*pb.Event, 0, len(advert.Events)) - for _, event := range advert.Events { - route := &pb.Route{ - Service: event.Route.Service, - Address: event.Route.Address, - Gateway: event.Route.Gateway, - Network: event.Route.Network, - Link: event.Route.Link, - Metric: event.Route.Metric, - Metadata: event.Route.Metadata, - } - e := &pb.Event{ - Id: event.Id, - Type: pb.EventType(event.Type), - Timestamp: event.Timestamp.UnixNano(), - Route: route, - } - events = append(events, e) - } - - advertReq := &pb.Advert{ - Id: s.Options().Id, - Type: pb.AdvertType(advert.Type), - Timestamp: advert.Timestamp.UnixNano(), - Events: events, - } - - if _, err := s.router.Process(context.Background(), advertReq, s.callOpts...); err != nil { - return err - } - - return nil -} - -// Remote router cannot be closed -func (s *svc) Close() error { - s.Lock() - defer s.Unlock() - - select { - case <-s.exit: - return nil - default: - close(s.exit) - } - - return nil -} - -// Lookup looks up routes in the routing table and returns them -func (s *svc) Lookup(q ...router.QueryOption) ([]router.Route, error) { - // call the router - query := router.NewQuery(q...) - - resp, err := s.router.Lookup(context.Background(), &pb.LookupRequest{ - Query: &pb.Query{ - Service: query.Service, - Gateway: query.Gateway, - Network: query.Network, - }, - }, s.callOpts...) - - if verr, ok := err.(*errors.Error); ok && verr.Code == http.StatusNotFound { - return nil, router.ErrRouteNotFound - } else if err != nil { - return nil, err - } - - routes := make([]router.Route, len(resp.Routes)) - for i, route := range resp.Routes { - routes[i] = router.Route{ - Service: route.Service, - Address: route.Address, - Gateway: route.Gateway, - Network: route.Network, - Link: route.Link, - Metric: route.Metric, - Metadata: route.Metadata, - } - } - - return routes, nil -} - -// Watch returns a watcher which allows to track updates to the routing table -func (s *svc) Watch(opts ...router.WatchOption) (router.Watcher, error) { - rsp, err := s.router.Watch(context.Background(), &pb.WatchRequest{}, s.callOpts...) - if err != nil { - return nil, err - } - options := router.WatchOptions{ - Service: "*", - } - for _, o := range opts { - o(&options) - } - return newWatcher(rsp, options) -} - -// Returns the router implementation -func (s *svc) String() string { - return "service" -} diff --git a/router/service/table.go b/router/service/table.go deleted file mode 100644 index 8590d323..00000000 --- a/router/service/table.go +++ /dev/null @@ -1,123 +0,0 @@ -package service - -import ( - "context" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/router" - pb "github.com/micro/go-micro/v2/router/service/proto" -) - -type table struct { - table pb.TableService - callOpts []client.CallOption -} - -// Create new route in the routing table -func (t *table) Create(r router.Route) error { - route := &pb.Route{ - Service: r.Service, - Address: r.Address, - Gateway: r.Gateway, - Network: r.Network, - Link: r.Link, - Metric: r.Metric, - } - - if _, err := t.table.Create(context.Background(), route, t.callOpts...); err != nil { - return err - } - - return nil -} - -// Delete deletes existing route from the routing table -func (t *table) Delete(r router.Route) error { - route := &pb.Route{ - Service: r.Service, - Address: r.Address, - Gateway: r.Gateway, - Network: r.Network, - Link: r.Link, - Metric: r.Metric, - } - - if _, err := t.table.Delete(context.Background(), route, t.callOpts...); err != nil { - return err - } - - return nil -} - -// Update updates route in the routing table -func (t *table) Update(r router.Route) error { - route := &pb.Route{ - Service: r.Service, - Address: r.Address, - Gateway: r.Gateway, - Network: r.Network, - Link: r.Link, - Metric: r.Metric, - } - - if _, err := t.table.Update(context.Background(), route, t.callOpts...); err != nil { - return err - } - - return nil -} - -// List returns the list of all routes in the table -func (t *table) List() ([]router.Route, error) { - resp, err := t.table.List(context.Background(), &pb.Request{}, t.callOpts...) - if err != nil { - return nil, err - } - - routes := make([]router.Route, len(resp.Routes)) - for i, route := range resp.Routes { - routes[i] = router.Route{ - Service: route.Service, - Address: route.Address, - Gateway: route.Gateway, - Network: route.Network, - Link: route.Link, - Metric: route.Metric, - } - } - - return routes, nil -} - -// Lookup looks up routes in the routing table and returns them -func (t *table) Query(q ...router.QueryOption) ([]router.Route, error) { - query := router.NewQuery(q...) - - // call the router - resp, err := t.table.Query(context.Background(), &pb.QueryRequest{ - Query: &pb.Query{ - Service: query.Service, - Gateway: query.Gateway, - Network: query.Network, - }, - }, t.callOpts...) - - // errored out - if err != nil { - return nil, err - } - - routes := make([]router.Route, len(resp.Routes)) - for i, route := range resp.Routes { - routes[i] = router.Route{ - Service: route.Service, - Address: route.Address, - Gateway: route.Gateway, - Network: route.Network, - Link: route.Link, - Metric: route.Metric, - } - } - - return routes, nil -} diff --git a/router/service/watcher.go b/router/service/watcher.go deleted file mode 100644 index 3a365491..00000000 --- a/router/service/watcher.go +++ /dev/null @@ -1,118 +0,0 @@ -package service - -import ( - "io" - "sync" - "time" - - "github.com/micro/go-micro/v2/router" - pb "github.com/micro/go-micro/v2/router/service/proto" -) - -type watcher struct { - sync.RWMutex - opts router.WatchOptions - resChan chan *router.Event - done chan struct{} - stream pb.Router_WatchService -} - -func newWatcher(rsp pb.Router_WatchService, opts router.WatchOptions) (*watcher, error) { - w := &watcher{ - opts: opts, - resChan: make(chan *router.Event), - done: make(chan struct{}), - stream: rsp, - } - - go func() { - for { - select { - case <-w.done: - return - default: - if err := w.watch(rsp); err != nil { - w.Stop() - return - } - } - } - }() - - return w, nil -} - -// watchRouter watches router and send events to all registered watchers -func (w *watcher) watch(stream pb.Router_WatchService) error { - var watchErr error - - for { - resp, err := stream.Recv() - if err != nil { - if err != io.EOF { - watchErr = err - } - break - } - - route := router.Route{ - Service: resp.Route.Service, - Address: resp.Route.Address, - Gateway: resp.Route.Gateway, - Network: resp.Route.Network, - Link: resp.Route.Link, - Metric: resp.Route.Metric, - Metadata: resp.Route.Metadata, - } - - event := &router.Event{ - Id: resp.Id, - Type: router.EventType(resp.Type), - Timestamp: time.Unix(0, resp.Timestamp), - Route: route, - } - - select { - case w.resChan <- event: - case <-w.done: - } - } - - return watchErr -} - -// Next is a blocking call that returns watch result -func (w *watcher) Next() (*router.Event, error) { - for { - select { - case res := <-w.resChan: - switch w.opts.Service { - case res.Route.Service, "*": - return res, nil - default: - continue - } - case <-w.done: - return nil, router.ErrWatcherStopped - } - } -} - -// Chan returns event channel -func (w *watcher) Chan() (<-chan *router.Event, error) { - return w.resChan, nil -} - -// Stop stops watcher -func (w *watcher) Stop() { - w.Lock() - defer w.Unlock() - - select { - case <-w.done: - return - default: - w.stream.Close() - close(w.done) - } -} diff --git a/router/static/static.go b/router/static/static.go index 299c8f8f..439b2c8d 100644 --- a/router/static/static.go +++ b/router/static/static.go @@ -1,7 +1,7 @@ package static import ( - "github.com/micro/go-micro/v2/router" + "github.com/micro/go-micro/v3/router" ) // NewRouter returns an initialized static router diff --git a/router/watcher.go b/router/watcher.go index 4b259fba..4895cbe7 100644 --- a/router/watcher.go +++ b/router/watcher.go @@ -2,7 +2,6 @@ package router import ( "errors" - "sync" "time" ) @@ -77,48 +76,3 @@ func WatchService(s string) WatchOption { o.Service = s } } - -// tableWatcher implements routing table Watcher -type tableWatcher struct { - sync.RWMutex - id string - opts WatchOptions - resChan chan *Event - done chan struct{} -} - -// Next returns the next noticed action taken on table -// TODO: right now we only allow to watch particular service -func (w *tableWatcher) Next() (*Event, error) { - for { - select { - case res := <-w.resChan: - switch w.opts.Service { - case res.Route.Service, "*": - return res, nil - default: - continue - } - case <-w.done: - return nil, ErrWatcherStopped - } - } -} - -// Chan returns watcher events channel -func (w *tableWatcher) Chan() (<-chan *Event, error) { - return w.resChan, nil -} - -// Stop stops routing table watcher -func (w *tableWatcher) Stop() { - w.Lock() - defer w.Unlock() - - select { - case <-w.done: - return - default: - close(w.done) - } -} diff --git a/runtime/default.go b/runtime/default.go deleted file mode 100644 index c96963a4..00000000 --- a/runtime/default.go +++ /dev/null @@ -1,621 +0,0 @@ -package runtime - -import ( - "errors" - "fmt" - "io" - "log" - "os" - "path/filepath" - "strings" - "sync" - "time" - - "github.com/hpcloud/tail" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/runtime/local/git" -) - -// defaultNamespace to use if not provided as an option -const defaultNamespace = "default" - -type runtime struct { - sync.RWMutex - // options configure runtime - options Options - // used to stop the runtime - closed chan bool - // used to start new services - start chan *service - // indicates if we're running - running bool - // namespaces stores services grouped by namespace, e.g. namespaces["foo"]["go.micro.auth:latest"] - // would return the latest version of go.micro.auth from the foo namespace - namespaces map[string]map[string]*service -} - -// NewRuntime creates new local runtime and returns it -func NewRuntime(opts ...Option) Runtime { - // get default options - options := Options{} - - // apply requested options - for _, o := range opts { - o(&options) - } - - // make the logs directory - path := filepath.Join(os.TempDir(), "micro", "logs") - _ = os.MkdirAll(path, 0755) - - return &runtime{ - options: options, - closed: make(chan bool), - start: make(chan *service, 128), - namespaces: make(map[string]map[string]*service), - } -} - -func (r *runtime) checkoutSourceIfNeeded(s *Service) error { - // Runtime service like config have no source. - // Skip checkout in that case - if len(s.Source) == 0 { - return nil - } - // @todo make this come from config - cpath := filepath.Join(os.TempDir(), "micro", "uploads", s.Source) - path := strings.ReplaceAll(cpath, ".tar.gz", "") - if ex, _ := exists(cpath); ex { - err := os.RemoveAll(path) - if err != nil { - return err - } - err = os.MkdirAll(path, 0777) - if err != nil { - return err - } - err = git.Uncompress(cpath, path) - if err != nil { - return err - } - s.Source = path - return nil - } - source, err := git.ParseSourceLocal("", s.Source) - if err != nil { - return err - } - source.Ref = s.Version - - err = git.CheckoutSource(os.TempDir(), source) - if err != nil { - return err - } - s.Source = source.FullPath - return nil -} - -// Init initializes runtime options -func (r *runtime) Init(opts ...Option) error { - r.Lock() - defer r.Unlock() - - for _, o := range opts { - o(&r.options) - } - - return nil -} - -// run runs the runtime management loop -func (r *runtime) run(events <-chan Event) { - t := time.NewTicker(time.Second * 5) - defer t.Stop() - - // process event processes an incoming event - processEvent := func(event Event, service *service, ns string) error { - // get current vals - r.RLock() - name := service.Name - updated := service.updated - r.RUnlock() - - // only process if the timestamp is newer - if !event.Timestamp.After(updated) { - return nil - } - - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime updating service %s in %v namespace", name, ns) - } - - // this will cause a delete followed by created - if err := r.Update(service.Service, UpdateNamespace(ns)); err != nil { - return err - } - - // update the local timestamp - r.Lock() - service.updated = updated - r.Unlock() - - return nil - } - - for { - select { - case <-t.C: - // check running services - r.RLock() - for _, sevices := range r.namespaces { - for _, service := range sevices { - if !service.ShouldStart() { - continue - } - - // TODO: check service error - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime starting %s", service.Name) - } - if err := service.Start(); err != nil { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime error starting %s: %v", service.Name, err) - } - } - } - } - r.RUnlock() - case service := <-r.start: - if !service.ShouldStart() { - continue - } - // TODO: check service error - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime starting service %s", service.Name) - } - if err := service.Start(); err != nil { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime error starting service %s: %v", service.Name, err) - } - } - case event := <-events: - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime received notification event: %v", event) - } - // NOTE: we only handle Update events for now - switch event.Type { - case Update: - if event.Service != nil { - ns := defaultNamespace - if event.Options != nil && len(event.Options.Namespace) > 0 { - ns = event.Options.Namespace - } - - r.RLock() - if _, ok := r.namespaces[ns]; !ok { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime unknown namespace: %s", ns) - } - r.RUnlock() - continue - } - service, ok := r.namespaces[ns][fmt.Sprintf("%v:%v", event.Service.Name, event.Service.Version)] - r.RUnlock() - if !ok { - logger.Debugf("Runtime unknown service: %s", event.Service) - } - - if err := processEvent(event, service, ns); err != nil { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime error updating service %s: %v", event.Service, err) - } - } - continue - } - - r.RLock() - namespaces := r.namespaces - r.RUnlock() - - // if blank service was received we update all services - for ns, services := range namespaces { - for _, service := range services { - if err := processEvent(event, service, ns); err != nil { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime error updating service %s: %v", service.Name, err) - } - } - } - } - } - case <-r.closed: - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime stopped") - } - return - } - } -} - -func logFile(serviceName string) string { - // make the directory - name := strings.Replace(serviceName, "/", "-", -1) - path := filepath.Join(os.TempDir(), "micro", "logs") - return filepath.Join(path, fmt.Sprintf("%v.log", name)) -} - -func serviceKey(s *Service) string { - return fmt.Sprintf("%v:%v", s.Name, s.Version) -} - -// Create creates a new service which is then started by runtime -func (r *runtime) Create(s *Service, opts ...CreateOption) error { - err := r.checkoutSourceIfNeeded(s) - if err != nil { - return err - } - r.Lock() - defer r.Unlock() - - var options CreateOptions - for _, o := range opts { - o(&options) - } - if len(options.Namespace) == 0 { - options.Namespace = defaultNamespace - } - if len(options.Command) == 0 { - options.Command = []string{"go"} - options.Args = []string{"run", "."} - } - - // pass credentials as env vars - if len(options.Credentials) > 0 { - // validate the creds - comps := strings.Split(options.Credentials, ":") - if len(comps) != 2 { - return errors.New("Invalid credentials, expected format 'user:pass'") - } - - options.Env = append(options.Env, "MICRO_AUTH_ID", comps[0]) - options.Env = append(options.Env, "MICRO_AUTH_SECRET", comps[1]) - } - - if _, ok := r.namespaces[options.Namespace]; !ok { - r.namespaces[options.Namespace] = make(map[string]*service) - } - if _, ok := r.namespaces[options.Namespace][serviceKey(s)]; ok { - return errors.New("service already running") - } - - // create new service - service := newService(s, options) - - f, err := os.OpenFile(logFile(service.Name), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - log.Fatal(err) - } - - if service.output != nil { - service.output = io.MultiWriter(service.output, f) - } else { - service.output = f - } - // start the service - if err := service.Start(); err != nil { - return err - } - // save service - r.namespaces[options.Namespace][serviceKey(s)] = service - - return nil -} - -// exists returns whether the given file or directory exists -func exists(path string) (bool, error) { - _, err := os.Stat(path) - if err == nil { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return true, err -} - -// @todo: Getting existing lines is not supported yet. -// The reason for this is because it's hard to calculate line offset -// as opposed to character offset. -// This logger streams by default and only supports the `StreamCount` option. -func (r *runtime) Logs(s *Service, options ...LogsOption) (LogStream, error) { - lopts := LogsOptions{} - for _, o := range options { - o(&lopts) - } - ret := &logStream{ - service: s.Name, - stream: make(chan LogRecord), - stop: make(chan bool), - } - - fpath := logFile(s.Name) - if ex, err := exists(fpath); err != nil { - return nil, err - } else if !ex { - return nil, fmt.Errorf("Logs not found for service %s", s.Name) - } - - // have to check file size to avoid too big of a seek - fi, err := os.Stat(fpath) - if err != nil { - return nil, err - } - size := fi.Size() - - whence := 2 - // Multiply by length of an average line of log in bytes - offset := lopts.Count * 200 - - if offset > size { - offset = size - } - offset *= -1 - - t, err := tail.TailFile(fpath, tail.Config{Follow: lopts.Stream, Location: &tail.SeekInfo{ - Whence: whence, - Offset: int64(offset), - }, Logger: tail.DiscardingLogger}) - if err != nil { - return nil, err - } - - ret.tail = t - go func() { - for { - select { - case line, ok := <-t.Lines: - if !ok { - ret.Stop() - return - } - ret.stream <- LogRecord{Message: line.Text} - case <-ret.stop: - return - } - } - - }() - return ret, nil -} - -type logStream struct { - tail *tail.Tail - service string - stream chan LogRecord - sync.Mutex - stop chan bool - err error -} - -func (l *logStream) Chan() chan LogRecord { - return l.stream -} - -func (l *logStream) Error() error { - return l.err -} - -func (l *logStream) Stop() error { - l.Lock() - defer l.Unlock() - - select { - case <-l.stop: - return nil - default: - close(l.stop) - close(l.stream) - err := l.tail.Stop() - if err != nil { - logger.Errorf("Error stopping tail: %v", err) - return err - } - } - return nil -} - -// Read returns all instances of requested service -// If no service name is provided we return all the track services. -func (r *runtime) Read(opts ...ReadOption) ([]*Service, error) { - r.Lock() - defer r.Unlock() - - gopts := ReadOptions{} - for _, o := range opts { - o(&gopts) - } - if len(gopts.Namespace) == 0 { - gopts.Namespace = defaultNamespace - } - - save := func(k, v string) bool { - if len(k) == 0 { - return true - } - return k == v - } - - //nolint:prealloc - var services []*Service - - if _, ok := r.namespaces[gopts.Namespace]; !ok { - return make([]*Service, 0), nil - } - - for _, service := range r.namespaces[gopts.Namespace] { - if !save(gopts.Service, service.Name) { - continue - } - if !save(gopts.Version, service.Version) { - continue - } - // TODO deal with service type - // no version has sbeen requested, just append the service - services = append(services, service.Service) - } - - return services, nil -} - -// Update attempts to update the service -func (r *runtime) Update(s *Service, opts ...UpdateOption) error { - var options UpdateOptions - for _, o := range opts { - o(&options) - } - if len(options.Namespace) == 0 { - options.Namespace = defaultNamespace - } - - err := r.checkoutSourceIfNeeded(s) - if err != nil { - return err - } - - r.Lock() - srvs, ok := r.namespaces[options.Namespace] - r.Unlock() - if !ok { - return errors.New("Service not found") - } - - r.Lock() - service, ok := srvs[serviceKey(s)] - r.Unlock() - if !ok { - return errors.New("Service not found") - } - - if err := service.Stop(); err != nil && err.Error() != "no such process" { - logger.Errorf("Error stopping service %s: %s", service.Name, err) - return err - } - - return service.Start() -} - -// Delete removes the service from the runtime and stops it -func (r *runtime) Delete(s *Service, opts ...DeleteOption) error { - r.Lock() - defer r.Unlock() - - var options DeleteOptions - for _, o := range opts { - o(&options) - } - if len(options.Namespace) == 0 { - options.Namespace = defaultNamespace - } - - srvs, ok := r.namespaces[options.Namespace] - if !ok { - return nil - } - - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime deleting service %s", s.Name) - } - - service, ok := srvs[serviceKey(s)] - if !ok { - return nil - } - - // check if running - if !service.Running() { - delete(srvs, service.key()) - r.namespaces[options.Namespace] = srvs - return nil - } - // otherwise stop it - if err := service.Stop(); err != nil { - return err - } - // delete it - delete(srvs, service.key()) - r.namespaces[options.Namespace] = srvs - return nil -} - -// Start starts the runtime -func (r *runtime) Start() error { - r.Lock() - defer r.Unlock() - - // already running - if r.running { - return nil - } - - // set running - r.running = true - r.closed = make(chan bool) - - var events <-chan Event - if r.options.Scheduler != nil { - var err error - events, err = r.options.Scheduler.Notify() - if err != nil { - // TODO: should we bail here? - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime failed to start update notifier") - } - } - } - - go r.run(events) - - return nil -} - -// Stop stops the runtime -func (r *runtime) Stop() error { - r.Lock() - defer r.Unlock() - - if !r.running { - return nil - } - - select { - case <-r.closed: - return nil - default: - close(r.closed) - - // set not running - r.running = false - - // stop all the services - for _, services := range r.namespaces { - for _, service := range services { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("Runtime stopping %s", service.Name) - } - service.Stop() - } - } - - // stop the scheduler - if r.options.Scheduler != nil { - return r.options.Scheduler.Close() - } - } - - return nil -} - -// String implements stringer interface -func (r *runtime) String() string { - return "local" -} diff --git a/runtime/kubernetes/kubernetes.go b/runtime/kubernetes/kubernetes.go index 78b7abf3..085bda04 100644 --- a/runtime/kubernetes/kubernetes.go +++ b/runtime/kubernetes/kubernetes.go @@ -9,10 +9,10 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/logger" - log "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/runtime" - "github.com/micro/go-micro/v2/util/kubernetes/client" + "github.com/micro/go-micro/v3/logger" + log "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/runtime" + "github.com/micro/go-micro/v3/util/kubernetes/client" ) // action to take on runtime service diff --git a/runtime/kubernetes/logs.go b/runtime/kubernetes/logs.go index 4c297ab3..5af51d35 100644 --- a/runtime/kubernetes/logs.go +++ b/runtime/kubernetes/logs.go @@ -9,9 +9,9 @@ import ( "strconv" "time" - "github.com/micro/go-micro/v2/runtime" - "github.com/micro/go-micro/v2/util/kubernetes/client" - "github.com/micro/go-micro/v2/util/log" + "github.com/micro/go-micro/v3/runtime" + "github.com/micro/go-micro/v3/util/kubernetes/client" + "github.com/micro/go-micro/v3/util/log" ) type klog struct { diff --git a/runtime/kubernetes/service.go b/runtime/kubernetes/service.go index 6decd16e..9cbf890a 100644 --- a/runtime/kubernetes/service.go +++ b/runtime/kubernetes/service.go @@ -5,10 +5,10 @@ import ( "strings" "time" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/runtime" - "github.com/micro/go-micro/v2/util/kubernetes/api" - "github.com/micro/go-micro/v2/util/kubernetes/client" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/runtime" + "github.com/micro/go-micro/v3/util/kubernetes/api" + "github.com/micro/go-micro/v3/util/kubernetes/client" ) type service struct { diff --git a/runtime/local/build/build.go b/runtime/local/build/build.go index 568ddc3f..8d26e4a2 100644 --- a/runtime/local/build/build.go +++ b/runtime/local/build/build.go @@ -2,7 +2,7 @@ package build import ( - "github.com/micro/go-micro/v2/runtime/local/source" + "github.com/micro/go-micro/v3/runtime/local/source" ) // Builder builds binaries diff --git a/runtime/local/build/docker/docker.go b/runtime/local/build/docker/docker.go index e164df55..db80a262 100644 --- a/runtime/local/build/docker/docker.go +++ b/runtime/local/build/docker/docker.go @@ -9,8 +9,8 @@ import ( "path/filepath" docker "github.com/fsouza/go-dockerclient" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/runtime/local/build" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/runtime/local/build" ) type Builder struct { diff --git a/runtime/local/build/go/golang.go b/runtime/local/build/go/golang.go index ce12124d..a64ff79f 100644 --- a/runtime/local/build/go/golang.go +++ b/runtime/local/build/go/golang.go @@ -6,7 +6,7 @@ import ( "os/exec" "path/filepath" - "github.com/micro/go-micro/v2/runtime/local/build" + "github.com/micro/go-micro/v3/runtime/local/build" ) type Builder struct { diff --git a/runtime/local/local.go b/runtime/local/local.go index e8ed179e..a92a1a15 100644 --- a/runtime/local/local.go +++ b/runtime/local/local.go @@ -1,11 +1,622 @@ -// Package local provides a local runtime package local import ( - "github.com/micro/go-micro/v2/runtime" + "errors" + "fmt" + "io" + "log" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/hpcloud/tail" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/runtime" + "github.com/micro/go-micro/v3/runtime/local/git" ) -// NewRuntime returns a new local runtime -func NewRuntime(opts ...runtime.Option) runtime.Runtime { - return runtime.NewRuntime(opts...) +// defaultNamespace to use if not provided as an option +const defaultNamespace = "default" + +type localRuntime struct { + sync.RWMutex + // options configure runtime + options runtime.Options + // used to stop the runtime + closed chan bool + // used to start new services + start chan *service + // indicates if we're running + running bool + // namespaces stores services grouped by namespace, e.g. namespaces["foo"]["go.micro.auth:latest"] + // would return the latest version of go.micro.auth from the foo namespace + namespaces map[string]map[string]*service +} + +// NewRuntime creates new local runtime and returns it +func NewRuntime(opts ...runtime.Option) runtime.Runtime { + // get default options + options := runtime.Options{} + + // apply requested options + for _, o := range opts { + o(&options) + } + + // make the logs directory + path := filepath.Join(os.TempDir(), "micro", "logs") + _ = os.MkdirAll(path, 0755) + + return &localRuntime{ + options: options, + closed: make(chan bool), + start: make(chan *service, 128), + namespaces: make(map[string]map[string]*service), + } +} + +func (r *localRuntime) checkoutSourceIfNeeded(s *runtime.Service) error { + // Runtime service like config have no source. + // Skip checkout in that case + if len(s.Source) == 0 { + return nil + } + // @todo make this come from config + cpath := filepath.Join(os.TempDir(), "micro", "uploads", s.Source) + path := strings.ReplaceAll(cpath, ".tar.gz", "") + if ex, _ := exists(cpath); ex { + err := os.RemoveAll(path) + if err != nil { + return err + } + err = os.MkdirAll(path, 0777) + if err != nil { + return err + } + err = git.Uncompress(cpath, path) + if err != nil { + return err + } + s.Source = path + return nil + } + source, err := git.ParseSourceLocal("", s.Source) + if err != nil { + return err + } + source.Ref = s.Version + + err = git.CheckoutSource(os.TempDir(), source) + if err != nil { + return err + } + s.Source = source.FullPath + return nil +} + +// Init initializes runtime options +func (r *localRuntime) Init(opts ...runtime.Option) error { + r.Lock() + defer r.Unlock() + + for _, o := range opts { + o(&r.options) + } + + return nil +} + +// run runs the runtime management loop +func (r *localRuntime) run(events <-chan runtime.Event) { + t := time.NewTicker(time.Second * 5) + defer t.Stop() + + // process event processes an incoming event + processEvent := func(event runtime.Event, service *service, ns string) error { + // get current vals + r.RLock() + name := service.Name + updated := service.updated + r.RUnlock() + + // only process if the timestamp is newer + if !event.Timestamp.After(updated) { + return nil + } + + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime updating service %s in %v namespace", name, ns) + } + + // this will cause a delete followed by created + if err := r.Update(service.Service, runtime.UpdateNamespace(ns)); err != nil { + return err + } + + // update the local timestamp + r.Lock() + service.updated = updated + r.Unlock() + + return nil + } + + for { + select { + case <-t.C: + // check running services + r.RLock() + for _, sevices := range r.namespaces { + for _, service := range sevices { + if !service.ShouldStart() { + continue + } + + // TODO: check service error + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime starting %s", service.Name) + } + if err := service.Start(); err != nil { + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime error starting %s: %v", service.Name, err) + } + } + } + } + r.RUnlock() + case service := <-r.start: + if !service.ShouldStart() { + continue + } + // TODO: check service error + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime starting service %s", service.Name) + } + if err := service.Start(); err != nil { + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime error starting service %s: %v", service.Name, err) + } + } + case event := <-events: + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime received notification event: %v", event) + } + // NOTE: we only handle Update events for now + switch event.Type { + case runtime.Update: + if event.Service != nil { + ns := defaultNamespace + if event.Options != nil && len(event.Options.Namespace) > 0 { + ns = event.Options.Namespace + } + + r.RLock() + if _, ok := r.namespaces[ns]; !ok { + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime unknown namespace: %s", ns) + } + r.RUnlock() + continue + } + service, ok := r.namespaces[ns][fmt.Sprintf("%v:%v", event.Service.Name, event.Service.Version)] + r.RUnlock() + if !ok { + logger.Debugf("Runtime unknown service: %s", event.Service) + } + + if err := processEvent(event, service, ns); err != nil { + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime error updating service %s: %v", event.Service, err) + } + } + continue + } + + r.RLock() + namespaces := r.namespaces + r.RUnlock() + + // if blank service was received we update all services + for ns, services := range namespaces { + for _, service := range services { + if err := processEvent(event, service, ns); err != nil { + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime error updating service %s: %v", service.Name, err) + } + } + } + } + } + case <-r.closed: + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime stopped") + } + return + } + } +} + +func logFile(serviceName string) string { + // make the directory + name := strings.Replace(serviceName, "/", "-", -1) + path := filepath.Join(os.TempDir(), "micro", "logs") + return filepath.Join(path, fmt.Sprintf("%v.log", name)) +} + +func serviceKey(s *runtime.Service) string { + return fmt.Sprintf("%v:%v", s.Name, s.Version) +} + +// Create creates a new service which is then started by runtime +func (r *localRuntime) Create(s *runtime.Service, opts ...runtime.CreateOption) error { + err := r.checkoutSourceIfNeeded(s) + if err != nil { + return err + } + r.Lock() + defer r.Unlock() + + var options runtime.CreateOptions + for _, o := range opts { + o(&options) + } + if len(options.Namespace) == 0 { + options.Namespace = defaultNamespace + } + if len(options.Command) == 0 { + options.Command = []string{"go"} + options.Args = []string{"run", "."} + } + + // pass credentials as env vars + if len(options.Credentials) > 0 { + // validate the creds + comps := strings.Split(options.Credentials, ":") + if len(comps) != 2 { + return errors.New("Invalid credentials, expected format 'user:pass'") + } + + options.Env = append(options.Env, "MICRO_AUTH_ID", comps[0]) + options.Env = append(options.Env, "MICRO_AUTH_SECRET", comps[1]) + } + + if _, ok := r.namespaces[options.Namespace]; !ok { + r.namespaces[options.Namespace] = make(map[string]*service) + } + if _, ok := r.namespaces[options.Namespace][serviceKey(s)]; ok { + return errors.New("service already running") + } + + // create new service + service := newService(s, options) + + f, err := os.OpenFile(logFile(service.Name), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + log.Fatal(err) + } + + if service.output != nil { + service.output = io.MultiWriter(service.output, f) + } else { + service.output = f + } + // start the service + if err := service.Start(); err != nil { + return err + } + // save service + r.namespaces[options.Namespace][serviceKey(s)] = service + + return nil +} + +// exists returns whether the given file or directory exists +func exists(path string) (bool, error) { + _, err := os.Stat(path) + if err == nil { + return true, nil + } + if os.IsNotExist(err) { + return false, nil + } + return true, err +} + +// @todo: Getting existing lines is not supported yet. +// The reason for this is because it's hard to calculate line offset +// as opposed to character offset. +// This logger streams by default and only supports the `StreamCount` option. +func (r *localRuntime) Logs(s *runtime.Service, options ...runtime.LogsOption) (runtime.LogStream, error) { + lopts := runtime.LogsOptions{} + for _, o := range options { + o(&lopts) + } + ret := &logStream{ + service: s.Name, + stream: make(chan runtime.LogRecord), + stop: make(chan bool), + } + + fpath := logFile(s.Name) + if ex, err := exists(fpath); err != nil { + return nil, err + } else if !ex { + return nil, fmt.Errorf("Logs not found for service %s", s.Name) + } + + // have to check file size to avoid too big of a seek + fi, err := os.Stat(fpath) + if err != nil { + return nil, err + } + size := fi.Size() + + whence := 2 + // Multiply by length of an average line of log in bytes + offset := lopts.Count * 200 + + if offset > size { + offset = size + } + offset *= -1 + + t, err := tail.TailFile(fpath, tail.Config{Follow: lopts.Stream, Location: &tail.SeekInfo{ + Whence: whence, + Offset: int64(offset), + }, Logger: tail.DiscardingLogger}) + if err != nil { + return nil, err + } + + ret.tail = t + go func() { + for { + select { + case line, ok := <-t.Lines: + if !ok { + ret.Stop() + return + } + ret.stream <- runtime.LogRecord{Message: line.Text} + case <-ret.stop: + return + } + } + + }() + return ret, nil +} + +type logStream struct { + tail *tail.Tail + service string + stream chan runtime.LogRecord + sync.Mutex + stop chan bool + err error +} + +func (l *logStream) Chan() chan runtime.LogRecord { + return l.stream +} + +func (l *logStream) Error() error { + return l.err +} + +func (l *logStream) Stop() error { + l.Lock() + defer l.Unlock() + + select { + case <-l.stop: + return nil + default: + close(l.stop) + close(l.stream) + err := l.tail.Stop() + if err != nil { + logger.Errorf("Error stopping tail: %v", err) + return err + } + } + return nil +} + +// Read returns all instances of requested service +// If no service name is provided we return all the track services. +func (r *localRuntime) Read(opts ...runtime.ReadOption) ([]*runtime.Service, error) { + r.Lock() + defer r.Unlock() + + gopts := runtime.ReadOptions{} + for _, o := range opts { + o(&gopts) + } + if len(gopts.Namespace) == 0 { + gopts.Namespace = defaultNamespace + } + + save := func(k, v string) bool { + if len(k) == 0 { + return true + } + return k == v + } + + //nolint:prealloc + var services []*runtime.Service + + if _, ok := r.namespaces[gopts.Namespace]; !ok { + return make([]*runtime.Service, 0), nil + } + + for _, service := range r.namespaces[gopts.Namespace] { + if !save(gopts.Service, service.Name) { + continue + } + if !save(gopts.Version, service.Version) { + continue + } + // TODO deal with service type + // no version has sbeen requested, just append the service + services = append(services, service.Service) + } + + return services, nil +} + +// Update attempts to update the service +func (r *localRuntime) Update(s *runtime.Service, opts ...runtime.UpdateOption) error { + var options runtime.UpdateOptions + for _, o := range opts { + o(&options) + } + if len(options.Namespace) == 0 { + options.Namespace = defaultNamespace + } + + err := r.checkoutSourceIfNeeded(s) + if err != nil { + return err + } + + r.Lock() + srvs, ok := r.namespaces[options.Namespace] + r.Unlock() + if !ok { + return errors.New("Service not found") + } + + r.Lock() + service, ok := srvs[serviceKey(s)] + r.Unlock() + if !ok { + return errors.New("Service not found") + } + + if err := service.Stop(); err != nil && err.Error() != "no such process" { + logger.Errorf("Error stopping service %s: %s", service.Name, err) + return err + } + + return service.Start() +} + +// Delete removes the service from the runtime and stops it +func (r *localRuntime) Delete(s *runtime.Service, opts ...runtime.DeleteOption) error { + r.Lock() + defer r.Unlock() + + var options runtime.DeleteOptions + for _, o := range opts { + o(&options) + } + if len(options.Namespace) == 0 { + options.Namespace = defaultNamespace + } + + srvs, ok := r.namespaces[options.Namespace] + if !ok { + return nil + } + + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime deleting service %s", s.Name) + } + + service, ok := srvs[serviceKey(s)] + if !ok { + return nil + } + + // check if running + if !service.Running() { + delete(srvs, service.key()) + r.namespaces[options.Namespace] = srvs + return nil + } + // otherwise stop it + if err := service.Stop(); err != nil { + return err + } + // delete it + delete(srvs, service.key()) + r.namespaces[options.Namespace] = srvs + return nil +} + +// Start starts the runtime +func (r *localRuntime) Start() error { + r.Lock() + defer r.Unlock() + + // already running + if r.running { + return nil + } + + // set running + r.running = true + r.closed = make(chan bool) + + var events <-chan runtime.Event + if r.options.Scheduler != nil { + var err error + events, err = r.options.Scheduler.Notify() + if err != nil { + // TODO: should we bail here? + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime failed to start update notifier") + } + } + } + + go r.run(events) + + return nil +} + +// Stop stops the runtime +func (r *localRuntime) Stop() error { + r.Lock() + defer r.Unlock() + + if !r.running { + return nil + } + + select { + case <-r.closed: + return nil + default: + close(r.closed) + + // set not running + r.running = false + + // stop all the services + for _, services := range r.namespaces { + for _, service := range services { + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("Runtime stopping %s", service.Name) + } + service.Stop() + } + } + + // stop the scheduler + if r.options.Scheduler != nil { + return r.options.Scheduler.Close() + } + } + + return nil +} + +// String implements stringer interface +func (r *localRuntime) String() string { + return "local" } diff --git a/runtime/local/process/os/os.go b/runtime/local/process/os/os.go index d285f7a4..6c9e83c7 100644 --- a/runtime/local/process/os/os.go +++ b/runtime/local/process/os/os.go @@ -10,7 +10,7 @@ import ( "strconv" "syscall" - "github.com/micro/go-micro/v2/runtime/local/process" + "github.com/micro/go-micro/v3/runtime/local/process" ) func (p *Process) Exec(exe *process.Executable) error { diff --git a/runtime/local/process/os/os_windows.go b/runtime/local/process/os/os_windows.go index d5c7869d..3f9c2c29 100644 --- a/runtime/local/process/os/os_windows.go +++ b/runtime/local/process/os/os_windows.go @@ -7,7 +7,7 @@ import ( "os/exec" "strconv" - "github.com/micro/go-micro/v2/runtime/local/process" + "github.com/micro/go-micro/v3/runtime/local/process" ) func (p *Process) Exec(exe *process.Executable) error { diff --git a/runtime/local/process/os/process.go b/runtime/local/process/os/process.go index 8a939177..0d6b10be 100644 --- a/runtime/local/process/os/process.go +++ b/runtime/local/process/os/process.go @@ -2,7 +2,7 @@ package os import ( - "github.com/micro/go-micro/v2/runtime/local/process" + "github.com/micro/go-micro/v3/runtime/local/process" ) type Process struct{} diff --git a/runtime/local/process/process.go b/runtime/local/process/process.go index ffeae63e..446d715e 100644 --- a/runtime/local/process/process.go +++ b/runtime/local/process/process.go @@ -4,7 +4,7 @@ package process import ( "io" - "github.com/micro/go-micro/v2/runtime/local/build" + "github.com/micro/go-micro/v3/runtime/local/build" ) // Process manages a running process diff --git a/runtime/service.go b/runtime/local/service.go similarity index 93% rename from runtime/service.go rename to runtime/local/service.go index 4b07d6e9..e65fe4d9 100644 --- a/runtime/service.go +++ b/runtime/local/service.go @@ -1,4 +1,4 @@ -package runtime +package local import ( "fmt" @@ -9,10 +9,11 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/runtime/local/build" - "github.com/micro/go-micro/v2/runtime/local/process" - proc "github.com/micro/go-micro/v2/runtime/local/process/os" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/runtime" + "github.com/micro/go-micro/v3/runtime/local/build" + "github.com/micro/go-micro/v3/runtime/local/process" + proc "github.com/micro/go-micro/v3/runtime/local/process/os" ) type service struct { @@ -30,7 +31,7 @@ type service struct { output io.Writer // service to manage - *Service + *runtime.Service // process creator Process *proc.Process // Exec @@ -39,7 +40,7 @@ type service struct { PID *process.PID } -func newService(s *Service, c CreateOptions) *service { +func newService(s *runtime.Service, c runtime.CreateOptions) *service { var exec string var args []string diff --git a/runtime/local/source/git/git.go b/runtime/local/source/git/git.go index 0f412988..34b5a189 100644 --- a/runtime/local/source/git/git.go +++ b/runtime/local/source/git/git.go @@ -7,7 +7,7 @@ import ( "strings" "github.com/go-git/go-git/v5" - "github.com/micro/go-micro/v2/runtime/local/source" + "github.com/micro/go-micro/v3/runtime/local/source" ) // Source retrieves source code diff --git a/runtime/local/source/go/golang.go b/runtime/local/source/go/golang.go index 82df5920..0cb0dc5f 100644 --- a/runtime/local/source/go/golang.go +++ b/runtime/local/source/go/golang.go @@ -7,7 +7,7 @@ import ( "path/filepath" "strings" - "github.com/micro/go-micro/v2/runtime/local/source" + "github.com/micro/go-micro/v3/runtime/local/source" ) type Source struct { diff --git a/runtime/options.go b/runtime/options.go index 95540315..9c806b0f 100644 --- a/runtime/options.go +++ b/runtime/options.go @@ -4,7 +4,7 @@ import ( "context" "io" - "github.com/micro/go-micro/v2/client" + "github.com/micro/go-micro/v3/client" ) type Option func(o *Options) diff --git a/runtime/runtime.go b/runtime/runtime.go index 1299baf5..9007b936 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -7,11 +7,6 @@ import ( ) var ( - // DefaultRuntime is default micro runtime - DefaultRuntime Runtime = NewRuntime() - // DefaultName is default runtime service name - DefaultName = "go.micro.runtime" - ErrAlreadyExists = errors.New("already exists") ) diff --git a/runtime/service/proto/runtime.pb.go b/runtime/service/proto/runtime.pb.go deleted file mode 100644 index f09a8dbf..00000000 --- a/runtime/service/proto/runtime.pb.go +++ /dev/null @@ -1,1332 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: runtime/service/proto/runtime.proto - -package go_micro_runtime - -import ( - context "context" - fmt "fmt" - proto "github.com/golang/protobuf/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -type Service struct { - // name of the service - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // version of the service - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` - // git url of the source - Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"` - // service metadata - Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Service) Reset() { *m = Service{} } -func (m *Service) String() string { return proto.CompactTextString(m) } -func (*Service) ProtoMessage() {} -func (*Service) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{0} -} - -func (m *Service) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Service.Unmarshal(m, b) -} -func (m *Service) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Service.Marshal(b, m, deterministic) -} -func (m *Service) XXX_Merge(src proto.Message) { - xxx_messageInfo_Service.Merge(m, src) -} -func (m *Service) XXX_Size() int { - return xxx_messageInfo_Service.Size(m) -} -func (m *Service) XXX_DiscardUnknown() { - xxx_messageInfo_Service.DiscardUnknown(m) -} - -var xxx_messageInfo_Service proto.InternalMessageInfo - -func (m *Service) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Service) GetVersion() string { - if m != nil { - return m.Version - } - return "" -} - -func (m *Service) GetSource() string { - if m != nil { - return m.Source - } - return "" -} - -func (m *Service) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -type Event struct { - Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - Timestamp int64 `protobuf:"varint,2,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - Service string `protobuf:"bytes,3,opt,name=service,proto3" json:"service,omitempty"` - Version string `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Event) Reset() { *m = Event{} } -func (m *Event) String() string { return proto.CompactTextString(m) } -func (*Event) ProtoMessage() {} -func (*Event) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{1} -} - -func (m *Event) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Event.Unmarshal(m, b) -} -func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Event.Marshal(b, m, deterministic) -} -func (m *Event) XXX_Merge(src proto.Message) { - xxx_messageInfo_Event.Merge(m, src) -} -func (m *Event) XXX_Size() int { - return xxx_messageInfo_Event.Size(m) -} -func (m *Event) XXX_DiscardUnknown() { - xxx_messageInfo_Event.DiscardUnknown(m) -} - -var xxx_messageInfo_Event proto.InternalMessageInfo - -func (m *Event) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *Event) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -func (m *Event) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -func (m *Event) GetVersion() string { - if m != nil { - return m.Version - } - return "" -} - -type CreateOptions struct { - // command to pass in - Command []string `protobuf:"bytes,1,rep,name=command,proto3" json:"command,omitempty"` - // args to pass into command - Args []string `protobuf:"bytes,2,rep,name=args,proto3" json:"args,omitempty"` - // environment to pass in - Env []string `protobuf:"bytes,3,rep,name=env,proto3" json:"env,omitempty"` - // output to send to - Output string `protobuf:"bytes,4,opt,name=output,proto3" json:"output,omitempty"` - // create type of service - Type string `protobuf:"bytes,5,opt,name=type,proto3" json:"type,omitempty"` - // image to use - Image string `protobuf:"bytes,6,opt,name=image,proto3" json:"image,omitempty"` - // namespace to create the service in - Namespace string `protobuf:"bytes,7,opt,name=namespace,proto3" json:"namespace,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateOptions) Reset() { *m = CreateOptions{} } -func (m *CreateOptions) String() string { return proto.CompactTextString(m) } -func (*CreateOptions) ProtoMessage() {} -func (*CreateOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{2} -} - -func (m *CreateOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateOptions.Unmarshal(m, b) -} -func (m *CreateOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateOptions.Marshal(b, m, deterministic) -} -func (m *CreateOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateOptions.Merge(m, src) -} -func (m *CreateOptions) XXX_Size() int { - return xxx_messageInfo_CreateOptions.Size(m) -} -func (m *CreateOptions) XXX_DiscardUnknown() { - xxx_messageInfo_CreateOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateOptions proto.InternalMessageInfo - -func (m *CreateOptions) GetCommand() []string { - if m != nil { - return m.Command - } - return nil -} - -func (m *CreateOptions) GetArgs() []string { - if m != nil { - return m.Args - } - return nil -} - -func (m *CreateOptions) GetEnv() []string { - if m != nil { - return m.Env - } - return nil -} - -func (m *CreateOptions) GetOutput() string { - if m != nil { - return m.Output - } - return "" -} - -func (m *CreateOptions) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *CreateOptions) GetImage() string { - if m != nil { - return m.Image - } - return "" -} - -func (m *CreateOptions) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -type CreateRequest struct { - Service *Service `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - Options *CreateOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateRequest) Reset() { *m = CreateRequest{} } -func (m *CreateRequest) String() string { return proto.CompactTextString(m) } -func (*CreateRequest) ProtoMessage() {} -func (*CreateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{3} -} - -func (m *CreateRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateRequest.Unmarshal(m, b) -} -func (m *CreateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateRequest.Marshal(b, m, deterministic) -} -func (m *CreateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateRequest.Merge(m, src) -} -func (m *CreateRequest) XXX_Size() int { - return xxx_messageInfo_CreateRequest.Size(m) -} -func (m *CreateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_CreateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateRequest proto.InternalMessageInfo - -func (m *CreateRequest) GetService() *Service { - if m != nil { - return m.Service - } - return nil -} - -func (m *CreateRequest) GetOptions() *CreateOptions { - if m != nil { - return m.Options - } - return nil -} - -type CreateResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateResponse) Reset() { *m = CreateResponse{} } -func (m *CreateResponse) String() string { return proto.CompactTextString(m) } -func (*CreateResponse) ProtoMessage() {} -func (*CreateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{4} -} - -func (m *CreateResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateResponse.Unmarshal(m, b) -} -func (m *CreateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateResponse.Marshal(b, m, deterministic) -} -func (m *CreateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateResponse.Merge(m, src) -} -func (m *CreateResponse) XXX_Size() int { - return xxx_messageInfo_CreateResponse.Size(m) -} -func (m *CreateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CreateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateResponse proto.InternalMessageInfo - -type ReadOptions struct { - // service name - Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - // version of the service - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` - // type of service - Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` - // namespace of the service - Namespace string `protobuf:"bytes,4,opt,name=namespace,proto3" json:"namespace,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadOptions) Reset() { *m = ReadOptions{} } -func (m *ReadOptions) String() string { return proto.CompactTextString(m) } -func (*ReadOptions) ProtoMessage() {} -func (*ReadOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{5} -} - -func (m *ReadOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadOptions.Unmarshal(m, b) -} -func (m *ReadOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadOptions.Marshal(b, m, deterministic) -} -func (m *ReadOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadOptions.Merge(m, src) -} -func (m *ReadOptions) XXX_Size() int { - return xxx_messageInfo_ReadOptions.Size(m) -} -func (m *ReadOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ReadOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadOptions proto.InternalMessageInfo - -func (m *ReadOptions) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -func (m *ReadOptions) GetVersion() string { - if m != nil { - return m.Version - } - return "" -} - -func (m *ReadOptions) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *ReadOptions) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -type ReadRequest struct { - Options *ReadOptions `protobuf:"bytes,1,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadRequest) Reset() { *m = ReadRequest{} } -func (m *ReadRequest) String() string { return proto.CompactTextString(m) } -func (*ReadRequest) ProtoMessage() {} -func (*ReadRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{6} -} - -func (m *ReadRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadRequest.Unmarshal(m, b) -} -func (m *ReadRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadRequest.Marshal(b, m, deterministic) -} -func (m *ReadRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadRequest.Merge(m, src) -} -func (m *ReadRequest) XXX_Size() int { - return xxx_messageInfo_ReadRequest.Size(m) -} -func (m *ReadRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ReadRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadRequest proto.InternalMessageInfo - -func (m *ReadRequest) GetOptions() *ReadOptions { - if m != nil { - return m.Options - } - return nil -} - -type ReadResponse struct { - Services []*Service `protobuf:"bytes,1,rep,name=services,proto3" json:"services,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadResponse) Reset() { *m = ReadResponse{} } -func (m *ReadResponse) String() string { return proto.CompactTextString(m) } -func (*ReadResponse) ProtoMessage() {} -func (*ReadResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{7} -} - -func (m *ReadResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadResponse.Unmarshal(m, b) -} -func (m *ReadResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadResponse.Marshal(b, m, deterministic) -} -func (m *ReadResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadResponse.Merge(m, src) -} -func (m *ReadResponse) XXX_Size() int { - return xxx_messageInfo_ReadResponse.Size(m) -} -func (m *ReadResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ReadResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadResponse proto.InternalMessageInfo - -func (m *ReadResponse) GetServices() []*Service { - if m != nil { - return m.Services - } - return nil -} - -type DeleteOptions struct { - // namespace of the service - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteOptions) Reset() { *m = DeleteOptions{} } -func (m *DeleteOptions) String() string { return proto.CompactTextString(m) } -func (*DeleteOptions) ProtoMessage() {} -func (*DeleteOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{8} -} - -func (m *DeleteOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteOptions.Unmarshal(m, b) -} -func (m *DeleteOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteOptions.Marshal(b, m, deterministic) -} -func (m *DeleteOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteOptions.Merge(m, src) -} -func (m *DeleteOptions) XXX_Size() int { - return xxx_messageInfo_DeleteOptions.Size(m) -} -func (m *DeleteOptions) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteOptions proto.InternalMessageInfo - -func (m *DeleteOptions) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -type DeleteRequest struct { - Service *Service `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - Options *DeleteOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteRequest) Reset() { *m = DeleteRequest{} } -func (m *DeleteRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteRequest) ProtoMessage() {} -func (*DeleteRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{9} -} - -func (m *DeleteRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteRequest.Unmarshal(m, b) -} -func (m *DeleteRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteRequest.Marshal(b, m, deterministic) -} -func (m *DeleteRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteRequest.Merge(m, src) -} -func (m *DeleteRequest) XXX_Size() int { - return xxx_messageInfo_DeleteRequest.Size(m) -} -func (m *DeleteRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteRequest proto.InternalMessageInfo - -func (m *DeleteRequest) GetService() *Service { - if m != nil { - return m.Service - } - return nil -} - -func (m *DeleteRequest) GetOptions() *DeleteOptions { - if m != nil { - return m.Options - } - return nil -} - -type DeleteResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteResponse) Reset() { *m = DeleteResponse{} } -func (m *DeleteResponse) String() string { return proto.CompactTextString(m) } -func (*DeleteResponse) ProtoMessage() {} -func (*DeleteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{10} -} - -func (m *DeleteResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteResponse.Unmarshal(m, b) -} -func (m *DeleteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteResponse.Marshal(b, m, deterministic) -} -func (m *DeleteResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteResponse.Merge(m, src) -} -func (m *DeleteResponse) XXX_Size() int { - return xxx_messageInfo_DeleteResponse.Size(m) -} -func (m *DeleteResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteResponse proto.InternalMessageInfo - -type UpdateOptions struct { - // namespace of the service - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpdateOptions) Reset() { *m = UpdateOptions{} } -func (m *UpdateOptions) String() string { return proto.CompactTextString(m) } -func (*UpdateOptions) ProtoMessage() {} -func (*UpdateOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{11} -} - -func (m *UpdateOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpdateOptions.Unmarshal(m, b) -} -func (m *UpdateOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpdateOptions.Marshal(b, m, deterministic) -} -func (m *UpdateOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateOptions.Merge(m, src) -} -func (m *UpdateOptions) XXX_Size() int { - return xxx_messageInfo_UpdateOptions.Size(m) -} -func (m *UpdateOptions) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateOptions proto.InternalMessageInfo - -func (m *UpdateOptions) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -type UpdateRequest struct { - Service *Service `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - Options *UpdateOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpdateRequest) Reset() { *m = UpdateRequest{} } -func (m *UpdateRequest) String() string { return proto.CompactTextString(m) } -func (*UpdateRequest) ProtoMessage() {} -func (*UpdateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{12} -} - -func (m *UpdateRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpdateRequest.Unmarshal(m, b) -} -func (m *UpdateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpdateRequest.Marshal(b, m, deterministic) -} -func (m *UpdateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateRequest.Merge(m, src) -} -func (m *UpdateRequest) XXX_Size() int { - return xxx_messageInfo_UpdateRequest.Size(m) -} -func (m *UpdateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateRequest proto.InternalMessageInfo - -func (m *UpdateRequest) GetService() *Service { - if m != nil { - return m.Service - } - return nil -} - -func (m *UpdateRequest) GetOptions() *UpdateOptions { - if m != nil { - return m.Options - } - return nil -} - -type UpdateResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpdateResponse) Reset() { *m = UpdateResponse{} } -func (m *UpdateResponse) String() string { return proto.CompactTextString(m) } -func (*UpdateResponse) ProtoMessage() {} -func (*UpdateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{13} -} - -func (m *UpdateResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpdateResponse.Unmarshal(m, b) -} -func (m *UpdateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpdateResponse.Marshal(b, m, deterministic) -} -func (m *UpdateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateResponse.Merge(m, src) -} -func (m *UpdateResponse) XXX_Size() int { - return xxx_messageInfo_UpdateResponse.Size(m) -} -func (m *UpdateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateResponse proto.InternalMessageInfo - -type ListOptions struct { - // namespace of the service - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListOptions) Reset() { *m = ListOptions{} } -func (m *ListOptions) String() string { return proto.CompactTextString(m) } -func (*ListOptions) ProtoMessage() {} -func (*ListOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{14} -} - -func (m *ListOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListOptions.Unmarshal(m, b) -} -func (m *ListOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListOptions.Marshal(b, m, deterministic) -} -func (m *ListOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListOptions.Merge(m, src) -} -func (m *ListOptions) XXX_Size() int { - return xxx_messageInfo_ListOptions.Size(m) -} -func (m *ListOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ListOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ListOptions proto.InternalMessageInfo - -func (m *ListOptions) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -type ListRequest struct { - Options *ListOptions `protobuf:"bytes,1,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListRequest) Reset() { *m = ListRequest{} } -func (m *ListRequest) String() string { return proto.CompactTextString(m) } -func (*ListRequest) ProtoMessage() {} -func (*ListRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{15} -} - -func (m *ListRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListRequest.Unmarshal(m, b) -} -func (m *ListRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListRequest.Marshal(b, m, deterministic) -} -func (m *ListRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListRequest.Merge(m, src) -} -func (m *ListRequest) XXX_Size() int { - return xxx_messageInfo_ListRequest.Size(m) -} -func (m *ListRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListRequest proto.InternalMessageInfo - -func (m *ListRequest) GetOptions() *ListOptions { - if m != nil { - return m.Options - } - return nil -} - -type ListResponse struct { - Services []*Service `protobuf:"bytes,1,rep,name=services,proto3" json:"services,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListResponse) Reset() { *m = ListResponse{} } -func (m *ListResponse) String() string { return proto.CompactTextString(m) } -func (*ListResponse) ProtoMessage() {} -func (*ListResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{16} -} - -func (m *ListResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListResponse.Unmarshal(m, b) -} -func (m *ListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListResponse.Marshal(b, m, deterministic) -} -func (m *ListResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListResponse.Merge(m, src) -} -func (m *ListResponse) XXX_Size() int { - return xxx_messageInfo_ListResponse.Size(m) -} -func (m *ListResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListResponse proto.InternalMessageInfo - -func (m *ListResponse) GetServices() []*Service { - if m != nil { - return m.Services - } - return nil -} - -type LogsOptions struct { - // namespace of the service - Namespace string `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LogsOptions) Reset() { *m = LogsOptions{} } -func (m *LogsOptions) String() string { return proto.CompactTextString(m) } -func (*LogsOptions) ProtoMessage() {} -func (*LogsOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{17} -} - -func (m *LogsOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LogsOptions.Unmarshal(m, b) -} -func (m *LogsOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LogsOptions.Marshal(b, m, deterministic) -} -func (m *LogsOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_LogsOptions.Merge(m, src) -} -func (m *LogsOptions) XXX_Size() int { - return xxx_messageInfo_LogsOptions.Size(m) -} -func (m *LogsOptions) XXX_DiscardUnknown() { - xxx_messageInfo_LogsOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_LogsOptions proto.InternalMessageInfo - -func (m *LogsOptions) GetNamespace() string { - if m != nil { - return m.Namespace - } - return "" -} - -type LogsRequest struct { - // service to request logs for - Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - // stream records continuously - Stream bool `protobuf:"varint,2,opt,name=stream,proto3" json:"stream,omitempty"` - // count of records to request - Count int64 `protobuf:"varint,3,opt,name=count,proto3" json:"count,omitempty"` - // relative time in seconds - // before the current time - // from which to show logs - Since int64 `protobuf:"varint,4,opt,name=since,proto3" json:"since,omitempty"` - // options to use - Options *LogsOptions `protobuf:"bytes,5,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LogsRequest) Reset() { *m = LogsRequest{} } -func (m *LogsRequest) String() string { return proto.CompactTextString(m) } -func (*LogsRequest) ProtoMessage() {} -func (*LogsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{18} -} - -func (m *LogsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LogsRequest.Unmarshal(m, b) -} -func (m *LogsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LogsRequest.Marshal(b, m, deterministic) -} -func (m *LogsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_LogsRequest.Merge(m, src) -} -func (m *LogsRequest) XXX_Size() int { - return xxx_messageInfo_LogsRequest.Size(m) -} -func (m *LogsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_LogsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_LogsRequest proto.InternalMessageInfo - -func (m *LogsRequest) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -func (m *LogsRequest) GetStream() bool { - if m != nil { - return m.Stream - } - return false -} - -func (m *LogsRequest) GetCount() int64 { - if m != nil { - return m.Count - } - return 0 -} - -func (m *LogsRequest) GetSince() int64 { - if m != nil { - return m.Since - } - return 0 -} - -func (m *LogsRequest) GetOptions() *LogsOptions { - if m != nil { - return m.Options - } - return nil -} - -type LogRecord struct { - // timestamp of log record - Timestamp int64 `protobuf:"varint,1,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - // record metadata - Metadata map[string]string `protobuf:"bytes,2,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // message - Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LogRecord) Reset() { *m = LogRecord{} } -func (m *LogRecord) String() string { return proto.CompactTextString(m) } -func (*LogRecord) ProtoMessage() {} -func (*LogRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_2434d8152598889b, []int{19} -} - -func (m *LogRecord) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LogRecord.Unmarshal(m, b) -} -func (m *LogRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LogRecord.Marshal(b, m, deterministic) -} -func (m *LogRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_LogRecord.Merge(m, src) -} -func (m *LogRecord) XXX_Size() int { - return xxx_messageInfo_LogRecord.Size(m) -} -func (m *LogRecord) XXX_DiscardUnknown() { - xxx_messageInfo_LogRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_LogRecord proto.InternalMessageInfo - -func (m *LogRecord) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -func (m *LogRecord) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *LogRecord) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func init() { - proto.RegisterType((*Service)(nil), "go.micro.runtime.Service") - proto.RegisterMapType((map[string]string)(nil), "go.micro.runtime.Service.MetadataEntry") - proto.RegisterType((*Event)(nil), "go.micro.runtime.Event") - proto.RegisterType((*CreateOptions)(nil), "go.micro.runtime.CreateOptions") - proto.RegisterType((*CreateRequest)(nil), "go.micro.runtime.CreateRequest") - proto.RegisterType((*CreateResponse)(nil), "go.micro.runtime.CreateResponse") - proto.RegisterType((*ReadOptions)(nil), "go.micro.runtime.ReadOptions") - proto.RegisterType((*ReadRequest)(nil), "go.micro.runtime.ReadRequest") - proto.RegisterType((*ReadResponse)(nil), "go.micro.runtime.ReadResponse") - proto.RegisterType((*DeleteOptions)(nil), "go.micro.runtime.DeleteOptions") - proto.RegisterType((*DeleteRequest)(nil), "go.micro.runtime.DeleteRequest") - proto.RegisterType((*DeleteResponse)(nil), "go.micro.runtime.DeleteResponse") - proto.RegisterType((*UpdateOptions)(nil), "go.micro.runtime.UpdateOptions") - proto.RegisterType((*UpdateRequest)(nil), "go.micro.runtime.UpdateRequest") - proto.RegisterType((*UpdateResponse)(nil), "go.micro.runtime.UpdateResponse") - proto.RegisterType((*ListOptions)(nil), "go.micro.runtime.ListOptions") - proto.RegisterType((*ListRequest)(nil), "go.micro.runtime.ListRequest") - proto.RegisterType((*ListResponse)(nil), "go.micro.runtime.ListResponse") - proto.RegisterType((*LogsOptions)(nil), "go.micro.runtime.LogsOptions") - proto.RegisterType((*LogsRequest)(nil), "go.micro.runtime.LogsRequest") - proto.RegisterType((*LogRecord)(nil), "go.micro.runtime.LogRecord") - proto.RegisterMapType((map[string]string)(nil), "go.micro.runtime.LogRecord.MetadataEntry") -} - -func init() { - proto.RegisterFile("runtime/service/proto/runtime.proto", fileDescriptor_2434d8152598889b) -} - -var fileDescriptor_2434d8152598889b = []byte{ - // 711 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0x4d, 0x6f, 0xd3, 0x4c, - 0x10, 0xae, 0x63, 0x27, 0x69, 0x27, 0x6f, 0x5e, 0x55, 0xab, 0x0a, 0x99, 0xf2, 0x15, 0x99, 0x03, - 0x45, 0xa8, 0x2e, 0x4a, 0x85, 0xf8, 0x3a, 0x96, 0x94, 0x4b, 0x2b, 0x24, 0x23, 0x7e, 0xc0, 0xe2, - 0x8c, 0x22, 0x8b, 0xda, 0x6b, 0xbc, 0xeb, 0x48, 0x3d, 0x71, 0xe4, 0x8f, 0x70, 0xe7, 0x67, 0x70, - 0xe6, 0x1f, 0xa1, 0xfd, 0x8a, 0x3f, 0x1a, 0x47, 0xad, 0xaa, 0xde, 0x76, 0xc6, 0xb3, 0xb3, 0xcf, - 0xf3, 0xcc, 0xec, 0xac, 0xe1, 0x69, 0x51, 0x66, 0x22, 0x49, 0xf1, 0x88, 0x63, 0xb1, 0x4c, 0x62, - 0x3c, 0xca, 0x0b, 0x26, 0xd8, 0x91, 0xf1, 0x86, 0xca, 0x22, 0xbb, 0x0b, 0x16, 0xa6, 0x49, 0x5c, - 0xb0, 0xd0, 0xf8, 0x83, 0xbf, 0x0e, 0x0c, 0x3f, 0xeb, 0x1d, 0x84, 0x80, 0x97, 0xd1, 0x14, 0x7d, - 0x67, 0xe2, 0x1c, 0xec, 0x44, 0x6a, 0x4d, 0x7c, 0x18, 0x2e, 0xb1, 0xe0, 0x09, 0xcb, 0xfc, 0x9e, - 0x72, 0x5b, 0x93, 0xdc, 0x83, 0x01, 0x67, 0x65, 0x11, 0xa3, 0xef, 0xaa, 0x0f, 0xc6, 0x22, 0x27, - 0xb0, 0x9d, 0xa2, 0xa0, 0x73, 0x2a, 0xa8, 0xef, 0x4d, 0xdc, 0x83, 0xd1, 0xf4, 0x59, 0xd8, 0x3e, - 0x36, 0x34, 0x47, 0x86, 0xe7, 0x26, 0x72, 0x96, 0x89, 0xe2, 0x32, 0x5a, 0x6d, 0xdc, 0x7f, 0x0f, - 0xe3, 0xc6, 0x27, 0xb2, 0x0b, 0xee, 0x37, 0xbc, 0x34, 0xd0, 0xe4, 0x92, 0xec, 0x41, 0x7f, 0x49, - 0x2f, 0x4a, 0x34, 0xb8, 0xb4, 0xf1, 0xae, 0xf7, 0xc6, 0x09, 0x52, 0xe8, 0xcf, 0x96, 0x98, 0x09, - 0x49, 0x48, 0x5c, 0xe6, 0x2b, 0x42, 0x72, 0x4d, 0x1e, 0xc2, 0x8e, 0x44, 0xc0, 0x05, 0x4d, 0x73, - 0xb5, 0xd5, 0x8d, 0x2a, 0x87, 0xa4, 0x6b, 0xf4, 0x33, 0xac, 0xac, 0x59, 0x17, 0xc2, 0x6b, 0x08, - 0x11, 0xfc, 0x76, 0x60, 0x7c, 0x52, 0x20, 0x15, 0xf8, 0x29, 0x17, 0x09, 0xcb, 0xb8, 0x8c, 0x8d, - 0x59, 0x9a, 0xd2, 0x6c, 0xee, 0x3b, 0x13, 0x57, 0xc6, 0x1a, 0x53, 0x22, 0xa2, 0xc5, 0x82, 0xfb, - 0x3d, 0xe5, 0x56, 0x6b, 0x49, 0x0d, 0xb3, 0xa5, 0xef, 0x2a, 0x97, 0x5c, 0x4a, 0x69, 0x59, 0x29, - 0xf2, 0x52, 0x98, 0xa3, 0x8c, 0xb5, 0xe2, 0xd3, 0xaf, 0xf1, 0xd9, 0x83, 0x7e, 0x92, 0xd2, 0x05, - 0xfa, 0x03, 0x2d, 0x83, 0x32, 0x24, 0x4b, 0x59, 0x3e, 0x9e, 0xd3, 0x18, 0xfd, 0xa1, 0xfa, 0x52, - 0x39, 0x82, 0x1f, 0x16, 0x70, 0x84, 0xdf, 0x4b, 0xe4, 0x82, 0x1c, 0x57, 0xb4, 0xa5, 0x56, 0xa3, - 0xe9, 0xfd, 0xce, 0x92, 0x55, 0x8a, 0xbc, 0x85, 0x21, 0xd3, 0x84, 0x95, 0x8e, 0xa3, 0xe9, 0x93, - 0xab, 0x9b, 0x1a, 0xba, 0x44, 0x36, 0x3e, 0xd8, 0x85, 0xff, 0x2d, 0x00, 0x9e, 0xb3, 0x8c, 0x63, - 0xc0, 0x61, 0x14, 0x21, 0x9d, 0xd7, 0x14, 0xac, 0x03, 0x5a, 0x5f, 0x87, 0x56, 0x43, 0x5a, 0x75, - 0xdc, 0x66, 0xb5, 0x2b, 0x1d, 0xbc, 0xb6, 0x0e, 0xa7, 0xfa, 0x50, 0xab, 0xc2, 0xeb, 0x8a, 0x90, - 0x56, 0xe1, 0xd1, 0x55, 0x42, 0x35, 0x90, 0x15, 0x9d, 0x19, 0xfc, 0xa7, 0xf3, 0x68, 0x32, 0xe4, - 0x15, 0x6c, 0x1b, 0xb8, 0x5c, 0x35, 0xc0, 0x46, 0x3d, 0x57, 0xa1, 0xc1, 0x21, 0x8c, 0x3f, 0xe0, - 0x05, 0x56, 0x7d, 0xd4, 0x40, 0xef, 0xac, 0xa9, 0xa2, 0x0e, 0xbf, 0xf3, 0x2a, 0x36, 0x50, 0x35, - 0xaa, 0x68, 0x01, 0x98, 0x2a, 0x1e, 0xc2, 0xf8, 0x4b, 0x3e, 0xa7, 0x37, 0x60, 0xa0, 0xc3, 0xef, - 0x9c, 0x41, 0x03, 0x55, 0x83, 0x81, 0x05, 0x60, 0x18, 0xbc, 0x80, 0xd1, 0x59, 0xc2, 0xc5, 0xf5, - 0xf0, 0x9f, 0xea, 0xe0, 0x9b, 0xf4, 0x4f, 0x2d, 0x79, 0xa3, 0x7f, 0x74, 0x9e, 0xdb, 0xf5, 0x8f, - 0xc4, 0xce, 0x16, 0xfc, 0x7a, 0xd8, 0x7f, 0x39, 0x3a, 0xda, 0x82, 0xef, 0xbe, 0x71, 0x72, 0xd0, - 0x8b, 0x02, 0x69, 0xaa, 0xe4, 0xdd, 0x8e, 0x8c, 0x25, 0x27, 0x4f, 0xcc, 0xca, 0x4c, 0xa8, 0x0b, - 0xe7, 0x46, 0xda, 0x90, 0x5e, 0x9e, 0x64, 0xe6, 0xb6, 0xb9, 0x91, 0x36, 0xea, 0xd2, 0xf4, 0x3b, - 0xa5, 0xa9, 0xb0, 0x57, 0xd2, 0xfc, 0x71, 0x60, 0xe7, 0x8c, 0x2d, 0x22, 0x8c, 0x59, 0x31, 0x6f, - 0x0e, 0x6f, 0xa7, 0x3d, 0xbc, 0x67, 0xb5, 0x97, 0xa7, 0xa7, 0x64, 0x7b, 0xbe, 0xf6, 0x14, 0x9d, - 0xac, 0xeb, 0xed, 0x91, 0x4a, 0xa4, 0xc8, 0xb9, 0x9c, 0xa9, 0xe6, 0x0d, 0x30, 0xe6, 0xad, 0x5e, - 0xa5, 0xe9, 0x4f, 0x17, 0x86, 0x91, 0x06, 0x41, 0xce, 0x61, 0xa0, 0xe7, 0x1f, 0xe9, 0x9c, 0x99, - 0xa6, 0x2e, 0xfb, 0x93, 0xee, 0x00, 0xd3, 0xb2, 0x5b, 0xe4, 0x23, 0x78, 0x72, 0xfe, 0x90, 0x8e, - 0x79, 0x65, 0x53, 0x3d, 0xee, 0xfa, 0xbc, 0x4a, 0x74, 0x0e, 0x03, 0x7d, 0xa3, 0x49, 0xe7, 0x14, - 0xd8, 0x80, 0xab, 0x35, 0x0c, 0x54, 0x3a, 0x7d, 0xbd, 0x48, 0xe7, 0x95, 0xdc, 0x90, 0xae, 0x75, - 0x33, 0xb7, 0xc8, 0x29, 0x78, 0xb2, 0x47, 0x48, 0x47, 0xef, 0xd8, 0x54, 0x0f, 0x36, 0x14, 0x3d, - 0xd8, 0x7a, 0xe9, 0x7c, 0x1d, 0xa8, 0x9f, 0xa1, 0xe3, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x8e, - 0x6c, 0x03, 0x59, 0x33, 0x09, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// RuntimeClient is the client API for Runtime service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type RuntimeClient interface { - Create(ctx context.Context, in *CreateRequest, opts ...grpc.CallOption) (*CreateResponse, error) - Read(ctx context.Context, in *ReadRequest, opts ...grpc.CallOption) (*ReadResponse, error) - Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) - Update(ctx context.Context, in *UpdateRequest, opts ...grpc.CallOption) (*UpdateResponse, error) - Logs(ctx context.Context, in *LogsRequest, opts ...grpc.CallOption) (Runtime_LogsClient, error) -} - -type runtimeClient struct { - cc *grpc.ClientConn -} - -func NewRuntimeClient(cc *grpc.ClientConn) RuntimeClient { - return &runtimeClient{cc} -} - -func (c *runtimeClient) Create(ctx context.Context, in *CreateRequest, opts ...grpc.CallOption) (*CreateResponse, error) { - out := new(CreateResponse) - err := c.cc.Invoke(ctx, "/go.micro.runtime.Runtime/Create", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *runtimeClient) Read(ctx context.Context, in *ReadRequest, opts ...grpc.CallOption) (*ReadResponse, error) { - out := new(ReadResponse) - err := c.cc.Invoke(ctx, "/go.micro.runtime.Runtime/Read", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *runtimeClient) Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) { - out := new(DeleteResponse) - err := c.cc.Invoke(ctx, "/go.micro.runtime.Runtime/Delete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *runtimeClient) Update(ctx context.Context, in *UpdateRequest, opts ...grpc.CallOption) (*UpdateResponse, error) { - out := new(UpdateResponse) - err := c.cc.Invoke(ctx, "/go.micro.runtime.Runtime/Update", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *runtimeClient) Logs(ctx context.Context, in *LogsRequest, opts ...grpc.CallOption) (Runtime_LogsClient, error) { - stream, err := c.cc.NewStream(ctx, &_Runtime_serviceDesc.Streams[0], "/go.micro.runtime.Runtime/Logs", opts...) - if err != nil { - return nil, err - } - x := &runtimeLogsClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Runtime_LogsClient interface { - Recv() (*LogRecord, error) - grpc.ClientStream -} - -type runtimeLogsClient struct { - grpc.ClientStream -} - -func (x *runtimeLogsClient) Recv() (*LogRecord, error) { - m := new(LogRecord) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// RuntimeServer is the server API for Runtime service. -type RuntimeServer interface { - Create(context.Context, *CreateRequest) (*CreateResponse, error) - Read(context.Context, *ReadRequest) (*ReadResponse, error) - Delete(context.Context, *DeleteRequest) (*DeleteResponse, error) - Update(context.Context, *UpdateRequest) (*UpdateResponse, error) - Logs(*LogsRequest, Runtime_LogsServer) error -} - -// UnimplementedRuntimeServer can be embedded to have forward compatible implementations. -type UnimplementedRuntimeServer struct { -} - -func (*UnimplementedRuntimeServer) Create(ctx context.Context, req *CreateRequest) (*CreateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Create not implemented") -} -func (*UnimplementedRuntimeServer) Read(ctx context.Context, req *ReadRequest) (*ReadResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Read not implemented") -} -func (*UnimplementedRuntimeServer) Delete(ctx context.Context, req *DeleteRequest) (*DeleteResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") -} -func (*UnimplementedRuntimeServer) Update(ctx context.Context, req *UpdateRequest) (*UpdateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Update not implemented") -} -func (*UnimplementedRuntimeServer) Logs(req *LogsRequest, srv Runtime_LogsServer) error { - return status.Errorf(codes.Unimplemented, "method Logs not implemented") -} - -func RegisterRuntimeServer(s *grpc.Server, srv RuntimeServer) { - s.RegisterService(&_Runtime_serviceDesc, srv) -} - -func _Runtime_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CreateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RuntimeServer).Create(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.runtime.Runtime/Create", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RuntimeServer).Create(ctx, req.(*CreateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Runtime_Read_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ReadRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RuntimeServer).Read(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.runtime.Runtime/Read", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RuntimeServer).Read(ctx, req.(*ReadRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Runtime_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RuntimeServer).Delete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.runtime.Runtime/Delete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RuntimeServer).Delete(ctx, req.(*DeleteRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Runtime_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpdateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RuntimeServer).Update(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.runtime.Runtime/Update", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RuntimeServer).Update(ctx, req.(*UpdateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Runtime_Logs_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(LogsRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(RuntimeServer).Logs(m, &runtimeLogsServer{stream}) -} - -type Runtime_LogsServer interface { - Send(*LogRecord) error - grpc.ServerStream -} - -type runtimeLogsServer struct { - grpc.ServerStream -} - -func (x *runtimeLogsServer) Send(m *LogRecord) error { - return x.ServerStream.SendMsg(m) -} - -var _Runtime_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.runtime.Runtime", - HandlerType: (*RuntimeServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Create", - Handler: _Runtime_Create_Handler, - }, - { - MethodName: "Read", - Handler: _Runtime_Read_Handler, - }, - { - MethodName: "Delete", - Handler: _Runtime_Delete_Handler, - }, - { - MethodName: "Update", - Handler: _Runtime_Update_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Logs", - Handler: _Runtime_Logs_Handler, - ServerStreams: true, - }, - }, - Metadata: "runtime/service/proto/runtime.proto", -} diff --git a/runtime/service/proto/runtime.pb.micro.go b/runtime/service/proto/runtime.pb.micro.go deleted file mode 100644 index 73b7c3ca..00000000 --- a/runtime/service/proto/runtime.pb.micro.go +++ /dev/null @@ -1,236 +0,0 @@ -// Code generated by protoc-gen-micro. DO NOT EDIT. -// source: runtime/service/proto/runtime.proto - -package go_micro_runtime - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -import ( - context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ api.Endpoint -var _ context.Context -var _ client.Option -var _ server.Option - -// Api Endpoints for Runtime service - -func NewRuntimeEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Runtime service - -type RuntimeService interface { - Create(ctx context.Context, in *CreateRequest, opts ...client.CallOption) (*CreateResponse, error) - Read(ctx context.Context, in *ReadRequest, opts ...client.CallOption) (*ReadResponse, error) - Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) - Update(ctx context.Context, in *UpdateRequest, opts ...client.CallOption) (*UpdateResponse, error) - Logs(ctx context.Context, in *LogsRequest, opts ...client.CallOption) (Runtime_LogsService, error) -} - -type runtimeService struct { - c client.Client - name string -} - -func NewRuntimeService(name string, c client.Client) RuntimeService { - return &runtimeService{ - c: c, - name: name, - } -} - -func (c *runtimeService) Create(ctx context.Context, in *CreateRequest, opts ...client.CallOption) (*CreateResponse, error) { - req := c.c.NewRequest(c.name, "Runtime.Create", in) - out := new(CreateResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *runtimeService) Read(ctx context.Context, in *ReadRequest, opts ...client.CallOption) (*ReadResponse, error) { - req := c.c.NewRequest(c.name, "Runtime.Read", in) - out := new(ReadResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *runtimeService) Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) { - req := c.c.NewRequest(c.name, "Runtime.Delete", in) - out := new(DeleteResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *runtimeService) Update(ctx context.Context, in *UpdateRequest, opts ...client.CallOption) (*UpdateResponse, error) { - req := c.c.NewRequest(c.name, "Runtime.Update", in) - out := new(UpdateResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *runtimeService) Logs(ctx context.Context, in *LogsRequest, opts ...client.CallOption) (Runtime_LogsService, error) { - req := c.c.NewRequest(c.name, "Runtime.Logs", &LogsRequest{}) - stream, err := c.c.Stream(ctx, req, opts...) - if err != nil { - return nil, err - } - if err := stream.Send(in); err != nil { - return nil, err - } - return &runtimeServiceLogs{stream}, nil -} - -type Runtime_LogsService interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Recv() (*LogRecord, error) -} - -type runtimeServiceLogs struct { - stream client.Stream -} - -func (x *runtimeServiceLogs) Close() error { - return x.stream.Close() -} - -func (x *runtimeServiceLogs) Context() context.Context { - return x.stream.Context() -} - -func (x *runtimeServiceLogs) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *runtimeServiceLogs) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *runtimeServiceLogs) Recv() (*LogRecord, error) { - m := new(LogRecord) - err := x.stream.Recv(m) - if err != nil { - return nil, err - } - return m, nil -} - -// Server API for Runtime service - -type RuntimeHandler interface { - Create(context.Context, *CreateRequest, *CreateResponse) error - Read(context.Context, *ReadRequest, *ReadResponse) error - Delete(context.Context, *DeleteRequest, *DeleteResponse) error - Update(context.Context, *UpdateRequest, *UpdateResponse) error - Logs(context.Context, *LogsRequest, Runtime_LogsStream) error -} - -func RegisterRuntimeHandler(s server.Server, hdlr RuntimeHandler, opts ...server.HandlerOption) error { - type runtime interface { - Create(ctx context.Context, in *CreateRequest, out *CreateResponse) error - Read(ctx context.Context, in *ReadRequest, out *ReadResponse) error - Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error - Update(ctx context.Context, in *UpdateRequest, out *UpdateResponse) error - Logs(ctx context.Context, stream server.Stream) error - } - type Runtime struct { - runtime - } - h := &runtimeHandler{hdlr} - return s.Handle(s.NewHandler(&Runtime{h}, opts...)) -} - -type runtimeHandler struct { - RuntimeHandler -} - -func (h *runtimeHandler) Create(ctx context.Context, in *CreateRequest, out *CreateResponse) error { - return h.RuntimeHandler.Create(ctx, in, out) -} - -func (h *runtimeHandler) Read(ctx context.Context, in *ReadRequest, out *ReadResponse) error { - return h.RuntimeHandler.Read(ctx, in, out) -} - -func (h *runtimeHandler) Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error { - return h.RuntimeHandler.Delete(ctx, in, out) -} - -func (h *runtimeHandler) Update(ctx context.Context, in *UpdateRequest, out *UpdateResponse) error { - return h.RuntimeHandler.Update(ctx, in, out) -} - -func (h *runtimeHandler) Logs(ctx context.Context, stream server.Stream) error { - m := new(LogsRequest) - if err := stream.Recv(m); err != nil { - return err - } - return h.RuntimeHandler.Logs(ctx, m, &runtimeLogsStream{stream}) -} - -type Runtime_LogsStream interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Send(*LogRecord) error -} - -type runtimeLogsStream struct { - stream server.Stream -} - -func (x *runtimeLogsStream) Close() error { - return x.stream.Close() -} - -func (x *runtimeLogsStream) Context() context.Context { - return x.stream.Context() -} - -func (x *runtimeLogsStream) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *runtimeLogsStream) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *runtimeLogsStream) Send(m *LogRecord) error { - return x.stream.Send(m) -} diff --git a/runtime/service/proto/runtime.proto b/runtime/service/proto/runtime.proto deleted file mode 100644 index 2dd472e5..00000000 --- a/runtime/service/proto/runtime.proto +++ /dev/null @@ -1,139 +0,0 @@ -syntax = "proto3"; - -package go.micro.runtime; - -service Runtime { - rpc Create(CreateRequest) returns (CreateResponse) {}; - rpc Read(ReadRequest) returns (ReadResponse) {}; - rpc Delete(DeleteRequest) returns (DeleteResponse) {}; - rpc Update(UpdateRequest) returns (UpdateResponse) {}; - rpc Logs(LogsRequest) returns (stream LogRecord) {}; -} - -message Service { - // name of the service - string name = 1; - // version of the service - string version = 2; - // git url of the source - string source = 3; - // service metadata - map metadata = 4; -} - -message Event { - string type = 1; - int64 timestamp = 2; - string service = 3; - string version = 4; -} - -message CreateOptions { - // command to pass in - repeated string command = 1; - // args to pass into command - repeated string args = 2; - // environment to pass in - repeated string env = 3; - // output to send to - string output = 4; - // create type of service - string type = 5; - // image to use - string image = 6; - // namespace to create the service in - string namespace = 7; -} - -message CreateRequest { - Service service = 1; - CreateOptions options = 2; -} - -message CreateResponse {} - -message ReadOptions { - // service name - string service = 1; - // version of the service - string version = 2; - // type of service - string type = 3; - // namespace of the service - string namespace = 4; -} - -message ReadRequest { - ReadOptions options = 1; -} - -message ReadResponse { - repeated Service services = 1; -} - -message DeleteOptions { - // namespace of the service - string namespace = 1; -} - -message DeleteRequest { - Service service = 1; - DeleteOptions options = 2; -} - -message DeleteResponse {} - -message UpdateOptions { - // namespace of the service - string namespace = 1; -} - -message UpdateRequest { - Service service = 1; - UpdateOptions options = 2; -} - -message UpdateResponse {} - -message ListOptions { - // namespace of the service - string namespace = 1; -} - -message ListRequest { - ListOptions options = 1; -} - -message ListResponse { - repeated Service services = 1; -} - -message LogsOptions { - // namespace of the service - string namespace = 1; -} - -message LogsRequest{ - // service to request logs for - string service = 1; - // stream records continuously - bool stream = 2; - // count of records to request - int64 count = 3; - // relative time in seconds - // before the current time - // from which to show logs - int64 since = 4; - // options to use - LogsOptions options = 5; -} - -message LogRecord { - // timestamp of log record - int64 timestamp = 1; - // record metadata - map metadata = 2; - // message - string message = 3; -} - diff --git a/runtime/service/service.go b/runtime/service/service.go deleted file mode 100644 index 8dc5dc41..00000000 --- a/runtime/service/service.go +++ /dev/null @@ -1,301 +0,0 @@ -package service - -import ( - "context" - "io" - "sync" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/runtime" - pb "github.com/micro/go-micro/v2/runtime/service/proto" -) - -type svc struct { - sync.RWMutex - options runtime.Options - runtime pb.RuntimeService -} - -// Init initializes runtime with given options -func (s *svc) Init(opts ...runtime.Option) error { - s.Lock() - defer s.Unlock() - - for _, o := range opts { - o(&s.options) - } - - // reset the runtime as the client could have changed - s.runtime = pb.NewRuntimeService(runtime.DefaultName, s.options.Client) - - return nil -} - -// Create registers a service in the runtime -func (s *svc) Create(svc *runtime.Service, opts ...runtime.CreateOption) error { - var options runtime.CreateOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.Background() - } - - // set the default source from MICRO_RUNTIME_SOURCE - if len(svc.Source) == 0 { - svc.Source = s.options.Source - } - - // runtime service create request - req := &pb.CreateRequest{ - Service: &pb.Service{ - Name: svc.Name, - Version: svc.Version, - Source: svc.Source, - Metadata: svc.Metadata, - }, - Options: &pb.CreateOptions{ - Command: options.Command, - Args: options.Args, - Env: options.Env, - Type: options.Type, - Image: options.Image, - Namespace: options.Namespace, - }, - } - - if _, err := s.runtime.Create(options.Context, req); err != nil { - return err - } - - return nil -} - -func (s *svc) Logs(service *runtime.Service, opts ...runtime.LogsOption) (runtime.LogStream, error) { - var options runtime.LogsOptions - for _, o := range opts { - o(&options) - } - - if options.Context == nil { - options.Context = context.Background() - } - - ls, err := s.runtime.Logs(options.Context, &pb.LogsRequest{ - Service: service.Name, - Stream: options.Stream, - Count: options.Count, - Options: &pb.LogsOptions{ - Namespace: options.Namespace, - }, - }) - if err != nil { - return nil, err - } - logStream := &serviceLogStream{ - service: service.Name, - stream: make(chan runtime.LogRecord), - stop: make(chan bool), - } - - go func() { - for { - select { - // @todo this never seems to return, investigate - case <-ls.Context().Done(): - logStream.Stop() - } - } - }() - - go func() { - for { - select { - // @todo this never seems to return, investigate - case <-ls.Context().Done(): - return - case _, ok := <-logStream.stream: - if !ok { - return - } - default: - record := pb.LogRecord{} - err := ls.RecvMsg(&record) - if err != nil { - if err != io.EOF { - logStream.err = err - } - logStream.Stop() - return - } - logStream.stream <- runtime.LogRecord{ - Message: record.GetMessage(), - Metadata: record.GetMetadata(), - } - } - } - }() - return logStream, nil -} - -type serviceLogStream struct { - service string - stream chan runtime.LogRecord - sync.Mutex - stop chan bool - err error -} - -func (l *serviceLogStream) Error() error { - return l.err -} - -func (l *serviceLogStream) Chan() chan runtime.LogRecord { - return l.stream -} - -func (l *serviceLogStream) Stop() error { - l.Lock() - defer l.Unlock() - select { - case <-l.stop: - return nil - default: - close(l.stream) - close(l.stop) - } - return nil -} - -// Read returns the service with the given name from the runtime -func (s *svc) Read(opts ...runtime.ReadOption) ([]*runtime.Service, error) { - var options runtime.ReadOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.Background() - } - - // runtime service create request - req := &pb.ReadRequest{ - Options: &pb.ReadOptions{ - Service: options.Service, - Version: options.Version, - Type: options.Type, - Namespace: options.Namespace, - }, - } - - resp, err := s.runtime.Read(options.Context, req) - if err != nil { - return nil, err - } - - services := make([]*runtime.Service, 0, len(resp.Services)) - for _, service := range resp.Services { - svc := &runtime.Service{ - Name: service.Name, - Version: service.Version, - Source: service.Source, - Metadata: service.Metadata, - } - services = append(services, svc) - } - - return services, nil -} - -// Update updates the running service -func (s *svc) Update(svc *runtime.Service, opts ...runtime.UpdateOption) error { - var options runtime.UpdateOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.Background() - } - - // runtime service create request - req := &pb.UpdateRequest{ - Service: &pb.Service{ - Name: svc.Name, - Version: svc.Version, - Source: svc.Source, - Metadata: svc.Metadata, - }, - Options: &pb.UpdateOptions{ - Namespace: options.Namespace, - }, - } - - if _, err := s.runtime.Update(options.Context, req); err != nil { - return err - } - - return nil -} - -// Delete stops and removes the service from the runtime -func (s *svc) Delete(svc *runtime.Service, opts ...runtime.DeleteOption) error { - var options runtime.DeleteOptions - for _, o := range opts { - o(&options) - } - if options.Context == nil { - options.Context = context.Background() - } - - // runtime service create request - req := &pb.DeleteRequest{ - Service: &pb.Service{ - Name: svc.Name, - Version: svc.Version, - Source: svc.Source, - Metadata: svc.Metadata, - }, - Options: &pb.DeleteOptions{ - Namespace: options.Namespace, - }, - } - - if _, err := s.runtime.Delete(options.Context, req); err != nil { - return err - } - - return nil -} - -// Start starts the runtime -func (s *svc) Start() error { - // NOTE: nothing to be done here - return nil -} - -// Stop stops the runtime -func (s *svc) Stop() error { - // NOTE: nothing to be done here - return nil -} - -// Returns the runtime service implementation -func (s *svc) String() string { - return "service" -} - -// NewRuntime creates new service runtime and returns it -func NewRuntime(opts ...runtime.Option) runtime.Runtime { - var options runtime.Options - - for _, o := range opts { - o(&options) - } - if options.Client == nil { - options.Client = client.DefaultClient - } - - return &svc{ - options: options, - runtime: pb.NewRuntimeService(runtime.DefaultName, options.Client), - } -} diff --git a/selector/options.go b/selector/options.go index 2f6efd92..2a27becc 100644 --- a/selector/options.go +++ b/selector/options.go @@ -1,6 +1,6 @@ package selector -import "github.com/micro/go-micro/v2/router" +import "github.com/micro/go-micro/v3/router" // Options used to configure a selector type Options struct{} diff --git a/selector/random.go b/selector/random.go index d761aa8d..6c40409e 100644 --- a/selector/random.go +++ b/selector/random.go @@ -3,7 +3,7 @@ package selector import ( "math/rand" - "github.com/micro/go-micro/v2/router" + "github.com/micro/go-micro/v3/router" ) type random struct{} diff --git a/selector/random/random.go b/selector/random/random.go index 8bc4553c..72486ad2 100644 --- a/selector/random/random.go +++ b/selector/random/random.go @@ -1,7 +1,7 @@ package random import ( - "github.com/micro/go-micro/v2/selector" + "github.com/micro/go-micro/v3/selector" ) // NewSelector returns a random selector diff --git a/selector/random/random_test.go b/selector/random/random_test.go index e8703ed5..66da138c 100644 --- a/selector/random/random_test.go +++ b/selector/random/random_test.go @@ -3,7 +3,7 @@ package random import ( "testing" - "github.com/micro/go-micro/v2/selector" + "github.com/micro/go-micro/v3/selector" ) func TestRandom(t *testing.T) { diff --git a/selector/roundrobin/roundrobin.go b/selector/roundrobin/roundrobin.go index e70f8280..c77004c5 100644 --- a/selector/roundrobin/roundrobin.go +++ b/selector/roundrobin/roundrobin.go @@ -5,8 +5,8 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/selector" + "github.com/micro/go-micro/v3/router" + "github.com/micro/go-micro/v3/selector" ) var routeTTL = time.Minute * 15 diff --git a/selector/roundrobin/roundrobin_test.go b/selector/roundrobin/roundrobin_test.go index c3063a7e..3a5d97e9 100644 --- a/selector/roundrobin/roundrobin_test.go +++ b/selector/roundrobin/roundrobin_test.go @@ -3,8 +3,8 @@ package roundrobin import ( "testing" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/selector" + "github.com/micro/go-micro/v3/router" + "github.com/micro/go-micro/v3/selector" "github.com/stretchr/testify/assert" ) diff --git a/selector/selector.go b/selector/selector.go index 29cb61d8..727afc22 100644 --- a/selector/selector.go +++ b/selector/selector.go @@ -4,7 +4,7 @@ package selector import ( "errors" - "github.com/micro/go-micro/v2/router" + "github.com/micro/go-micro/v3/router" ) var ( diff --git a/selector/tests.go b/selector/tests.go index 38499a6c..ff854107 100644 --- a/selector/tests.go +++ b/selector/tests.go @@ -3,7 +3,7 @@ package selector import ( "testing" - "github.com/micro/go-micro/v2/router" + "github.com/micro/go-micro/v3/router" "github.com/stretchr/testify/assert" ) diff --git a/server/context.go b/server/context.go index 2bc3aec6..fdd9ff75 100644 --- a/server/context.go +++ b/server/context.go @@ -2,22 +2,10 @@ package server import ( "context" - "sync" ) type serverKey struct{} -func wait(ctx context.Context) *sync.WaitGroup { - if ctx == nil { - return nil - } - wg, ok := ctx.Value("wait").(*sync.WaitGroup) - if !ok { - return nil - } - return wg -} - func FromContext(ctx context.Context) (Server, bool) { c, ok := ctx.Value(serverKey{}).(Server) return c, ok diff --git a/server/grpc/codec.go b/server/grpc/codec.go index 55287f6b..597420bf 100644 --- a/server/grpc/codec.go +++ b/server/grpc/codec.go @@ -8,8 +8,8 @@ import ( "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/codec/bytes" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/codec/bytes" "google.golang.org/grpc" "google.golang.org/grpc/encoding" "google.golang.org/grpc/metadata" diff --git a/server/grpc/context.go b/server/grpc/context.go index 0b246d7e..fe8ac3d7 100644 --- a/server/grpc/context.go +++ b/server/grpc/context.go @@ -3,7 +3,7 @@ package grpc import ( "context" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/server" ) func setServerOption(k, v interface{}) server.Option { diff --git a/server/grpc/error.go b/server/grpc/error.go index 45564152..83046a5c 100644 --- a/server/grpc/error.go +++ b/server/grpc/error.go @@ -3,7 +3,7 @@ package grpc import ( "net/http" - "github.com/micro/go-micro/v2/errors" + "github.com/micro/go-micro/v3/errors" "google.golang.org/grpc/codes" ) diff --git a/server/grpc/extractor.go b/server/grpc/extractor.go index 5576182b..d1d9d0ff 100644 --- a/server/grpc/extractor.go +++ b/server/grpc/extractor.go @@ -5,7 +5,7 @@ import ( "reflect" "strings" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) func extractValue(v reflect.Type, d int) *registry.Value { diff --git a/server/grpc/extractor_test.go b/server/grpc/extractor_test.go index ccf99424..9eac7606 100644 --- a/server/grpc/extractor_test.go +++ b/server/grpc/extractor_test.go @@ -5,7 +5,7 @@ import ( "reflect" "testing" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) type testHandler struct{} diff --git a/server/grpc/grpc.go b/server/grpc/grpc.go index fdaec7e7..32cb53e4 100644 --- a/server/grpc/grpc.go +++ b/server/grpc/grpc.go @@ -15,17 +15,17 @@ import ( "time" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/errors" - pberr "github.com/micro/go-micro/v2/errors/proto" - "github.com/micro/go-micro/v2/logger" - meta "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/server" - "github.com/micro/go-micro/v2/util/addr" - "github.com/micro/go-micro/v2/util/backoff" - mgrpc "github.com/micro/go-micro/v2/util/grpc" - mnet "github.com/micro/go-micro/v2/util/net" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/errors" + pberr "github.com/micro/go-micro/v3/errors/proto" + "github.com/micro/go-micro/v3/logger" + meta "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/server" + "github.com/micro/go-micro/v3/util/addr" + "github.com/micro/go-micro/v3/util/backoff" + mgrpc "github.com/micro/go-micro/v3/util/grpc" + mnet "github.com/micro/go-micro/v3/util/net" "golang.org/x/net/netutil" "google.golang.org/grpc" diff --git a/server/grpc/grpc_test.go b/server/grpc/grpc_test.go index d0b0aab7..e53240b5 100644 --- a/server/grpc/grpc_test.go +++ b/server/grpc/grpc_test.go @@ -5,21 +5,20 @@ import ( "fmt" "testing" - "github.com/micro/go-micro/v2" - bmemory "github.com/micro/go-micro/v2/broker/memory" - "github.com/micro/go-micro/v2/client" - gcli "github.com/micro/go-micro/v2/client/grpc" - "github.com/micro/go-micro/v2/errors" - pberr "github.com/micro/go-micro/v2/errors/proto" - rmemory "github.com/micro/go-micro/v2/registry/memory" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/server" - gsrv "github.com/micro/go-micro/v2/server/grpc" - tgrpc "github.com/micro/go-micro/v2/transport/grpc" + bmemory "github.com/micro/go-micro/v3/broker/memory" + "github.com/micro/go-micro/v3/client" + gcli "github.com/micro/go-micro/v3/client/grpc" + "github.com/micro/go-micro/v3/errors" + pberr "github.com/micro/go-micro/v3/errors/proto" + rmemory "github.com/micro/go-micro/v3/registry/memory" + "github.com/micro/go-micro/v3/router" + rtreg "github.com/micro/go-micro/v3/router/registry" + "github.com/micro/go-micro/v3/server" + gsrv "github.com/micro/go-micro/v3/server/grpc" + pb "github.com/micro/go-micro/v3/server/grpc/proto" + tgrpc "github.com/micro/go-micro/v3/transport/grpc" "google.golang.org/grpc" "google.golang.org/grpc/status" - - pb "github.com/micro/go-micro/v2/server/grpc/proto" ) // server is used to implement helloworld.GreeterServer. @@ -117,7 +116,7 @@ func TestGRPCServer(t *testing.T) { r := rmemory.NewRegistry() b := bmemory.NewBroker() tr := tgrpc.NewTransport() - rtr := router.NewRouter(router.Registry(r)) + rtr := rtreg.NewRouter(router.Registry(r)) s := gsrv.NewServer( server.Broker(b), @@ -136,10 +135,7 @@ func TestGRPCServer(t *testing.T) { h := &testServer{} pb.RegisterTestHandler(s, h) - if err := micro.RegisterSubscriber("test_topic", s, h.Handle); err != nil { - t.Fatal(err) - } - if err := micro.RegisterSubscriber("error_topic", s, h.HandleError); err != nil { + if err := s.Subscribe(s.NewSubscriber("test_topic", h.Handle)); err != nil { t.Fatal(err) } @@ -159,11 +155,10 @@ func TestGRPCServer(t *testing.T) { } }() - pub := micro.NewEvent("test_topic", c) - pubErr := micro.NewEvent("error_topic", c) cnt := 4 for i := 0; i < cnt; i++ { - if err = pub.Publish(ctx, &pb.Request{Name: fmt.Sprintf("msg %d", i)}); err != nil { + msg := c.NewMessage("test_topic", &pb.Request{Name: fmt.Sprintf("msg %d", i)}) + if err = c.Publish(ctx, msg); err != nil { t.Fatal(err) } } @@ -171,9 +166,6 @@ func TestGRPCServer(t *testing.T) { if h.msgCount != cnt { t.Fatalf("pub/sub not work, or invalid message count %d", h.msgCount) } - if err = pubErr.Publish(ctx, &pb.Request{}); err == nil { - t.Fatal("this must return error, as we return error from handler") - } cc, err := grpc.Dial(s.Options().Address, grpc.WithInsecure()) if err != nil { diff --git a/server/grpc/handler.go b/server/grpc/handler.go index fb4e2bbe..9e701c72 100644 --- a/server/grpc/handler.go +++ b/server/grpc/handler.go @@ -3,8 +3,8 @@ package grpc import ( "reflect" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/server" ) type rpcHandler struct { diff --git a/server/grpc/options.go b/server/grpc/options.go index 6591fac2..c2e00f5e 100644 --- a/server/grpc/options.go +++ b/server/grpc/options.go @@ -5,12 +5,11 @@ import ( "crypto/tls" "net" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/server" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/broker/http" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/registry/mdns" + "github.com/micro/go-micro/v3/server" + "github.com/micro/go-micro/v3/transport" "google.golang.org/grpc" "google.golang.org/grpc/encoding" ) @@ -67,11 +66,10 @@ func MaxMsgSize(s int) server.Option { func newOptions(opt ...server.Option) server.Options { opts := server.Options{ - Auth: auth.DefaultAuth, Codecs: make(map[string]codec.NewCodec), Metadata: map[string]string{}, - Broker: broker.DefaultBroker, - Registry: registry.DefaultRegistry, + Broker: http.NewBroker(), + Registry: mdns.NewRegistry(), Transport: transport.DefaultTransport, Address: server.DefaultAddress, Name: server.DefaultName, diff --git a/server/grpc/proto/test.pb.micro.go b/server/grpc/proto/test.pb.micro.go index 8ca37bfd..1f636854 100644 --- a/server/grpc/proto/test.pb.micro.go +++ b/server/grpc/proto/test.pb.micro.go @@ -12,9 +12,9 @@ import ( import ( context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" + api "github.com/micro/go-micro/v3/api" + client "github.com/micro/go-micro/v3/client" + server "github.com/micro/go-micro/v3/server" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/server/grpc/request.go b/server/grpc/request.go index 1261bbc8..437d0ed6 100644 --- a/server/grpc/request.go +++ b/server/grpc/request.go @@ -1,8 +1,8 @@ package grpc import ( - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/codec/bytes" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/codec/bytes" ) type rpcRequest struct { diff --git a/server/grpc/response.go b/server/grpc/response.go index e5c74fc2..d78ec442 100644 --- a/server/grpc/response.go +++ b/server/grpc/response.go @@ -1,7 +1,7 @@ package grpc import ( - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type rpcResponse struct { diff --git a/server/grpc/server.go b/server/grpc/server.go index 80abb711..5a7d2a0b 100644 --- a/server/grpc/server.go +++ b/server/grpc/server.go @@ -14,8 +14,8 @@ import ( "unicode" "unicode/utf8" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/server" ) var ( diff --git a/server/grpc/stream.go b/server/grpc/stream.go index 92165864..38139c54 100644 --- a/server/grpc/stream.go +++ b/server/grpc/stream.go @@ -3,7 +3,7 @@ package grpc import ( "context" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/server" "google.golang.org/grpc" ) diff --git a/server/grpc/subscriber.go b/server/grpc/subscriber.go index 5ac957c2..47e36403 100644 --- a/server/grpc/subscriber.go +++ b/server/grpc/subscriber.go @@ -7,12 +7,12 @@ import ( "runtime/debug" "strings" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/server" ) const ( diff --git a/server/mock/mock.go b/server/mock/mock.go index 0725cbfc..dc4bff30 100644 --- a/server/mock/mock.go +++ b/server/mock/mock.go @@ -5,7 +5,7 @@ import ( "sync" "github.com/google/uuid" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/server" ) type MockServer struct { diff --git a/server/mock/mock_handler.go b/server/mock/mock_handler.go index de46fe52..1b194b64 100644 --- a/server/mock/mock_handler.go +++ b/server/mock/mock_handler.go @@ -1,8 +1,8 @@ package mock import ( - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/server" ) type MockHandler struct { diff --git a/server/mock/mock_subscriber.go b/server/mock/mock_subscriber.go index fb2bb7da..e6f47a22 100644 --- a/server/mock/mock_subscriber.go +++ b/server/mock/mock_subscriber.go @@ -1,8 +1,8 @@ package mock import ( - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/server" ) type MockSubscriber struct { diff --git a/server/mock/mock_test.go b/server/mock/mock_test.go index 6c76af91..a3d537ca 100644 --- a/server/mock/mock_test.go +++ b/server/mock/mock_test.go @@ -3,7 +3,7 @@ package mock import ( "testing" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/server" ) func TestMockServer(t *testing.T) { diff --git a/server/extractor.go b/server/mucp/extractor.go similarity index 97% rename from server/extractor.go rename to server/mucp/extractor.go index 49655605..338a5a0d 100644 --- a/server/extractor.go +++ b/server/mucp/extractor.go @@ -1,11 +1,11 @@ -package server +package mucp import ( "fmt" "reflect" "strings" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) func extractValue(v reflect.Type, d int) *registry.Value { diff --git a/server/extractor_test.go b/server/mucp/extractor_test.go similarity index 96% rename from server/extractor_test.go rename to server/mucp/extractor_test.go index 8512f241..d8bd914f 100644 --- a/server/extractor_test.go +++ b/server/mucp/extractor_test.go @@ -1,11 +1,11 @@ -package server +package mucp import ( "context" "reflect" "testing" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) type testHandler struct{} diff --git a/server/mucp/mucp.go b/server/mucp/mucp.go index 25e0c734..c678cc05 100644 --- a/server/mucp/mucp.go +++ b/server/mucp/mucp.go @@ -2,10 +2,14 @@ package mucp import ( - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/server" +) + +var ( + DefaultRouter = newRpcRouter() ) // NewServer returns a micro server interface func NewServer(opts ...server.Option) server.Server { - return server.NewServer(opts...) + return newServer(opts...) } diff --git a/server/mucp/options.go b/server/mucp/options.go new file mode 100644 index 00000000..8304c046 --- /dev/null +++ b/server/mucp/options.go @@ -0,0 +1,56 @@ +package mucp + +import ( + "github.com/micro/go-micro/v3/broker/http" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/registry/mdns" + "github.com/micro/go-micro/v3/server" + thttp "github.com/micro/go-micro/v3/transport/http" +) + +func newOptions(opt ...server.Option) server.Options { + opts := server.Options{ + Codecs: make(map[string]codec.NewCodec), + Metadata: map[string]string{}, + RegisterInterval: server.DefaultRegisterInterval, + RegisterTTL: server.DefaultRegisterTTL, + } + + for _, o := range opt { + o(&opts) + } + + if opts.Broker == nil { + opts.Broker = http.NewBroker() + } + + if opts.Registry == nil { + opts.Registry = mdns.NewRegistry() + } + + if opts.Transport == nil { + opts.Transport = thttp.NewTransport() + } + + if opts.RegisterCheck == nil { + opts.RegisterCheck = server.DefaultRegisterCheck + } + + if len(opts.Address) == 0 { + opts.Address = server.DefaultAddress + } + + if len(opts.Name) == 0 { + opts.Name = server.DefaultName + } + + if len(opts.Id) == 0 { + opts.Id = server.DefaultId + } + + if len(opts.Version) == 0 { + opts.Version = server.DefaultVersion + } + + return opts +} diff --git a/server/rpc_codec.go b/server/mucp/rpc_codec.go similarity index 95% rename from server/rpc_codec.go rename to server/mucp/rpc_codec.go index 0d902c3d..e0a0202a 100644 --- a/server/rpc_codec.go +++ b/server/mucp/rpc_codec.go @@ -1,17 +1,17 @@ -package server +package mucp import ( "bytes" "sync" - "github.com/micro/go-micro/v2/codec" - raw "github.com/micro/go-micro/v2/codec/bytes" - "github.com/micro/go-micro/v2/codec/grpc" - "github.com/micro/go-micro/v2/codec/json" - "github.com/micro/go-micro/v2/codec/jsonrpc" - "github.com/micro/go-micro/v2/codec/proto" - "github.com/micro/go-micro/v2/codec/protorpc" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/codec" + raw "github.com/micro/go-micro/v3/codec/bytes" + "github.com/micro/go-micro/v3/codec/grpc" + "github.com/micro/go-micro/v3/codec/json" + "github.com/micro/go-micro/v3/codec/jsonrpc" + "github.com/micro/go-micro/v3/codec/proto" + "github.com/micro/go-micro/v3/codec/protorpc" + "github.com/micro/go-micro/v3/transport" "github.com/oxtoacart/bpool" "github.com/pkg/errors" ) diff --git a/server/rpc_codec_test.go b/server/mucp/rpc_codec_test.go similarity index 95% rename from server/rpc_codec_test.go rename to server/mucp/rpc_codec_test.go index 47289c6d..61a7bd9f 100644 --- a/server/rpc_codec_test.go +++ b/server/mucp/rpc_codec_test.go @@ -1,12 +1,12 @@ -package server +package mucp import ( "bytes" "errors" "testing" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/transport" ) // testCodec is a dummy codec that only knows how to encode nil bodies diff --git a/server/rpc_event.go b/server/mucp/rpc_event.go similarity index 85% rename from server/rpc_event.go rename to server/mucp/rpc_event.go index f45f6c87..7d886afe 100644 --- a/server/rpc_event.go +++ b/server/mucp/rpc_event.go @@ -1,8 +1,8 @@ -package server +package mucp import ( - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/transport" ) // event is a broker event we handle on the server transport diff --git a/server/rpc_handler.go b/server/mucp/rpc_handler.go similarity index 75% rename from server/rpc_handler.go rename to server/mucp/rpc_handler.go index 7d2923ca..194ee439 100644 --- a/server/rpc_handler.go +++ b/server/mucp/rpc_handler.go @@ -1,20 +1,21 @@ -package server +package mucp import ( "reflect" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/server" ) type rpcHandler struct { name string handler interface{} endpoints []*registry.Endpoint - opts HandlerOptions + opts server.HandlerOptions } -func newRpcHandler(handler interface{}, opts ...HandlerOption) Handler { - options := HandlerOptions{ +func newRpcHandler(handler interface{}, opts ...server.HandlerOption) server.Handler { + options := server.HandlerOptions{ Metadata: make(map[string]map[string]string), } @@ -60,6 +61,6 @@ func (r *rpcHandler) Endpoints() []*registry.Endpoint { return r.endpoints } -func (r *rpcHandler) Options() HandlerOptions { +func (r *rpcHandler) Options() server.HandlerOptions { return r.opts } diff --git a/server/rpc_request.go b/server/mucp/rpc_request.go similarity index 92% rename from server/rpc_request.go rename to server/mucp/rpc_request.go index 767f1ac8..5520adee 100644 --- a/server/rpc_request.go +++ b/server/mucp/rpc_request.go @@ -1,11 +1,11 @@ -package server +package mucp import ( "bytes" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/transport" - "github.com/micro/go-micro/v2/util/buf" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/transport" + "github.com/micro/go-micro/v3/util/buf" ) type rpcRequest struct { diff --git a/server/rpc_response.go b/server/mucp/rpc_response.go similarity index 84% rename from server/rpc_response.go rename to server/mucp/rpc_response.go index d42a2ac8..5a161d8e 100644 --- a/server/rpc_response.go +++ b/server/mucp/rpc_response.go @@ -1,10 +1,10 @@ -package server +package mucp import ( "net/http" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/transport" ) type rpcResponse struct { diff --git a/server/rpc_router.go b/server/mucp/rpc_router.go similarity index 90% rename from server/rpc_router.go rename to server/mucp/rpc_router.go index 749a6591..d527f3f6 100644 --- a/server/rpc_router.go +++ b/server/mucp/rpc_router.go @@ -1,4 +1,4 @@ -package server +package mucp // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style @@ -18,8 +18,9 @@ import ( "unicode" "unicode/utf8" - "github.com/micro/go-micro/v2/codec" - merrors "github.com/micro/go-micro/v2/errors" + "github.com/micro/go-micro/v3/codec" + merrors "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/server" ) var ( @@ -70,9 +71,9 @@ type router struct { freeResp *response // handler wrappers - hdlrWrappers []HandlerWrapper + hdlrWrappers []server.HandlerWrapper // subscriber wrappers - subWrappers []SubscriberWrapper + subWrappers []server.SubscriberWrapper su sync.RWMutex subscribers map[string][]*subscriber @@ -80,15 +81,15 @@ type router struct { // rpcRouter encapsulates functions that become a server.Router type rpcRouter struct { - h func(context.Context, Request, interface{}) error - m func(context.Context, Message) error + h func(context.Context, server.Request, interface{}) error + m func(context.Context, server.Message) error } -func (r rpcRouter) ProcessMessage(ctx context.Context, msg Message) error { +func (r rpcRouter) ProcessMessage(ctx context.Context, msg server.Message) error { return r.m(ctx, msg) } -func (r rpcRouter) ServeRequest(ctx context.Context, req Request, rsp Response) error { +func (r rpcRouter) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error { return r.h(ctx, req, rsp) } @@ -146,7 +147,7 @@ func prepareMethod(method reflect.Method) *methodType { if stream { // check stream type - streamType := reflect.TypeOf((*Stream)(nil)).Elem() + streamType := reflect.TypeOf((*server.Stream)(nil)).Elem() if !argType.Implements(streamType) { log.Errorf("%v argument does not implement Stream interface: %v", mname, argType) return nil @@ -220,7 +221,7 @@ func (s *service) call(ctx context.Context, router *router, sending *sync.Mutex, } if !mtype.stream { - fn := func(ctx context.Context, req Request, rsp interface{}) error { + fn := func(ctx context.Context, req server.Request, rsp interface{}) error { returnValues = function.Call([]reflect.Value{s.rcvr, mtype.prepareContext(ctx), reflect.ValueOf(argv.Interface()), reflect.ValueOf(rsp)}) // The return value for the method is an error. @@ -256,7 +257,7 @@ func (s *service) call(ctx context.Context, router *router, sending *sync.Mutex, } // Invoke the method, providing a new value for the reply. - fn := func(ctx context.Context, req Request, stream interface{}) error { + fn := func(ctx context.Context, req server.Request, stream interface{}) error { returnValues = function.Call([]reflect.Value{s.rcvr, mtype.prepareContext(ctx), reflect.ValueOf(stream)}) if err := returnValues[0].Interface(); err != nil { // the function returned an error, we use that @@ -328,7 +329,7 @@ func (router *router) freeResponse(resp *response) { router.respLock.Unlock() } -func (router *router) readRequest(r Request) (service *service, mtype *methodType, req *request, argv, replyv reflect.Value, keepReading bool, err error) { +func (router *router) readRequest(r server.Request) (service *service, mtype *methodType, req *request, argv, replyv reflect.Value, keepReading bool, err error) { cc := r.Codec() service, mtype, req, keepReading, err = router.readHeader(cc) @@ -411,11 +412,11 @@ func (router *router) readHeader(cc codec.Reader) (service *service, mtype *meth return } -func (router *router) NewHandler(h interface{}, opts ...HandlerOption) Handler { +func (router *router) NewHandler(h interface{}, opts ...server.HandlerOption) server.Handler { return newRpcHandler(h, opts...) } -func (router *router) Handle(h Handler) error { +func (router *router) Handle(h server.Handler) error { router.mu.Lock() defer router.mu.Unlock() if router.serviceMap == nil { @@ -460,7 +461,7 @@ func (router *router) Handle(h Handler) error { return nil } -func (router *router) ServeRequest(ctx context.Context, r Request, rsp Response) error { +func (router *router) ServeRequest(ctx context.Context, r server.Request, rsp server.Response) error { sending := new(sync.Mutex) service, mtype, req, argv, replyv, keepReading, err := router.readRequest(r) if err != nil { @@ -476,11 +477,11 @@ func (router *router) ServeRequest(ctx context.Context, r Request, rsp Response) return service.call(ctx, router, sending, mtype, req, argv, replyv, rsp.Codec()) } -func (router *router) NewSubscriber(topic string, handler interface{}, opts ...SubscriberOption) Subscriber { +func (router *router) NewSubscriber(topic string, handler interface{}, opts ...server.SubscriberOption) server.Subscriber { return newSubscriber(topic, handler, opts...) } -func (router *router) Subscribe(s Subscriber) error { +func (router *router) Subscribe(s server.Subscriber) error { sub, ok := s.(*subscriber) if !ok { return fmt.Errorf("invalid subscriber: expected *subscriber") @@ -504,7 +505,11 @@ func (router *router) Subscribe(s Subscriber) error { return nil } -func (router *router) ProcessMessage(ctx context.Context, msg Message) (err error) { +func (router *router) String() string { + return "mucp" +} + +func (router *router) ProcessMessage(ctx context.Context, msg server.Message) (err error) { defer func() { // recover any panics if r := recover(); r != nil { @@ -561,7 +566,7 @@ func (router *router) ProcessMessage(ctx context.Context, msg Message) (err erro } // create the handler which will honour the SubscriberFunc type - fn := func(ctx context.Context, msg Message) error { + fn := func(ctx context.Context, msg server.Message) error { var vals []reflect.Value if sub.typ.Kind() != reflect.Func { vals = append(vals, sub.rcvr) diff --git a/server/rpc_server.go b/server/mucp/rpc_server.go similarity index 92% rename from server/rpc_server.go rename to server/mucp/rpc_server.go index 44e635b5..bea912ad 100644 --- a/server/rpc_server.go +++ b/server/mucp/rpc_server.go @@ -1,4 +1,4 @@ -package server +package mucp import ( "context" @@ -12,17 +12,18 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/codec" - raw "github.com/micro/go-micro/v2/codec/bytes" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/transport" - "github.com/micro/go-micro/v2/util/addr" - "github.com/micro/go-micro/v2/util/backoff" - mnet "github.com/micro/go-micro/v2/util/net" - "github.com/micro/go-micro/v2/util/socket" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/codec" + raw "github.com/micro/go-micro/v3/codec/bytes" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/server" + "github.com/micro/go-micro/v3/transport" + "github.com/micro/go-micro/v3/util/addr" + "github.com/micro/go-micro/v3/util/backoff" + mnet "github.com/micro/go-micro/v3/util/net" + "github.com/micro/go-micro/v3/util/socket" ) type rpcServer struct { @@ -30,9 +31,9 @@ type rpcServer struct { exit chan chan error sync.RWMutex - opts Options - handlers map[string]Handler - subscribers map[Subscriber][]broker.Subscriber + opts server.Options + handlers map[string]server.Handler + subscribers map[server.Subscriber][]broker.Subscriber // marks the serve as started started bool // used for first registration @@ -45,7 +46,22 @@ type rpcServer struct { rsvc *registry.Service } -func newRpcServer(opts ...Option) Server { +var ( + log = logger.NewHelper(logger.DefaultLogger).WithFields(map[string]interface{}{"service": "server"}) +) + +func wait(ctx context.Context) *sync.WaitGroup { + if ctx == nil { + return nil + } + wg, ok := ctx.Value("wait").(*sync.WaitGroup) + if !ok { + return nil + } + return wg +} + +func newServer(opts ...server.Option) server.Server { options := newOptions(opts...) router := newRpcRouter() router.hdlrWrappers = options.HdlrWrappers @@ -54,8 +70,8 @@ func newRpcServer(opts ...Option) Server { return &rpcServer{ opts: options, router: router, - handlers: make(map[string]Handler), - subscribers: make(map[Subscriber][]broker.Subscriber), + handlers: make(map[string]server.Handler), + subscribers: make(map[server.Subscriber][]broker.Subscriber), exit: make(chan chan error), wg: wait(options.Context), } @@ -110,7 +126,7 @@ func (s *rpcServer) HandleEvent(e broker.Event) error { } // existing router - r := Router(s.router) + r := server.Router(s.router) // if the router is present then execute it if s.opts.Router != nil { @@ -333,13 +349,13 @@ func (s *rpcServer) ServeConn(sock transport.Socket) { } // set router - r := Router(s.router) + r := server.Router(s.router) // if not nil use the router specified if s.opts.Router != nil { // create a wrapped function - handler := func(ctx context.Context, req Request, rsp interface{}) error { - return s.opts.Router.ServeRequest(ctx, req, rsp.(Response)) + handler := func(ctx context.Context, req server.Request, rsp interface{}) error { + return s.opts.Router.ServeRequest(ctx, req, rsp.(server.Response)) } // execute the wrapper for it @@ -439,14 +455,14 @@ func (s *rpcServer) newCodec(contentType string) (codec.NewCodec, error) { return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType) } -func (s *rpcServer) Options() Options { +func (s *rpcServer) Options() server.Options { s.RLock() opts := s.opts s.RUnlock() return opts } -func (s *rpcServer) Init(opts ...Option) error { +func (s *rpcServer) Init(opts ...server.Option) error { s.Lock() defer s.Unlock() @@ -467,11 +483,11 @@ func (s *rpcServer) Init(opts ...Option) error { return nil } -func (s *rpcServer) NewHandler(h interface{}, opts ...HandlerOption) Handler { +func (s *rpcServer) NewHandler(h interface{}, opts ...server.HandlerOption) server.Handler { return s.router.NewHandler(h, opts...) } -func (s *rpcServer) Handle(h Handler) error { +func (s *rpcServer) Handle(h server.Handler) error { s.Lock() defer s.Unlock() @@ -484,11 +500,11 @@ func (s *rpcServer) Handle(h Handler) error { return nil } -func (s *rpcServer) NewSubscriber(topic string, sb interface{}, opts ...SubscriberOption) Subscriber { +func (s *rpcServer) NewSubscriber(topic string, sb interface{}, opts ...server.SubscriberOption) server.Subscriber { return s.router.NewSubscriber(topic, sb, opts...) } -func (s *rpcServer) Subscribe(sb Subscriber) error { +func (s *rpcServer) Subscribe(sb server.Subscriber) error { s.Lock() defer s.Unlock() @@ -606,7 +622,7 @@ func (s *rpcServer) Register() error { sort.Strings(handlerList) - var subscriberList []Subscriber + var subscriberList []server.Subscriber for e := range s.subscribers { // Only advertise non internal subscribers if !e.Options().Internal { diff --git a/server/rpc_stream.go b/server/mucp/rpc_stream.go similarity index 90% rename from server/rpc_stream.go rename to server/mucp/rpc_stream.go index dbee673e..ce032caa 100644 --- a/server/rpc_stream.go +++ b/server/mucp/rpc_stream.go @@ -1,4 +1,4 @@ -package server +package mucp import ( "context" @@ -6,7 +6,8 @@ import ( "io" "sync" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/server" ) // Implements the Streamer interface @@ -15,7 +16,7 @@ type rpcStream struct { id string closed bool err error - request Request + request server.Request codec codec.Codec context context.Context } @@ -24,7 +25,7 @@ func (r *rpcStream) Context() context.Context { return r.context } -func (r *rpcStream) Request() Request { +func (r *rpcStream) Request() server.Request { return r.request } diff --git a/server/rpc_stream_test.go b/server/mucp/rpc_stream_test.go similarity index 95% rename from server/rpc_stream_test.go rename to server/mucp/rpc_stream_test.go index f4b0b7bd..c7bdb0f7 100644 --- a/server/rpc_stream_test.go +++ b/server/mucp/rpc_stream_test.go @@ -1,4 +1,4 @@ -package server +package mucp import ( "bytes" @@ -10,8 +10,8 @@ import ( "time" "github.com/golang/protobuf/proto" - "github.com/micro/go-micro/v2/codec/json" - protoCodec "github.com/micro/go-micro/v2/codec/proto" + "github.com/micro/go-micro/v3/codec/json" + protoCodec "github.com/micro/go-micro/v3/codec/proto" ) // protoStruct implements proto.Message diff --git a/server/rpc_util.go b/server/mucp/rpc_util.go similarity index 96% rename from server/rpc_util.go rename to server/mucp/rpc_util.go index a15be0ac..66cf8674 100644 --- a/server/rpc_util.go +++ b/server/mucp/rpc_util.go @@ -1,4 +1,4 @@ -package server +package mucp import ( "sync" diff --git a/server/subscriber.go b/server/mucp/subscriber.go similarity index 90% rename from server/subscriber.go rename to server/mucp/subscriber.go index 6278175a..a2142f34 100644 --- a/server/subscriber.go +++ b/server/mucp/subscriber.go @@ -1,10 +1,11 @@ -package server +package mucp import ( "fmt" "reflect" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/server" ) const ( @@ -24,11 +25,11 @@ type subscriber struct { subscriber interface{} handlers []*handler endpoints []*registry.Endpoint - opts SubscriberOptions + opts server.SubscriberOptions } -func newSubscriber(topic string, sub interface{}, opts ...SubscriberOption) Subscriber { - options := SubscriberOptions{ +func newSubscriber(topic string, sub interface{}, opts ...server.SubscriberOption) server.Subscriber { + options := server.SubscriberOptions{ AutoAck: true, } @@ -104,7 +105,7 @@ func newSubscriber(topic string, sub interface{}, opts ...SubscriberOption) Subs } } -func validateSubscriber(sub Subscriber) error { +func validateSubscriber(sub server.Subscriber) error { typ := reflect.TypeOf(sub.Subscriber()) var argType reflect.Type @@ -170,6 +171,6 @@ func (s *subscriber) Endpoints() []*registry.Endpoint { return s.endpoints } -func (s *subscriber) Options() SubscriberOptions { +func (s *subscriber) Options() server.SubscriberOptions { return s.opts } diff --git a/server/options.go b/server/options.go index ebe02bf2..b4c5b636 100644 --- a/server/options.go +++ b/server/options.go @@ -6,12 +6,14 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/debug/trace" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/auth" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/broker/http" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/debug/trace" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/mdns" + "github.com/micro/go-micro/v3/transport" ) type Options struct { @@ -61,16 +63,12 @@ func newOptions(opt ...Option) Options { o(&opts) } - if opts.Auth == nil { - opts.Auth = auth.DefaultAuth - } - if opts.Broker == nil { - opts.Broker = broker.DefaultBroker + opts.Broker = http.NewBroker() } if opts.Registry == nil { - opts.Registry = registry.DefaultRegistry + opts.Registry = mdns.NewRegistry() } if opts.Transport == nil { diff --git a/server/proto/server.pb.micro.go b/server/proto/server.pb.micro.go index 5d84eda9..ecb350e8 100644 --- a/server/proto/server.pb.micro.go +++ b/server/proto/server.pb.micro.go @@ -11,9 +11,9 @@ import ( import ( context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" + api "github.com/micro/go-micro/v3/api" + client "github.com/micro/go-micro/v3/client" + server "github.com/micro/go-micro/v3/server" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/server/server.go b/server/server.go index a7c00fca..c70656d6 100644 --- a/server/server.go +++ b/server/server.go @@ -3,15 +3,11 @@ package server import ( "context" - "os" - "os/signal" "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/registry" - signalutil "github.com/micro/go-micro/v2/util/signal" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/registry" ) // Server is a simple micro server abstraction @@ -137,105 +133,11 @@ type Subscriber interface { type Option func(*Options) var ( - DefaultAddress = ":0" - DefaultName = "go.micro.server" - DefaultVersion = "latest" - DefaultId = uuid.New().String() - DefaultServer Server = newRpcServer() - DefaultRouter = newRpcRouter() - DefaultRegisterCheck = func(context.Context) error { return nil } - DefaultRegisterInterval = time.Second * 30 - DefaultRegisterTTL = time.Second * 90 - - // NewServer creates a new server - NewServer func(...Option) Server = newRpcServer - log = logger.NewHelper(logger.DefaultLogger).WithFields(map[string]interface{}{"service": "server"}) + DefaultAddress = ":0" + DefaultName = "go.micro.server" + DefaultVersion = "latest" + DefaultId = uuid.New().String() + DefaultRegisterCheck = func(context.Context) error { return nil } + DefaultRegisterInterval = time.Second * 30 + DefaultRegisterTTL = time.Second * 90 ) - -// DefaultOptions returns config options for the default service -func DefaultOptions() Options { - return DefaultServer.Options() -} - -// Init initialises the default server with options passed in -func Init(opt ...Option) { - if DefaultServer == nil { - DefaultServer = newRpcServer(opt...) - } - DefaultServer.Init(opt...) -} - -// NewRouter returns a new router -func NewRouter() *router { - return newRpcRouter() -} - -// NewSubscriber creates a new subscriber interface with the given topic -// and handler using the default server -func NewSubscriber(topic string, h interface{}, opts ...SubscriberOption) Subscriber { - return DefaultServer.NewSubscriber(topic, h, opts...) -} - -// NewHandler creates a new handler interface using the default server -// Handlers are required to be a public object with public -// endpoints. Call to a service endpoint such as Foo.Bar expects -// the type: -// -// type Foo struct {} -// func (f *Foo) Bar(ctx, req, rsp) error { -// return nil -// } -// -func NewHandler(h interface{}, opts ...HandlerOption) Handler { - return DefaultServer.NewHandler(h, opts...) -} - -// Handle registers a handler interface with the default server to -// handle inbound requests -func Handle(h Handler) error { - return DefaultServer.Handle(h) -} - -// Subscribe registers a subscriber interface with the default server -// which subscribes to specified topic with the broker -func Subscribe(s Subscriber) error { - return DefaultServer.Subscribe(s) -} - -// Run starts the default server and waits for a kill -// signal before exiting. Also registers/deregisters the server -func Run() error { - if err := Start(); err != nil { - return err - } - - ch := make(chan os.Signal, 1) - signal.Notify(ch, signalutil.Shutdown()...) - - if logger.V(logger.InfoLevel, log) { - log.Infof("Received signal %s", <-ch) - } - return Stop() -} - -// Start starts the default server -func Start() error { - config := DefaultServer.Options() - if logger.V(logger.InfoLevel, log) { - log.Infof("Starting server %s id %s", config.Name, config.Id) - } - return DefaultServer.Start() -} - -// Stop stops the default server -func Stop() error { - if logger.V(logger.InfoLevel, log) { - log.Infof("Stopping server") - } - return DefaultServer.Stop() -} - -// String returns name of Server implementation -func String() string { - return DefaultServer.String() -} diff --git a/service.go b/service.go deleted file mode 100644 index a60f1bec..00000000 --- a/service.go +++ /dev/null @@ -1,231 +0,0 @@ -package micro - -import ( - "os" - "os/signal" - rtime "runtime" - "strings" - "sync" - - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/cmd" - "github.com/micro/go-micro/v2/debug/service/handler" - "github.com/micro/go-micro/v2/debug/stats" - "github.com/micro/go-micro/v2/debug/trace" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/plugin" - "github.com/micro/go-micro/v2/server" - "github.com/micro/go-micro/v2/store" - signalutil "github.com/micro/go-micro/v2/util/signal" - "github.com/micro/go-micro/v2/util/wrapper" -) - -type service struct { - opts Options - - once sync.Once -} - -func newService(opts ...Option) Service { - service := new(service) - options := newOptions(opts...) - - // service name - serviceName := options.Server.Options().Name - - // we pass functions to the wrappers since the values can change during initialisation - authFn := func() auth.Auth { return options.Server.Options().Auth } - cacheFn := func() *client.Cache { return options.Client.Options().Cache } - - // wrap client to inject From-Service header on any calls - options.Client = wrapper.FromService(serviceName, options.Client) - options.Client = wrapper.TraceCall(serviceName, trace.DefaultTracer, options.Client) - options.Client = wrapper.CacheClient(cacheFn, options.Client) - options.Client = wrapper.AuthClient(authFn, options.Client) - - // pass the services auth namespace to the auth handler so it - // uses this to verify requests, preventing the reliance on the - // insecure Micro-Namespace header. - handlerNS := wrapper.AuthHandlerNamespace(options.Auth.Options().Issuer) - - // wrap the server to provide handler stats - options.Server.Init( - server.WrapHandler(wrapper.HandlerStats(stats.DefaultStats)), - server.WrapHandler(wrapper.TraceHandler(trace.DefaultTracer)), - server.WrapHandler(wrapper.AuthHandler(authFn, handlerNS)), - ) - - // set opts - service.opts = options - - return service -} - -func (s *service) Name() string { - return s.opts.Server.Options().Name -} - -// Init initialises options. Additionally it calls cmd.Init -// which parses command line flags. cmd.Init is only called -// on first Init. -func (s *service) Init(opts ...Option) { - // process options - for _, o := range opts { - o(&s.opts) - } - - s.once.Do(func() { - // setup the plugins - for _, p := range strings.Split(os.Getenv("MICRO_PLUGIN"), ",") { - if len(p) == 0 { - continue - } - - // load the plugin - c, err := plugin.Load(p) - if err != nil { - logger.Fatal(err) - } - - // initialise the plugin - if err := plugin.Init(c); err != nil { - logger.Fatal(err) - } - } - - // set cmd name - if len(s.opts.Cmd.App().Name) == 0 { - s.opts.Cmd.App().Name = s.Server().Options().Name - } - - // Initialise the command options - if err := s.opts.Cmd.Init( - cmd.Auth(&s.opts.Auth), - cmd.Broker(&s.opts.Broker), - cmd.Registry(&s.opts.Registry), - cmd.Runtime(&s.opts.Runtime), - cmd.Transport(&s.opts.Transport), - cmd.Client(&s.opts.Client), - cmd.Config(&s.opts.Config), - cmd.Server(&s.opts.Server), - cmd.Store(&s.opts.Store), - cmd.Profile(&s.opts.Profile), - ); err != nil { - logger.Fatal(err) - } - - // execute the command - // TODO: do this in service.Run() - if err := s.opts.Cmd.Run(); err != nil { - logger.Fatal(err) - } - - // Explicitly set the table name to the service name - name := s.opts.Cmd.App().Name - s.opts.Store.Init(store.Table(name)) - }) -} - -func (s *service) Options() Options { - return s.opts -} - -func (s *service) Client() client.Client { - return s.opts.Client -} - -func (s *service) Server() server.Server { - return s.opts.Server -} - -func (s *service) String() string { - return "micro" -} - -func (s *service) Start() error { - for _, fn := range s.opts.BeforeStart { - if err := fn(); err != nil { - return err - } - } - - if err := s.opts.Server.Start(); err != nil { - return err - } - - for _, fn := range s.opts.AfterStart { - if err := fn(); err != nil { - return err - } - } - - return nil -} - -func (s *service) Stop() error { - var gerr error - - for _, fn := range s.opts.BeforeStop { - if err := fn(); err != nil { - gerr = err - } - } - - if err := s.opts.Server.Stop(); err != nil { - return err - } - - for _, fn := range s.opts.AfterStop { - if err := fn(); err != nil { - gerr = err - } - } - - return gerr -} - -func (s *service) Run() error { - // register the debug handler - s.opts.Server.Handle( - s.opts.Server.NewHandler( - handler.NewHandler(s.opts.Client), - server.InternalHandler(true), - ), - ) - - // start the profiler - if s.opts.Profile != nil { - // to view mutex contention - rtime.SetMutexProfileFraction(5) - // to view blocking profile - rtime.SetBlockProfileRate(1) - - if err := s.opts.Profile.Start(); err != nil { - return err - } - defer s.opts.Profile.Stop() - } - - if logger.V(logger.InfoLevel, logger.DefaultLogger) { - logger.Infof("Starting [service] %s", s.Name()) - } - - if err := s.Start(); err != nil { - return err - } - - ch := make(chan os.Signal, 1) - if s.opts.Signal { - signal.Notify(ch, signalutil.Shutdown()...) - } - - select { - // wait on kill signal - case <-ch: - // wait on context cancel - case <-s.opts.Context.Done(): - } - - return s.Stop() -} diff --git a/service/grpc/grpc.go b/service/grpc/grpc.go index 1ab6cb23..243e5ae2 100644 --- a/service/grpc/grpc.go +++ b/service/grpc/grpc.go @@ -1,12 +1,12 @@ package grpc import ( - "github.com/micro/go-micro/v2/client" - gclient "github.com/micro/go-micro/v2/client/grpc" - "github.com/micro/go-micro/v2/model" - "github.com/micro/go-micro/v2/server" - gserver "github.com/micro/go-micro/v2/server/grpc" - "github.com/micro/go-micro/v2/service" + "github.com/micro/go-micro/v3/client" + gclient "github.com/micro/go-micro/v3/client/grpc" + "github.com/micro/go-micro/v3/model" + "github.com/micro/go-micro/v3/server" + gserver "github.com/micro/go-micro/v3/server/grpc" + "github.com/micro/go-micro/v3/service" ) type grpcService struct { diff --git a/service/grpc/grpc_test.go b/service/grpc/grpc_test.go index 1f213008..faf15336 100644 --- a/service/grpc/grpc_test.go +++ b/service/grpc/grpc_test.go @@ -7,10 +7,10 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/registry/memory" - "github.com/micro/go-micro/v2/service" - hello "github.com/micro/go-micro/v2/service/grpc/proto" - mls "github.com/micro/go-micro/v2/util/tls" + "github.com/micro/go-micro/v3/registry/memory" + "github.com/micro/go-micro/v3/service" + hello "github.com/micro/go-micro/v3/service/grpc/proto" + mls "github.com/micro/go-micro/v3/util/tls" ) type testHandler struct{} diff --git a/service/grpc/options.go b/service/grpc/options.go index 302f960b..4aa088b2 100644 --- a/service/grpc/options.go +++ b/service/grpc/options.go @@ -3,9 +3,9 @@ package grpc import ( "crypto/tls" - gc "github.com/micro/go-micro/v2/client/grpc" - gs "github.com/micro/go-micro/v2/server/grpc" - "github.com/micro/go-micro/v2/service" + gc "github.com/micro/go-micro/v3/client/grpc" + gs "github.com/micro/go-micro/v3/server/grpc" + "github.com/micro/go-micro/v3/service" ) // WithTLS sets the TLS config for the service diff --git a/service/grpc/proto/test.pb.micro.go b/service/grpc/proto/test.pb.micro.go index 0c748d47..e35dbeff 100644 --- a/service/grpc/proto/test.pb.micro.go +++ b/service/grpc/proto/test.pb.micro.go @@ -11,9 +11,9 @@ import ( import ( context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" + api "github.com/micro/go-micro/v3/api" + client "github.com/micro/go-micro/v3/client" + server "github.com/micro/go-micro/v3/server" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/service/mucp/mucp.go b/service/mucp/mucp.go index b8854cfd..38093069 100644 --- a/service/mucp/mucp.go +++ b/service/mucp/mucp.go @@ -2,12 +2,12 @@ package mucp import ( - "github.com/micro/go-micro/v2/client" - cmucp "github.com/micro/go-micro/v2/client/mucp" - "github.com/micro/go-micro/v2/model" - "github.com/micro/go-micro/v2/server" - smucp "github.com/micro/go-micro/v2/server/mucp" - "github.com/micro/go-micro/v2/service" + "github.com/micro/go-micro/v3/client" + cmucp "github.com/micro/go-micro/v3/client/mucp" + "github.com/micro/go-micro/v3/model" + "github.com/micro/go-micro/v3/server" + smucp "github.com/micro/go-micro/v3/server/mucp" + "github.com/micro/go-micro/v3/service" ) type mucpService struct { diff --git a/service/options.go b/service/options.go index 424c5746..0829e27b 100644 --- a/service/options.go +++ b/service/options.go @@ -4,12 +4,17 @@ import ( "context" "time" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/model" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/server" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/broker/http" + "github.com/micro/go-micro/v3/client" + mucpClient "github.com/micro/go-micro/v3/client/mucp" + "github.com/micro/go-micro/v3/model" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/mdns" + "github.com/micro/go-micro/v3/server" + mucpServer "github.com/micro/go-micro/v3/server/mucp" + "github.com/micro/go-micro/v3/transport" + thttp "github.com/micro/go-micro/v3/transport/http" ) type Options struct { @@ -35,11 +40,11 @@ type Option func(*Options) func NewOptions(opts ...Option) Options { opt := Options{ - Broker: broker.DefaultBroker, - Client: client.DefaultClient, - Server: server.DefaultServer, - Registry: registry.DefaultRegistry, - Transport: transport.DefaultTransport, + Broker: http.NewBroker(), + Client: mucpClient.NewClient(), + Server: mucpServer.NewServer(), + Registry: mdns.NewRegistry(), + Transport: thttp.NewTransport(), Context: context.Background(), } diff --git a/service/service.go b/service/service.go index 67430316..c9ad69f5 100644 --- a/service/service.go +++ b/service/service.go @@ -2,9 +2,9 @@ package service import ( - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/model" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/model" + "github.com/micro/go-micro/v3/server" ) // Service is an interface for a micro service diff --git a/service_test.go b/service_test.go deleted file mode 100644 index 0c3d1829..00000000 --- a/service_test.go +++ /dev/null @@ -1,175 +0,0 @@ -package micro - -import ( - "context" - "errors" - "sync" - "testing" - - "github.com/micro/go-micro/v2/client" - proto "github.com/micro/go-micro/v2/debug/service/proto" - "github.com/micro/go-micro/v2/registry/memory" - "github.com/micro/go-micro/v2/util/test" -) - -func testShutdown(wg *sync.WaitGroup, cancel func()) { - // add 1 - wg.Add(1) - // shutdown the service - cancel() - // wait for stop - wg.Wait() -} - -func testService(ctx context.Context, wg *sync.WaitGroup, name string) Service { - // add self - wg.Add(1) - - r := memory.NewRegistry(memory.Services(test.Data)) - - // create service - return NewService( - Name(name), - Context(ctx), - Registry(r), - AfterStart(func() error { - wg.Done() - return nil - }), - AfterStop(func() error { - wg.Done() - return nil - }), - ) -} - -func testRequest(ctx context.Context, c client.Client, name string) error { - // test call debug - req := c.NewRequest( - name, - "Debug.Health", - new(proto.HealthRequest), - ) - - rsp := new(proto.HealthResponse) - - err := c.Call(context.TODO(), req, rsp) - if err != nil { - return err - } - - if rsp.Status != "ok" { - return errors.New("service response: " + rsp.Status) - } - - return nil -} - -// TestService tests running and calling a service -func TestService(t *testing.T) { - // waitgroup for server start - var wg sync.WaitGroup - - // cancellation context - ctx, cancel := context.WithCancel(context.Background()) - - // start test server - service := testService(ctx, &wg, "test.service") - - go func() { - // wait for service to start - wg.Wait() - - // make a test call - if err := testRequest(ctx, service.Client(), "test.service"); err != nil { - t.Fatal(err) - } - - // shutdown the service - testShutdown(&wg, cancel) - }() - - // start service - if err := service.Run(); err != nil { - t.Fatal(err) - } -} - -func benchmarkService(b *testing.B, n int, name string) { - // stop the timer - b.StopTimer() - - // waitgroup for server start - var wg sync.WaitGroup - - // cancellation context - ctx, cancel := context.WithCancel(context.Background()) - - // create test server - service := testService(ctx, &wg, name) - - // start the server - go func() { - if err := service.Run(); err != nil { - b.Fatal(err) - } - }() - - // wait for service to start - wg.Wait() - - // make a test call to warm the cache - for i := 0; i < 10; i++ { - if err := testRequest(ctx, service.Client(), name); err != nil { - b.Fatal(err) - } - } - - // start the timer - b.StartTimer() - - // number of iterations - for i := 0; i < b.N; i++ { - // for concurrency - for j := 0; j < n; j++ { - wg.Add(1) - - go func() { - err := testRequest(ctx, service.Client(), name) - wg.Done() - if err != nil { - b.Fatal(err) - } - }() - } - - // wait for test completion - wg.Wait() - } - - // stop the timer - b.StopTimer() - - // shutdown service - testShutdown(&wg, cancel) -} - -func BenchmarkService1(b *testing.B) { - benchmarkService(b, 1, "test.service.1") -} - -func BenchmarkService8(b *testing.B) { - benchmarkService(b, 8, "test.service.8") -} - -func BenchmarkService16(b *testing.B) { - benchmarkService(b, 16, "test.service.16") -} - -func BenchmarkService32(b *testing.B) { - benchmarkService(b, 32, "test.service.32") -} - -func BenchmarkService64(b *testing.B) { - benchmarkService(b, 64, "test.service.64") -} diff --git a/store/cache/cache.go b/store/cache/cache.go index 10b5c8a4..775f4096 100644 --- a/store/cache/cache.go +++ b/store/cache/cache.go @@ -1,8 +1,8 @@ package cache import ( - "github.com/micro/go-micro/v2/store" - "github.com/micro/go-micro/v2/store/memory" + "github.com/micro/go-micro/v3/store" + "github.com/micro/go-micro/v3/store/memory" ) // cache store is a store with caching to reduce IO where applicable. diff --git a/store/cache/cache_test.go b/store/cache/cache_test.go index 0da6808b..08e664ca 100644 --- a/store/cache/cache_test.go +++ b/store/cache/cache_test.go @@ -5,8 +5,8 @@ import ( "path/filepath" "testing" - "github.com/micro/go-micro/v2/store" - "github.com/micro/go-micro/v2/store/file" + "github.com/micro/go-micro/v3/store" + "github.com/micro/go-micro/v3/store/file" "github.com/stretchr/testify/assert" ) diff --git a/store/cockroach/cockroach.go b/store/cockroach/cockroach.go index 85e90d82..03950a63 100644 --- a/store/cockroach/cockroach.go +++ b/store/cockroach/cockroach.go @@ -11,8 +11,8 @@ import ( "time" "github.com/lib/pq" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/store" "github.com/pkg/errors" ) diff --git a/store/cockroach/cockroach_test.go b/store/cockroach/cockroach_test.go index 8664c5dc..1c7eabf5 100644 --- a/store/cockroach/cockroach_test.go +++ b/store/cockroach/cockroach_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/kr/pretty" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" ) func TestSQL(t *testing.T) { diff --git a/store/file/file.go b/store/file/file.go index 2457471c..11cbfdd1 100644 --- a/store/file/file.go +++ b/store/file/file.go @@ -9,7 +9,7 @@ import ( "strings" "time" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" bolt "go.etcd.io/bbolt" ) diff --git a/store/file/file_test.go b/store/file/file_test.go index fded4644..7f9cf7c8 100644 --- a/store/file/file_test.go +++ b/store/file/file_test.go @@ -10,7 +10,7 @@ import ( "github.com/davecgh/go-spew/spew" "github.com/kr/pretty" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" ) func cleanup(db string, s store.Store) { diff --git a/store/memory/memory.go b/store/memory/memory.go index bb3578c2..20c190ca 100644 --- a/store/memory/memory.go +++ b/store/memory/memory.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" "github.com/patrickmn/go-cache" "github.com/pkg/errors" ) diff --git a/store/memory/memory_test.go b/store/memory/memory_test.go index 91cd2b12..59dba5d5 100644 --- a/store/memory/memory_test.go +++ b/store/memory/memory_test.go @@ -7,7 +7,7 @@ import ( "time" "github.com/kr/pretty" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" ) func TestMemoryReInit(t *testing.T) { diff --git a/store/options.go b/store/options.go index d89cb766..27224731 100644 --- a/store/options.go +++ b/store/options.go @@ -3,8 +3,6 @@ package store import ( "context" "time" - - "github.com/micro/go-micro/v2/client" ) // Options contains configuration for the Store @@ -19,8 +17,6 @@ type Options struct { Table string // Context should contain all implementation specific options, using context.WithValue. Context context.Context - // Client to use for RPC - Client client.Client } // Option sets values in Options @@ -56,13 +52,6 @@ func WithContext(c context.Context) Option { } } -// WithClient sets the stores client to use for RPC -func WithClient(c client.Client) Option { - return func(o *Options) { - o.Client = c - } -} - // ReadOptions configures an individual Read operation type ReadOptions struct { Database, Table string diff --git a/store/service/proto/store.pb.go b/store/service/proto/store.pb.go deleted file mode 100644 index c3d35701..00000000 --- a/store/service/proto/store.pb.go +++ /dev/null @@ -1,1236 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: store/service/proto/store.proto - -package go_micro_store - -import ( - context "context" - fmt "fmt" - proto "github.com/golang/protobuf/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -type Field struct { - // type of value e.g string, int, int64, bool, float64 - Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - // the actual value - Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Field) Reset() { *m = Field{} } -func (m *Field) String() string { return proto.CompactTextString(m) } -func (*Field) ProtoMessage() {} -func (*Field) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{0} -} - -func (m *Field) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Field.Unmarshal(m, b) -} -func (m *Field) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Field.Marshal(b, m, deterministic) -} -func (m *Field) XXX_Merge(src proto.Message) { - xxx_messageInfo_Field.Merge(m, src) -} -func (m *Field) XXX_Size() int { - return xxx_messageInfo_Field.Size(m) -} -func (m *Field) XXX_DiscardUnknown() { - xxx_messageInfo_Field.DiscardUnknown(m) -} - -var xxx_messageInfo_Field proto.InternalMessageInfo - -func (m *Field) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *Field) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -type Record struct { - // key of the record - Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - // value in the record - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - // time.Duration (signed int64 nanoseconds) - Expiry int64 `protobuf:"varint,3,opt,name=expiry,proto3" json:"expiry,omitempty"` - // the associated metadata - Metadata map[string]*Field `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Record) Reset() { *m = Record{} } -func (m *Record) String() string { return proto.CompactTextString(m) } -func (*Record) ProtoMessage() {} -func (*Record) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{1} -} - -func (m *Record) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Record.Unmarshal(m, b) -} -func (m *Record) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Record.Marshal(b, m, deterministic) -} -func (m *Record) XXX_Merge(src proto.Message) { - xxx_messageInfo_Record.Merge(m, src) -} -func (m *Record) XXX_Size() int { - return xxx_messageInfo_Record.Size(m) -} -func (m *Record) XXX_DiscardUnknown() { - xxx_messageInfo_Record.DiscardUnknown(m) -} - -var xxx_messageInfo_Record proto.InternalMessageInfo - -func (m *Record) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *Record) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func (m *Record) GetExpiry() int64 { - if m != nil { - return m.Expiry - } - return 0 -} - -func (m *Record) GetMetadata() map[string]*Field { - if m != nil { - return m.Metadata - } - return nil -} - -type ReadOptions struct { - Database string `protobuf:"bytes,1,opt,name=database,proto3" json:"database,omitempty"` - Table string `protobuf:"bytes,2,opt,name=table,proto3" json:"table,omitempty"` - Prefix bool `protobuf:"varint,3,opt,name=prefix,proto3" json:"prefix,omitempty"` - Suffix bool `protobuf:"varint,4,opt,name=suffix,proto3" json:"suffix,omitempty"` - Limit uint64 `protobuf:"varint,5,opt,name=limit,proto3" json:"limit,omitempty"` - Offset uint64 `protobuf:"varint,6,opt,name=offset,proto3" json:"offset,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadOptions) Reset() { *m = ReadOptions{} } -func (m *ReadOptions) String() string { return proto.CompactTextString(m) } -func (*ReadOptions) ProtoMessage() {} -func (*ReadOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{2} -} - -func (m *ReadOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadOptions.Unmarshal(m, b) -} -func (m *ReadOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadOptions.Marshal(b, m, deterministic) -} -func (m *ReadOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadOptions.Merge(m, src) -} -func (m *ReadOptions) XXX_Size() int { - return xxx_messageInfo_ReadOptions.Size(m) -} -func (m *ReadOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ReadOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadOptions proto.InternalMessageInfo - -func (m *ReadOptions) GetDatabase() string { - if m != nil { - return m.Database - } - return "" -} - -func (m *ReadOptions) GetTable() string { - if m != nil { - return m.Table - } - return "" -} - -func (m *ReadOptions) GetPrefix() bool { - if m != nil { - return m.Prefix - } - return false -} - -func (m *ReadOptions) GetSuffix() bool { - if m != nil { - return m.Suffix - } - return false -} - -func (m *ReadOptions) GetLimit() uint64 { - if m != nil { - return m.Limit - } - return 0 -} - -func (m *ReadOptions) GetOffset() uint64 { - if m != nil { - return m.Offset - } - return 0 -} - -type ReadRequest struct { - Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - Options *ReadOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadRequest) Reset() { *m = ReadRequest{} } -func (m *ReadRequest) String() string { return proto.CompactTextString(m) } -func (*ReadRequest) ProtoMessage() {} -func (*ReadRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{3} -} - -func (m *ReadRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadRequest.Unmarshal(m, b) -} -func (m *ReadRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadRequest.Marshal(b, m, deterministic) -} -func (m *ReadRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadRequest.Merge(m, src) -} -func (m *ReadRequest) XXX_Size() int { - return xxx_messageInfo_ReadRequest.Size(m) -} -func (m *ReadRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ReadRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadRequest proto.InternalMessageInfo - -func (m *ReadRequest) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *ReadRequest) GetOptions() *ReadOptions { - if m != nil { - return m.Options - } - return nil -} - -type ReadResponse struct { - Records []*Record `protobuf:"bytes,1,rep,name=records,proto3" json:"records,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadResponse) Reset() { *m = ReadResponse{} } -func (m *ReadResponse) String() string { return proto.CompactTextString(m) } -func (*ReadResponse) ProtoMessage() {} -func (*ReadResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{4} -} - -func (m *ReadResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadResponse.Unmarshal(m, b) -} -func (m *ReadResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadResponse.Marshal(b, m, deterministic) -} -func (m *ReadResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadResponse.Merge(m, src) -} -func (m *ReadResponse) XXX_Size() int { - return xxx_messageInfo_ReadResponse.Size(m) -} -func (m *ReadResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ReadResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadResponse proto.InternalMessageInfo - -func (m *ReadResponse) GetRecords() []*Record { - if m != nil { - return m.Records - } - return nil -} - -type WriteOptions struct { - Database string `protobuf:"bytes,1,opt,name=database,proto3" json:"database,omitempty"` - Table string `protobuf:"bytes,2,opt,name=table,proto3" json:"table,omitempty"` - // time.Time - Expiry int64 `protobuf:"varint,3,opt,name=expiry,proto3" json:"expiry,omitempty"` - // time.Duration - Ttl int64 `protobuf:"varint,4,opt,name=ttl,proto3" json:"ttl,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *WriteOptions) Reset() { *m = WriteOptions{} } -func (m *WriteOptions) String() string { return proto.CompactTextString(m) } -func (*WriteOptions) ProtoMessage() {} -func (*WriteOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{5} -} - -func (m *WriteOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_WriteOptions.Unmarshal(m, b) -} -func (m *WriteOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_WriteOptions.Marshal(b, m, deterministic) -} -func (m *WriteOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_WriteOptions.Merge(m, src) -} -func (m *WriteOptions) XXX_Size() int { - return xxx_messageInfo_WriteOptions.Size(m) -} -func (m *WriteOptions) XXX_DiscardUnknown() { - xxx_messageInfo_WriteOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_WriteOptions proto.InternalMessageInfo - -func (m *WriteOptions) GetDatabase() string { - if m != nil { - return m.Database - } - return "" -} - -func (m *WriteOptions) GetTable() string { - if m != nil { - return m.Table - } - return "" -} - -func (m *WriteOptions) GetExpiry() int64 { - if m != nil { - return m.Expiry - } - return 0 -} - -func (m *WriteOptions) GetTtl() int64 { - if m != nil { - return m.Ttl - } - return 0 -} - -type WriteRequest struct { - Record *Record `protobuf:"bytes,1,opt,name=record,proto3" json:"record,omitempty"` - Options *WriteOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *WriteRequest) Reset() { *m = WriteRequest{} } -func (m *WriteRequest) String() string { return proto.CompactTextString(m) } -func (*WriteRequest) ProtoMessage() {} -func (*WriteRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{6} -} - -func (m *WriteRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_WriteRequest.Unmarshal(m, b) -} -func (m *WriteRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_WriteRequest.Marshal(b, m, deterministic) -} -func (m *WriteRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_WriteRequest.Merge(m, src) -} -func (m *WriteRequest) XXX_Size() int { - return xxx_messageInfo_WriteRequest.Size(m) -} -func (m *WriteRequest) XXX_DiscardUnknown() { - xxx_messageInfo_WriteRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_WriteRequest proto.InternalMessageInfo - -func (m *WriteRequest) GetRecord() *Record { - if m != nil { - return m.Record - } - return nil -} - -func (m *WriteRequest) GetOptions() *WriteOptions { - if m != nil { - return m.Options - } - return nil -} - -type WriteResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *WriteResponse) Reset() { *m = WriteResponse{} } -func (m *WriteResponse) String() string { return proto.CompactTextString(m) } -func (*WriteResponse) ProtoMessage() {} -func (*WriteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{7} -} - -func (m *WriteResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_WriteResponse.Unmarshal(m, b) -} -func (m *WriteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_WriteResponse.Marshal(b, m, deterministic) -} -func (m *WriteResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_WriteResponse.Merge(m, src) -} -func (m *WriteResponse) XXX_Size() int { - return xxx_messageInfo_WriteResponse.Size(m) -} -func (m *WriteResponse) XXX_DiscardUnknown() { - xxx_messageInfo_WriteResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_WriteResponse proto.InternalMessageInfo - -type DeleteOptions struct { - Database string `protobuf:"bytes,1,opt,name=database,proto3" json:"database,omitempty"` - Table string `protobuf:"bytes,2,opt,name=table,proto3" json:"table,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteOptions) Reset() { *m = DeleteOptions{} } -func (m *DeleteOptions) String() string { return proto.CompactTextString(m) } -func (*DeleteOptions) ProtoMessage() {} -func (*DeleteOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{8} -} - -func (m *DeleteOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteOptions.Unmarshal(m, b) -} -func (m *DeleteOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteOptions.Marshal(b, m, deterministic) -} -func (m *DeleteOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteOptions.Merge(m, src) -} -func (m *DeleteOptions) XXX_Size() int { - return xxx_messageInfo_DeleteOptions.Size(m) -} -func (m *DeleteOptions) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteOptions proto.InternalMessageInfo - -func (m *DeleteOptions) GetDatabase() string { - if m != nil { - return m.Database - } - return "" -} - -func (m *DeleteOptions) GetTable() string { - if m != nil { - return m.Table - } - return "" -} - -type DeleteRequest struct { - Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - Options *DeleteOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteRequest) Reset() { *m = DeleteRequest{} } -func (m *DeleteRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteRequest) ProtoMessage() {} -func (*DeleteRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{9} -} - -func (m *DeleteRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteRequest.Unmarshal(m, b) -} -func (m *DeleteRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteRequest.Marshal(b, m, deterministic) -} -func (m *DeleteRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteRequest.Merge(m, src) -} -func (m *DeleteRequest) XXX_Size() int { - return xxx_messageInfo_DeleteRequest.Size(m) -} -func (m *DeleteRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteRequest proto.InternalMessageInfo - -func (m *DeleteRequest) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *DeleteRequest) GetOptions() *DeleteOptions { - if m != nil { - return m.Options - } - return nil -} - -type DeleteResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteResponse) Reset() { *m = DeleteResponse{} } -func (m *DeleteResponse) String() string { return proto.CompactTextString(m) } -func (*DeleteResponse) ProtoMessage() {} -func (*DeleteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{10} -} - -func (m *DeleteResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteResponse.Unmarshal(m, b) -} -func (m *DeleteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteResponse.Marshal(b, m, deterministic) -} -func (m *DeleteResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteResponse.Merge(m, src) -} -func (m *DeleteResponse) XXX_Size() int { - return xxx_messageInfo_DeleteResponse.Size(m) -} -func (m *DeleteResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteResponse proto.InternalMessageInfo - -type ListOptions struct { - Database string `protobuf:"bytes,1,opt,name=database,proto3" json:"database,omitempty"` - Table string `protobuf:"bytes,2,opt,name=table,proto3" json:"table,omitempty"` - Prefix string `protobuf:"bytes,3,opt,name=prefix,proto3" json:"prefix,omitempty"` - Suffix string `protobuf:"bytes,4,opt,name=suffix,proto3" json:"suffix,omitempty"` - Limit uint64 `protobuf:"varint,5,opt,name=limit,proto3" json:"limit,omitempty"` - Offset uint64 `protobuf:"varint,6,opt,name=offset,proto3" json:"offset,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListOptions) Reset() { *m = ListOptions{} } -func (m *ListOptions) String() string { return proto.CompactTextString(m) } -func (*ListOptions) ProtoMessage() {} -func (*ListOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{11} -} - -func (m *ListOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListOptions.Unmarshal(m, b) -} -func (m *ListOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListOptions.Marshal(b, m, deterministic) -} -func (m *ListOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListOptions.Merge(m, src) -} -func (m *ListOptions) XXX_Size() int { - return xxx_messageInfo_ListOptions.Size(m) -} -func (m *ListOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ListOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ListOptions proto.InternalMessageInfo - -func (m *ListOptions) GetDatabase() string { - if m != nil { - return m.Database - } - return "" -} - -func (m *ListOptions) GetTable() string { - if m != nil { - return m.Table - } - return "" -} - -func (m *ListOptions) GetPrefix() string { - if m != nil { - return m.Prefix - } - return "" -} - -func (m *ListOptions) GetSuffix() string { - if m != nil { - return m.Suffix - } - return "" -} - -func (m *ListOptions) GetLimit() uint64 { - if m != nil { - return m.Limit - } - return 0 -} - -func (m *ListOptions) GetOffset() uint64 { - if m != nil { - return m.Offset - } - return 0 -} - -type ListRequest struct { - Options *ListOptions `protobuf:"bytes,1,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListRequest) Reset() { *m = ListRequest{} } -func (m *ListRequest) String() string { return proto.CompactTextString(m) } -func (*ListRequest) ProtoMessage() {} -func (*ListRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{12} -} - -func (m *ListRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListRequest.Unmarshal(m, b) -} -func (m *ListRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListRequest.Marshal(b, m, deterministic) -} -func (m *ListRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListRequest.Merge(m, src) -} -func (m *ListRequest) XXX_Size() int { - return xxx_messageInfo_ListRequest.Size(m) -} -func (m *ListRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListRequest proto.InternalMessageInfo - -func (m *ListRequest) GetOptions() *ListOptions { - if m != nil { - return m.Options - } - return nil -} - -type ListResponse struct { - Keys []string `protobuf:"bytes,2,rep,name=keys,proto3" json:"keys,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListResponse) Reset() { *m = ListResponse{} } -func (m *ListResponse) String() string { return proto.CompactTextString(m) } -func (*ListResponse) ProtoMessage() {} -func (*ListResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{13} -} - -func (m *ListResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListResponse.Unmarshal(m, b) -} -func (m *ListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListResponse.Marshal(b, m, deterministic) -} -func (m *ListResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListResponse.Merge(m, src) -} -func (m *ListResponse) XXX_Size() int { - return xxx_messageInfo_ListResponse.Size(m) -} -func (m *ListResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListResponse proto.InternalMessageInfo - -func (m *ListResponse) GetKeys() []string { - if m != nil { - return m.Keys - } - return nil -} - -type DatabasesRequest struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DatabasesRequest) Reset() { *m = DatabasesRequest{} } -func (m *DatabasesRequest) String() string { return proto.CompactTextString(m) } -func (*DatabasesRequest) ProtoMessage() {} -func (*DatabasesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{14} -} - -func (m *DatabasesRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DatabasesRequest.Unmarshal(m, b) -} -func (m *DatabasesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DatabasesRequest.Marshal(b, m, deterministic) -} -func (m *DatabasesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DatabasesRequest.Merge(m, src) -} -func (m *DatabasesRequest) XXX_Size() int { - return xxx_messageInfo_DatabasesRequest.Size(m) -} -func (m *DatabasesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DatabasesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DatabasesRequest proto.InternalMessageInfo - -type DatabasesResponse struct { - Databases []string `protobuf:"bytes,1,rep,name=databases,proto3" json:"databases,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DatabasesResponse) Reset() { *m = DatabasesResponse{} } -func (m *DatabasesResponse) String() string { return proto.CompactTextString(m) } -func (*DatabasesResponse) ProtoMessage() {} -func (*DatabasesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{15} -} - -func (m *DatabasesResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DatabasesResponse.Unmarshal(m, b) -} -func (m *DatabasesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DatabasesResponse.Marshal(b, m, deterministic) -} -func (m *DatabasesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DatabasesResponse.Merge(m, src) -} -func (m *DatabasesResponse) XXX_Size() int { - return xxx_messageInfo_DatabasesResponse.Size(m) -} -func (m *DatabasesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DatabasesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DatabasesResponse proto.InternalMessageInfo - -func (m *DatabasesResponse) GetDatabases() []string { - if m != nil { - return m.Databases - } - return nil -} - -type TablesRequest struct { - Database string `protobuf:"bytes,1,opt,name=database,proto3" json:"database,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TablesRequest) Reset() { *m = TablesRequest{} } -func (m *TablesRequest) String() string { return proto.CompactTextString(m) } -func (*TablesRequest) ProtoMessage() {} -func (*TablesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{16} -} - -func (m *TablesRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TablesRequest.Unmarshal(m, b) -} -func (m *TablesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TablesRequest.Marshal(b, m, deterministic) -} -func (m *TablesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_TablesRequest.Merge(m, src) -} -func (m *TablesRequest) XXX_Size() int { - return xxx_messageInfo_TablesRequest.Size(m) -} -func (m *TablesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_TablesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_TablesRequest proto.InternalMessageInfo - -func (m *TablesRequest) GetDatabase() string { - if m != nil { - return m.Database - } - return "" -} - -type TablesResponse struct { - Tables []string `protobuf:"bytes,1,rep,name=tables,proto3" json:"tables,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TablesResponse) Reset() { *m = TablesResponse{} } -func (m *TablesResponse) String() string { return proto.CompactTextString(m) } -func (*TablesResponse) ProtoMessage() {} -func (*TablesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1ba364858f5c3cdb, []int{17} -} - -func (m *TablesResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TablesResponse.Unmarshal(m, b) -} -func (m *TablesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TablesResponse.Marshal(b, m, deterministic) -} -func (m *TablesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TablesResponse.Merge(m, src) -} -func (m *TablesResponse) XXX_Size() int { - return xxx_messageInfo_TablesResponse.Size(m) -} -func (m *TablesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TablesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TablesResponse proto.InternalMessageInfo - -func (m *TablesResponse) GetTables() []string { - if m != nil { - return m.Tables - } - return nil -} - -func init() { - proto.RegisterType((*Field)(nil), "go.micro.store.Field") - proto.RegisterType((*Record)(nil), "go.micro.store.Record") - proto.RegisterMapType((map[string]*Field)(nil), "go.micro.store.Record.MetadataEntry") - proto.RegisterType((*ReadOptions)(nil), "go.micro.store.ReadOptions") - proto.RegisterType((*ReadRequest)(nil), "go.micro.store.ReadRequest") - proto.RegisterType((*ReadResponse)(nil), "go.micro.store.ReadResponse") - proto.RegisterType((*WriteOptions)(nil), "go.micro.store.WriteOptions") - proto.RegisterType((*WriteRequest)(nil), "go.micro.store.WriteRequest") - proto.RegisterType((*WriteResponse)(nil), "go.micro.store.WriteResponse") - proto.RegisterType((*DeleteOptions)(nil), "go.micro.store.DeleteOptions") - proto.RegisterType((*DeleteRequest)(nil), "go.micro.store.DeleteRequest") - proto.RegisterType((*DeleteResponse)(nil), "go.micro.store.DeleteResponse") - proto.RegisterType((*ListOptions)(nil), "go.micro.store.ListOptions") - proto.RegisterType((*ListRequest)(nil), "go.micro.store.ListRequest") - proto.RegisterType((*ListResponse)(nil), "go.micro.store.ListResponse") - proto.RegisterType((*DatabasesRequest)(nil), "go.micro.store.DatabasesRequest") - proto.RegisterType((*DatabasesResponse)(nil), "go.micro.store.DatabasesResponse") - proto.RegisterType((*TablesRequest)(nil), "go.micro.store.TablesRequest") - proto.RegisterType((*TablesResponse)(nil), "go.micro.store.TablesResponse") -} - -func init() { proto.RegisterFile("store/service/proto/store.proto", fileDescriptor_1ba364858f5c3cdb) } - -var fileDescriptor_1ba364858f5c3cdb = []byte{ - // 655 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0xdb, 0x6e, 0xd3, 0x40, - 0x10, 0xad, 0x6b, 0xc7, 0x8d, 0xa7, 0x49, 0x09, 0x2b, 0xa8, 0xac, 0xd0, 0x42, 0x58, 0xf1, 0x60, - 0xa9, 0x92, 0x7b, 0x41, 0x5c, 0xc4, 0x53, 0x11, 0x6d, 0x25, 0x10, 0x08, 0x69, 0x41, 0x20, 0xf1, - 0xe6, 0x36, 0x1b, 0x64, 0xea, 0xc6, 0xc6, 0xbb, 0x89, 0x9a, 0x8f, 0xe1, 0x73, 0xf8, 0x0d, 0xbe, - 0x05, 0xed, 0xcd, 0xb1, 0x1d, 0xbb, 0x0f, 0x94, 0xb7, 0x9d, 0xd9, 0xd9, 0x33, 0xe7, 0x9c, 0x19, - 0x27, 0xf0, 0x88, 0xf1, 0x34, 0xa7, 0xfb, 0x8c, 0xe6, 0xf3, 0xf8, 0x82, 0xee, 0x67, 0x79, 0xca, - 0xd3, 0x7d, 0x99, 0x0b, 0xe5, 0x19, 0x6d, 0x7d, 0x4f, 0xc3, 0xab, 0xf8, 0x22, 0x4f, 0x43, 0x99, - 0xc5, 0x87, 0xd0, 0x39, 0x8b, 0x69, 0x32, 0x46, 0x08, 0x1c, 0xbe, 0xc8, 0xa8, 0x6f, 0x8d, 0xac, - 0xc0, 0x23, 0xf2, 0x8c, 0xee, 0x41, 0x67, 0x1e, 0x25, 0x33, 0xea, 0xaf, 0xcb, 0xa4, 0x0a, 0xf0, - 0x1f, 0x0b, 0x5c, 0x42, 0x2f, 0xd2, 0x7c, 0x8c, 0x06, 0x60, 0x5f, 0xd2, 0x85, 0x7e, 0x23, 0x8e, - 0xd5, 0x27, 0x3d, 0xfd, 0x04, 0x6d, 0x83, 0x4b, 0xaf, 0xb3, 0x38, 0x5f, 0xf8, 0xf6, 0xc8, 0x0a, - 0x6c, 0xa2, 0x23, 0x74, 0x0c, 0xdd, 0x2b, 0xca, 0xa3, 0x71, 0xc4, 0x23, 0xdf, 0x19, 0xd9, 0xc1, - 0xe6, 0xd1, 0x93, 0xb0, 0x4a, 0x30, 0x54, 0x9d, 0xc2, 0x0f, 0xba, 0xec, 0x74, 0xca, 0xf3, 0x05, - 0x29, 0x5e, 0x0d, 0x09, 0xf4, 0x2b, 0x57, 0x0d, 0x94, 0xf6, 0xca, 0x94, 0x36, 0x8f, 0xee, 0xd7, - 0x3b, 0x48, 0xfd, 0x9a, 0xe9, 0xab, 0xf5, 0x97, 0x16, 0xfe, 0x65, 0xc1, 0x26, 0xa1, 0xd1, 0xf8, - 0x63, 0xc6, 0xe3, 0x74, 0xca, 0xd0, 0x10, 0xba, 0x02, 0xff, 0x3c, 0x62, 0xc6, 0x9e, 0x22, 0x16, - 0x7a, 0x79, 0x74, 0x9e, 0x14, 0x16, 0xc9, 0x40, 0xe8, 0xcd, 0x72, 0x3a, 0x89, 0xaf, 0xa5, 0xde, - 0x2e, 0xd1, 0x91, 0xc8, 0xb3, 0xd9, 0x44, 0xe4, 0x1d, 0x95, 0x57, 0x91, 0x40, 0x49, 0xe2, 0xab, - 0x98, 0xfb, 0x9d, 0x91, 0x15, 0x38, 0x44, 0x05, 0xa2, 0x3a, 0x9d, 0x4c, 0x18, 0xe5, 0xbe, 0x2b, - 0xd3, 0x3a, 0xc2, 0x5f, 0x14, 0x3d, 0x42, 0x7f, 0xce, 0x28, 0xe3, 0x0d, 0x8a, 0x9f, 0xc1, 0x46, - 0xaa, 0xb8, 0x6b, 0xcd, 0x0f, 0x56, 0x5d, 0x2d, 0xe4, 0x11, 0x53, 0x8b, 0x8f, 0xa1, 0xa7, 0x70, - 0x59, 0x96, 0x4e, 0x19, 0x45, 0x07, 0xb0, 0x91, 0x4b, 0xf7, 0x99, 0x6f, 0xc9, 0xe1, 0x6c, 0x37, - 0x0f, 0x87, 0x98, 0x32, 0xfc, 0x03, 0x7a, 0x5f, 0xf3, 0x98, 0xd3, 0x5b, 0x39, 0xd7, 0xb8, 0x29, - 0x03, 0xb0, 0x39, 0x4f, 0xa4, 0x6d, 0x36, 0x11, 0x47, 0x3c, 0xd7, 0xbd, 0x8c, 0x0d, 0x21, 0xb8, - 0x8a, 0x86, 0xec, 0xd4, 0x4e, 0x56, 0x57, 0xa1, 0xe7, 0x75, 0x93, 0x76, 0xea, 0x0f, 0xca, 0x52, - 0x96, 0x2e, 0xdd, 0x81, 0xbe, 0xee, 0xab, 0x6c, 0xc2, 0xaf, 0xa1, 0x7f, 0x42, 0x13, 0x7a, 0x0b, - 0xd5, 0xf8, 0x9b, 0x81, 0x68, 0x9f, 0xe9, 0x8b, 0x3a, 0xdd, 0xdd, 0x3a, 0xdd, 0x0a, 0x89, 0x25, - 0xdf, 0x01, 0x6c, 0x19, 0x6c, 0x4d, 0x58, 0xec, 0xf7, 0xfb, 0x98, 0xf1, 0xff, 0xb5, 0xdf, 0x5e, - 0xcb, 0x7e, 0x7b, 0xff, 0xb8, 0xdf, 0x27, 0x8a, 0x9e, 0xf1, 0xa2, 0xb4, 0xcd, 0x56, 0xf3, 0x36, - 0x97, 0xc4, 0x2c, 0x75, 0x07, 0xd0, 0x53, 0x28, 0x7a, 0x9b, 0x11, 0x38, 0x97, 0x74, 0x21, 0xdc, - 0xb3, 0xc5, 0x0f, 0x9c, 0x38, 0xbf, 0x73, 0xba, 0xd6, 0x60, 0x1d, 0x23, 0x18, 0x9c, 0x68, 0xbd, - 0x4c, 0x37, 0xc5, 0x87, 0x70, 0xb7, 0x94, 0xd3, 0x10, 0x3b, 0xe0, 0x19, 0x63, 0xd4, 0x27, 0xe1, - 0x91, 0x65, 0x02, 0xef, 0x41, 0xff, 0xb3, 0x70, 0xc7, 0x60, 0xdc, 0xe4, 0x2b, 0x0e, 0x60, 0xcb, - 0x14, 0x6b, 0xf0, 0x6d, 0x70, 0xa5, 0xb9, 0x06, 0x59, 0x47, 0x47, 0xbf, 0x6d, 0xe8, 0x7c, 0x12, - 0x32, 0xd1, 0x1b, 0x70, 0xc4, 0xf7, 0x89, 0x1a, 0xbf, 0x66, 0xdd, 0x74, 0xb8, 0xd3, 0x7c, 0xa9, - 0x47, 0xbf, 0x86, 0xce, 0xa0, 0x23, 0xd7, 0x17, 0x35, 0xaf, 0xbb, 0x81, 0xd9, 0x6d, 0xb9, 0x2d, - 0x70, 0xde, 0x82, 0xab, 0xd6, 0x0a, 0xb5, 0x2c, 0xa2, 0x41, 0x7a, 0xd8, 0x76, 0x5d, 0x40, 0x9d, - 0x82, 0x23, 0x26, 0x85, 0x1a, 0xe7, 0xda, 0xaa, 0xab, 0x3c, 0x5c, 0xbc, 0x76, 0x60, 0x21, 0x02, - 0x5e, 0x31, 0x32, 0x34, 0x5a, 0xe9, 0x5a, 0x9b, 0xf0, 0xf0, 0xf1, 0x0d, 0x15, 0x65, 0x95, 0x6a, - 0x4c, 0xab, 0x2a, 0x2b, 0xb3, 0x5e, 0x55, 0x59, 0x9d, 0x2e, 0x5e, 0x3b, 0x77, 0xe5, 0x1f, 0xf0, - 0xd3, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xe9, 0x8d, 0xa6, 0x4b, 0xa3, 0x07, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// StoreClient is the client API for Store service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type StoreClient interface { - Read(ctx context.Context, in *ReadRequest, opts ...grpc.CallOption) (*ReadResponse, error) - Write(ctx context.Context, in *WriteRequest, opts ...grpc.CallOption) (*WriteResponse, error) - Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) - List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (Store_ListClient, error) - Databases(ctx context.Context, in *DatabasesRequest, opts ...grpc.CallOption) (*DatabasesResponse, error) - Tables(ctx context.Context, in *TablesRequest, opts ...grpc.CallOption) (*TablesResponse, error) -} - -type storeClient struct { - cc *grpc.ClientConn -} - -func NewStoreClient(cc *grpc.ClientConn) StoreClient { - return &storeClient{cc} -} - -func (c *storeClient) Read(ctx context.Context, in *ReadRequest, opts ...grpc.CallOption) (*ReadResponse, error) { - out := new(ReadResponse) - err := c.cc.Invoke(ctx, "/go.micro.store.Store/Read", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storeClient) Write(ctx context.Context, in *WriteRequest, opts ...grpc.CallOption) (*WriteResponse, error) { - out := new(WriteResponse) - err := c.cc.Invoke(ctx, "/go.micro.store.Store/Write", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storeClient) Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) { - out := new(DeleteResponse) - err := c.cc.Invoke(ctx, "/go.micro.store.Store/Delete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storeClient) List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (Store_ListClient, error) { - stream, err := c.cc.NewStream(ctx, &_Store_serviceDesc.Streams[0], "/go.micro.store.Store/List", opts...) - if err != nil { - return nil, err - } - x := &storeListClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Store_ListClient interface { - Recv() (*ListResponse, error) - grpc.ClientStream -} - -type storeListClient struct { - grpc.ClientStream -} - -func (x *storeListClient) Recv() (*ListResponse, error) { - m := new(ListResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *storeClient) Databases(ctx context.Context, in *DatabasesRequest, opts ...grpc.CallOption) (*DatabasesResponse, error) { - out := new(DatabasesResponse) - err := c.cc.Invoke(ctx, "/go.micro.store.Store/Databases", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storeClient) Tables(ctx context.Context, in *TablesRequest, opts ...grpc.CallOption) (*TablesResponse, error) { - out := new(TablesResponse) - err := c.cc.Invoke(ctx, "/go.micro.store.Store/Tables", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// StoreServer is the server API for Store service. -type StoreServer interface { - Read(context.Context, *ReadRequest) (*ReadResponse, error) - Write(context.Context, *WriteRequest) (*WriteResponse, error) - Delete(context.Context, *DeleteRequest) (*DeleteResponse, error) - List(*ListRequest, Store_ListServer) error - Databases(context.Context, *DatabasesRequest) (*DatabasesResponse, error) - Tables(context.Context, *TablesRequest) (*TablesResponse, error) -} - -// UnimplementedStoreServer can be embedded to have forward compatible implementations. -type UnimplementedStoreServer struct { -} - -func (*UnimplementedStoreServer) Read(ctx context.Context, req *ReadRequest) (*ReadResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Read not implemented") -} -func (*UnimplementedStoreServer) Write(ctx context.Context, req *WriteRequest) (*WriteResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Write not implemented") -} -func (*UnimplementedStoreServer) Delete(ctx context.Context, req *DeleteRequest) (*DeleteResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") -} -func (*UnimplementedStoreServer) List(req *ListRequest, srv Store_ListServer) error { - return status.Errorf(codes.Unimplemented, "method List not implemented") -} -func (*UnimplementedStoreServer) Databases(ctx context.Context, req *DatabasesRequest) (*DatabasesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Databases not implemented") -} -func (*UnimplementedStoreServer) Tables(ctx context.Context, req *TablesRequest) (*TablesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Tables not implemented") -} - -func RegisterStoreServer(s *grpc.Server, srv StoreServer) { - s.RegisterService(&_Store_serviceDesc, srv) -} - -func _Store_Read_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ReadRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(StoreServer).Read(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.store.Store/Read", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(StoreServer).Read(ctx, req.(*ReadRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Store_Write_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(WriteRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(StoreServer).Write(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.store.Store/Write", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(StoreServer).Write(ctx, req.(*WriteRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Store_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(StoreServer).Delete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.store.Store/Delete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(StoreServer).Delete(ctx, req.(*DeleteRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Store_List_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(ListRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(StoreServer).List(m, &storeListServer{stream}) -} - -type Store_ListServer interface { - Send(*ListResponse) error - grpc.ServerStream -} - -type storeListServer struct { - grpc.ServerStream -} - -func (x *storeListServer) Send(m *ListResponse) error { - return x.ServerStream.SendMsg(m) -} - -func _Store_Databases_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DatabasesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(StoreServer).Databases(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.store.Store/Databases", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(StoreServer).Databases(ctx, req.(*DatabasesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Store_Tables_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(TablesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(StoreServer).Tables(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/go.micro.store.Store/Tables", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(StoreServer).Tables(ctx, req.(*TablesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Store_serviceDesc = grpc.ServiceDesc{ - ServiceName: "go.micro.store.Store", - HandlerType: (*StoreServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Read", - Handler: _Store_Read_Handler, - }, - { - MethodName: "Write", - Handler: _Store_Write_Handler, - }, - { - MethodName: "Delete", - Handler: _Store_Delete_Handler, - }, - { - MethodName: "Databases", - Handler: _Store_Databases_Handler, - }, - { - MethodName: "Tables", - Handler: _Store_Tables_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "List", - Handler: _Store_List_Handler, - ServerStreams: true, - }, - }, - Metadata: "store/service/proto/store.proto", -} diff --git a/store/service/proto/store.pb.micro.go b/store/service/proto/store.pb.micro.go deleted file mode 100644 index 0e622f09..00000000 --- a/store/service/proto/store.pb.micro.go +++ /dev/null @@ -1,253 +0,0 @@ -// Code generated by protoc-gen-micro. DO NOT EDIT. -// source: store/service/proto/store.proto - -package go_micro_store - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -import ( - context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ api.Endpoint -var _ context.Context -var _ client.Option -var _ server.Option - -// Api Endpoints for Store service - -func NewStoreEndpoints() []*api.Endpoint { - return []*api.Endpoint{} -} - -// Client API for Store service - -type StoreService interface { - Read(ctx context.Context, in *ReadRequest, opts ...client.CallOption) (*ReadResponse, error) - Write(ctx context.Context, in *WriteRequest, opts ...client.CallOption) (*WriteResponse, error) - Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) - List(ctx context.Context, in *ListRequest, opts ...client.CallOption) (Store_ListService, error) - Databases(ctx context.Context, in *DatabasesRequest, opts ...client.CallOption) (*DatabasesResponse, error) - Tables(ctx context.Context, in *TablesRequest, opts ...client.CallOption) (*TablesResponse, error) -} - -type storeService struct { - c client.Client - name string -} - -func NewStoreService(name string, c client.Client) StoreService { - return &storeService{ - c: c, - name: name, - } -} - -func (c *storeService) Read(ctx context.Context, in *ReadRequest, opts ...client.CallOption) (*ReadResponse, error) { - req := c.c.NewRequest(c.name, "Store.Read", in) - out := new(ReadResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storeService) Write(ctx context.Context, in *WriteRequest, opts ...client.CallOption) (*WriteResponse, error) { - req := c.c.NewRequest(c.name, "Store.Write", in) - out := new(WriteResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storeService) Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) { - req := c.c.NewRequest(c.name, "Store.Delete", in) - out := new(DeleteResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storeService) List(ctx context.Context, in *ListRequest, opts ...client.CallOption) (Store_ListService, error) { - req := c.c.NewRequest(c.name, "Store.List", &ListRequest{}) - stream, err := c.c.Stream(ctx, req, opts...) - if err != nil { - return nil, err - } - if err := stream.Send(in); err != nil { - return nil, err - } - return &storeServiceList{stream}, nil -} - -type Store_ListService interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Recv() (*ListResponse, error) -} - -type storeServiceList struct { - stream client.Stream -} - -func (x *storeServiceList) Close() error { - return x.stream.Close() -} - -func (x *storeServiceList) Context() context.Context { - return x.stream.Context() -} - -func (x *storeServiceList) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *storeServiceList) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *storeServiceList) Recv() (*ListResponse, error) { - m := new(ListResponse) - err := x.stream.Recv(m) - if err != nil { - return nil, err - } - return m, nil -} - -func (c *storeService) Databases(ctx context.Context, in *DatabasesRequest, opts ...client.CallOption) (*DatabasesResponse, error) { - req := c.c.NewRequest(c.name, "Store.Databases", in) - out := new(DatabasesResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storeService) Tables(ctx context.Context, in *TablesRequest, opts ...client.CallOption) (*TablesResponse, error) { - req := c.c.NewRequest(c.name, "Store.Tables", in) - out := new(TablesResponse) - err := c.c.Call(ctx, req, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Store service - -type StoreHandler interface { - Read(context.Context, *ReadRequest, *ReadResponse) error - Write(context.Context, *WriteRequest, *WriteResponse) error - Delete(context.Context, *DeleteRequest, *DeleteResponse) error - List(context.Context, *ListRequest, Store_ListStream) error - Databases(context.Context, *DatabasesRequest, *DatabasesResponse) error - Tables(context.Context, *TablesRequest, *TablesResponse) error -} - -func RegisterStoreHandler(s server.Server, hdlr StoreHandler, opts ...server.HandlerOption) error { - type store interface { - Read(ctx context.Context, in *ReadRequest, out *ReadResponse) error - Write(ctx context.Context, in *WriteRequest, out *WriteResponse) error - Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error - List(ctx context.Context, stream server.Stream) error - Databases(ctx context.Context, in *DatabasesRequest, out *DatabasesResponse) error - Tables(ctx context.Context, in *TablesRequest, out *TablesResponse) error - } - type Store struct { - store - } - h := &storeHandler{hdlr} - return s.Handle(s.NewHandler(&Store{h}, opts...)) -} - -type storeHandler struct { - StoreHandler -} - -func (h *storeHandler) Read(ctx context.Context, in *ReadRequest, out *ReadResponse) error { - return h.StoreHandler.Read(ctx, in, out) -} - -func (h *storeHandler) Write(ctx context.Context, in *WriteRequest, out *WriteResponse) error { - return h.StoreHandler.Write(ctx, in, out) -} - -func (h *storeHandler) Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error { - return h.StoreHandler.Delete(ctx, in, out) -} - -func (h *storeHandler) List(ctx context.Context, stream server.Stream) error { - m := new(ListRequest) - if err := stream.Recv(m); err != nil { - return err - } - return h.StoreHandler.List(ctx, m, &storeListStream{stream}) -} - -type Store_ListStream interface { - Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error - Close() error - Send(*ListResponse) error -} - -type storeListStream struct { - stream server.Stream -} - -func (x *storeListStream) Close() error { - return x.stream.Close() -} - -func (x *storeListStream) Context() context.Context { - return x.stream.Context() -} - -func (x *storeListStream) SendMsg(m interface{}) error { - return x.stream.Send(m) -} - -func (x *storeListStream) RecvMsg(m interface{}) error { - return x.stream.Recv(m) -} - -func (x *storeListStream) Send(m *ListResponse) error { - return x.stream.Send(m) -} - -func (h *storeHandler) Databases(ctx context.Context, in *DatabasesRequest, out *DatabasesResponse) error { - return h.StoreHandler.Databases(ctx, in, out) -} - -func (h *storeHandler) Tables(ctx context.Context, in *TablesRequest, out *TablesResponse) error { - return h.StoreHandler.Tables(ctx, in, out) -} diff --git a/store/service/proto/store.proto b/store/service/proto/store.proto deleted file mode 100644 index 80fbc40f..00000000 --- a/store/service/proto/store.proto +++ /dev/null @@ -1,109 +0,0 @@ -syntax = "proto3"; - -package go.micro.store; - -service Store { - rpc Read(ReadRequest) returns (ReadResponse) {}; - rpc Write(WriteRequest) returns (WriteResponse) {}; - rpc Delete(DeleteRequest) returns (DeleteResponse) {}; - rpc List(ListRequest) returns (stream ListResponse) {}; - rpc Databases(DatabasesRequest) returns (DatabasesResponse) {}; - rpc Tables(TablesRequest) returns (TablesResponse) {}; -} - -message Field { - // type of value e.g string, int, int64, bool, float64 - string type = 1; - // the actual value - string value = 2; -} - -message Record { - // key of the record - string key = 1; - // value in the record - bytes value = 2; - // time.Duration (signed int64 nanoseconds) - int64 expiry = 3; - // the associated metadata - map metadata = 4; -} - -message ReadOptions { - string database = 1; - string table = 2; - bool prefix = 3; - bool suffix = 4; - uint64 limit = 5; - uint64 offset = 6; -} - -message ReadRequest { - string key = 1; - ReadOptions options = 2; -} - -message ReadResponse { - repeated Record records = 1; -} - -message WriteOptions { - string database = 1; - string table = 2; - // time.Time - int64 expiry = 3; - // time.Duration - int64 ttl = 4; -} - -message WriteRequest { - Record record = 1; - WriteOptions options = 2; -} - -message WriteResponse {} - -message DeleteOptions { - string database = 1; - string table = 2; -} - -message DeleteRequest { - string key = 1; - DeleteOptions options = 2; -} - -message DeleteResponse {} - -message ListOptions { - string database = 1; - string table = 2; - string prefix = 3; - string suffix = 4; - uint64 limit = 5; - uint64 offset = 6; -} - - -message ListRequest { - ListOptions options = 1; -} - -message ListResponse { - reserved 1; //repeated Record records = 1; - repeated string keys = 2; -} - -message DatabasesRequest {} - -message DatabasesResponse { - repeated string databases = 1; -} - -message TablesRequest { - string database = 1; -} - -message TablesResponse { - repeated string tables = 1; -} diff --git a/store/service/service.go b/store/service/service.go deleted file mode 100644 index 9c164164..00000000 --- a/store/service/service.go +++ /dev/null @@ -1,263 +0,0 @@ -// Package service implements the store service interface -package service - -import ( - "context" - "fmt" - "io" - "reflect" - "time" - - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/store" - pb "github.com/micro/go-micro/v2/store/service/proto" -) - -type serviceStore struct { - options store.Options - - // The database to use - Database string - - // The table to use - Table string - - // Addresses of the nodes - Nodes []string - - // store service client - Client pb.StoreService -} - -func (s *serviceStore) Close() error { - return nil -} - -func (s *serviceStore) Init(opts ...store.Option) error { - for _, o := range opts { - o(&s.options) - } - s.Database = s.options.Database - s.Table = s.options.Table - s.Nodes = s.options.Nodes - - if s.options.Client == nil { - s.options.Client = client.DefaultClient - } - s.Client = pb.NewStoreService("go.micro.store", s.options.Client) - - return nil -} - -func (s *serviceStore) Context() context.Context { - ctx := context.Background() - md := make(metadata.Metadata) - if len(s.Database) > 0 { - md["Micro-Database"] = s.Database - } - - if len(s.Table) > 0 { - md["Micro-Table"] = s.Table - } - return metadata.NewContext(ctx, md) -} - -// Sync all the known records -func (s *serviceStore) List(opts ...store.ListOption) ([]string, error) { - options := store.ListOptions{ - Database: s.Database, - Table: s.Table, - } - - for _, o := range opts { - o(&options) - } - - listOpts := &pb.ListOptions{ - Database: options.Database, - Table: options.Table, - Prefix: options.Prefix, - Suffix: options.Suffix, - Limit: uint64(options.Limit), - Offset: uint64(options.Offset), - } - - stream, err := s.Client.List(s.Context(), &pb.ListRequest{Options: listOpts}, client.WithAddress(s.Nodes...)) - if err != nil && errors.Equal(err, errors.NotFound("", "")) { - return nil, store.ErrNotFound - } else if err != nil { - return nil, err - } - defer stream.Close() - - var keys []string - - for { - rsp, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - return keys, err - } - - for _, key := range rsp.Keys { - keys = append(keys, key) - } - } - - return keys, nil -} - -// Read a record with key -func (s *serviceStore) Read(key string, opts ...store.ReadOption) ([]*store.Record, error) { - options := store.ReadOptions{ - Database: s.Database, - Table: s.Table, - } - - for _, o := range opts { - o(&options) - } - - readOpts := &pb.ReadOptions{ - Database: options.Database, - Table: options.Table, - Prefix: options.Prefix, - Suffix: options.Suffix, - Limit: uint64(options.Limit), - Offset: uint64(options.Offset), - } - - rsp, err := s.Client.Read(s.Context(), &pb.ReadRequest{ - Key: key, - Options: readOpts, - }, client.WithAddress(s.Nodes...)) - if err != nil && errors.Equal(err, errors.NotFound("", "")) { - return nil, store.ErrNotFound - } else if err != nil { - return nil, err - } - - records := make([]*store.Record, 0, len(rsp.Records)) - - for _, val := range rsp.Records { - metadata := make(map[string]interface{}) - - for k, v := range val.Metadata { - switch v.Type { - // TODO: parse all types - default: - metadata[k] = v - } - } - - records = append(records, &store.Record{ - Key: val.Key, - Value: val.Value, - Expiry: time.Duration(val.Expiry) * time.Second, - Metadata: metadata, - }) - } - - return records, nil -} - -// Write a record -func (s *serviceStore) Write(record *store.Record, opts ...store.WriteOption) error { - options := store.WriteOptions{ - Database: s.Database, - Table: s.Table, - } - - for _, o := range opts { - o(&options) - } - - writeOpts := &pb.WriteOptions{ - Database: options.Database, - Table: options.Table, - } - - metadata := make(map[string]*pb.Field) - - for k, v := range record.Metadata { - metadata[k] = &pb.Field{ - Type: reflect.TypeOf(v).String(), - Value: fmt.Sprintf("%v", v), - } - } - - _, err := s.Client.Write(s.Context(), &pb.WriteRequest{ - Record: &pb.Record{ - Key: record.Key, - Value: record.Value, - Expiry: int64(record.Expiry.Seconds()), - Metadata: metadata, - }, - Options: writeOpts}, client.WithAddress(s.Nodes...)) - if err != nil && errors.Equal(err, errors.NotFound("", "")) { - return store.ErrNotFound - } - - return err -} - -// Delete a record with key -func (s *serviceStore) Delete(key string, opts ...store.DeleteOption) error { - options := store.DeleteOptions{ - Database: s.Database, - Table: s.Table, - } - - for _, o := range opts { - o(&options) - } - - deleteOpts := &pb.DeleteOptions{ - Database: options.Database, - Table: options.Table, - } - - _, err := s.Client.Delete(s.Context(), &pb.DeleteRequest{ - Key: key, - Options: deleteOpts, - }, client.WithAddress(s.Nodes...)) - if err != nil && errors.Equal(err, errors.NotFound("", "")) { - return store.ErrNotFound - } - - return err -} - -func (s *serviceStore) String() string { - return "service" -} - -func (s *serviceStore) Options() store.Options { - return s.options -} - -// NewStore returns a new store service implementation -func NewStore(opts ...store.Option) store.Store { - var options store.Options - for _, o := range opts { - o(&options) - } - - if options.Client == nil { - options.Client = client.DefaultClient - } - - service := &serviceStore{ - options: options, - Database: options.Database, - Table: options.Table, - Nodes: options.Nodes, - Client: pb.NewStoreService("go.micro.store", options.Client), - } - - return service -} diff --git a/sync/etcd/etcd.go b/sync/etcd/etcd.go index 7d493942..553a6b25 100644 --- a/sync/etcd/etcd.go +++ b/sync/etcd/etcd.go @@ -11,7 +11,7 @@ import ( client "github.com/coreos/etcd/clientv3" cc "github.com/coreos/etcd/clientv3/concurrency" - "github.com/micro/go-micro/v2/sync" + "github.com/micro/go-micro/v3/sync" ) type etcdSync struct { diff --git a/sync/memory/memory.go b/sync/memory/memory.go index f3a92180..1f201b20 100644 --- a/sync/memory/memory.go +++ b/sync/memory/memory.go @@ -5,7 +5,7 @@ import ( gosync "sync" "time" - "github.com/micro/go-micro/v2/sync" + "github.com/micro/go-micro/v3/sync" ) type memorySync struct { diff --git a/transport/grpc/grpc.go b/transport/grpc/grpc.go index 23c5d095..d5ee7083 100644 --- a/transport/grpc/grpc.go +++ b/transport/grpc/grpc.go @@ -6,15 +6,15 @@ import ( "crypto/tls" "net" - "github.com/micro/go-micro/v2/transport" - maddr "github.com/micro/go-micro/v2/util/addr" - mnet "github.com/micro/go-micro/v2/util/net" - mls "github.com/micro/go-micro/v2/util/tls" + "github.com/micro/go-micro/v3/transport" + maddr "github.com/micro/go-micro/v3/util/addr" + mnet "github.com/micro/go-micro/v3/util/net" + mls "github.com/micro/go-micro/v3/util/tls" "google.golang.org/grpc" "google.golang.org/grpc/credentials" - pb "github.com/micro/go-micro/v2/transport/grpc/proto" + pb "github.com/micro/go-micro/v3/transport/grpc/proto" ) type grpcTransport struct { diff --git a/transport/grpc/grpc_test.go b/transport/grpc/grpc_test.go index 5fbca5b8..6d577f9c 100644 --- a/transport/grpc/grpc_test.go +++ b/transport/grpc/grpc_test.go @@ -4,7 +4,7 @@ import ( "net" "testing" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) func expectedPort(t *testing.T, expected string, lsn transport.Listener) { diff --git a/transport/grpc/handler.go b/transport/grpc/handler.go index 01ab2049..956d55cf 100644 --- a/transport/grpc/handler.go +++ b/transport/grpc/handler.go @@ -3,10 +3,10 @@ package grpc import ( "runtime/debug" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/transport" - pb "github.com/micro/go-micro/v2/transport/grpc/proto" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/transport" + pb "github.com/micro/go-micro/v3/transport/grpc/proto" "google.golang.org/grpc/peer" ) diff --git a/transport/grpc/proto/transport.pb.micro.go b/transport/grpc/proto/transport.pb.micro.go index 96532171..c5a18636 100644 --- a/transport/grpc/proto/transport.pb.micro.go +++ b/transport/grpc/proto/transport.pb.micro.go @@ -11,9 +11,9 @@ import ( import ( context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" + api "github.com/micro/go-micro/v3/api" + client "github.com/micro/go-micro/v3/client" + server "github.com/micro/go-micro/v3/server" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/transport/grpc/socket.go b/transport/grpc/socket.go index 866ee7ae..d260800c 100644 --- a/transport/grpc/socket.go +++ b/transport/grpc/socket.go @@ -1,8 +1,8 @@ package grpc import ( - "github.com/micro/go-micro/v2/transport" - pb "github.com/micro/go-micro/v2/transport/grpc/proto" + "github.com/micro/go-micro/v3/transport" + pb "github.com/micro/go-micro/v3/transport/grpc/proto" "google.golang.org/grpc" ) diff --git a/transport/http/http.go b/transport/http/http.go index b9fd0b11..03c73fac 100644 --- a/transport/http/http.go +++ b/transport/http/http.go @@ -2,7 +2,7 @@ package http import ( - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) // NewTransport returns a new http transport using net/http and supporting http2 diff --git a/transport/http/http_test.go b/transport/http/http_test.go index fd519063..72b4314b 100644 --- a/transport/http/http_test.go +++ b/transport/http/http_test.go @@ -4,7 +4,7 @@ import ( "sync" "testing" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) func call(b *testing.B, c int) { diff --git a/transport/http/options.go b/transport/http/options.go index c5210f09..1f45dba4 100644 --- a/transport/http/options.go +++ b/transport/http/options.go @@ -4,7 +4,7 @@ import ( "context" "net/http" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) // Handle registers the handler for the given pattern. diff --git a/transport/http_transport.go b/transport/http_transport.go index 2dfe7944..16dc3b34 100644 --- a/transport/http_transport.go +++ b/transport/http_transport.go @@ -13,10 +13,10 @@ import ( "sync" "time" - maddr "github.com/micro/go-micro/v2/util/addr" - "github.com/micro/go-micro/v2/util/buf" - mnet "github.com/micro/go-micro/v2/util/net" - mls "github.com/micro/go-micro/v2/util/tls" + maddr "github.com/micro/go-micro/v3/util/addr" + "github.com/micro/go-micro/v3/util/buf" + mnet "github.com/micro/go-micro/v3/util/net" + mls "github.com/micro/go-micro/v3/util/tls" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) diff --git a/transport/memory/memory.go b/transport/memory/memory.go index ae831cc6..6d1488e5 100644 --- a/transport/memory/memory.go +++ b/transport/memory/memory.go @@ -10,9 +10,9 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/transport" - maddr "github.com/micro/go-micro/v2/util/addr" - mnet "github.com/micro/go-micro/v2/util/net" + "github.com/micro/go-micro/v3/transport" + maddr "github.com/micro/go-micro/v3/util/addr" + mnet "github.com/micro/go-micro/v3/util/net" ) type memorySocket struct { diff --git a/transport/memory/memory_test.go b/transport/memory/memory_test.go index 1d46d401..5c53fde2 100644 --- a/transport/memory/memory_test.go +++ b/transport/memory/memory_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) func TestMemoryTransport(t *testing.T) { diff --git a/transport/options.go b/transport/options.go index d30e4c28..343bed8d 100644 --- a/transport/options.go +++ b/transport/options.go @@ -5,7 +5,7 @@ import ( "crypto/tls" "time" - "github.com/micro/go-micro/v2/codec" + "github.com/micro/go-micro/v3/codec" ) type Options struct { diff --git a/transport/quic/quic.go b/transport/quic/quic.go index 4bb65202..76305b9c 100644 --- a/transport/quic/quic.go +++ b/transport/quic/quic.go @@ -8,8 +8,8 @@ import ( "time" quic "github.com/lucas-clemente/quic-go" - "github.com/micro/go-micro/v2/transport" - utls "github.com/micro/go-micro/v2/util/tls" + "github.com/micro/go-micro/v3/transport" + utls "github.com/micro/go-micro/v3/util/tls" ) type quicSocket struct { diff --git a/tunnel/broker/broker.go b/tunnel/broker/broker.go index 259115dd..49593845 100644 --- a/tunnel/broker/broker.go +++ b/tunnel/broker/broker.go @@ -4,9 +4,9 @@ package broker import ( "context" - "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-micro/v2/transport" - "github.com/micro/go-micro/v2/tunnel" + "github.com/micro/go-micro/v3/broker" + "github.com/micro/go-micro/v3/transport" + "github.com/micro/go-micro/v3/tunnel" ) type tunBroker struct { diff --git a/tunnel/default.go b/tunnel/default.go index b573b4e9..99bdd7bb 100644 --- a/tunnel/default.go +++ b/tunnel/default.go @@ -8,8 +8,8 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/transport" ) var ( diff --git a/tunnel/link.go b/tunnel/link.go index 5872d9df..0c615e22 100644 --- a/tunnel/link.go +++ b/tunnel/link.go @@ -8,8 +8,8 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/transport" ) type link struct { diff --git a/tunnel/listener.go b/tunnel/listener.go index d775804e..0d93c5f1 100644 --- a/tunnel/listener.go +++ b/tunnel/listener.go @@ -4,7 +4,7 @@ import ( "io" "sync" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/logger" ) type tunListener struct { diff --git a/tunnel/options.go b/tunnel/options.go index 954ccd50..8c9d2f11 100644 --- a/tunnel/options.go +++ b/tunnel/options.go @@ -4,9 +4,9 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/transport" - "github.com/micro/go-micro/v2/transport/quic" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/transport" + "github.com/micro/go-micro/v3/transport/quic" ) var ( diff --git a/tunnel/session.go b/tunnel/session.go index 8037546e..8ad0593a 100644 --- a/tunnel/session.go +++ b/tunnel/session.go @@ -7,8 +7,8 @@ import ( "sync" "time" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/transport" ) // session is our pseudo session for transport.Socket diff --git a/tunnel/transport/listener.go b/tunnel/transport/listener.go index 337ab72a..bdb848ea 100644 --- a/tunnel/transport/listener.go +++ b/tunnel/transport/listener.go @@ -1,8 +1,8 @@ package transport import ( - "github.com/micro/go-micro/v2/transport" - "github.com/micro/go-micro/v2/tunnel" + "github.com/micro/go-micro/v3/transport" + "github.com/micro/go-micro/v3/tunnel" ) type tunListener struct { diff --git a/tunnel/transport/transport.go b/tunnel/transport/transport.go index 0448d969..0cfc5d53 100644 --- a/tunnel/transport/transport.go +++ b/tunnel/transport/transport.go @@ -4,8 +4,8 @@ package transport import ( "context" - "github.com/micro/go-micro/v2/transport" - "github.com/micro/go-micro/v2/tunnel" + "github.com/micro/go-micro/v3/transport" + "github.com/micro/go-micro/v3/tunnel" ) type tunTransport struct { diff --git a/tunnel/tunnel.go b/tunnel/tunnel.go index 4075029b..041f8344 100644 --- a/tunnel/tunnel.go +++ b/tunnel/tunnel.go @@ -5,7 +5,7 @@ import ( "errors" "time" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) const ( diff --git a/tunnel/tunnel_test.go b/tunnel/tunnel_test.go index 1c620347..3f77552a 100644 --- a/tunnel/tunnel_test.go +++ b/tunnel/tunnel_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) func testBrokenTunAccept(t *testing.T, tun Tunnel, wait chan bool, wg *sync.WaitGroup) { diff --git a/util/auth/auth.go b/util/auth/auth.go index f46899d8..07eea23a 100644 --- a/util/auth/auth.go +++ b/util/auth/auth.go @@ -4,8 +4,8 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/auth" + "github.com/micro/go-micro/v3/logger" ) // Verify the auth credentials and refresh the auth token periodically diff --git a/util/ctx/ctx.go b/util/ctx/ctx.go index 019c6a2f..c28e30a4 100644 --- a/util/ctx/ctx.go +++ b/util/ctx/ctx.go @@ -6,7 +6,7 @@ import ( "net/textproto" "strings" - "github.com/micro/go-micro/v2/metadata" + "github.com/micro/go-micro/v3/metadata" ) func FromRequest(r *http.Request) context.Context { diff --git a/util/ctx/ctx_test.go b/util/ctx/ctx_test.go index 03effcf3..8e28a4cc 100644 --- a/util/ctx/ctx_test.go +++ b/util/ctx/ctx_test.go @@ -4,7 +4,7 @@ import ( "net/http" "testing" - "github.com/micro/go-micro/v2/metadata" + "github.com/micro/go-micro/v3/metadata" ) func TestRequestToContext(t *testing.T) { diff --git a/util/file/client.go b/util/file/client.go index a25739b9..1be623a5 100644 --- a/util/file/client.go +++ b/util/file/client.go @@ -9,8 +9,8 @@ import ( "log" "os" - "github.com/micro/go-micro/v2/client" - proto "github.com/micro/go-micro/v2/util/file/proto" + "github.com/micro/go-micro/v3/client" + proto "github.com/micro/go-micro/v3/util/file/proto" ) // Client is the client interface to access files diff --git a/util/file/handler.go b/util/file/handler.go index b5f1388f..11824288 100644 --- a/util/file/handler.go +++ b/util/file/handler.go @@ -6,10 +6,10 @@ import ( "path/filepath" "sync" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/server" - proto "github.com/micro/go-micro/v2/util/file/proto" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/server" + proto "github.com/micro/go-micro/v3/util/file/proto" "golang.org/x/net/context" ) diff --git a/util/file/proto/file.pb.micro.go b/util/file/proto/file.pb.micro.go index ac135745..b5ed664e 100644 --- a/util/file/proto/file.pb.micro.go +++ b/util/file/proto/file.pb.micro.go @@ -11,9 +11,9 @@ import ( import ( context "context" - api "github.com/micro/go-micro/v2/api" - client "github.com/micro/go-micro/v2/client" - server "github.com/micro/go-micro/v2/server" + api "github.com/micro/go-micro/v3/api" + client "github.com/micro/go-micro/v3/client" + server "github.com/micro/go-micro/v3/server" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/util/http/http.go b/util/http/http.go index 80a2ddb6..9b80c899 100644 --- a/util/http/http.go +++ b/util/http/http.go @@ -8,9 +8,9 @@ import ( "net/http" "strings" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/selector/random" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/router/registry" + "github.com/micro/go-micro/v3/selector/random" ) // Write sets the status and body on a http ResponseWriter @@ -47,7 +47,7 @@ func WriteInternalServerError(w http.ResponseWriter, err error) { func NewRoundTripper(opts ...Option) http.RoundTripper { options := Options{ - Router: router.DefaultRouter, + Router: registry.NewRouter(), } for _, o := range opts { o(&options) diff --git a/util/http/http_test.go b/util/http/http_test.go index c6d4c578..7d659f9a 100644 --- a/util/http/http_test.go +++ b/util/http/http_test.go @@ -6,10 +6,10 @@ import ( "net/http" "testing" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/registry/memory" - "github.com/micro/go-micro/v2/router" - regRouter "github.com/micro/go-micro/v2/router/registry" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/memory" + "github.com/micro/go-micro/v3/router" + regRouter "github.com/micro/go-micro/v3/router/registry" ) func TestRoundTripper(t *testing.T) { diff --git a/util/http/options.go b/util/http/options.go index 0132db45..d7b8d6b8 100644 --- a/util/http/options.go +++ b/util/http/options.go @@ -1,6 +1,6 @@ package http -import "github.com/micro/go-micro/v2/router" +import "github.com/micro/go-micro/v3/router" type Options struct { Router router.Router diff --git a/util/http/roundtripper.go b/util/http/roundtripper.go index 898c75d2..26718e5f 100644 --- a/util/http/roundtripper.go +++ b/util/http/roundtripper.go @@ -4,8 +4,8 @@ import ( "errors" "net/http" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/selector" + "github.com/micro/go-micro/v3/router" + "github.com/micro/go-micro/v3/selector" ) type roundTripper struct { diff --git a/util/io/io.go b/util/io/io.go index 257d9b93..d06bb7bb 100644 --- a/util/io/io.go +++ b/util/io/io.go @@ -4,7 +4,7 @@ package io import ( "io" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) type rwc struct { diff --git a/util/kubernetes/api/request.go b/util/kubernetes/api/request.go index 938654c1..db73f615 100644 --- a/util/kubernetes/api/request.go +++ b/util/kubernetes/api/request.go @@ -10,7 +10,7 @@ import ( "net/http" "net/url" - "github.com/micro/go-micro/v2/logger" + "github.com/micro/go-micro/v3/logger" ) // Request is used to construct a http request for the k8s API. diff --git a/util/kubernetes/client/client.go b/util/kubernetes/client/client.go index 1109d7f3..910ec64d 100644 --- a/util/kubernetes/client/client.go +++ b/util/kubernetes/client/client.go @@ -13,8 +13,8 @@ import ( "regexp" "strings" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/util/kubernetes/api" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/util/kubernetes/api" ) var ( diff --git a/util/kubernetes/client/watch.go b/util/kubernetes/client/watch.go index 833ee534..81999209 100644 --- a/util/kubernetes/client/watch.go +++ b/util/kubernetes/client/watch.go @@ -7,7 +7,7 @@ import ( "errors" "net/http" - "github.com/micro/go-micro/v2/util/kubernetes/api" + "github.com/micro/go-micro/v3/util/kubernetes/api" ) const ( diff --git a/util/log/README.md b/util/log/README.md index 97ddacf3..e59e305d 100644 --- a/util/log/README.md +++ b/util/log/README.md @@ -1,6 +1,6 @@ # Log -DEPRECATED: use github.com/micro/go-micro/v2/logger interface +DEPRECATED: use github.com/micro/go-micro/v3/logger interface This is the global logger for all micro based libraries. diff --git a/util/log/log.go b/util/log/log.go index 16e5cd83..75167947 100644 --- a/util/log/log.go +++ b/util/log/log.go @@ -1,5 +1,5 @@ // Package log is a global internal logger -// DEPRECATED: this is frozen package, use github.com/micro/go-micro/v2/logger +// DEPRECATED: this is frozen package, use github.com/micro/go-micro/v3/logger package log import ( @@ -7,8 +7,8 @@ import ( "os" "sync/atomic" - dlog "github.com/micro/go-micro/v2/debug/log" - nlog "github.com/micro/go-micro/v2/logger" + dlog "github.com/micro/go-micro/v3/debug/log" + nlog "github.com/micro/go-micro/v3/logger" ) // level is a log level diff --git a/util/mdns/server.go b/util/mdns/server.go index e62d3e92..cdc2695b 100644 --- a/util/mdns/server.go +++ b/util/mdns/server.go @@ -8,7 +8,7 @@ import ( "sync/atomic" "time" - log "github.com/micro/go-micro/v2/logger" + log "github.com/micro/go-micro/v3/logger" "github.com/miekg/dns" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" diff --git a/util/mux/mux.go b/util/mux/mux.go index 7ad7731f..2f3ab968 100644 --- a/util/mux/mux.go +++ b/util/mux/mux.go @@ -5,10 +5,11 @@ import ( "context" "sync" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/debug/service/handler" - "github.com/micro/go-micro/v2/proxy" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/client/grpc" + "github.com/micro/go-micro/v3/debug/service/handler" + "github.com/micro/go-micro/v3/proxy" + "github.com/micro/go-micro/v3/server" + "github.com/micro/go-micro/v3/server/mucp" ) // Server is a proxy muxer that incudes the use of the DefaultHandler @@ -17,6 +18,14 @@ type Server struct { Name string // Proxy handler Proxy proxy.Proxy + // The default handler + Handler Handler +} + +type Handler interface { + proxy.Proxy + NewHandler(interface{}, ...server.HandlerOption) server.Handler + Handle(server.Handler) error } var ( @@ -25,32 +34,35 @@ var ( func (s *Server) ProcessMessage(ctx context.Context, msg server.Message) error { if msg.Topic() == s.Name { - return server.DefaultRouter.ProcessMessage(ctx, msg) + return s.Handler.ProcessMessage(ctx, msg) } return s.Proxy.ProcessMessage(ctx, msg) } func (s *Server) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error { if req.Service() == s.Name { - return server.DefaultRouter.ServeRequest(ctx, req, rsp) + return s.Handler.ServeRequest(ctx, req, rsp) } return s.Proxy.ServeRequest(ctx, req, rsp) } func New(name string, p proxy.Proxy) *Server { + r := mucp.DefaultRouter + // only register this once once.Do(func() { - server.DefaultRouter.Handle( + r.Handle( // inject the debug handler - server.DefaultRouter.NewHandler( - handler.NewHandler(client.DefaultClient), + r.NewHandler( + handler.NewHandler(grpc.NewClient()), server.InternalHandler(true), ), ) }) return &Server{ - Name: name, - Proxy: p, + Name: name, + Proxy: p, + Handler: r, } } diff --git a/util/pool/default.go b/util/pool/default.go index 7175b2bb..d27350c2 100644 --- a/util/pool/default.go +++ b/util/pool/default.go @@ -5,7 +5,7 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) type pool struct { diff --git a/util/pool/default_test.go b/util/pool/default_test.go index 74c84bb7..20a49300 100644 --- a/util/pool/default_test.go +++ b/util/pool/default_test.go @@ -4,8 +4,8 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/transport" - "github.com/micro/go-micro/v2/transport/memory" + "github.com/micro/go-micro/v3/transport" + "github.com/micro/go-micro/v3/transport/memory" ) func testPool(t *testing.T, size int, ttl time.Duration) { diff --git a/util/pool/options.go b/util/pool/options.go index 5b6632ac..a4c3178f 100644 --- a/util/pool/options.go +++ b/util/pool/options.go @@ -3,7 +3,7 @@ package pool import ( "time" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) type Options struct { diff --git a/util/pool/pool.go b/util/pool/pool.go index 533879dd..ce540f46 100644 --- a/util/pool/pool.go +++ b/util/pool/pool.go @@ -4,7 +4,7 @@ package pool import ( "time" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) // Pool is an interface for connection pooling diff --git a/util/proto/proto.go b/util/proto/proto.go deleted file mode 100644 index ef49f123..00000000 --- a/util/proto/proto.go +++ /dev/null @@ -1,33 +0,0 @@ -// Package proto contains utility functions for working with protobufs -package proto - -import ( - "github.com/micro/go-micro/v2/router" - pbRtr "github.com/micro/go-micro/v2/router/service/proto" -) - -// RouteToProto encodes route into protobuf and returns it -func RouteToProto(route router.Route) *pbRtr.Route { - return &pbRtr.Route{ - Service: route.Service, - Address: route.Address, - Gateway: route.Gateway, - Network: route.Network, - Router: route.Router, - Link: route.Link, - Metric: int64(route.Metric), - } -} - -// ProtoToRoute decodes protobuf route into router route and returns it -func ProtoToRoute(route *pbRtr.Route) router.Route { - return router.Route{ - Service: route.Service, - Address: route.Address, - Gateway: route.Gateway, - Network: route.Network, - Router: route.Router, - Link: route.Link, - Metric: route.Metric, - } -} diff --git a/util/registry/util.go b/util/registry/util.go index 140faedd..e0d67ab3 100644 --- a/util/registry/util.go +++ b/util/registry/util.go @@ -1,7 +1,7 @@ package registry import ( - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) func addNodes(old, neu []*registry.Node) []*registry.Node { diff --git a/util/registry/util_test.go b/util/registry/util_test.go index 740ab5b1..1b7eef6d 100644 --- a/util/registry/util_test.go +++ b/util/registry/util_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) func TestRemove(t *testing.T) { diff --git a/util/scope/scope.go b/util/scope/scope.go index cb2344df..eb75a7bb 100644 --- a/util/scope/scope.go +++ b/util/scope/scope.go @@ -3,7 +3,7 @@ package scope import ( "fmt" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" ) // Scope extends the store, applying a prefix to each request diff --git a/util/socket/socket.go b/util/socket/socket.go index 91fac4bc..4a8bc6a8 100644 --- a/util/socket/socket.go +++ b/util/socket/socket.go @@ -4,7 +4,7 @@ package socket import ( "io" - "github.com/micro/go-micro/v2/transport" + "github.com/micro/go-micro/v3/transport" ) // Socket is our pseudo socket for transport.Socket diff --git a/util/stream/stream.go b/util/stream/stream.go index 22f0703e..1c26350e 100644 --- a/util/stream/stream.go +++ b/util/stream/stream.go @@ -5,10 +5,11 @@ import ( "context" "sync" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/codec" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/client/mucp" + "github.com/micro/go-micro/v3/codec" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/server" ) type Stream interface { @@ -81,7 +82,7 @@ func New(service, endpoint string, req interface{}, s Stream) server.Stream { Stream: s, request: &request{ context: s.Context(), - Request: client.DefaultClient.NewRequest(service, endpoint, req), + Request: mucp.NewClient().NewRequest(service, endpoint, req), }, } } diff --git a/util/sync/manager.go b/util/sync/manager.go index 6f7c5d6e..794c60a7 100644 --- a/util/sync/manager.go +++ b/util/sync/manager.go @@ -3,7 +3,7 @@ package sync import ( "time" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" "github.com/pkg/errors" ) diff --git a/util/sync/options.go b/util/sync/options.go index 30e493f2..ed2cbec0 100644 --- a/util/sync/options.go +++ b/util/sync/options.go @@ -3,7 +3,7 @@ package sync import ( "time" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" ) // Options represents Sync options diff --git a/util/sync/sync.go b/util/sync/sync.go index d1f0e240..43d73fc4 100644 --- a/util/sync/sync.go +++ b/util/sync/sync.go @@ -7,7 +7,7 @@ import ( "time" "github.com/ef-ds/deque" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" "github.com/pkg/errors" ) diff --git a/util/test/test.go b/util/test/test.go index f95b1f68..b7be6b63 100644 --- a/util/test/test.go +++ b/util/test/test.go @@ -1,7 +1,7 @@ package test import ( - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" ) var ( diff --git a/util/token/basic/basic.go b/util/token/basic/basic.go index 70d4f73b..53cb0284 100644 --- a/util/token/basic/basic.go +++ b/util/token/basic/basic.go @@ -6,9 +6,9 @@ import ( "time" "github.com/google/uuid" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/store" - "github.com/micro/go-micro/v2/util/token" + "github.com/micro/go-micro/v3/auth" + "github.com/micro/go-micro/v3/store" + "github.com/micro/go-micro/v3/util/token" ) // Basic implementation of token provider, backed by the store diff --git a/util/token/basic/basic_test.go b/util/token/basic/basic_test.go index f3962706..2bb775b4 100644 --- a/util/token/basic/basic_test.go +++ b/util/token/basic/basic_test.go @@ -3,9 +3,9 @@ package basic import ( "testing" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/store/memory" - "github.com/micro/go-micro/v2/util/token" + "github.com/micro/go-micro/v3/auth" + "github.com/micro/go-micro/v3/store/memory" + "github.com/micro/go-micro/v3/util/token" ) func TestGenerate(t *testing.T) { diff --git a/util/token/jwt/jwt.go b/util/token/jwt/jwt.go index 9e1c471e..40673192 100644 --- a/util/token/jwt/jwt.go +++ b/util/token/jwt/jwt.go @@ -5,8 +5,8 @@ import ( "time" "github.com/dgrijalva/jwt-go" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/util/token" + "github.com/micro/go-micro/v3/auth" + "github.com/micro/go-micro/v3/util/token" ) // authClaims to be encoded in the JWT diff --git a/util/token/jwt/jwt_test.go b/util/token/jwt/jwt_test.go index 94ad0f7e..2afd9f7d 100644 --- a/util/token/jwt/jwt_test.go +++ b/util/token/jwt/jwt_test.go @@ -5,8 +5,8 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/util/token" + "github.com/micro/go-micro/v3/auth" + "github.com/micro/go-micro/v3/util/token" ) func TestGenerate(t *testing.T) { diff --git a/util/token/options.go b/util/token/options.go index 8afe174d..1e7be0e4 100644 --- a/util/token/options.go +++ b/util/token/options.go @@ -3,7 +3,7 @@ package token import ( "time" - "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v3/store" ) type Options struct { diff --git a/util/token/token.go b/util/token/token.go index 61b1b6f5..ae8e4c78 100644 --- a/util/token/token.go +++ b/util/token/token.go @@ -4,7 +4,7 @@ import ( "errors" "time" - "github.com/micro/go-micro/v2/auth" + "github.com/micro/go-micro/v3/auth" ) var ( diff --git a/util/wrapper/wrapper.go b/util/wrapper/wrapper.go index 78e09664..061fdcec 100644 --- a/util/wrapper/wrapper.go +++ b/util/wrapper/wrapper.go @@ -5,13 +5,13 @@ import ( "reflect" "strings" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/debug/stats" - "github.com/micro/go-micro/v2/debug/trace" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/auth" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/debug/stats" + "github.com/micro/go-micro/v3/debug/trace" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/server" ) type fromServiceWrapper struct { @@ -313,7 +313,7 @@ func (c *cacheWrapper) Call(ctx context.Context, req client.Request, rsp interfa } // check to see if there is a response cached, if there is assign it - if r, ok := cache.Get(ctx, &req); ok { + if r, ok := cache.Get(ctx, req); ok { val := reflect.ValueOf(rsp).Elem() val.Set(reflect.ValueOf(r).Elem()) return nil @@ -325,7 +325,7 @@ func (c *cacheWrapper) Call(ctx context.Context, req client.Request, rsp interfa } // set the result in the cache - cache.Set(ctx, &req, rsp, options.CacheExpiry) + cache.Set(ctx, req, rsp, options.CacheExpiry) return nil } diff --git a/util/wrapper/wrapper_static_client_test.go b/util/wrapper/wrapper_static_client_test.go index a3851ff2..dafa17fe 100644 --- a/util/wrapper/wrapper_static_client_test.go +++ b/util/wrapper/wrapper_static_client_test.go @@ -4,14 +4,17 @@ import ( "context" "testing" - "github.com/micro/go-micro/v2/broker" - bmemory "github.com/micro/go-micro/v2/broker/memory" - "github.com/micro/go-micro/v2/client" - rmemory "github.com/micro/go-micro/v2/registry/memory" - "github.com/micro/go-micro/v2/router" - "github.com/micro/go-micro/v2/server" - tmemory "github.com/micro/go-micro/v2/transport/memory" - wrapper "github.com/micro/go-micro/v2/util/wrapper" + "github.com/micro/go-micro/v3/broker" + bmemory "github.com/micro/go-micro/v3/broker/memory" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/client/grpc" + rmemory "github.com/micro/go-micro/v3/registry/memory" + "github.com/micro/go-micro/v3/router" + rtreg "github.com/micro/go-micro/v3/router/registry" + "github.com/micro/go-micro/v3/server" + grpcsrv "github.com/micro/go-micro/v3/server/grpc" + tmemory "github.com/micro/go-micro/v3/transport/memory" + wrapper "github.com/micro/go-micro/v3/util/wrapper" ) type TestFoo struct { @@ -31,15 +34,20 @@ func (h *TestFoo) Bar(ctx context.Context, req *TestReq, rsp *TestRsp) error { func TestStaticClientWrapper(t *testing.T) { var err error - req := client.NewRequest("go.micro.service.foo", "TestFoo.Bar", &TestReq{}, client.WithContentType("application/json")) + req := grpc.NewClient().NewRequest( + "go.micro.service.foo", + "TestFoo.Bar", + &TestReq{}, + client.WithContentType("application/json"), + ) rsp := &TestRsp{} reg := rmemory.NewRegistry() brk := bmemory.NewBroker(broker.Registry(reg)) tr := tmemory.NewTransport() - rtr := router.NewRouter(router.Registry(reg)) + rtr := rtreg.NewRouter(router.Registry(reg)) - srv := server.NewServer( + srv := grpcsrv.NewServer( server.Broker(brk), server.Registry(reg), server.Name("go.micro.service.foo"), @@ -54,7 +62,7 @@ func TestStaticClientWrapper(t *testing.T) { t.Fatal(err) } - cli := client.NewClient( + cli := grpc.NewClient( client.Router(rtr), client.Broker(brk), client.Transport(tr), diff --git a/util/wrapper/wrapper_test.go b/util/wrapper/wrapper_test.go index 09d7fcb1..2e9535f0 100644 --- a/util/wrapper/wrapper_test.go +++ b/util/wrapper/wrapper_test.go @@ -7,11 +7,12 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/auth" - "github.com/micro/go-micro/v2/client" - "github.com/micro/go-micro/v2/errors" - "github.com/micro/go-micro/v2/metadata" - "github.com/micro/go-micro/v2/server" + "github.com/micro/go-micro/v3/auth" + "github.com/micro/go-micro/v3/client" + "github.com/micro/go-micro/v3/client/grpc" + "github.com/micro/go-micro/v3/errors" + "github.com/micro/go-micro/v3/metadata" + "github.com/micro/go-micro/v3/server" ) func TestWrapper(t *testing.T) { @@ -371,7 +372,7 @@ type testRsp struct { } func TestCacheWrapper(t *testing.T) { - req := client.NewRequest("go.micro.service.foo", "Foo.Bar", nil) + req := grpc.NewClient().NewRequest("go.micro.service.foo", "Foo.Bar", nil) t.Run("NilCache", func(t *testing.T) { cli := new(testClient) diff --git a/web/options.go b/web/options.go index c0325564..200050f4 100644 --- a/web/options.go +++ b/web/options.go @@ -6,9 +6,8 @@ import ( "net/http" "time" - "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2" - "github.com/micro/go-micro/v2/registry" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/memory" ) //Options for web @@ -20,9 +19,6 @@ type Options struct { Address string Advertise string - Action func(*cli.Context) - Flags []cli.Flag - RegisterTTL time.Duration RegisterInterval time.Duration @@ -36,7 +32,6 @@ type Options struct { Context context.Context Registry registry.Registry - Service micro.Service Secure bool TLSConfig *tls.Config @@ -60,7 +55,6 @@ func newOptions(opts ...Option) Options { RegisterTTL: DefaultRegisterTTL, RegisterInterval: DefaultRegisterInterval, StaticDir: DefaultStaticDir, - Service: micro.NewService(), Context: context.TODO(), Signal: true, } @@ -69,6 +63,10 @@ func newOptions(opts ...Option) Options { o(&opt) } + if opt.Registry == nil { + opt.Registry = memory.NewRegistry() + } + if opt.RegisterCheck == nil { opt.RegisterCheck = DefaultRegisterCheck } @@ -172,27 +170,6 @@ func Server(srv *http.Server) Option { } } -// MicroService sets the micro.Service used internally -func MicroService(s micro.Service) Option { - return func(o *Options) { - o.Service = s - } -} - -// Flags sets the command flags. -func Flags(flags ...cli.Flag) Option { - return func(o *Options) { - o.Flags = append(o.Flags, flags...) - } -} - -// Action sets the command action. -func Action(a func(*cli.Context)) Option { - return func(o *Options) { - o.Action = a - } -} - // BeforeStart is executed before the server starts. func BeforeStart(fn func() error) Option { return func(o *Options) { diff --git a/web/service.go b/web/service.go index 70fe5d5f..227cd084 100644 --- a/web/service.go +++ b/web/service.go @@ -12,17 +12,13 @@ import ( "sync" "time" - "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/registry" - maddr "github.com/micro/go-micro/v2/util/addr" - authutil "github.com/micro/go-micro/v2/util/auth" - "github.com/micro/go-micro/v2/util/backoff" - mhttp "github.com/micro/go-micro/v2/util/http" - mnet "github.com/micro/go-micro/v2/util/net" - signalutil "github.com/micro/go-micro/v2/util/signal" - mls "github.com/micro/go-micro/v2/util/tls" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/registry" + maddr "github.com/micro/go-micro/v3/util/addr" + "github.com/micro/go-micro/v3/util/backoff" + mnet "github.com/micro/go-micro/v3/util/net" + signalutil "github.com/micro/go-micro/v3/util/signal" + mls "github.com/micro/go-micro/v3/util/tls" ) type service struct { @@ -120,11 +116,7 @@ func (s *service) register() error { return nil } // default to service registry - r := s.opts.Service.Options().Registry - // switch to option if specified - if s.opts.Registry != nil { - r = s.opts.Registry - } + r := s.opts.Registry // service node need modify, node address maybe changed srv := s.genSrv() @@ -144,7 +136,6 @@ func (s *service) register() error { // register options rOpts := []registry.RegisterOption{ registry.RegisterTTL(s.opts.RegisterTTL), - registry.RegisterDomain(s.opts.Service.Server().Options().Namespace), } // try three times if necessary @@ -173,11 +164,8 @@ func (s *service) deregister() error { return nil } // default to service registry - r := s.opts.Service.Options().Registry - // switch to option if specified - if s.opts.Registry != nil { - r = s.opts.Registry - } + r := s.opts.Registry + return r.Deregister(s.srv) } @@ -300,15 +288,6 @@ func (s *service) stop() error { return <-ch } -func (s *service) Client() *http.Client { - rt := mhttp.NewRoundTripper( - mhttp.WithRouter(s.opts.Service.Options().Router), - ) - return &http.Client{ - Transport: rt, - } -} - func (s *service) Handle(pattern string, handler http.Handler) { var seen bool s.RLock() @@ -377,68 +356,6 @@ func (s *service) Init(opts ...Option) error { o(&s.opts) } - serviceOpts := []micro.Option{} - - if len(s.opts.Flags) > 0 { - serviceOpts = append(serviceOpts, micro.Flags(s.opts.Flags...)) - } - - if s.opts.Registry != nil { - serviceOpts = append(serviceOpts, micro.Registry(s.opts.Registry)) - } - - s.Unlock() - - serviceOpts = append(serviceOpts, micro.Action(func(ctx *cli.Context) error { - s.Lock() - defer s.Unlock() - - if ttl := ctx.Int("register_ttl"); ttl > 0 { - s.opts.RegisterTTL = time.Duration(ttl) * time.Second - } - - if interval := ctx.Int("register_interval"); interval > 0 { - s.opts.RegisterInterval = time.Duration(interval) * time.Second - } - - if name := ctx.String("server_name"); len(name) > 0 { - s.opts.Name = name - } - - if ver := ctx.String("server_version"); len(ver) > 0 { - s.opts.Version = ver - } - - if id := ctx.String("server_id"); len(id) > 0 { - s.opts.Id = id - } - - if addr := ctx.String("server_address"); len(addr) > 0 { - s.opts.Address = addr - } - - if adv := ctx.String("server_advertise"); len(adv) > 0 { - s.opts.Advertise = adv - } - - if s.opts.Action != nil { - s.opts.Action(ctx) - } - - return nil - })) - - s.RLock() - // pass in own name and version - if s.opts.Service.Name() == "" { - serviceOpts = append(serviceOpts, micro.Name(s.opts.Name)) - } - serviceOpts = append(serviceOpts, micro.Version(s.opts.Version)) - s.RUnlock() - - s.opts.Service.Init(serviceOpts...) - - s.Lock() srv := s.genSrv() srv.Endpoints = s.srv.Endpoints s.srv = srv @@ -448,11 +365,6 @@ func (s *service) Init(opts ...Option) error { } func (s *service) Run() error { - // generate an auth account - if err := authutil.Verify(s.opts.Service.Options().Auth); err != nil { - return err - } - if err := s.start(); err != nil { return err } diff --git a/web/service_test.go b/web/service_test.go index ee7eba32..bd865774 100644 --- a/web/service_test.go +++ b/web/service_test.go @@ -11,8 +11,8 @@ import ( "testing" "time" - "github.com/micro/go-micro/v2/registry" - "github.com/micro/go-micro/v2/registry/memory" + "github.com/micro/go-micro/v3/registry" + "github.com/micro/go-micro/v3/registry/memory" ) func TestService(t *testing.T) { diff --git a/web/web.go b/web/web.go index 6bd9c82b..c59ba1c0 100644 --- a/web/web.go +++ b/web/web.go @@ -11,7 +11,6 @@ import ( // Service is a web service with service discovery built in type Service interface { - Client() *http.Client Init(opts ...Option) error Options() Options Handle(pattern string, handler http.Handler) diff --git a/web/web_test.go b/web/web_test.go index d385bdf4..6647aead 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -7,14 +7,12 @@ import ( "testing" "time" - "github.com/micro/cli/v2" - "github.com/micro/go-micro/v2" - "github.com/micro/go-micro/v2/logger" - "github.com/micro/go-micro/v2/web" + "github.com/micro/go-micro/v3/logger" + "github.com/micro/go-micro/v3/web" ) func TestWeb(t *testing.T) { - for i := 0; i < 10; i++ { + for i := 0; i < 3; i++ { fmt.Println("Test nr", i) testFunc() } @@ -24,27 +22,7 @@ func testFunc() { ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*250) defer cancel() - s := micro.NewService( - micro.Name("test"), - micro.Context(ctx), - micro.HandleSignal(false), - micro.Flags( - &cli.StringFlag{ - Name: "test.timeout", - }, - &cli.BoolFlag{ - Name: "test.v", - }, - &cli.StringFlag{ - Name: "test.run", - }, - &cli.StringFlag{ - Name: "test.testlogfile", - }, - ), - ) w := web.NewService( - web.MicroService(s), web.Context(ctx), web.HandleSignal(false), ) @@ -52,14 +30,7 @@ func testFunc() { //w.Init() var wg sync.WaitGroup - wg.Add(2) - go func() { - defer wg.Done() - err := s.Run() - if err != nil { - logger.Errorf("micro run error: %v", err) - } - }() + wg.Add(1) go func() { defer wg.Done() err := w.Run()