-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout.zig
More file actions
502 lines (403 loc) · 14.2 KB
/
timeout.zig
File metadata and controls
502 lines (403 loc) · 14.2 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
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
const std = @import("std");
const suite = @import("suite.zig");
const compat = @import("compat.zig");
/// Global timeout configuration
pub const GlobalTimeoutConfig = struct {
/// Default timeout for all tests (milliseconds)
default_timeout_ms: u64 = 5000,
/// Enable global timeout enforcement
enabled: bool = true,
/// Grace period after timeout before force termination (milliseconds)
grace_period_ms: u64 = 1000,
/// Allow tests to extend their timeout
allow_extension: bool = true,
/// Maximum timeout extension allowed (milliseconds)
max_extension_ms: u64 = 30000,
};
/// Timeout configuration
pub const TimeoutConfig = struct {
/// Test timeout in milliseconds (0 = no timeout)
timeout_ms: u64 = 0,
/// Suite timeout in milliseconds (0 = no timeout)
suite_timeout_ms: u64 = 0,
/// Use global timeout if no specific timeout set
use_global: bool = true,
};
/// Timeout status
pub const TimeoutStatus = enum {
not_started,
running,
completed_in_time,
timed_out,
extended,
grace_period,
};
/// Timeout result
pub const TimeoutResult = struct {
status: TimeoutStatus,
elapsed_ms: u64,
timeout_ms: u64,
extended_ms: u64 = 0,
message: ?[]const u8 = null,
allocator: std.mem.Allocator,
pub fn deinit(self: *TimeoutResult) void {
if (self.message) |msg| {
self.allocator.free(msg);
}
}
pub fn format(
self: TimeoutResult,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
try writer.print("Timeout Result:\n", .{});
try writer.print(" Status: {s}\n", .{@tagName(self.status)});
try writer.print(" Elapsed: {d}ms\n", .{self.elapsed_ms});
try writer.print(" Timeout: {d}ms\n", .{self.timeout_ms});
if (self.extended_ms > 0) {
try writer.print(" Extended: {d}ms\n", .{self.extended_ms});
}
if (self.message) |msg| {
try writer.print(" Message: {s}\n", .{msg});
}
}
};
/// Timeout context for tracking test execution time
pub const TimeoutContext = struct {
allocator: std.mem.Allocator,
timeout_ms: u64,
start_time: i64,
extension_ms: u64 = 0,
status: std.atomic.Value(u32) = std.atomic.Value(u32).init(0), // 0=not_started, 1=running, 2=completed, 3=timed_out, 4=extended, 5=grace_period
completed: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
allow_extension: bool = true,
max_extension_ms: u64 = 30000,
const Self = @This();
pub fn init(allocator: std.mem.Allocator, timeout_ms: u64) Self {
return .{
.allocator = allocator,
.timeout_ms = timeout_ms,
.start_time = compat.milliTimestamp(),
};
}
/// Start the timeout timer
pub fn start(self: *Self) void {
self.start_time = compat.milliTimestamp();
self.status.store(1, .monotonic); // running
}
/// Check if timeout has been exceeded
pub fn isTimedOut(self: *Self) bool {
if (self.completed.load(.monotonic)) {
return false;
}
const elapsed = self.getElapsedMs();
const total_timeout = self.timeout_ms + self.extension_ms;
return elapsed >= total_timeout;
}
/// Get elapsed time in milliseconds
pub fn getElapsedMs(self: *Self) u64 {
const now = compat.milliTimestamp();
return @intCast(now - self.start_time);
}
/// Get remaining time in milliseconds
pub fn getRemainingMs(self: *Self) u64 {
const elapsed = self.getElapsedMs();
const total_timeout = self.timeout_ms + self.extension_ms;
if (elapsed >= total_timeout) {
return 0;
}
return total_timeout - elapsed;
}
/// Extend the timeout by specified milliseconds
pub fn extend(self: *Self, additional_ms: u64) !void {
if (!self.allow_extension) {
return error.ExtensionNotAllowed;
}
const new_extension = self.extension_ms + additional_ms;
if (new_extension > self.max_extension_ms) {
return error.ExtensionLimitExceeded;
}
self.extension_ms = new_extension;
self.status.store(4, .monotonic); // extended
}
/// Mark as completed
pub fn complete(self: *Self) void {
self.completed.store(true, .monotonic);
self.status.store(2, .monotonic); // completed_in_time
}
/// Mark as timed out
pub fn markTimedOut(self: *Self) void {
self.status.store(3, .monotonic); // timed_out
}
fn statusToEnum(status_int: u32) TimeoutStatus {
return switch (status_int) {
0 => .not_started,
1 => .running,
2 => .completed_in_time,
3 => .timed_out,
4 => .extended,
5 => .grace_period,
else => .not_started,
};
}
/// Get the timeout result
pub fn getResult(self: *Self) !TimeoutResult {
const elapsed = self.getElapsedMs();
const status_int = self.status.load(.monotonic);
const status_value = statusToEnum(status_int);
var message: ?[]const u8 = null;
if (status_value == .timed_out) {
message = try std.fmt.allocPrint(
self.allocator,
"Test exceeded timeout of {d}ms (elapsed: {d}ms)",
.{ self.timeout_ms + self.extension_ms, elapsed },
);
} else if (status_value == .extended) {
message = try std.fmt.allocPrint(
self.allocator,
"Timeout extended by {d}ms",
.{self.extension_ms},
);
}
return TimeoutResult{
.status = status_value,
.elapsed_ms = elapsed,
.timeout_ms = self.timeout_ms,
.extended_ms = self.extension_ms,
.message = message,
.allocator = self.allocator,
};
}
};
/// Timeout enforcer - monitors and enforces test timeouts
pub const TimeoutEnforcer = struct {
allocator: std.mem.Allocator,
global_config: GlobalTimeoutConfig,
active_contexts: std.ArrayList(*TimeoutContext),
monitor_thread: ?std.Thread = null,
running: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
mutex: compat.Mutex = .{},
const Self = @This();
pub fn init(allocator: std.mem.Allocator, global_config: GlobalTimeoutConfig) Self {
return .{
.allocator = allocator,
.global_config = global_config,
.active_contexts = std.ArrayList(*TimeoutContext).empty,
};
}
pub fn deinit(self: *Self) void {
self.stop();
self.active_contexts.deinit(self.allocator);
}
/// Start monitoring timeouts
pub fn startMonitoring(self: *Self) !void {
if (self.running.load(.monotonic)) {
return;
}
self.running.store(true, .monotonic);
self.monitor_thread = try std.Thread.spawn(.{}, Self.monitorLoop, .{self});
}
/// Stop monitoring
pub fn stop(self: *Self) void {
if (!self.running.load(.monotonic)) {
return;
}
self.running.store(false, .monotonic);
if (self.monitor_thread) |thread| {
thread.join();
self.monitor_thread = null;
}
}
/// Register a timeout context for monitoring
pub fn registerContext(self: *Self, context: *TimeoutContext) !void {
self.mutex.lock();
defer self.mutex.unlock();
try self.active_contexts.append(self.allocator, context);
}
/// Unregister a timeout context
pub fn unregisterContext(self: *Self, context: *TimeoutContext) void {
self.mutex.lock();
defer self.mutex.unlock();
var i: usize = 0;
while (i < self.active_contexts.items.len) {
if (self.active_contexts.items[i] == context) {
_ = self.active_contexts.swapRemove(i);
return;
}
i += 1;
}
}
/// Monitor loop that runs in a separate thread
fn monitorLoop(self: *Self) void {
while (self.running.load(.monotonic)) {
compat.sleep(100 * std.time.ns_per_ms); // Check every 100ms
self.mutex.lock();
var i: usize = 0;
while (i < self.active_contexts.items.len) {
const context = self.active_contexts.items[i];
if (context.completed.load(.monotonic)) {
// Remove completed contexts
_ = self.active_contexts.swapRemove(i);
continue;
}
if (context.isTimedOut()) {
context.markTimedOut();
// Don't remove yet, let the test handler clean up
}
i += 1;
}
self.mutex.unlock();
}
}
/// Get the effective timeout for a test
pub fn getEffectiveTimeout(self: *Self, test_timeout_ms: u64, suite_timeout_ms: u64) u64 {
// Priority: test timeout > suite timeout > global timeout
if (test_timeout_ms > 0) {
return test_timeout_ms;
}
if (suite_timeout_ms > 0) {
return suite_timeout_ms;
}
if (self.global_config.enabled) {
return self.global_config.default_timeout_ms;
}
return 0; // No timeout
}
};
/// Suite timeout tracker
pub const SuiteTimeoutTracker = struct {
allocator: std.mem.Allocator,
suite_name: []const u8,
timeout_ms: u64,
start_time: i64,
test_count: usize = 0,
completed_count: usize = 0,
timed_out: bool = false,
const Self = @This();
pub fn init(allocator: std.mem.Allocator, suite_name: []const u8, timeout_ms: u64) Self {
return .{
.allocator = allocator,
.suite_name = suite_name,
.timeout_ms = timeout_ms,
.start_time = compat.milliTimestamp(),
};
}
pub fn isTimedOut(self: *Self) bool {
if (self.timed_out) {
return true;
}
if (self.timeout_ms == 0) {
return false;
}
const elapsed = self.getElapsedMs();
self.timed_out = elapsed >= self.timeout_ms;
return self.timed_out;
}
pub fn getElapsedMs(self: *Self) u64 {
const now = compat.milliTimestamp();
return @intCast(now - self.start_time);
}
pub fn incrementTest(self: *Self) void {
self.test_count += 1;
}
pub fn incrementCompleted(self: *Self) void {
self.completed_count += 1;
}
pub fn getRemainingMs(self: *Self) u64 {
if (self.timeout_ms == 0) {
return 0;
}
const elapsed = self.getElapsedMs();
if (elapsed >= self.timeout_ms) {
return 0;
}
return self.timeout_ms - elapsed;
}
};
// Tests
test "TimeoutContext basic timeout" {
const allocator = std.testing.allocator;
var context = TimeoutContext.init(allocator, 100);
context.start();
// Should not be timed out immediately
try std.testing.expect(!context.isTimedOut());
// Wait for timeout
compat.sleep(150 * std.time.ns_per_ms);
// Should be timed out now
try std.testing.expect(context.isTimedOut());
}
test "TimeoutContext extension" {
const allocator = std.testing.allocator;
var context = TimeoutContext.init(allocator, 100);
context.start();
// Extend timeout
try context.extend(100);
compat.sleep(120 * std.time.ns_per_ms);
// Should not be timed out (extended to 200ms total)
try std.testing.expect(!context.isTimedOut());
compat.sleep(100 * std.time.ns_per_ms);
// Should be timed out now
try std.testing.expect(context.isTimedOut());
}
test "TimeoutContext completion before timeout" {
const allocator = std.testing.allocator;
var context = TimeoutContext.init(allocator, 1000);
context.start();
compat.sleep(50 * std.time.ns_per_ms);
context.complete();
// Should not be timed out when completed
try std.testing.expect(!context.isTimedOut());
var result = try context.getResult();
defer result.deinit();
try std.testing.expectEqual(TimeoutStatus.completed_in_time, result.status);
try std.testing.expect(result.elapsed_ms < 1000);
}
test "TimeoutContext get result" {
const allocator = std.testing.allocator;
var context = TimeoutContext.init(allocator, 100);
context.start();
compat.sleep(150 * std.time.ns_per_ms);
context.markTimedOut();
var result = try context.getResult();
defer result.deinit();
try std.testing.expectEqual(TimeoutStatus.timed_out, result.status);
try std.testing.expect(result.elapsed_ms >= 100);
}
test "TimeoutEnforcer effective timeout priority" {
const allocator = std.testing.allocator;
var enforcer = TimeoutEnforcer.init(allocator, .{
.default_timeout_ms = 5000,
.enabled = true,
});
defer enforcer.deinit();
// Test timeout takes priority
const timeout1 = enforcer.getEffectiveTimeout(1000, 2000);
try std.testing.expectEqual(@as(u64, 1000), timeout1);
// Suite timeout takes priority over global
const timeout2 = enforcer.getEffectiveTimeout(0, 2000);
try std.testing.expectEqual(@as(u64, 2000), timeout2);
// Global timeout when no specific timeout
const timeout3 = enforcer.getEffectiveTimeout(0, 0);
try std.testing.expectEqual(@as(u64, 5000), timeout3);
}
test "SuiteTimeoutTracker basic functionality" {
const allocator = std.testing.allocator;
var tracker = SuiteTimeoutTracker.init(allocator, "test suite", 200);
try std.testing.expect(!tracker.isTimedOut());
tracker.incrementTest();
tracker.incrementCompleted();
compat.sleep(250 * std.time.ns_per_ms);
try std.testing.expect(tracker.isTimedOut());
}
test "SuiteTimeoutTracker remaining time" {
const allocator = std.testing.allocator;
var tracker = SuiteTimeoutTracker.init(allocator, "test suite", 1000);
const remaining1 = tracker.getRemainingMs();
try std.testing.expect(remaining1 > 900 and remaining1 <= 1000);
compat.sleep(100 * std.time.ns_per_ms);
const remaining2 = tracker.getRemainingMs();
try std.testing.expect(remaining2 < remaining1);
}