From e7bc6799edc6e413ad368492019bd210d38979b5 Mon Sep 17 00:00:00 2001 From: Richard Ramos Date: Sun, 24 Jul 2022 16:51:42 -0400 Subject: [PATCH] refactor: decouple rpc and rest http servers --- go.mod | 19 --- go.sum | 11 -- waku.go | 36 +++++ waku/node.go | 12 ++ waku/options.go | 11 ++ waku/v2/protocol/relay/waku_relay.go | 9 +- waku/v2/rest/debug.go | 53 ++++++++ waku/v2/{rpc => rest}/debug_api.yaml | 0 waku/v2/rest/debug_test.go | 33 +++++ waku/v2/rest/relay.go | 195 +++++++++++++++++++++++++++ waku/v2/{rpc => rest}/relay_api.yaml | 0 waku/v2/rest/relay_test.go | 162 ++++++++++++++++++++++ waku/v2/rest/runner.go | 42 ++++++ waku/v2/rest/utils.go | 27 ++++ waku/v2/rest/waku_rest.go | 60 +++++++++ waku/v2/rest/waku_rest_test.go | 20 +++ waku/v2/rpc/debug.go | 22 +-- waku/v2/rpc/relay.go | 80 +---------- waku/v2/rpc/relay_test.go | 5 +- waku/v2/rpc/utils.go | 21 --- waku/v2/rpc/waku_rpc.go | 4 +- 21 files changed, 662 insertions(+), 160 deletions(-) create mode 100644 waku/v2/rest/debug.go rename waku/v2/{rpc => rest}/debug_api.yaml (100%) create mode 100644 waku/v2/rest/debug_test.go create mode 100644 waku/v2/rest/relay.go rename waku/v2/{rpc => rest}/relay_api.yaml (100%) create mode 100644 waku/v2/rest/relay_test.go create mode 100644 waku/v2/rest/runner.go create mode 100644 waku/v2/rest/utils.go create mode 100644 waku/v2/rest/waku_rest.go create mode 100644 waku/v2/rest/waku_rest_test.go diff --git a/go.mod b/go.mod index 4747d002..fe87d6ca 100644 --- a/go.mod +++ b/go.mod @@ -45,8 +45,6 @@ require ( ) require ( - github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6 // indirect - github.com/VictoriaMetrics/fastcache v1.6.0 // indirect github.com/benbjohnson/clock v1.3.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/btcsuite/btcd v0.22.1 // indirect @@ -62,14 +60,11 @@ require ( github.com/deckarep/golang-set v1.8.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect github.com/docker/go-units v0.4.0 // indirect - github.com/edsrzf/mmap-go v1.0.0 // indirect github.com/elastic/gosigar v0.14.1 // indirect github.com/francoispqt/gojay v1.2.13 // indirect github.com/fsnotify/fsnotify v1.4.9 // indirect - github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff // indirect github.com/go-kit/log v0.1.0 // indirect github.com/go-logfmt/logfmt v0.5.0 // indirect - github.com/go-ole/go-ole v1.2.1 // indirect github.com/go-stack/stack v1.8.0 // indirect github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 // indirect github.com/godbus/dbus/v5 v5.0.6 // indirect @@ -81,8 +76,6 @@ require ( github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect - github.com/holiman/bloomfilter/v2 v2.0.3 // indirect - github.com/holiman/uint256 v1.2.0 // indirect github.com/huin/goupnp v1.0.2 // indirect github.com/ipfs/go-cid v0.1.0 // indirect github.com/ipfs/go-datastore v0.5.1 // indirect @@ -91,7 +84,6 @@ require ( github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect github.com/jbenet/goprocess v0.1.4 // indirect - github.com/karalabe/usb v0.0.2 // indirect github.com/klauspost/compress v1.15.1 // indirect github.com/klauspost/cpuid/v2 v2.0.9 // indirect github.com/koron/go-ssdp v0.0.2 // indirect @@ -121,7 +113,6 @@ require ( github.com/marten-seemann/qtls-go1-18 v0.1.1 // indirect github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd // indirect github.com/mattn/go-isatty v0.0.14 // indirect - github.com/mattn/go-runewidth v0.0.9 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect github.com/miekg/dns v1.1.43 // indirect github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b // indirect @@ -139,11 +130,9 @@ require ( github.com/multiformats/go-multistream v0.3.3 // indirect github.com/multiformats/go-varint v0.0.6 // indirect github.com/nxadm/tail v1.4.8 // indirect - github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 // indirect github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect - github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_golang v1.12.1 // indirect @@ -151,20 +140,13 @@ require ( github.com/prometheus/common v0.32.1 // indirect github.com/prometheus/procfs v0.7.3 // indirect github.com/prometheus/statsd_exporter v0.21.0 // indirect - github.com/prometheus/tsdb v0.7.1 // indirect github.com/raulk/clock v1.1.0 // indirect github.com/raulk/go-watchdog v1.2.0 // indirect github.com/rjeczalik/notify v0.9.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect github.com/spacemonkeygo/spacelog v0.0.0-20180420211403-2296661a0572 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/status-im/status-go/extkeys v1.1.2 // indirect - github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4 // indirect - github.com/status-im/status-go/extkeys v1.1.2 // indirect - github.com/tklauser/go-sysconf v0.3.5 // indirect - github.com/tklauser/numcpus v0.2.2 // indirect - github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef // indirect github.com/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7 // indirect github.com/whyrusleeping/timecache v0.0.0-20160911033111-cfcb2f1abfee // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect @@ -178,7 +160,6 @@ require ( golang.org/x/tools v0.1.8-0.20211022200916-316ba0b74098 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/protobuf v1.28.0 // indirect - gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect diff --git a/go.sum b/go.sum index 4f0768c9..fc803428 100644 --- a/go.sum +++ b/go.sum @@ -153,7 +153,6 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk= -github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= @@ -515,7 +514,6 @@ github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1 github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= -github.com/edsrzf/mmap-go v1.0.0 h1:CEBF7HpRnUCSJgGUb5h1Gm7e3VkmVDrR8lvWVLtrOFw= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elastic/gosigar v0.12.0/go.mod h1:iXRIGg2tLnu7LBdpqzyQfGDEidKCfWcCMS0WKyPWoMs= github.com/elastic/gosigar v0.14.1 h1:T0aQ7n/n2ZA9W7DmAnj60v+qzqKERdBgJBO1CG2W6rc= @@ -561,7 +559,6 @@ github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa/go.mod h1:KnogPXt github.com/gabriel-vasile/mimetype v1.3.1/go.mod h1:fA8fi6KUiG7MgQQ+mEWotXoEOvmxRtOJlERCzSmRvr8= github.com/gabriel-vasile/mimetype v1.4.0/go.mod h1:fA8fi6KUiG7MgQQ+mEWotXoEOvmxRtOJlERCzSmRvr8= github.com/garyburd/redigo v0.0.0-20150301180006-535138d7bcd7/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= -github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= github.com/getkin/kin-openapi v0.53.0/go.mod h1:7Yn5whZr5kJi6t+kShccXS8ae1APpYTW6yheSwk8Yi4= github.com/getkin/kin-openapi v0.61.0/go.mod h1:7Yn5whZr5kJi6t+kShccXS8ae1APpYTW6yheSwk8Yi4= @@ -583,7 +580,6 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2 github.com/go-ini/ini v1.25.4/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.10.0 h1:dXFJfIHVvUcpSgDOV+Ne6t7jXri8Tfv2uOLHUZ2XNuo= github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= github.com/go-kit/log v0.1.0 h1:DGJh0Sm43HbOeYDNnVZFl8BvcYVvjD5bqYJvp0REbwQ= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= @@ -856,7 +852,6 @@ github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2p github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/holiman/bloomfilter/v2 v2.0.3 h1:73e0e/V0tCydx14a0SCYS/EWCxgwLZ18CZcZKVu0fao= github.com/holiman/bloomfilter/v2 v2.0.3/go.mod h1:zpoh+gs7qcpqrHr3dB55AMiJwo0iURXE7ZOP9L9hSkA= -github.com/holiman/uint256 v1.2.0 h1:gpSYcPLWGv4sG43I2mVLiDZCNDh/EpGjSk8tmtxitHM= github.com/holiman/uint256 v1.2.0/go.mod h1:y4ga/t+u+Xwd7CpDgZESaRcWy0I7XMlTMA25ApIH5Jw= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= @@ -1012,7 +1007,6 @@ github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q github.com/k0kubun/pp v2.3.0+incompatible/go.mod h1:GWse8YhT0p8pT4ir3ZgBbfZild3tgzSScAn6HmfYukg= github.com/kami-zh/go-capturer v0.0.0-20171211120116-e492ea43421d/go.mod h1:P2viExyCEfeWGU259JnaQ34Inuec4R38JCyBx2edgD0= github.com/karalabe/usb v0.0.0-20190919080040-51dc0efba356/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU= -github.com/karalabe/usb v0.0.2 h1:M6QQBNxF+CQ8OFvxrT90BA0qBOXymndZnk5q235mFc4= github.com/karalabe/usb v0.0.2/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU= github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4= @@ -1239,7 +1233,6 @@ github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcncea github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-ieproxy v0.0.0-20190610004146-91bb50d98149/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= github.com/mattn/go-ieproxy v0.0.0-20190702010315-6dee0af9227d/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= @@ -1492,7 +1485,6 @@ github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCko github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= github.com/peterh/liner v1.0.1-0.20180619022028-8c1271fcf47f/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= -github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7 h1:oYW+YCJ1pachXTQmzR3rNLYGGz4g/UgFcjb28p/viDM= github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0= github.com/philhofer/fwd v1.0.0/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= github.com/phpdave11/gofpdf v1.4.2/go.mod h1:zpO6xFn9yxo3YLyMvW8HcKWVdbNqgIfOOp2dXMnm1mY= @@ -1689,7 +1681,6 @@ github.com/status-im/go-waku-rendezvous v0.0.0-20211018070416-a93f3b70c432 h1:cb github.com/status-im/go-waku-rendezvous v0.0.0-20211018070416-a93f3b70c432/go.mod h1:A8t3i0CUGtXCA0aiLsP7iyikmk/KaD/2XVvNJqGCU20= github.com/status-im/go-watchdog v1.2.0-ios-nolibproc h1:BJwZEF7OVKaXc2zErBUAolFSGzwrTBbWnN8e/6MER5E= github.com/status-im/go-watchdog v1.2.0-ios-nolibproc/go.mod h1:lzSbAl5sh4rtI8tYHU01BWIDzgzqaQLj6RcA1i4mlqI= -github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4 h1:Gb2Tyox57NRNuZ2d3rmvB3pcmbu7O1RS3m8WRx7ilrg= github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4/go.mod h1:RZLeN1LMWmRsyYjvAu+I6Dm9QmlDaIIt+Y+4Kd7Tp+Q= github.com/status-im/noise v1.0.1-handshakeMessages h1:mj1btE58Qk2pS0qz+BHE22HYIOhZoEFNTnRpQeMfHYk= github.com/status-im/noise v1.0.1-handshakeMessages/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag= @@ -1734,7 +1725,6 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1 github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tv42/httpunix v0.0.0-20191220191345-2ba4b9c3382c/go.mod h1:hzIxponao9Kjc7aWznkXaL4U4TWaDSs8zcsY4Ka08nM= -github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef h1:wHSqTBrZW24CsNJDfeh9Ex6Pm0Rcpc7qrgKBiL44vF4= github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= @@ -2547,7 +2537,6 @@ gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:a gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= -gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= gopkg.in/olebedev/go-duktape.v3 v3.0.0-20200619000410-60c24ae608a6/go.mod h1:uAJfkITjFhyEEuUfm7bsmCZRbW5WRq8s9EY8HZ6hCns= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= diff --git a/waku.go b/waku.go index e2114696..5d5ae977 100644 --- a/waku.go +++ b/waku.go @@ -385,6 +385,42 @@ func main() { Usage: "Enable access to JSON-RPC Private API", Destination: &options.RPCServer.Private, }, + + &cli.BoolFlag{ + Name: "rest", + Usage: "Enable Waku REST HTTP server", + Destination: &options.RESTServer.Enable, + }, + &cli.StringFlag{ + Name: "rest-address", + Value: "127.0.0.1", + Usage: "Listening address of the REST HTTP server", + Destination: &options.RESTServer.Address, + }, + &cli.IntFlag{ + Name: "rest-port", + Value: 8645, + Usage: "Listening port of the REST HTTP server", + Destination: &options.RESTServer.Port, + }, + &cli.IntFlag{ + Name: "rest-relay-cache-capacity", + Value: 30, + Usage: "Capacity of the Relay REST API message cache", + Destination: &options.RESTServer.RelayCacheCapacity, + }, + &cli.BoolFlag{ + Name: "rest-admin", + Value: false, + Usage: "Enable access to REST HTTP Admin API", + Destination: &options.RESTServer.Admin, + }, + &cli.BoolFlag{ + Name: "rest-private", + Value: false, + Usage: "Enable access to REST HTTP Private API", + Destination: &options.RESTServer.Private, + }, }, Action: func(c *cli.Context) error { // for go-libp2p loggers diff --git a/waku/node.go b/waku/node.go index f8fed39f..55cb5bf9 100644 --- a/waku/node.go +++ b/waku/node.go @@ -40,6 +40,7 @@ import ( "github.com/status-im/go-waku/waku/v2/protocol/lightpush" "github.com/status-im/go-waku/waku/v2/protocol/relay" "github.com/status-im/go-waku/waku/v2/protocol/store" + "github.com/status-im/go-waku/waku/v2/rest" "github.com/status-im/go-waku/waku/v2/rpc" "github.com/status-im/go-waku/waku/v2/utils" ) @@ -315,6 +316,12 @@ func Execute(options Options) { rpcServer.Start() } + var restServer *rest.WakuRest + if options.RESTServer.Enable { + restServer = rest.NewWakuRest(wakuNode, options.RESTServer.Address, options.RESTServer.Port, options.RESTServer.Admin, options.RESTServer.Private, options.RESTServer.RelayCacheCapacity, logger) + restServer.Start() + } + logger.Info("Node setup complete") // Wait for a SIGINT or SIGTERM signal @@ -331,6 +338,11 @@ func Execute(options Options) { failOnErr(err, "RPCClose") } + if options.RESTServer.Enable { + err := restServer.Stop(ctx) + failOnErr(err, "RESTClose") + } + if options.Metrics.Enable { err = metricsServer.Stop(ctx) failOnErr(err, "MetricsClose") diff --git a/waku/options.go b/waku/options.go index 614e6b0e..e7015aba 100644 --- a/waku/options.go +++ b/waku/options.go @@ -111,6 +111,16 @@ type RPCServerOptions struct { Private bool } +// RESTServerOptions are settings used to start a rest http server +type RESTServerOptions struct { + Enable bool + Port int + Address string + Admin bool + Private bool + RelayCacheCapacity int +} + // WSOptions are settings used for enabling websockets and secure websockets // support type WSOptions struct { @@ -157,4 +167,5 @@ type Options struct { DNSDiscovery DNSDiscoveryOptions Metrics MetricsOptions RPCServer RPCServerOptions + RESTServer RESTServerOptions } diff --git a/waku/v2/protocol/relay/waku_relay.go b/waku/v2/protocol/relay/waku_relay.go index 58e94fd3..ef54d647 100644 --- a/waku/v2/protocol/relay/waku_relay.go +++ b/waku/v2/protocol/relay/waku_relay.go @@ -145,7 +145,7 @@ func (w *WakuRelay) subscribe(topic string) (subs *pubsub.Subscription, err erro } w.relaySubs[topic] = sub - w.log.Info("subscribing to topic", zap.String("topic", topic)) + w.log.Info("subscribing to topic", zap.String("topic", sub.Topic())) } return sub, nil @@ -253,10 +253,11 @@ func (w *WakuRelay) Subscribe(ctx context.Context) (*Subscription, error) { // Unsubscribe closes a subscription to a pubsub topic func (w *WakuRelay) Unsubscribe(ctx context.Context, topic string) error { - if _, ok := w.relaySubs[topic]; !ok { - return fmt.Errorf("topics %s is not subscribed", (string)(topic)) + sub, ok := w.relaySubs[topic] + if !ok { + return fmt.Errorf("not subscribed to topic") } - w.log.Info("unsubscribing from topic", zap.String("topic", topic)) + w.log.Info("unsubscribing from topic", zap.String("topic", sub.Topic())) for _, sub := range w.subscriptions[topic] { sub.Unsubscribe() diff --git a/waku/v2/rest/debug.go b/waku/v2/rest/debug.go new file mode 100644 index 00000000..1f8135a4 --- /dev/null +++ b/waku/v2/rest/debug.go @@ -0,0 +1,53 @@ +package rest + +import ( + "fmt" + "net/http" + + "github.com/gorilla/mux" + "github.com/status-im/go-waku/waku/v2/node" +) + +type DebugService struct { + node *node.WakuNode + mux *mux.Router +} + +type InfoArgs struct { +} + +type InfoReply struct { + ENRUri string `json:"enrUri,omitempty"` + ListenAddresses []string `json:"listenAddresses,omitempty"` +} + +const ROUTE_DEBUG_INFOV1 = "/debug/v1/info" +const ROUTE_DEBUG_VERSIONV1 = "/debug/v1/info" + +func NewDebugService(node *node.WakuNode, m *mux.Router) *DebugService { + d := &DebugService{ + node: node, + mux: m, + } + + m.HandleFunc(ROUTE_DEBUG_INFOV1, d.getV1Info).Methods(http.MethodGet) + m.HandleFunc(ROUTE_DEBUG_VERSIONV1, d.getV1Version).Methods(http.MethodGet) + + return d +} + +type VersionResponse string + +func (d *DebugService) getV1Info(w http.ResponseWriter, r *http.Request) { + response := new(InfoReply) + response.ENRUri = d.node.ENR().String() + for _, addr := range d.node.ListenAddresses() { + response.ListenAddresses = append(response.ListenAddresses, addr.String()) + } + writeErrOrResponse(w, nil, response) +} + +func (d *DebugService) getV1Version(w http.ResponseWriter, r *http.Request) { + response := VersionResponse(fmt.Sprintf("%s-%s", node.Version, node.GitCommit)) + writeErrOrResponse(w, nil, response) +} diff --git a/waku/v2/rpc/debug_api.yaml b/waku/v2/rest/debug_api.yaml similarity index 100% rename from waku/v2/rpc/debug_api.yaml rename to waku/v2/rest/debug_api.yaml diff --git a/waku/v2/rest/debug_test.go b/waku/v2/rest/debug_test.go new file mode 100644 index 00000000..3903261e --- /dev/null +++ b/waku/v2/rest/debug_test.go @@ -0,0 +1,33 @@ +package rest + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/status-im/go-waku/waku/v2/node" + "github.com/stretchr/testify/require" +) + +func TestGetV1Info(t *testing.T) { + wakuNode1, err := node.New(context.Background()) + require.NoError(t, err) + defer wakuNode1.Stop() + err = wakuNode1.Start() + require.NoError(t, err) + + d := &DebugService{ + node: wakuNode1, + } + + request, err := http.NewRequest(http.MethodPost, ROUTE_DEBUG_INFOV1, bytes.NewReader([]byte(""))) + require.NoError(t, err) + + rr := httptest.NewRecorder() + + d.getV1Info(rr, request) + + require.Equal(t, http.StatusOK, rr.Code) +} diff --git a/waku/v2/rest/relay.go b/waku/v2/rest/relay.go new file mode 100644 index 00000000..b41997e1 --- /dev/null +++ b/waku/v2/rest/relay.go @@ -0,0 +1,195 @@ +package rest + +import ( + "encoding/json" + "net/http" + "strings" + "sync" + + "github.com/gorilla/mux" + "github.com/status-im/go-waku/waku/v2/node" + "github.com/status-im/go-waku/waku/v2/protocol" + "github.com/status-im/go-waku/waku/v2/protocol/pb" + "github.com/status-im/go-waku/waku/v2/protocol/relay" + "go.uber.org/zap" +) + +const ROUTE_RELAY_SUBSCRIPTIONSV1 = "/relay/v1/subscriptions" +const ROUTE_RELAY_MESSAGESV1 = "/relay/v1/messages/{topic}" + +type RelayService struct { + node *node.WakuNode + mux *mux.Router + + log *zap.Logger + + messages map[string][]*pb.WakuMessage + cacheCapacity int + messagesMutex sync.RWMutex + + runner *runnerService +} + +func NewRelayService(node *node.WakuNode, m *mux.Router, cacheCapacity int, log *zap.Logger) *RelayService { + s := &RelayService{ + node: node, + mux: m, + log: log.Named("relay"), + cacheCapacity: cacheCapacity, + messages: make(map[string][]*pb.WakuMessage), + } + + s.runner = newRunnerService(node.Broadcaster(), s.addEnvelope) + + m.HandleFunc(ROUTE_RELAY_SUBSCRIPTIONSV1, s.postV1Subscriptions).Methods(http.MethodPost) + m.HandleFunc(ROUTE_RELAY_SUBSCRIPTIONSV1, s.deleteV1Subscriptions).Methods(http.MethodDelete) + m.HandleFunc(ROUTE_RELAY_MESSAGESV1, s.getV1Messages).Methods(http.MethodGet) + m.HandleFunc(ROUTE_RELAY_MESSAGESV1, s.postV1Message).Methods(http.MethodPost) + + return s +} + +func (r *RelayService) addEnvelope(envelope *protocol.Envelope) { + r.messagesMutex.Lock() + defer r.messagesMutex.Unlock() + + if _, ok := r.messages[envelope.PubsubTopic()]; !ok { + return + } + + // Keep a specific max number of messages per topic + if len(r.messages[envelope.PubsubTopic()]) >= r.cacheCapacity { + r.messages[envelope.PubsubTopic()] = r.messages[envelope.PubsubTopic()][1:] + } + + r.messages[envelope.PubsubTopic()] = append(r.messages[envelope.PubsubTopic()], envelope.Message()) +} + +func (r *RelayService) Start() { + // Node may already be subscribed to some topics when Relay API handlers are installed. Let's add these + for _, topic := range r.node.Relay().Topics() { + r.log.Info("adding topic handler for existing subscription", zap.String("topic", topic)) + r.messages[topic] = make([]*pb.WakuMessage, 0) + } + + r.runner.Start() +} + +func (r *RelayService) Stop() { + r.runner.Stop() +} + +func (d *RelayService) deleteV1Subscriptions(w http.ResponseWriter, r *http.Request) { + var topics []string + decoder := json.NewDecoder(r.Body) + if err := decoder.Decode(&topics); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + defer r.Body.Close() + + d.messagesMutex.Lock() + defer d.messagesMutex.Unlock() + + var err error + for _, topic := range topics { + err = d.node.Relay().Unsubscribe(r.Context(), topic) + if err != nil { + d.log.Error("unsubscribing from topic", zap.String("topic", strings.Replace(strings.Replace(topic, "\n", "", -1), "\r", "", -1)), zap.Error(err)) + } else { + delete(d.messages, topic) + } + } + + writeErrOrResponse(w, err, true) +} + +func (d *RelayService) postV1Subscriptions(w http.ResponseWriter, r *http.Request) { + var topics []string + decoder := json.NewDecoder(r.Body) + if err := decoder.Decode(&topics); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + defer r.Body.Close() + + var err error + var sub *relay.Subscription + var topicToSubscribe string + for _, topic := range topics { + if topic == "" { + sub, err = d.node.Relay().Subscribe(r.Context()) + topicToSubscribe = relay.DefaultWakuTopic + } else { + sub, err = d.node.Relay().SubscribeToTopic(r.Context(), topic) + topicToSubscribe = topic + } + if err != nil { + d.log.Error("subscribing to topic", zap.String("topic", strings.Replace(topicToSubscribe, "\n", "", -1)), zap.Error(err)) + } else { + d.node.Broadcaster().Unregister(&topicToSubscribe, sub.C) + + d.messages[topic] = make([]*pb.WakuMessage, 0) + } + } + + writeErrOrResponse(w, err, true) +} + +func (d *RelayService) getV1Messages(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + topic, ok := vars["topic"] + if !ok { + w.WriteHeader(http.StatusBadRequest) + return + } + + var err error + var response []*pb.WakuMessage + + d.messagesMutex.Lock() + defer d.messagesMutex.Unlock() + + if _, ok := d.messages[topic]; !ok { + w.WriteHeader(http.StatusNotFound) + w.Write([]byte("not subscribed to topic")) + return + } else { + for i := range d.messages[topic] { + response = append(response, d.messages[topic][i]) + } + d.messages[topic] = make([]*pb.WakuMessage, 0) + } + + writeErrOrResponse(w, err, response) +} + +func (d *RelayService) postV1Message(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + topic, ok := vars["topic"] + if !ok { + w.WriteHeader(http.StatusBadRequest) + return + } + + var message *pb.WakuMessage + decoder := json.NewDecoder(r.Body) + if err := decoder.Decode(&message); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + defer r.Body.Close() + + var err error + if topic == "" { + _, err = d.node.Relay().Publish(r.Context(), message) + } else { + _, err = d.node.Relay().PublishToTopic(r.Context(), message, strings.Replace(topic, "\n", "", -1)) + } + + if err != nil { + d.log.Error("publishing message", zap.Error(err)) + } + + writeErrOrResponse(w, err, true) +} diff --git a/waku/v2/rpc/relay_api.yaml b/waku/v2/rest/relay_api.yaml similarity index 100% rename from waku/v2/rpc/relay_api.yaml rename to waku/v2/rest/relay_api.yaml diff --git a/waku/v2/rest/relay_test.go b/waku/v2/rest/relay_test.go new file mode 100644 index 00000000..c9ce6946 --- /dev/null +++ b/waku/v2/rest/relay_test.go @@ -0,0 +1,162 @@ +package rest + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gorilla/mux" + "github.com/multiformats/go-multiaddr" + "github.com/status-im/go-waku/tests" + "github.com/status-im/go-waku/waku/v2/node" + "github.com/status-im/go-waku/waku/v2/protocol" + "github.com/status-im/go-waku/waku/v2/protocol/pb" + "github.com/status-im/go-waku/waku/v2/utils" + "github.com/stretchr/testify/require" +) + +func makeRelayService(t *testing.T) *RelayService { + options := node.WithWakuRelayAndMinPeers(0) + n, err := node.New(context.Background(), options) + require.NoError(t, err) + err = n.Start() + require.NoError(t, err) + + mux := mux.NewRouter() + + return NewRelayService(n, mux, 3, utils.Logger()) +} + +func TestPostV1Message(t *testing.T) { + d := makeRelayService(t) + + msg := &pb.WakuMessage{ + Payload: []byte{1, 2, 3}, + ContentTopic: "abc", + Version: 0, + Timestamp: utils.GetUnixEpoch(), + } + msgJsonBytes, err := json.Marshal(msg) + require.NoError(t, err) + + rr := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodPost, "/relay/v1/messages/test", bytes.NewReader(msgJsonBytes)) + d.mux.ServeHTTP(rr, req) + require.Equal(t, http.StatusOK, rr.Code) + require.Equal(t, "true", rr.Body.String()) +} + +func TestRelaySubscription(t *testing.T) { + d := makeRelayService(t) + + go d.Start() + defer d.Stop() + + topics := []string{"test"} + topicsJSONBytes, err := json.Marshal(topics) + require.NoError(t, err) + + rr := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodPost, "/relay/v1/subscriptions", bytes.NewReader(topicsJSONBytes)) + d.mux.ServeHTTP(rr, req) + require.Equal(t, http.StatusOK, rr.Code) + require.Equal(t, "true", rr.Body.String()) + + // Test max messages in subscription + d.runner.broadcaster.Submit(protocol.NewEnvelope(tests.CreateWakuMessage("test", 1), 1, "test")) + d.runner.broadcaster.Submit(protocol.NewEnvelope(tests.CreateWakuMessage("test", 2), 2, "test")) + d.runner.broadcaster.Submit(protocol.NewEnvelope(tests.CreateWakuMessage("test", 3), 3, "test")) + + // Wait for the messages to be processed + time.Sleep(500 * time.Millisecond) + + require.Len(t, d.messages["test"], 3) + + d.runner.broadcaster.Submit(protocol.NewEnvelope(tests.CreateWakuMessage("test", 4), 4, "test")) + + time.Sleep(500 * time.Millisecond) + + // Should only have 3 messages + require.Len(t, d.messages["test"], 3) + + // Test deletion + rr = httptest.NewRecorder() + req, _ = http.NewRequest(http.MethodDelete, "/relay/v1/subscriptions", bytes.NewReader(topicsJSONBytes)) + d.mux.ServeHTTP(rr, req) + require.Equal(t, http.StatusOK, rr.Code) + require.Equal(t, "true", rr.Body.String()) + require.Len(t, d.messages["test"], 0) + +} + +func TestRelayGetV1Messages(t *testing.T) { + serviceA := makeRelayService(t) + go serviceA.Start() + defer serviceA.Stop() + serviceB := makeRelayService(t) + go serviceB.Start() + defer serviceB.Stop() + + hostInfo, err := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s", serviceB.node.Host().ID().Pretty())) + require.NoError(t, err) + + var addr multiaddr.Multiaddr + for _, a := range serviceB.node.Host().Addrs() { + addr = a.Encapsulate(hostInfo) + break + } + err = serviceA.node.DialPeerWithMultiAddress(context.Background(), addr) + require.NoError(t, err) + + // Wait for the dial to complete + time.Sleep(1 * time.Second) + + topics := []string{"test"} + topicsJSONBytes, err := json.Marshal(topics) + require.NoError(t, err) + + rr := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodPost, "/relay/v1/subscriptions", bytes.NewReader(topicsJSONBytes)) + serviceB.mux.ServeHTTP(rr, req) + require.Equal(t, http.StatusOK, rr.Code) + + // Wait for the subscription to be started + time.Sleep(1 * time.Second) + + msg := &pb.WakuMessage{ + Payload: []byte{1, 2, 3}, + ContentTopic: "test", + Version: 0, + Timestamp: utils.GetUnixEpoch(), + } + msgJsonBytes, err := json.Marshal(msg) + require.NoError(t, err) + + rr = httptest.NewRecorder() + req, _ = http.NewRequest(http.MethodPost, "/relay/v1/messages/test", bytes.NewReader(msgJsonBytes)) + serviceA.mux.ServeHTTP(rr, req) + require.Equal(t, http.StatusOK, rr.Code) + + // Wait for the message to be received + time.Sleep(1 * time.Second) + + rr = httptest.NewRecorder() + req, _ = http.NewRequest(http.MethodGet, "/relay/v1/messages/test", bytes.NewReader([]byte{})) + serviceB.mux.ServeHTTP(rr, req) + require.Equal(t, http.StatusOK, rr.Code) + + var messages []*pb.WakuMessage + err = json.Unmarshal(rr.Body.Bytes(), &messages) + require.NoError(t, err) + require.Len(t, messages, 1) + + rr = httptest.NewRecorder() + req, _ = http.NewRequest(http.MethodGet, "/relay/v1/messages/test", bytes.NewReader([]byte{})) + serviceA.mux.ServeHTTP(rr, req) + require.Equal(t, http.StatusNotFound, rr.Code) +} diff --git a/waku/v2/rest/runner.go b/waku/v2/rest/runner.go new file mode 100644 index 00000000..88c0686a --- /dev/null +++ b/waku/v2/rest/runner.go @@ -0,0 +1,42 @@ +package rest + +import ( + v2 "github.com/status-im/go-waku/waku/v2" + "github.com/status-im/go-waku/waku/v2/protocol" +) + +type Adder func(msg *protocol.Envelope) + +type runnerService struct { + broadcaster v2.Broadcaster + ch chan *protocol.Envelope + quit chan bool + adder Adder +} + +func newRunnerService(broadcaster v2.Broadcaster, adder Adder) *runnerService { + return &runnerService{ + broadcaster: broadcaster, + quit: make(chan bool), + adder: adder, + } +} + +func (r *runnerService) Start() { + r.ch = make(chan *protocol.Envelope, 1024) + r.broadcaster.Register(nil, r.ch) + for { + select { + case <-r.quit: + return + case envelope := <-r.ch: + r.adder(envelope) + } + } +} + +func (r *runnerService) Stop() { + r.quit <- true + r.broadcaster.Unregister(nil, r.ch) + close(r.ch) +} diff --git a/waku/v2/rest/utils.go b/waku/v2/rest/utils.go new file mode 100644 index 00000000..f1fde64e --- /dev/null +++ b/waku/v2/rest/utils.go @@ -0,0 +1,27 @@ +package rest + +import ( + "encoding/json" + "net/http" +) + +func writeErrOrResponse(w http.ResponseWriter, err error, value interface{}) { + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + + jsonResponse, err := json.Marshal(value) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + + _, err = w.Write(jsonResponse) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } +} diff --git a/waku/v2/rest/waku_rest.go b/waku/v2/rest/waku_rest.go new file mode 100644 index 00000000..25fda0e8 --- /dev/null +++ b/waku/v2/rest/waku_rest.go @@ -0,0 +1,60 @@ +package rest + +import ( + "context" + "fmt" + "net/http" + + "github.com/gorilla/mux" + "github.com/status-im/go-waku/waku/v2/node" + "go.uber.org/zap" +) + +type WakuRest struct { + node *node.WakuNode + server *http.Server + + log *zap.Logger + + relayService *RelayService +} + +func NewWakuRest(node *node.WakuNode, address string, port int, enableAdmin bool, enablePrivate bool, relayCacheCapacity int, log *zap.Logger) *WakuRest { + wrpc := new(WakuRest) + wrpc.log = log.Named("rest") + + mux := mux.NewRouter() + + _ = NewDebugService(node, mux) + relayService := NewRelayService(node, mux, relayCacheCapacity, log) + + listenAddr := fmt.Sprintf("%s:%d", address, port) + + server := &http.Server{ + Addr: listenAddr, + Handler: mux, + } + + server.RegisterOnShutdown(func() { + relayService.Stop() + }) + + wrpc.node = node + wrpc.server = server + wrpc.relayService = relayService + + return wrpc +} + +func (r *WakuRest) Start() { + go r.relayService.Start() + go func() { + _ = r.server.ListenAndServe() + }() + r.log.Info("server started", zap.String("addr", r.server.Addr)) +} + +func (r *WakuRest) Stop(ctx context.Context) error { + r.log.Info("shutting down server") + return r.server.Shutdown(ctx) +} diff --git a/waku/v2/rest/waku_rest_test.go b/waku/v2/rest/waku_rest_test.go new file mode 100644 index 00000000..4a5e6dbc --- /dev/null +++ b/waku/v2/rest/waku_rest_test.go @@ -0,0 +1,20 @@ +package rest + +import ( + "context" + "testing" + + "github.com/status-im/go-waku/waku/v2/node" + "github.com/status-im/go-waku/waku/v2/utils" + "github.com/stretchr/testify/require" +) + +func TestWakuRest(t *testing.T) { + options := node.WithWakuStore(false, false) + n, err := node.New(context.Background(), options) + require.NoError(t, err) + + rpc := NewWakuRest(n, "127.0.0.1", 8080, true, true, 10, utils.Logger()) + require.NotNil(t, rpc.server) + require.Equal(t, rpc.server.Addr, "127.0.0.1:8080") +} diff --git a/waku/v2/rpc/debug.go b/waku/v2/rpc/debug.go index 75d3ddf9..bcbeef6b 100644 --- a/waku/v2/rpc/debug.go +++ b/waku/v2/rpc/debug.go @@ -4,7 +4,6 @@ import ( "fmt" "net/http" - "github.com/gorilla/mux" "github.com/status-im/go-waku/waku/v2/node" ) @@ -20,15 +19,10 @@ type InfoReply struct { ListenAddresses []string `json:"listenAddresses,omitempty"` } -func NewDebugService(node *node.WakuNode, m *mux.Router) *DebugService { - d := &DebugService{ +func NewDebugService(node *node.WakuNode) *DebugService { + return &DebugService{ node: node, } - - m.HandleFunc("/debug/v1/info", d.restGetV1Info).Methods(http.MethodGet) - m.HandleFunc("/debug/v1/version", d.restGetV1Version).Methods(http.MethodGet) - - return d } func (d *DebugService) GetV1Info(r *http.Request, args *InfoArgs, reply *InfoReply) error { @@ -45,15 +39,3 @@ func (d *DebugService) GetV1Version(r *http.Request, args *InfoArgs, reply *Vers *reply = VersionResponse(fmt.Sprintf("%s-%s", node.Version, node.GitCommit)) return nil } - -func (d *DebugService) restGetV1Info(w http.ResponseWriter, r *http.Request) { - response := new(InfoReply) - err := d.GetV1Info(r, nil, response) - writeErrOrResponse(w, err, response) -} - -func (d *DebugService) restGetV1Version(w http.ResponseWriter, r *http.Request) { - response := new(VersionResponse) - err := d.GetV1Version(r, nil, response) - writeErrOrResponse(w, err, response) -} diff --git a/waku/v2/rpc/relay.go b/waku/v2/rpc/relay.go index 1251b254..775937f7 100644 --- a/waku/v2/rpc/relay.go +++ b/waku/v2/rpc/relay.go @@ -1,12 +1,10 @@ package rpc import ( - "encoding/json" "fmt" "net/http" "sync" - "github.com/gorilla/mux" "github.com/status-im/go-waku/waku/v2/node" "github.com/status-im/go-waku/waku/v2/protocol" "github.com/status-im/go-waku/waku/v2/protocol/pb" @@ -38,7 +36,7 @@ type TopicArgs struct { Topic string `json:"topic,omitempty"` } -func NewRelayService(node *node.WakuNode, m *mux.Router, log *zap.Logger) *RelayService { +func NewRelayService(node *node.WakuNode, log *zap.Logger) *RelayService { s := &RelayService{ node: node, log: log.Named("relay"), @@ -47,11 +45,6 @@ func NewRelayService(node *node.WakuNode, m *mux.Router, log *zap.Logger) *Relay s.runner = newRunnerService(node.Broadcaster(), s.addEnvelope) - m.HandleFunc("/relay/v1/subscriptions", s.restPostV1Subscriptions).Methods(http.MethodPost) - m.HandleFunc("/relay/v1/subscriptions", s.restDeleteV1Subscriptions).Methods(http.MethodDelete) - m.HandleFunc("/relay/v1/messages/{topic}", s.restGetV1Messages).Methods(http.MethodGet) - m.HandleFunc("/relay/v1/messages/{topic}", s.restPostV1Message).Methods(http.MethodPost) - return s } @@ -155,74 +148,3 @@ func (r *RelayService) GetV1Messages(req *http.Request, args *TopicArgs, reply * return nil } - -func (d *RelayService) restDeleteV1Subscriptions(w http.ResponseWriter, r *http.Request) { - request := new(TopicsArgs) - decoder := json.NewDecoder(r.Body) - if err := decoder.Decode(&request.Topics); err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - defer r.Body.Close() - - response := new(SuccessReply) - err := d.DeleteV1Subscription(r, request, response) - - writeErrOrResponse(w, err, response) -} - -func (d *RelayService) restPostV1Subscriptions(w http.ResponseWriter, r *http.Request) { - request := new(TopicsArgs) - decoder := json.NewDecoder(r.Body) - if err := decoder.Decode(&request.Topics); err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - defer r.Body.Close() - - response := new(SuccessReply) - err := d.PostV1Subscription(r, request, response) - - writeErrOrResponse(w, err, response) -} - -func (d *RelayService) restGetV1Messages(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - topic, ok := vars["topic"] - if !ok { - w.WriteHeader(http.StatusBadRequest) - return - } - - request := new(TopicArgs) - request.Topic = topic - - response := new([]*RPCWakuRelayMessage) - err := d.GetV1Messages(r, request, response) - - writeErrOrResponse(w, err, response) -} - -func (d *RelayService) restPostV1Message(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - topic, ok := vars["topic"] - if !ok { - w.WriteHeader(http.StatusBadRequest) - return - } - - request := new(RelayMessageArgs) - request.Topic = topic - - decoder := json.NewDecoder(r.Body) - if err := decoder.Decode(&request.Message); err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - defer r.Body.Close() - - response := new(bool) - err := d.PostV1Message(r, request, response) - - writeErrOrResponse(w, err, response) -} diff --git a/waku/v2/rpc/relay_test.go b/waku/v2/rpc/relay_test.go index 0005ad85..744140ef 100644 --- a/waku/v2/rpc/relay_test.go +++ b/waku/v2/rpc/relay_test.go @@ -6,7 +6,6 @@ import ( "testing" "time" - "github.com/gorilla/mux" "github.com/multiformats/go-multiaddr" "github.com/status-im/go-waku/waku/v2/node" "github.com/status-im/go-waku/waku/v2/utils" @@ -20,9 +19,7 @@ func makeRelayService(t *testing.T) *RelayService { err = n.Start() require.NoError(t, err) - mux := mux.NewRouter() - - return NewRelayService(n, mux, utils.Logger()) + return NewRelayService(n, utils.Logger()) } func TestPostV1Message(t *testing.T) { diff --git a/waku/v2/rpc/utils.go b/waku/v2/rpc/utils.go index eacd24d0..96fa1446 100644 --- a/waku/v2/rpc/utils.go +++ b/waku/v2/rpc/utils.go @@ -2,9 +2,7 @@ package rpc import ( "encoding/hex" - "encoding/json" "fmt" - "net/http" "strings" "github.com/status-im/go-waku/waku/v2/protocol/pb" @@ -135,22 +133,3 @@ func (h *ByteArray) UnmarshalText(b []byte) error { return nil } - -func writeErrOrResponse(w http.ResponseWriter, err error, value interface{}) { - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - - jsonResponse, err := json.Marshal(value) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - - _, err = w.Write(jsonResponse) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } -} diff --git a/waku/v2/rpc/waku_rpc.go b/waku/v2/rpc/waku_rpc.go index 6166d258..f256768c 100644 --- a/waku/v2/rpc/waku_rpc.go +++ b/waku/v2/rpc/waku_rpc.go @@ -39,13 +39,13 @@ func NewWakuRpc(node *node.WakuNode, address string, port int, enableAdmin bool, wrpc.log.Info("served request", zap.String("path", r.URL.Path), zap.Duration("duration", time.Since(t))) }) - debugService := NewDebugService(node, mux) + debugService := NewDebugService(node) err := s.RegisterService(debugService, "Debug") if err != nil { wrpc.log.Error("registering debug service", zap.Error(err)) } - relayService := NewRelayService(node, mux, log) + relayService := NewRelayService(node, log) err = s.RegisterService(relayService, "Relay") if err != nil { wrpc.log.Error("registering relay service", zap.Error(err))