From 6631d849f35c6d74e0623b96f7265e81bae9e055 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Decoodt?= Date: Tue, 16 Jun 2020 09:40:17 +0200 Subject: [PATCH] feat(iot): add WaitForHub IoT helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Clément Decoodt --- api/iot/v1beta1/iot_helpers.go | 63 ++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 api/iot/v1beta1/iot_helpers.go diff --git a/api/iot/v1beta1/iot_helpers.go b/api/iot/v1beta1/iot_helpers.go new file mode 100644 index 000000000..43570d1f7 --- /dev/null +++ b/api/iot/v1beta1/iot_helpers.go @@ -0,0 +1,63 @@ +package iot + +import ( + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/async" + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +const ( + waitForHubDefaultTimeout = 15 * time.Minute + defaultRetryInterval = 5 * time.Second +) + +// WaitForHubRequest is used by WaitForHub method. +type WaitForHubRequest struct { + HubID string + Region scw.Region + Status HubStatus + Timeout *time.Duration + RetryInterval *time.Duration +} + +// WaitForHub waits for the hub to be in a ready state before returning. +func (s *API) WaitForHub(req *WaitForHubRequest) (*Hub, error) { + timeout := waitForHubDefaultTimeout + if req.Timeout != nil { + timeout = *req.Timeout + } + retryInterval := defaultRetryInterval + if req.RetryInterval != nil { + retryInterval = *req.RetryInterval + } + + terminalStatus := map[HubStatus]struct{}{ + HubStatusError: {}, + HubStatusReady: {}, + HubStatusDisabled: {}, + } + + hub, err := async.WaitSync(&async.WaitSyncConfig{ + Get: func() (interface{}, bool, error) { + hub, err := s.GetHub(&GetHubRequest{ + HubID: req.HubID, + Region: req.Region, + }) + if err != nil { + return nil, false, err + } + + _, isTerminal := terminalStatus[hub.Status] + return hub, isTerminal, nil + }, + Timeout: timeout, + IntervalStrategy: async.LinearIntervalStrategy(retryInterval), + }) + if err != nil { + return nil, errors.Wrap(err, "waiting for hub failed") + } + + return hub.(*Hub), nil +}