Lindenii Project Forge
Login

hare-ev

Temporary fork of hare-ev for... reasons
Commit info
ID
fd6583dac7371f14cb20ea0437699affa6184117
Author
Drew DeVault <sir@cmpwn.com>
Author date
Fri, 16 Dec 2022 18:04:16 +0100
Committer
Drew DeVault <sir@cmpwn.com>
Committer date
Fri, 16 Dec 2022 18:04:16 +0100
Actions
Implement timers

Implements: https://todo.sr.ht/~sircmpwn/hare-ev/9
use ev;
use log;
use time;

export fn main() void = {
	const loop = ev::newloop()!;
	defer ev::finish(&loop);

	const timer = ev::newtimer(&loop, &expired, time::clock::MONOTONIC)!;
	ev::timer_configure(timer, 1 * time::SECOND, 500 * time::MILLISECOND);

	for (ev::dispatch(&loop, -1)!) void;
};

fn expired(timer: *ev::file) void = {
	log::println("timer expired");
};
use errors;
use io;
use net;
use rt;
use unix::signal;

export type op = enum u64 {
	NONE     = 0,
	READV    = 1 << 0,
	WRITEV   = 1 << 1,

	READABLE = 1 << 16,
	WRITABLE = 2 << 16,
	ACCEPT   = 3 << 16,
	CONNECT  = 4 << 16,
	SIGNAL   = 5 << 16,
	TIMER    = 6 << 16,
};

export type fflags = enum uint {
	BLOCKING = 1 << 31,
};

export type file = struct {
	fd: io::file,
	ev: *loop,

	flags: fflags,
	op: op,
	cb: nullable *void,
	cb2: nullable *void,
	user: nullable *void,

	// Operation-specific data
	union {
		struct {
			rvbuf: rt::iovec,
			rvec: []rt::iovec,
			wvbuf: rt::iovec,
			wvec: []rt::iovec,
		},
		sockflags: net::sockflags,
		sigmask: signal::sigset,
	},
};

// Registers a file descriptor with an event loop.
export fn register(
	loop: *loop,
	fd: io::file,
) (*file | errors::error) = {
	const file = alloc(file {
		fd = fd,
		ev = loop,
		op = op::NONE,
		...
	});

	let ev = rt::epoll_event {
		events = 0,
		...
	};
	ev.data.ptr = file;
	match (rt::epoll_ctl(loop.fd, rt::EPOLL_CTL_ADD, fd, &ev)) {
	case void =>
		yield;
	case let err: rt::errno =>
		if (err: int == rt::EPERM) {
			// epoll(2) does not support regular files, use blocking
			// I/O instead
			file.flags = fflags::BLOCKING;
			return file;
		};
		return errors::errno(err);
	};

	return file;
};

// Unregisters a file object with an event loop and frees resources associated
// with it. Does not close the underlying file descriptor.
export fn unregister(file: *file) void = {
	const loop = file.ev;
	if (file.flags & fflags::BLOCKING == 0) {
		// The only way that this could fail is in the event of a
		// use-after-free or if the user fucks around and constructs a
		// custom [[file]] which was never registered, so assert on
		// error.
		rt::epoll_ctl(loop.fd, rt::EPOLL_CTL_DEL, file.fd, null)!;
	};
	if (file.op == op::SIGNAL) {
		signal_restore(file);
	};
	free(file);
};

// Unregisters a file object with an event loop, frees resources associated with
// it, and closes the underlying file descriptor.
export fn close(file: *file) void = {
	const fd = file.fd;
	unregister(file);
	io::close(fd)!;
};

// Sets the user data field on this file object to the provided object.
export fn setuser(file: *file, user: nullable *void) void = {
	file.user = user;
};

// Returns the user data field from this file object. If the field was null, an
// assertion is raised.
export fn getuser(file: *file) *void = {
	return file.user as *void;
};

// Returns the file descriptor for a given file. Note that ev assumes that it
// will be responsible for all I/O on the file and any user modifications may
// cause the event loop to enter an invalid state.
export fn getfd(file: *file) io::file = {
	return file.fd;
};

// Returns the event loop for a given file.
export fn getloop(file: *file) *loop = {
	return file.ev;
};

// Updates epoll events for a given file. For internal use.
fn file_epoll_ctl(file: *file) void = {
	let events = rt::EPOLLONESHOT;
	if (file.op & op::READV != 0 || file.op & op::READABLE != 0) {
		events |= rt::EPOLLIN | rt::EPOLLHUP;
	};
	if (file.op & op::WRITEV != 0 || file.op & op::WRITABLE != 0) {
		events |= rt::EPOLLOUT | rt::EPOLLHUP;
	};
	if (file.op & op::ACCEPT != 0) {
		events |= rt::EPOLLIN;
	};
	if (file.op & op::CONNECT != 0) {
		events |= rt::EPOLLOUT;
	};
	if (file.op & op::SIGNAL != 0) {
		events |= rt::EPOLLIN;
	};
	if (file.op & op::TIMER != 0) {
		events &= ~rt::EPOLLONESHOT;
		events |= rt::EPOLLIN;
	};

	let ev = rt::epoll_event {
		events = events,
		...
	};
	ev.data.ptr = file;
	// This can only fail under conditions associated with EPOLLEXCLUSIVE,
	// which we do not support.
	rt::epoll_ctl(file.ev.fd, rt::EPOLL_CTL_MOD, file.fd, &ev)!;
};
use errors;
use io;
use rt;
use time;
use types;
use unix::signal;

export type loop = struct {
	fd: io::file,
	events: []rt::epoll_event,
	stop: bool,
};

// Creates a new event loop. The user must pass the return value to [[finish]]
// to free associated resources when done using the loop.
export fn newloop() (loop | errors::error) = {
	const fd = match (rt::epoll_create1(rt::EPOLL_CLOEXEC)) {
	case let fd: int =>
		yield fd: io::file;
	case let err: rt::errno =>
		return errors::errno(err);
	};

	return loop {
		fd = fd,
		// XXX: Should the number of events be customizable?
		events = alloc([rt::epoll_event { ... }...], 256),
		stop = false,
	};
};

// Frees resources associated with an event loop. Must only be called once per
// event loop object. Calling finish invalidates all I/O objects associated with
// the event loop.
export fn finish(loop: *loop) void = {
	free(loop.events);
	io::close(loop.fd)!;
};

// Returns an [[io::file]] for this event loop which can be polled on when
// events are available for processing, for chaining together different event
// loops. The exact semantics of this function are platform-specific, and it may
// not be available for all implementations.
export fn loop_file(loop: *loop) io::file = {
	return loop.fd;
};

// Dispatches the event loop, waiting for new events and calling their callbacks
// as appropriate.
//
// A timeout of -1 will block indefinitely until the next event occurs. A
// timeout of 0 will cause dispatch to return immediately if no events are
// available to process. Portable use of the timeout argument supports only
// millisecond granularity of up to 24 days ([[types::INT_MAX]] milliseconds).
// Negative values other than -1 will cause the program to abort.
//
// Returns false if the loop has been stopped via [[stop]], or true otherwise.
export fn dispatch(
	loop: *loop,
	timeout: time::duration,
) (bool | errors::error) = {
	const millis: int = if (timeout == -1) {
		yield -1;
	} else if (timeout < 0) {
		abort("ev::dispatch: invalid timeout");
	} else {
		yield (timeout / time::MILLISECOND): int;
	};
	if (loop.stop) {
		return false;
	};
	if (len(loop.events) == 0) {
		return true;
	};

	// TODO: Deal with signals
	const maxev = len(loop.events);
	assert(maxev <= types::INT_MAX: size, "ev::dispatch: too many events");
	const nevent = rt::epoll_pwait(
		loop.fd, &loop.events[0],
		maxev: int, millis, null)!;

	for (let i = 0; i < nevent; i += 1) {
		const ev = &loop.events[i];
		const file = ev.data.ptr: *file;
		if (ev.events == 0) {
			continue;
		};
		const pending = file.op;
		if (ev.events & (rt::EPOLLIN | rt::EPOLLHUP) != 0
				&& pending & op::READV != 0) {
			readv_ready(file, ev);
		};
		if (ev.events & (rt::EPOLLOUT | rt::EPOLLHUP) != 0
				&& pending & op::WRITEV != 0) {
			writev_ready(file, ev);
		};
		switch (pending) {
		case op::NONE =>
			abort("No operation pending for ready object");
		case op::READABLE =>
			readable_ready(file, ev);
		case op::WRITABLE =>
			writable_ready(file, ev);
		case op::ACCEPT =>
			accept_ready(file, ev);
		case op::CONNECT =>
			connect_ready(file, ev);
		case op::SIGNAL =>
			signal_ready(file, ev);
		case op::TIMER =>
			timer_ready(file, ev);
		case =>
			yield;
			assert(pending & ~(op::READV | op::WRITEV) == 0);
		};
	};

	return !loop.stop;
};

// Signals the loop to stop processing events. If called during a callback, it
// will cause that invocation of [[dispatch]] to return false. Otherwise, false
// will be returned only upon the next call to [[dispatch]].
export fn stop(loop: *loop) void = {
	loop.stop = true;
};
use errors;
use io;
use rt;
use time;

// A callback which executes when a timer expires.
export type timercb = fn(file: *file) void;

// Creates a new timer. By default, this timer never expires; configure it with
// [[timer_configure]].
export fn newtimer(
	loop: *loop,
	cb: *timercb,
	clock: time::clock,
) (*file | errors::error) = {
	const fd = match (rt::timerfd_create(clock, rt::TFD_CLOEXEC)) {
	case let fd: int =>
		yield fd: io::file;
	case let errno: rt::errno =>
		return errors::errno(errno);
	};
	const file = register(loop, fd)?;
	file.op = op::TIMER;
	file.cb = cb;
	file_epoll_ctl(file);
	return file;
};

// Starts a timer created with [[newtimer]] to expire after the given "delay"
// and indefinitely thereafter following each interval of "repeat". Setting both
// values to zero disarms the timer; setting either value non-zero arms the
// timer.
export fn timer_configure(
	timer: *file,
	delay: time::duration,
	repeat: time::duration,
) void = {
	let spec = rt::itimerspec { ... };
	time::duration_to_timespec(delay, &spec.it_value);
	time::duration_to_timespec(repeat, &spec.it_interval);
	rt::timerfd_settime(timer.fd, 0, &spec, null)!;
};

fn timer_ready(timer: *file, ev: *rt::epoll_event) void = {
	assert(timer.op == op::TIMER);
	let buf: [8]u8 = [0...];
	io::read(timer.fd, buf)!;

	assert(timer.cb != null);
	const cb = timer.cb: *timercb;
	cb(timer);
};