-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvortex.zig
More file actions
286 lines (242 loc) · 10.3 KB
/
Copy pathvortex.zig
File metadata and controls
286 lines (242 loc) · 10.3 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
//! Vortex is a Zig library for structured concurrency and asynchronous event
//! processing. It builds on Zig's language support for async functions
//! (suspend/resume and async/await), providing the user with ergonomic task
//! spawning, joining, cancellation, and timeouts.
//!
//! This file provides the public API for Vortex, including access methods for:
//! - basic lifecycle management of the runtime
//! - task spawning, joining, and cancellation
//! - timekeeping and task-safe waiting ('sleeping')
//! - network communication
//! - recording events into a log or other event stream
//!
//! See the top-level README for more information and a feature roadmap.
//!
const std = @import("std");
const root = @import("root");
const ztracy = @import("ztracy");
const EventRegistry = @import("src/event.zig").EventRegistry;
const clock = @import("src/clock.zig");
const metricslib = @import("src/metrics.zig");
const network = @import("src/network.zig");
const pipe = @import("src/pipe.zig");
const runtime = @import("src/runtime.zig");
pub const Vortex = if (@hasDecl(root, "Runtime"))
VortexImpl(root.Runtime)
else
VortexImpl(runtime.DefaultRuntime);
pub const SimVortex = VortexImpl(runtime.SimRuntime);
fn VortexImpl(comptime R: type) type {
return struct {
pub const Config = R.Config;
pub const Timespec = clock.Timespec;
pub const DefaultTestConfig = R.Config{};
const Network = network.Impl(R);
const Scheduler = R.Scheduler;
var _instance: R = undefined;
pub fn init(alloc: std.mem.Allocator, config: R.Config) !void {
_instance = try R.init(alloc, config);
}
pub fn deinit(alloc: std.mem.Allocator) void {
_instance.deinit(alloc);
}
pub fn run(
comptime initFn: anytype,
initArgs: anytype,
) anyerror!void {
return _instance.run(initFn, initArgs);
}
/// Task spawning operations and types
pub const task = struct {
/// The currently running task id
pub fn id() Scheduler.TaskId {
return _instance.sched.currentTaskId();
}
/// A SpawnHandle holds the task-specific stack frame and associated state
/// necessary to implement the handle's join() and cancel() methods.
/// The intended usage is:
///
/// var handle: vx.SpawnHandle(my_entry) = undefined;
/// try vx.spawn(&handle, .{ ... }, timeout);
///
pub fn SpawnHandle(comptime entry: anytype) type {
return Scheduler.SpawnHandle(entry);
}
/// Spawns the task defined by spawnHandlePtr, passing args in as the entry
/// point arguments. If the task is not completed before req_timeout, it
/// is cancelled by the runtime and it returns a TaskTimeout error. If
/// that task has spawned child tasks, those and all their dependents are
/// also cancelled with TaskTimeout errors.
pub fn spawn(
spawnHandlePtr: anytype,
args: anytype,
req_timeout: ?Timespec,
) Scheduler.SpawnError!void {
const timeout = if (req_timeout) |t| t else clock.max_time;
return _instance.sched.spawnTask(spawnHandlePtr, args, timeout);
}
/// Waits for one of several tasks to complete, and cancels all
/// others. Expects `spawn_handles` to be a struct with one field
/// per task handle, and returns a tagged union of the task return
/// types, tagged by the task that completed first.
pub fn select(
spawn_handles: anytype,
) error{TaskCancelled}!Scheduler.SelectResultUnion(@TypeOf(spawn_handles)) {
return _instance.sched.select(spawn_handles);
}
};
/// Timekeeping methods
pub const time = struct {
/// Returns the current monotonic clock value, in nanoseconds elapsed since
/// an unspecified point in real-time.
/// TODO: remove this API, in favor of (1) a realtime() method for getting
/// the wall-clock time, and (2) an interval API to measure elapsed nanos
/// We should not expose the absolute value here for clients to somehow
/// rely on, as the basis value has no portable meaning.
pub fn now() Timespec {
return _instance.clock.now();
}
/// Suspend this task for interval nanoseconds
pub fn sleep(interval: Timespec) Scheduler.SuspendError!void {
return _instance.io().sleep(interval);
}
};
/// Networking methods
pub const net = struct {
pub const TcpListener = Network.Listener;
pub const TcpStream = Network.Stream;
/// Start a listener socket at the given address. Call accept() on
/// the returned TcpListener object to accept incoming connections.
pub fn startTcpListener(
addr: std.net.Address,
backlog: u31,
) TcpListener.InitError!TcpListener {
return TcpListener.init(&_instance, addr, backlog);
}
/// Open a TCP connection to a server listening at the given address.
/// Returns an IoTimeout error if the connection has not been made (and no
/// other error occurred) after timeout nanoseconds.
pub fn openTcpStream(
target: std.net.Address,
timeout: ?Timespec,
) TcpStream.ConnectError!TcpStream {
return TcpStream.connect(&_instance, target, timeout);
}
};
pub const ipc = struct {
pub const PipePair = pipe.Impl(R).PipePair;
/// Open a pipe, creating a read and write pair that can be accessed
/// from different contexts (usually between processes).
pub fn openPipe() !PipePair {
return PipePair.init(&_instance);
}
};
/// Synchronization methods
pub const sync = struct {
const Atomic = std.atomic.Atomic;
/// Task-aware Futex primitive
pub const Futex = struct {
const FutexImpl = @import("src/sync/futex.zig").Futex;
pub fn wait(
ptr: *const Atomic(u32),
expect: u32,
timeout: ?Timespec,
) !void {
return FutexImpl(R).wait(&_instance, ptr, expect, timeout);
}
pub fn wake(ptr: *const Atomic(u32), max_waiters: usize) void {
FutexImpl(R).wake(&_instance, ptr, max_waiters);
}
};
/// Channels to communicate values between tasks
pub fn Channel(comptime T: type) type {
const Impl = @import("src/sync/array_queue.zig").ArrayQueue;
return Impl(T, Futex);
}
/// Task-aware barrier synchronization
pub const Barrier = @import("src/sync/barrier.zig").Barrier(Futex);
};
/// Signals
pub const signal = struct {
pub const SupportedSignal = @import("src/signal.zig").SupportedSignal;
pub const SignalReader = struct {
fd: std.os.fd_t,
pub fn wait(sr: SignalReader, timeout_ns: ?Timespec) !void {
// read from the pipe, likely going async
var byte: [1]u8 = undefined;
const timeout = timeout_ns orelse clock.max_time;
_ = try _instance.io().read(sr.fd, &byte, 0, timeout);
// TODO: test byte is magic value?
}
};
pub fn register(sig: SupportedSignal) !SignalReader {
// register signal handler and get read-pipe fd
return SignalReader{
.fd = try _instance.signal_junction.register(sig),
};
}
};
/// Metrics tracking
pub const metrics = struct {
pub usingnamespace metricslib;
};
/// Tracing with tracy
pub const tracing = struct {
pub usingnamespace ztracy;
};
/// Event logging methods
pub const event = struct {
/// Emit an Event object with user-defined payload
pub fn emit(comptime Event: type, user: Event.User) void {
_instance.emitter.emit(
_instance.clock,
runtime.threadId(),
Event,
user,
);
}
/// Change the reporting level dynamically
pub fn setLevel(level: std.log.Level) void {
_instance.emitter.log_level = level;
}
/// Construct a scoped registry with the given namespace and enum of
/// event tags
pub fn Registry(
comptime namespace: []const u8,
comptime TagEnum: type,
) type {
return EventRegistry(namespace, TagEnum);
}
};
/// Testing-related methods
pub const testing = struct {
/// Convenience method to reduce boilerplate when writing tests.
pub fn runTest(
alloc: std.mem.Allocator,
config: R.Config,
comptime initFn: anytype,
initArgs: anytype,
) anyerror!void {
try init(alloc, config);
defer deinit(alloc);
try _instance.run(initFn, initArgs);
}
pub fn unusedTcpPort() !std.net.Address {
return Network.testing.unusedTcpPort(&_instance);
}
};
};
}
test "api" {
// TODO: re-enable Sim tests
_ = @import("tests/timer.zig");
_ = @import("tests/task.zig");
_ = @import("tests/cancel.zig");
_ = @import("tests/tcp.zig");
_ = @import("tests/pipe.zig");
_ = @import("tests/futex.zig");
_ = @import("tests/barrier.zig");
_ = @import("tests/select.zig");
_ = @import("tests/signal.zig");
_ = @import("tests/channel.zig");
}