github.com/filecoin-project/bacalhau@v0.3.23-0.20230228154132-45c989550ace/pkg/test/requester/publicapi/util.go (about) 1 package publicapi 2 3 import ( 4 "context" 5 "fmt" 6 "testing" 7 "time" 8 9 "github.com/filecoin-project/bacalhau/pkg/devstack" 10 "github.com/filecoin-project/bacalhau/pkg/jobstore/inmemory" 11 "github.com/filecoin-project/bacalhau/pkg/libp2p" 12 13 "github.com/filecoin-project/bacalhau/pkg/node" 14 "github.com/filecoin-project/bacalhau/pkg/publicapi" 15 requester_publicapi "github.com/filecoin-project/bacalhau/pkg/requester/publicapi" 16 "github.com/filecoin-project/bacalhau/pkg/system" 17 "github.com/phayes/freeport" 18 "github.com/stretchr/testify/require" 19 ) 20 21 const TimeToWaitForServerReply = 10 22 const TimeToWaitForHealthy = 50 23 24 //nolint:unused // used in tests 25 func setupNodeForTest(t *testing.T) (*node.Node, *requester_publicapi.RequesterAPIClient) { 26 // blank config should result in using defaults in node.Node constructor 27 return setupNodeForTestWithConfig(t, publicapi.APIServerConfig{}) 28 } 29 30 //nolint:unused // used in tests 31 func setupNodeForTestWithConfig(t *testing.T, config publicapi.APIServerConfig) (*node.Node, *requester_publicapi.RequesterAPIClient) { 32 require.NoError(t, system.InitConfigForTesting(t)) 33 ctx := context.Background() 34 35 datastore := inmemory.NewJobStore() 36 libp2pPort, err := freeport.GetFreePort() 37 require.NoError(t, err) 38 39 apiPort, err := freeport.GetFreePort() 40 require.NoError(t, err) 41 42 libp2pHost, err := libp2p.NewHost(libp2pPort) 43 require.NoError(t, err) 44 45 nodeConfig := node.NodeConfig{ 46 CleanupManager: system.NewCleanupManager(), 47 Host: libp2pHost, 48 HostAddress: "0.0.0.0", 49 APIPort: apiPort, 50 JobStore: datastore, 51 ComputeConfig: node.NewComputeConfigWithDefaults(), 52 RequesterNodeConfig: node.NewRequesterConfigWithDefaults(), 53 APIServerConfig: config, 54 IsRequesterNode: true, 55 IsComputeNode: true, 56 } 57 58 n, err := node.NewNode(ctx, nodeConfig, devstack.NewNoopNodeDependencyInjector()) 59 require.NoError(t, err) 60 61 err = n.Start(ctx) 62 require.NoError(t, err) 63 64 client := requester_publicapi.NewRequesterAPIClient(n.APIServer.GetURI()) 65 require.NoError(t, waitForHealthy(ctx, client)) 66 return n, client 67 } 68 69 //nolint:unused // used in tests 70 func waitForHealthy(ctx context.Context, c *requester_publicapi.RequesterAPIClient) error { 71 ch := make(chan bool) 72 go func() { 73 for { 74 alive, err := c.Alive(ctx) 75 if err == nil && alive { 76 ch <- true 77 return 78 } 79 80 time.Sleep(time.Duration(TimeToWaitForHealthy) * time.Millisecond) 81 } 82 }() 83 84 select { 85 case <-ch: 86 return nil 87 case <-time.After(time.Duration(TimeToWaitForServerReply) * time.Second): 88 return fmt.Errorf("server did not reply after %ss", time.Duration(TimeToWaitForServerReply)*time.Second) 89 } 90 }