-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathutils.d
232 lines (194 loc) · 5.43 KB
/
utils.d
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
module dlangbot.utils;
import core.time : seconds;
import dlangbot.app : runAsync;
import vibe.http.client : HTTPClientRequest, HTTPClientResponse, HTTPClientSettings;
import vibe.http.common : HTTPStatus;
import std.datetime : Duration;
import std.format : format;
version (unittest) int _expectedStatusCode;
bool expectedStatusCode(int statusCode) nothrow @safe @nogc
{
version (unittest)
{
if (_expectedStatusCode == statusCode)
{
_expectedStatusCode = 0;
return true;
}
}
return false;
}
private HTTPClientSettings httpClientSettings;
static this()
{
httpClientSettings = new HTTPClientSettings;
httpClientSettings.connectTimeout = 10.seconds;
httpClientSettings.readTimeout = 10.seconds;
}
HTTPClientResponse expectOK(HTTPClientResponse res)
{
if (res.statusCode / 100 != 2)
{
res.dropBody();
throw new Exception("HTTP request failed with status %d".format(res.statusCode));
}
return res;
}
HTTPClientResponse request(
string url,
scope void delegate(scope HTTPClientRequest) requester = cast(void delegate(scope HTTPClientRequest req))null
) @safe
{
import vibe.core.log : logWarn;
import vibe.http.client : requestHTTP;
import vibe.http.common : HTTPMethod;
HTTPMethod method;
auto res = requestHTTP(
url,
(scope req) {
if (requester !is null)
requester(req);
method = req.method;
},
httpClientSettings);
if (res.statusCode / 100 != 2 && !expectedStatusCode(res.statusCode))
logWarn("%s %s failed; %s %s.", method, url, res.statusPhrase, res.statusCode);
return res;
}
void request(
string url,
scope void delegate(scope HTTPClientRequest) requester,
scope void delegate(scope HTTPClientResponse) responder
) @safe
{
import vibe.core.log : logWarn;
import vibe.http.client : requestHTTP;
import vibe.http.common : HTTPMethod;
HTTPMethod method;
requestHTTP(
url,
(scope req) {
requester(req);
method = req.method;
},
(scope res) {
if (res.statusCode / 100 != 2 && !expectedStatusCode(res.statusCode))
logWarn("%s %s failed; %s %s.", method, url, res.statusPhrase, res.statusCode);
responder(res);
},
httpClientSettings
);
}
auto runTaskHelper(Fun, Args...)(Fun fun, auto ref Args args)
{
import std.functional : toDelegate;
import vibe.core.core : runTask;
if (runAsync)
runTask(fun.toDelegate, args);
else
return fun(args);
}
/**
Thottles subsequent calls to one per `throttleTime`.
-----
call(); // direct execution
call(); // will be executed in `throttleTime` (all further request will be ignored)
call(); // ignored
<wait>
call(); // direct execution
...
-----
*/
struct Throttler(Fun)
{
import std.typecons : Tuple;
import vibe.core.core : setTimer, Timer;
import std.datetime : Clock, SysTime;
private:
import std.traits : Parameters;
alias Args = Parameters!Fun;
static struct ThrottleEntry
{
SysTime startedTime;
Timer timer;
}
ThrottleEntry[Tuple!Args] timersPerArgs;
Fun fun;
Duration throttleTime;
public:
this(Fun fun, Duration throttleTime)
{
this.fun = fun;
this.throttleTime = throttleTime;
}
void reset()
{
foreach (entry; timersPerArgs)
if (entry.timer)
entry.timer.stop;
// can't use clear due to 2.070 support
timersPerArgs = null;
}
void opCall(Args args)
{
auto key = Tuple!Args(args);
auto entry = key in timersPerArgs;
// the first access fires directly
if (entry is null)
{
ThrottleEntry ep = {
startedTime: Clock.currTime,
};
timersPerArgs[key] = ep;
return runTaskHelper(fun, args);
}
else
{
// stop if there's a pending timer -> ignore request
if (entry.timer && entry.timer.pending)
return;
// depending on the time stamp of the last run,
// run directly or start a timer
if (entry.startedTime + throttleTime <= Clock.currTime)
runTaskHelper(fun, args);
else
entry.timer = setTimer(throttleTime, { fun(args); });
entry.startedTime = Clock.currTime;
}
}
}
unittest
{
int[string] cDict;
void count(string key)
{
cDict[key]++;
}
import core.thread : Thread;
import std.datetime : msecs;
import vibe.core.core : setTimer;
auto throttleTime = 1.msecs;
auto throttler = Throttler!(typeof(&count))(&count, throttleTime);
// now no timers are running -> immediate call
throttler("A");
throttler("B");
// there was a call before -> timer set
throttler("A");
throttler("B");
// now timers are running -> ignored
throttler("A");
throttler("B");
// we got throttled and need to wait
assert(cDict == ["A": 1, "B": 1]);
setTimer(throttleTime * 2, () {
assert(cDict == ["A": 2, "B": 2]);
// now no timers are running -> immediate call
throttler("A");
throttler("B");
assert(cDict == ["A": 3, "B": 3]);
// now timers are running -> delayed
throttler("A");
throttler("B");
assert(cDict == ["A": 3, "B": 3]);
});
}