Skip to content

Commit

Permalink
Add running chain hashes handler on http server (#908)
Browse files Browse the repository at this point in the history
* add running chain hashes handler
* add test for running chains on http relay
  • Loading branch information
emmanuelm41 committed Jan 31, 2022
1 parent 881cb50 commit ddb8677
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
17 changes: 17 additions & 0 deletions http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ func New(ctx context.Context, c client.Client, version string, logger log.Logger
mux.HandleFunc("/public/{"+roundParamKey+"}", withCommonHeaders(version, handler.PublicRand))
mux.HandleFunc("/info", withCommonHeaders(version, handler.ChainInfo))
mux.HandleFunc("/health", withCommonHeaders(version, handler.Health))
mux.HandleFunc("/chains", withCommonHeaders(version, handler.ChainHashes))

handler.httpHandler = promhttp.InstrumentHandlerCounter(
metrics.HTTPCallCounter,
Expand Down Expand Up @@ -529,6 +530,22 @@ func (h *DrandHandler) Health(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(b)
}

func (h *DrandHandler) ChainHashes(w http.ResponseWriter, r *http.Request) {
chainHashes := make([]string, 0)
for chainHash := range h.beacons {
if chainHash != common.DefaultChainHash {
chainHashes = append(chainHashes, chainHash)
}
}

w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "max-age=300")

w.WriteHeader(http.StatusOK)
b, _ := json.Marshal(chainHashes)
_, _ = w.Write(b)
}

func readChainHash(r *http.Request) ([]byte, error) {
var err error
chainHashHex := make([]byte, 0)
Expand Down
22 changes: 21 additions & 1 deletion http/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func withClient(t *testing.T) (c client.Client, emit func(bool)) {
return c, s.(mock.MockService).EmitRand
}

//nolint:funlen
func TestHTTPRelay(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
Expand Down Expand Up @@ -64,8 +65,27 @@ func TestHTTPRelay(t *testing.T) {
t.Fatal(err)
}

getChains := fmt.Sprintf("http://%s/chains", listener.Addr().String())
resp, err := http.Get(getChains)
require.NoError(t, err)

if resp.StatusCode != 200 {
t.Error("expected http status code 200")
}

var chains []string
require.NoError(t, json.NewDecoder(resp.Body).Decode(&chains))
require.NoError(t, resp.Body.Close())

if len(chains) != 1 {
t.Error("expected chain hash qty not valid")
}
if chains[0] != info.HashString() {
t.Error("expected chain hash not valid")
}

getChain := fmt.Sprintf("http://%s/%s/info", listener.Addr().String(), info.HashString())
resp, err := http.Get(getChain)
resp, err = http.Get(getChain)
require.NoError(t, err)
cip := new(drand.ChainInfoPacket)
require.NoError(t, json.NewDecoder(resp.Body).Decode(cip))
Expand Down

0 comments on commit ddb8677

Please sign in to comment.