github.com/bazelbuild/rules_webtesting@v0.2.0/go/healthreporter/health_reporter.go (about)

     1  // Copyright 2016 Google Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package healthreporter provides polling wait functions.
    16  package healthreporter
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  	"log"
    22  	"time"
    23  
    24  	"github.com/bazelbuild/rules_webtesting/go/errors"
    25  )
    26  
    27  const (
    28  	pollMin     = 50 * time.Millisecond
    29  	pollMax     = time.Second
    30  	pollDefault = pollMin
    31  	pollCount   = 20
    32  )
    33  
    34  // A HealthReporter knows its name and can check if it is healthy.
    35  type HealthReporter interface {
    36  	// Component is the name used in errors.
    37  	Name() string
    38  	// Healthy returns nil if this is healthy, and an Error describing the problem if not healthy.
    39  	// Healthy should respect Context's Done.
    40  	Healthy(context.Context) error
    41  }
    42  
    43  // WaitForHealthy waits until ctx is Done or h is Healthy, returning an error
    44  // if h does not become healthy.
    45  func WaitForHealthy(ctx context.Context, h HealthReporter) error {
    46  	poll := pollDefault
    47  	if deadline, ok := ctx.Deadline(); ok {
    48  		poll = deadline.Sub(time.Now()) / pollCount
    49  		if poll < pollMin {
    50  			poll = pollMin
    51  		}
    52  		if poll > pollMax {
    53  			poll = pollMax
    54  		}
    55  	} else {
    56  		log.Printf("%s WaitForHealthy being called without deadline; will potentially wait forever.", h.Name())
    57  	}
    58  
    59  	ticker := time.NewTicker(poll)
    60  	defer ticker.Stop()
    61  
    62  	for {
    63  		err := h.Healthy(ctx)
    64  		if err == nil {
    65  			return nil
    66  		}
    67  		if errors.IsPermanent(err) {
    68  			return err
    69  		}
    70  		select {
    71  		case <-ctx.Done():
    72  			return errors.New(h.Name(), fmt.Errorf("%v waiting for healthy: %v", ctx.Err(), err))
    73  		case <-ticker.C:
    74  		}
    75  	}
    76  }