//go:build hostedlive package main import ( "context" "flag" "reflect" "time" "github.com/aws/smithy-go/middleware" ) // maxPages bounds every paged list. const maxPages = 100 func tooManyPages() *failure { return &failure{exit: exitOther, Kind: "other", Message: "more than 100 pages; stopped reading"} } // failedState is a wait that reached a state it cannot leave for the one // it waits for (exit 6, the state as the code). func failedState(what, state string) *failure { return &failure{exit: exitFailed, Kind: "failed_state", Code: state, Message: what + " reached a failed state"} } // wait holds a wait's -timeout and -interval. type wait struct{ timeout, interval *time.Duration } func waitFlags(fs *flag.FlagSet, def time.Duration) wait { return wait{ timeout: fs.Duration("timeout", def, "give up after this long (at most 60m)"), interval: fs.Duration("interval", defaultInterval, "time between reads (at least 1s)"), } } // poll calls check until it reports done, returns an error, or the // timeout passes (exit 5). The first read is at once; reads are spaced // by the interval. The timeout is held two ways: on the wait's clock, // checked before each read and again after it, so an answer that comes // back after the deadline is never taken as success; and as a deadline on // e.ctx for the reads, so a call that stalls ends with the wait (each // call also has callTimeout of its own). func (w wait) poll(e *env, what string, check func() (bool, error)) error { timeout, interval := *w.timeout, *w.interval if timeout <= 0 || timeout > maxWait { return usage("-timeout must be above 0 and at most %v", maxWait) } if interval < time.Second { return usage("-interval must be at least 1s") } ranOut := &failure{exit: exitTimeout, Kind: "timeout", Message: "wait for " + what + " ran out after " + timeout.String()} outer := e.ctx ctx, cancel := context.WithTimeout(outer, timeout) defer cancel() e.ctx = ctx defer func() { e.ctx = outer }() deadline := e.clock.Now().Add(timeout) for { if !e.clock.Now().Before(deadline) || ctx.Err() != nil { return ranOut } done, err := check() if !e.clock.Now().Before(deadline) || ctx.Err() != nil { return ranOut } if done || err != nil { return err } e.clock.Sleep(min(interval, deadline.Sub(e.clock.Now()))) } } var metadataType = reflect.TypeOf(middleware.Metadata{}) // metadataOf returns the ResultMetadata field of an SDK output struct. func metadataOf(v any) (middleware.Metadata, bool) { rv := reflect.ValueOf(v) if rv.Kind() == reflect.Pointer { if rv.IsNil() { return middleware.Metadata{}, false } rv = rv.Elem() } if rv.Kind() != reflect.Struct { return middleware.Metadata{}, false } f := rv.FieldByName("ResultMetadata") if !f.IsValid() || f.Type() != metadataType { return middleware.Metadata{}, false } return f.Interface().(middleware.Metadata), true }