-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathclass_backoff.R
More file actions
78 lines (76 loc) · 1.69 KB
/
class_backoff.R
File metadata and controls
78 lines (76 loc) · 1.69 KB
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
# Exponential backoff algorithm
# similar to https://en.wikipedia.org/wiki/Exponential_backoff
backoff_init <- function(min = 0.001, max = 0.1, rate = 1.5) {
backoff_new(
min = min,
max = max,
rate = rate,
index = 0L
)
}
backoff_new <- function(
min = NULL,
max = NULL,
rate = NULL,
index = NULL
) {
backoff_class$new(
min = min,
max = max,
rate = rate,
index = index
)
}
backoff_class <- R6::R6Class(
classname = "tar_backoff",
class = TRUE,
portable = FALSE,
cloneable = FALSE,
public = list(
min = NULL,
max = NULL,
rate = NULL,
index = NULL,
initialize = function(
min = NULL,
max = NULL,
rate = NULL,
index = NULL
) {
self$min <- min
self$max <- max
self$rate <- rate
self$index <- index
},
reset = function() {
self$index <- 0L
},
increment = function() {
self$index <- min(self$index + 1L, as.integer(1e9))
},
bound = function() {
min(self$max, (self$min) * ((self$rate)^(self$index)))
},
interval = function() {
stats::runif(n = 1L, min = self$min, max = self$bound())
},
wait = function() {
Sys.sleep(self$interval())
self$increment()
},
validate = function() {
tar_assert_scalar(self$min)
tar_assert_scalar(self$max)
tar_assert_scalar(self$rate)
tar_assert_scalar(self$index)
tar_assert_dbl(self$min)
tar_assert_dbl(self$max)
tar_assert_dbl(self$rate)
tar_assert_int(self$index)
tar_assert_ge(self$min, sqrt(.Machine$double.eps))
tar_assert_ge(self$max, self$min)
tar_assert_ge(self$rate, 1)
tar_assert_ge(self$index, 0L)
}
)
)