Skip to content

Commit

Permalink
feat(client): add get health
Browse files Browse the repository at this point in the history
  • Loading branch information
yihau committed Nov 14, 2023
1 parent 22328cd commit 5702662
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 0 deletions.
24 changes: 24 additions & 0 deletions client/rpc_get_health.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package client

import (
"context"

"github.com/blocto/solana-go-sdk/rpc"
)

// GetHealthResponse returns the current health of the node. A healthy node is one that is within HEALTH_CHECK_SLOT_DISTANCE slots of the latest cluster confirmed slot.
func (c *Client) GetHealth(ctx context.Context) (bool, error) {
res, err := process(
func() (rpc.JsonRpcResponse[string], error) {
return c.RpcClient.GetHealth(ctx)
},
forward[string],
)
if err != nil {
return false, err
}
if res != "ok" {
return false, err
}
return true, nil
}
57 changes: 57 additions & 0 deletions client/rpc_get_health_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package client

import (
"context"
"testing"

"github.com/blocto/solana-go-sdk/internal/client_test"
"github.com/blocto/solana-go-sdk/rpc"
)

func TestClient_GetHealth(t *testing.T) {
client_test.TestAll(
t,
[]client_test.Param{
{
RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getHealth"}`,
ResponseBody: `{"jsonrpc":"2.0","result":"ok","id":1}`,
F: func(url string) (any, error) {
c := NewClient(url)
return c.GetHealth(context.TODO())
},
ExpectedValue: true,
ExpectedError: nil,
},
{
RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getHealth"}`,
ResponseBody: `{"jsonrpc":"2.0","error":{"code":-32005,"message":"Node is behind by 42 slots","data":{"numSlotsBehind":42}},"id":1}`,
F: func(url string) (any, error) {
c := NewClient(url)
return c.GetHealth(context.TODO())
},
ExpectedValue: false,
ExpectedError: &rpc.JsonRpcError{
Code: -32005,
Message: `Node is behind by 42 slots`,
Data: map[string]any{
"numSlotsBehind": float64(42),
},
},
},
{
RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getHealth"}`,
ResponseBody: `{"jsonrpc":"2.0","error":{"code":-32005,"message":"Node is unhealthy","data":{}},"id":1}`,
F: func(url string) (any, error) {
c := NewClient(url)
return c.GetHealth(context.TODO())
},
ExpectedValue: false,
ExpectedError: &rpc.JsonRpcError{
Code: -32005,
Message: `Node is unhealthy`,
Data: map[string]any{},
},
},
},
)
}
20 changes: 20 additions & 0 deletions docs/_examples/rpc/get-health/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package main

import (
"context"
"fmt"
"log"

"github.com/blocto/solana-go-sdk/client"
"github.com/blocto/solana-go-sdk/rpc"
)

func main() {
c := client.NewClient(rpc.DevnetRPCEndpoint)
ok, err := c.GetHealth(context.TODO())
if err != nil {
log.Fatalf("failed to get health, err: %v", err)
}

fmt.Println(ok)
}

0 comments on commit 5702662

Please sign in to comment.