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
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::ffi::c_void;
use std::io::{self, Read, Write};
use std::mem::forget;
use std::net::{SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::os::raw::c_char;
use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd};
use std::rc::Rc;
use std::time::Duration;
use core::ptr::null_mut;
use num_traits::Zero;
use crate::error::{Error, TarantoolError};
use crate::ffi::tarantool as ffi;
use crate::fiber::{unpack_callback, Cond};
const TIMEOUT_INFINITY: f64 = 365.0 * 86400.0 * 100.0;
pub struct CoIOStream {
fd: RawFd,
}
impl CoIOStream {
pub fn new<T>(inner: T) -> Result<CoIOStream, io::Error>
where
T: IntoRawFd,
{
let fd = inner.into_raw_fd();
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL, 0) };
if flags < 0 {
return Err(io::Error::last_os_error());
}
if unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 } {
Err(io::Error::last_os_error())
} else {
Ok(CoIOStream { fd })
}
}
pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<CoIOStream, io::Error> {
let inner_stream = TcpStream::connect(addr)?;
inner_stream.set_nonblocking(true)?;
Ok(CoIOStream {
fd: inner_stream.into_raw_fd(),
})
}
pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> Result<CoIOStream, io::Error> {
let inner_stream = TcpStream::connect_timeout(addr, timeout)?;
inner_stream.set_nonblocking(true)?;
Ok(CoIOStream {
fd: inner_stream.into_raw_fd(),
})
}
pub fn read_with_timeout(
&mut self,
buf: &mut [u8],
timeout: Option<Duration>,
) -> Result<usize, io::Error> {
read(self.fd, buf, timeout)
}
pub fn write_with_timeout(
&mut self,
buf: &[u8],
timeout: Option<Duration>,
) -> Result<usize, io::Error> {
write(self.fd, buf, timeout)
}
}
impl IntoRawFd for CoIOStream {
fn into_raw_fd(self) -> RawFd {
let fd = self.fd;
forget(self);
fd
}
}
impl AsRawFd for CoIOStream {
fn as_raw_fd(&self) -> RawFd {
self.fd
}
}
impl Read for CoIOStream {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
self.read_with_timeout(buf, None)
}
}
impl Write for CoIOStream {
fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
self.write_with_timeout(buf, None)
}
fn flush(&mut self) -> Result<(), io::Error> {
Ok(())
}
}
impl Drop for CoIOStream {
fn drop(&mut self) {
unsafe { ffi::coio_close(self.fd) };
}
}
pub struct CoIOListener {
inner: TcpListener,
}
impl CoIOListener {
pub fn accept(&self) -> Result<CoIOStream, io::Error> {
loop {
let res = self.inner.accept();
return match res {
Ok((stream, _)) => CoIOStream::new(stream),
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
coio_wait(
self.inner.as_raw_fd(),
ffi::CoIOFlags::READ,
TIMEOUT_INFINITY,
)?;
continue;
}
Err(e)
}
};
}
}
pub fn inner_listener(&mut self) -> &mut TcpListener {
&mut self.inner
}
}
impl TryFrom<TcpListener> for CoIOListener {
type Error = io::Error;
fn try_from(value: TcpListener) -> Result<Self, Self::Error> {
value.set_nonblocking(true)?;
Ok(Self { inner: value })
}
}
pub fn coio_wait(fd: RawFd, flags: ffi::CoIOFlags, timeout: f64) -> Result<(), io::Error> {
match unsafe { ffi::coio_wait(fd, flags.bits(), timeout) } {
0 => Err(io::ErrorKind::TimedOut.into()),
_ => Ok(()),
}
}
pub fn coio_call<F, T>(callback: &mut F, arg: T) -> isize
where
F: FnMut(Box<T>) -> i32,
{
let (callback_ptr, trampoline) = unsafe { unpack_callback(callback) };
unsafe { ffi::coio_call(trampoline, callback_ptr, Box::into_raw(Box::<T>::new(arg))) }
}
pub fn getaddrinfo(
host: &str,
port: &str,
hints: &libc::addrinfo,
timeout: f64,
) -> Result<libc::addrinfo, Error> {
let mut result: *mut libc::addrinfo = null_mut();
if unsafe {
ffi::coio_getaddrinfo(
host.as_ptr() as *const c_char,
port.as_ptr() as *const c_char,
&*hints,
&mut result,
timeout,
)
} < 0
{
Err(TarantoolError::last().into())
} else {
Ok(unsafe { result.read() })
}
}
#[inline(always)]
pub(crate) fn read(
fd: RawFd,
buf: &mut [u8],
timeout: Option<Duration>,
) -> Result<usize, io::Error> {
let buf_len = buf.len();
let result = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf_len) };
if result >= 0 {
return Ok(result as usize);
}
let err = io::Error::last_os_error();
if err.kind() != io::ErrorKind::WouldBlock {
return Err(err);
}
let timeout = match timeout {
None => TIMEOUT_INFINITY,
Some(timeout) => timeout.as_secs_f64(),
};
coio_wait(fd, ffi::CoIOFlags::READ, timeout)?;
let result = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf_len) };
if result < 0 {
Err(io::Error::last_os_error())
} else {
Ok(result as usize)
}
}
#[inline(always)]
pub(crate) fn write(fd: RawFd, buf: &[u8], timeout: Option<Duration>) -> Result<usize, io::Error> {
let result = unsafe { libc::write(fd, buf.as_ptr() as *mut c_void, buf.len()) };
if result >= 0 {
return Ok(result as usize);
}
let err = io::Error::last_os_error();
if err.kind() != io::ErrorKind::WouldBlock {
return Err(err);
}
let timeout = match timeout {
None => TIMEOUT_INFINITY,
Some(timeout) => timeout.as_secs_f64(),
};
coio_wait(fd, ffi::CoIOFlags::WRITE, timeout)?;
let result = unsafe { libc::write(fd, buf.as_ptr() as *mut c_void, buf.len()) };
if result < 0 {
Err(io::Error::last_os_error())
} else {
Ok(result as usize)
}
}
pub fn channel<T>(capacity: usize) -> (Sender<T>, Receiver<T>) {
let chan = Rc::new(Chan {
buffer: RefCell::new(VecDeque::with_capacity(capacity)),
cond: Cond::new(),
tx_count: Cell::new(1),
rx_is_active: Cell::new(true),
});
(Sender(chan.clone()), Receiver(chan))
}
pub struct Sender<T>(Rc<Chan<T>>);
impl<T> Sender<T> {
pub fn send(&self, value: T) -> Result<(), io::Error> {
if !self.0.rx_is_active.get() {
return Err(io::ErrorKind::NotConnected.into());
}
let was_empty = {
let mut buffer = self.0.buffer.borrow_mut();
let was_empty = buffer.len() == 0;
buffer.push_back(value);
was_empty
};
if was_empty {
self.0.cond.signal();
}
Ok(())
}
}
impl<T> Clone for Sender<T> {
fn clone(&self) -> Self {
self.0.tx_count.set(self.0.tx_count.get() + 1);
Sender(self.0.clone())
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
self.0.tx_count.set(self.0.tx_count.get() - 1);
self.0.cond.signal();
}
}
pub struct Receiver<T>(Rc<Chan<T>>);
impl<T> Receiver<T> {
pub fn recv(&self) -> Option<T> {
if self.0.buffer.borrow().len() == 0 {
if self.0.tx_count.get().is_zero() {
return None;
}
self.0.cond.wait();
}
self.0.buffer.borrow_mut().pop_front()
}
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
self.0.rx_is_active.set(false);
}
}
struct Chan<T> {
buffer: RefCell<VecDeque<T>>,
cond: Cond,
tx_count: Cell<usize>,
rx_is_active: Cell<bool>,
}