github.com/sacloud/iaas-api-go@v1.12.0/helper/query/wait.go (about)

     1  // Copyright 2016-2022 The sacloud/iaas-api-go Authors
     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 query
    16  
    17  import (
    18  	"context"
    19  	"time"
    20  )
    21  
    22  const (
    23  	// DefaultTimeoutDuration 被参照がなくなるまでのデフォルトタイムアウト
    24  	DefaultTimeoutDuration = time.Hour
    25  	// DefaultTick 被参照確認のデフォルト間隔
    26  	DefaultTick = 5 * time.Second
    27  )
    28  
    29  // DefaultCheckReferencedOption 被参照確認動作のデフォルトオプション
    30  var DefaultCheckReferencedOption = CheckReferencedOption{
    31  	Timeout: DefaultTimeoutDuration,
    32  	Tick:    DefaultTick,
    33  }
    34  
    35  // CheckReferencedOption 被参照確認動作のオプション
    36  type CheckReferencedOption struct {
    37  	// Timeout 被参照がなくなるまでのタイムアウト
    38  	Timeout time.Duration
    39  	// Tick 被参照確認の間隔
    40  	Tick time.Duration
    41  }
    42  
    43  func (c *CheckReferencedOption) init() {
    44  	if c.Timeout <= 0 {
    45  		c.Timeout = DefaultTimeoutDuration
    46  	}
    47  	if c.Tick <= 0 {
    48  		c.Tick = DefaultTick
    49  	}
    50  }
    51  
    52  // WaitWhileReferenced 参照されている間待ち合わせを行う
    53  func waitWhileReferenced(ctx context.Context, option CheckReferencedOption, f func() (bool, error)) error {
    54  	option.init()
    55  
    56  	if option.Timeout > 0 {
    57  		c, cancel := context.WithTimeout(ctx, option.Timeout)
    58  		defer cancel()
    59  		ctx = c
    60  	}
    61  
    62  	t := time.NewTicker(option.Tick)
    63  	defer t.Stop()
    64  
    65  	// initial call
    66  	if found, err := f(); !found || err != nil {
    67  		return err
    68  	}
    69  
    70  	for {
    71  		select {
    72  		case <-t.C:
    73  			if found, err := f(); !found || err != nil {
    74  				return err
    75  			}
    76  		case <-ctx.Done():
    77  			return ctx.Err()
    78  		}
    79  	}
    80  }