File: retry.go

package info (click to toggle)
golang-github-tideland-golib 4.24.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,144 kB
  • sloc: makefile: 4
file content (86 lines) | stat: -rw-r--r-- 2,096 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Tideland Go Library - Time Extensions
//
// Copyright (C) 2009-2017 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.

package timex

//--------------------
// IMPORTS
//--------------------

import (
	"time"

	"github.com/tideland/golib/errors"
)

//--------------------
// RETRY
//--------------------

// RetryStrategy describes how often the function in Retry is executed, the
// initial break between those retries, how much this time is incremented
// for each retry, and the maximum timeout.
type RetryStrategy struct {
	Count          int
	Break          time.Duration
	BreakIncrement time.Duration
	Timeout        time.Duration
}

// ShortAttempt returns a predefined short retry strategy.
func ShortAttempt() RetryStrategy {
	return RetryStrategy{
		Count:          10,
		Break:          50 * time.Millisecond,
		BreakIncrement: 0,
		Timeout:        5 * time.Second,
	}
}

// MediumAttempt returns a predefined medium retry strategy.
func MediumAttempt() RetryStrategy {
	return RetryStrategy{
		Count:          50,
		Break:          10 * time.Millisecond,
		BreakIncrement: 10 * time.Millisecond,
		Timeout:        30 * time.Second,
	}
}

// LongAttempt returns a predefined long retry strategy.
func LongAttempt() RetryStrategy {
	return RetryStrategy{
		Count:          100,
		Break:          10 * time.Millisecond,
		BreakIncrement: 25 * time.Millisecond,
		Timeout:        5 * time.Minute,
	}
}

// Retry executes the passed function until it returns true or an error.
// These retries are restricted by the retry strategy.
func Retry(f func() (bool, error), rs RetryStrategy) error {
	timeout := time.Now().Add(rs.Timeout)
	sleep := rs.Break
	for i := 0; i < rs.Count; i++ {
		done, err := f()
		if err != nil {
			return err
		}
		if done {
			return nil
		}
		if time.Now().After(timeout) {
			return errors.New(ErrRetriedTooLong, errorMessages, rs.Timeout)
		}
		time.Sleep(sleep)
		sleep += rs.BreakIncrement
	}
	return errors.New(ErrRetriedTooOften, errorMessages, rs.Count)
}

// EOF